friendica/php-cs-fixer.phar

150872 lines
2.6 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env php
<?php
/*
* This file is part of the PHP CS utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
if (defined('HHVM_VERSION_ID')) {
if (HHVM_VERSION_ID < 30900) {
fwrite(STDERR, "HHVM needs to be a minimum version of HHVM 3.9.0\n");
exit(1);
}
} elseif (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50306 || PHP_VERSION_ID >= 70200) {
fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.3.6 and maximum version of PHP 7.1.*\n");
exit(1);
}
set_error_handler(function ($severity, $message, $file, $line) {
if ($severity & error_reporting()) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
});
Phar::mapPhar('php-cs-fixer.phar');
require_once 'phar://php-cs-fixer.phar/vendor/autoload.php';
use Symfony\CS\Console\Application;
$application = new Application();
$application->run();
__HALT_COMPILER(); ?>
«–/vendor/symfony/finder/Comparator/Comparator.phpŒ<00>'êWŒwþT¶3vendor/symfony/finder/Comparator/DateComparator.php%<00>'êW%L¿EǶ5vendor/symfony/finder/Comparator/NumberComparator.php~<00>'êW~”‡ x¶9vendor/symfony/finder/Exception/AccessDeniedException.php„<00>'êW„½¾sœ¶6vendor/symfony/finder/Exception/ExceptionInterface.php„<00>'êW„Gz-¶ vendor/symfony/finder/Finder.phpà <00>'êWà “r‰n¶vendor/symfony/finder/Glob.phpK<00>'êWKjá±n¶7vendor/symfony/finder/Iterator/CustomFilterIterator.php]<00>'êW]tà±µ¶:vendor/symfony/finder/Iterator/DateRangeFilterIterator.phpz<00>'êWz}¢¶;vendor/symfony/finder/Iterator/DepthRangeFilterIterator.phpð<00>'êWðß0™Avendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.phpÊ<00>'êWÊ<00>96†¶9vendor/symfony/finder/Iterator/FileTypeFilterIterator.php\<00>'êW\p'˜¶<vendor/symfony/finder/Iterator/FilecontentFilterIterator.php5<00>'êW5ší9vendor/symfony/finder/Iterator/FilenameFilterIterator.phpr<00>'êWrt1vendor/symfony/finder/Iterator/FilterIterator.phpÀ<00>'êWÀE™½Œ¶=vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php/<00>'êW/»Ç5vendor/symfony/finder/Iterator/PathFilterIterator.phpÏ<00>'êWϺªÇ¶=vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.phpÃ<00>'êWÃMÐÖ¶:vendor/symfony/finder/Iterator/SizeRangeFilterIterator.phpg<00>'êWg!Ô—é¶3vendor/symfony/finder/Iterator/SortableIterator.phpØ<00>'êWØ`>c¶%vendor/symfony/finder/SplFileInfo.phpÿ<00>'êWÿË OÀ¶7vendor/symfony/process/Exception/ExceptionInterface.phpf<00>'êWf]ö>T¶=vendor/symfony/process/Exception/InvalidArgumentException.php¨<00>'êW¨ÐÀ+_¶3vendor/symfony/process/Exception/LogicException.php”<00>'êW” ³ãñ¶;vendor/symfony/process/Exception/ProcessFailedException.phpx<00>'êWx¨Ìzy¶=vendor/symfony/process/Exception/ProcessTimedOutException.php<00>'êW. Ãá¶5vendor/symfony/process/Exception/RuntimeException.php˜<00>'êW˜¢Ø:¶+vendor/symfony/process/ExecutableFinder.php<00>'êW³0&vendor/symfony/process/InputStream.php'<00>'êW'Tv9.vendor/symfony/process/PhpExecutableFinder.phpN<00>'êWNR”%vendor/symfony/process/PhpProcess.php<00>'êWY³Ô/¶.vendor/symfony/process/Pipes/AbstractPipes.php
<00>'êW
æh3@¶/vendor/symfony/process/Pipes/PipesInterface.phpm<00>'êWmï*vendor/symfony/process/Pipes/UnixPipes.php•<00>'êW•Y¨Ã¶-vendor/symfony/process/Pipes/WindowsPipes.phpd <00>'êWd "'û¶"vendor/symfony/process/Process.php¾V<00>'êW¾V×)vendor/symfony/process/ProcessBuilder.phpß
<00>'êWß
#-X˜'vendor/symfony/process/ProcessUtils.phpF<00>'êWFØú¦ÿ¶vendor/symfony/yaml/Dumper.php<68><00>'êW<C3AA>Íå¶vendor/symfony/yaml/Escaper.phpR<00>'êWR‚õ—¶/vendor/symfony/yaml/Exception/DumpException.phps<00>'êWs¢ƶ4vendor/symfony/yaml/Exception/ExceptionInterface.phpc<00>'êWc ñÛ¶0vendor/symfony/yaml/Exception/ParseException.phpD<00>'êWDX2vendor/symfony/yaml/Exception/RuntimeException.php•<00>'êW•Æî$ô¶vendor/symfony/yaml/Inline.php¥6<00>'êW¥6i«Û ¶vendor/symfony/yaml/Parser.phpÝE<00>'êWÝEå\ɯ¶!vendor/symfony/yaml/Unescaper.phpÚ<00>'êWÚ5ÜZY¶vendor/symfony/yaml/Yaml.phpi<00>'êWi51왶$vendor/symfony/stopwatch/Section.php(<00>'êW(”åL¶¶&vendor/symfony/stopwatch/Stopwatch.phpn<00>'êWnE +vendor/symfony/stopwatch/StopwatchEvent.php) <00>'êW) p©•,vendor/symfony/stopwatch/StopwatchPeriod.php<00>'êW<68>À¶-vendor/symfony/polyfill-mbstring/Mbstring.php0<00>'êW0‘ߥ@vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php2A<00>'êW2A½=¨¶@vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php¡A<00>'êW¡AÚ Í¶.vendor/symfony/polyfill-mbstring/bootstrap.phpo<00>'êWoc×&vendor/symfony/console/Application.php@R<00>'êW@RCyÁʶ*vendor/symfony/console/Command/Command.php£<00>'êW£§&`ë¶.vendor/symfony/console/Command/HelpCommand.php«<00>'êW«3´m.vendor/symfony/console/Command/ListCommand.php(<00>'êW($ƒXɶ(vendor/symfony/console/ConsoleEvents.phpç<00>'êWç#  <vendor/symfony/console/Descriptor/ApplicationDescription.phpß<00>'êWßµŒ°7¶0vendor/symfony/console/Descriptor/Descriptor.phpŸ<00>'êWŸLôsî¶9vendor/symfony/console/Descriptor/DescriptorInterface.phpü<00>'êWü±Qµ¶4vendor/symfony/console/Descriptor/JsonDescriptor.phpš <00>'êWš 8vendor/symfony/console/Descriptor/MarkdownDescriptor.php<00>'êW?w4vendor/symfony/console/Descriptor/TextDescriptor.phpt<00>'êWtbÊJ¶3vendor/symfony/console/Descriptor/XmlDescriptor.php<00>'êWP$¶4vendor/symfony/console/Event/ConsoleCommandEvent.php²<00>'êW²Zk‰2¶-vendor/symfony/console/Event/ConsoleEvent.phpÅ<00>'êWÅÒxÛ\¶6vendor/symfony/console/Event/ConsoleExceptionEvent.php<00>'êWá2é¶6vendor/symfony/console/Event/ConsoleTerminateEvent.phpz<00>'êWz³,îL¶=vendor/symfony/console/Exception/CommandNotFoundException.phpÔ<00>'êWÔÈ÷ L¶7vendor/symfony/console/Exception/ExceptionInterface.phpf<00>'êWf¡ABª¶=vendor/symfony/console/Exception/InvalidArgumentException.php¦<00>'êW¦Ö̽Z¶;vendor/symfony/console/Exception/InvalidOptionException.php¦<00>'êW¦Ë×3vendor/symfony/console/Exception/LogicException.php<00>'êWÍO\e¶5vendor/symfony/console/Exception/RuntimeException.php<00>'êWÙí,6¶4vendor/symfony/console/Formatter/OutputFormatter.php° <00>'êW° æ<>q@¶=vendor/symfony/console/Formatter/OutputFormatterInterface.phpŠ<00>'êWŠ9vendor/symfony/console/Formatter/OutputFormatterStyle.phpL<00>'êWLŠ<>8<¶Bvendor/symfony/console/Formatter/OutputFormatterStyleInterface.php†<00>'êW†ÝRÚ­>vendor/symfony/console/Formatter/OutputFormatterStyleStack.phpL<00>'êWL.=6vendor/symfony/console/Helper/DebugFormatterHelper.phpx<00>'êWxN©Ø¼¶2vendor/symfony/console/Helper/DescriptorHelper.phpz<00>'êWzfÉÚý¶1vendor/symfony/console/Helper/FormatterHelper.phpÙ<00>'êWÙý†Î(vendor/symfony/console/Helper/Helper.php<00>'êW‡Â<£¶1vendor/symfony/console/Helper/HelperInterface.phpç<00>'êWç Çã¶+vendor/symfony/console/Helper/HelperSet.phpv<00>'êWvð3¯O¶2vendor/symfony/console/Helper/InputAwareHelper.phpc<00>'êWcñø<C3B1>/vendor/symfony/console/Helper/ProcessHelper.phpÑ <00>'êWÑ a¥*-vendor/symfony/console/Helper/ProgressBar.phpR#<00>'êWR#Îíð¶3vendor/symfony/console/Helper/ProgressIndicator.phpY<00>'êWY_šÌc¶0vendor/symfony/console/Helper/QuestionHelper.phpG<00>'êWGÌjÛz¶7vendor/symfony/console/Helper/SymfonyQuestionHelper.php¶ <00>'êW¶ h§<>'vendor/symfony/console/Helper/Table.php¹+<00>'êW¹+Åõ+¶+vendor/symfony/console/Helper/TableCell.php:<00>'êW:<0F>0vendor/symfony/console/Helper/TableSeparator.phpÍ<00>'êWÍQßa²¶,vendor/symfony/console/Helper/TableStyle.php
<00>'êW
PÞµ¦¶*vendor/symfony/console/Input/ArgvInput.phpB<00>'êWBgvñ¶+vendor/symfony/console/Input/ArrayInput.php/ <00>'êW/ ÂE:ž¶&vendor/symfony/console/Input/Input.phpª <00>'êWª ¶¶.vendor/symfony/console/Input/InputArgument.php<00>'êWÁÜ<17>4vendor/symfony/console/Input/InputAwareInterface.phpš<00>'êWš‡jTŸ¶0vendor/symfony/console/Input/InputDefinition.php<00>'êWê0Ëh¶/vendor/symfony/console/Input/InputInterface.phpË<00>'êWË扷k¶,vendor/symfony/console/Input/InputOption.php <00>'êW ‡¹§¶,vendor/symfony/console/Input/StringInput.phpc<00>'êWcW½ÿ¶/vendor/symfony/console/Logger/ConsoleLogger.php< <00>'êW< :âÇl¶0vendor/symfony/console/Output/BufferedOutput.php_<00>'êW_ûBÍ·¶/vendor/symfony/console/Output/ConsoleOutput.php“<00>'êW“,&8vendor/symfony/console/Output/ConsoleOutputInterface.phpå<00>'êWårNô,vendor/symfony/console/Output/NullOutput.phpÏ<00>'êWÏ®˜(vendor/symfony/console/Output/Output.phpš <00>'êWš 01 ý¶1vendor/symfony/console/Output/OutputInterface.php¨<00>'êW¨ä[B?¶.vendor/symfony/console/Output/StreamOutput.phpÄ<00>'êWÄõ핶2vendor/symfony/console/Question/ChoiceQuestion.php"
<00>'êW"
_౶8vendor/symfony/console/Question/ConfirmationQuestion.phpé<00>'êWéƒQ@¶,vendor/symfony/console/Question/Question.php<
<00>'êW<
óHTn¶,vendor/symfony/console/Style/OutputStyle.php{<00>'êW{.²‚¶/vendor/symfony/console/Style/StyleInterface.phpÔ<00>'êWÔ ßÊj¶-vendor/symfony/console/Style/SymfonyStyle.phph<00>'êWhŠGѶ3vendor/symfony/console/Tester/ApplicationTester.php+ <00>'êW+ {¾ƒq¶/vendor/symfony/console/Tester/CommandTester.php®<00>'êW®EÙš|¶:vendor/symfony/filesystem/Exception/ExceptionInterface.phpi<00>'êWi$ ÿ›¶=vendor/symfony/filesystem/Exception/FileNotFoundException.php¼<00>'êW¼pí\¶¶3vendor/symfony/filesystem/Exception/IOException.php‡<00>'êW‡€ü#Ѷ<vendor/symfony/filesystem/Exception/IOExceptionInterface.php¦<00>'êW¦jÙwM¶(vendor/symfony/filesystem/Filesystem.php®-<00>'êW®-¥t)vendor/symfony/filesystem/LockHandler.phpŽ<00>'êWŽü Å¶%vendor/symfony/config/ConfigCache.phpê<00>'êWêp¸ š¶,vendor/symfony/config/ConfigCacheFactory.php2<00>'êW2Ž!¹R¶5vendor/symfony/config/ConfigCacheFactoryInterface.php—<00>'êW—3j-c¶.vendor/symfony/config/ConfigCacheInterface.php<00>'êWr,.vendor/symfony/config/Definition/ArrayNode.phpQ<00>'êWQ žÃ-vendor/symfony/config/Definition/BaseNode.phpK<00>'êWKI&pò¶0vendor/symfony/config/Definition/BooleanNode.php.<00>'êW. Vp½¶@vendor/symfony/config/Definition/Builder/ArrayNodeDefinition.php˜<00>'êW˜~Bvendor/symfony/config/Definition/Builder/BooleanNodeDefinition.php”<00>'êW”5… ?vendor/symfony/config/Definition/Builder/EnumNodeDefinition.php“<00>'êW“uUÒ4¶8vendor/symfony/config/Definition/Builder/ExprBuilder.php: <00>'êW: …“Ã+¶@vendor/symfony/config/Definition/Builder/FloatNodeDefinition.php5<00>'êW5,¹O¥¶Bvendor/symfony/config/Definition/Builder/IntegerNodeDefinition.php;<00>'êW;Ì1ìR¶9vendor/symfony/config/Definition/Builder/MergeBuilder.phpý<00>'êWýuºØl¶8vendor/symfony/config/Definition/Builder/NodeBuilder.php <00>'êW ܄ݶ;vendor/symfony/config/Definition/Builder/NodeDefinition.php™ <00>'êW™ Á¼„=¶@vendor/symfony/config/Definition/Builder/NodeParentInterface.phpo<00>'êWoé vr¶Avendor/symfony/config/Definition/Builder/NormalizationBuilder.phpS<00>'êWSà¦òö¶Bvendor/symfony/config/Definition/Builder/NumericNodeDefinition.php<68><00>'êW<C3AA>ùAøo¶Jvendor/symfony/config/Definition/Builder/ParentNodeDefinitionInterface.php÷<00>'êW÷>ç#?¶Avendor/symfony/config/Definition/Builder/ScalarNodeDefinition.php!<00>'êW!ƶ8vendor/symfony/config/Definition/Builder/TreeBuilder.php­<00>'êW­`1³¶>vendor/symfony/config/Definition/Builder/ValidationBuilder.php<00>'êW Cvendor/symfony/config/Definition/Builder/VariableNodeDefinition.phpë<00>'êWëè;˜;vendor/symfony/config/Definition/ConfigurationInterface.php—<00>'êW—<@Pä¶>vendor/symfony/config/Definition/Dumper/XmlReferenceDumper.php<00>'êWÛ1¸?vendor/symfony/config/Definition/Dumper/YamlReferenceDumper.php\<00>'êW\\<5C>-vendor/symfony/config/Definition/EnumNode.phpÉ<00>'êWÉø»%D¶Dvendor/symfony/config/Definition/Exception/DuplicateKeyException.php<00>'êW§‰Úa¶8vendor/symfony/config/Definition/Exception/Exception.php}<00>'êW}¢ÃÃú¶Jvendor/symfony/config/Definition/Exception/ForbiddenOverwriteException.phpœ<00>'êWœòÛ™Z¶Lvendor/symfony/config/Definition/Exception/InvalidConfigurationException.phpÕ<00>'êWÕ kƶIvendor/symfony/config/Definition/Exception/InvalidDefinitionException.php†<00>'êW†ï¡Cvendor/symfony/config/Definition/Exception/InvalidTypeException.php”<00>'êW”ø—¶@vendor/symfony/config/Definition/Exception/UnsetKeyException.php~<00>'êW~ŒÞî_¶.vendor/symfony/config/Definition/FloatNode.php<00>'êWQTÿ³¶0vendor/symfony/config/Definition/IntegerNode.phpè<00>'êWèT2vendor/symfony/config/Definition/NodeInterface.php©<00>'êW©`ÃP0vendor/symfony/config/Definition/NumericNode.php9<00>'êW9}ض.vendor/symfony/config/Definition/Processor.php­<00>'êW­ÅÍv¶;vendor/symfony/config/Definition/PrototypeNodeInterface.php¥<00>'êW¥²*/׶8vendor/symfony/config/Definition/PrototypedArrayNode.phpŸ<00>'êWŸãcX/vendor/symfony/config/Definition/ScalarNode.phpc<00>'êWc(
1vendor/symfony/config/Definition/VariableNode.php<00>'êWK짚¶Nvendor/symfony/config/Exception/FileLoaderImportCircularReferenceException.php»<00>'êW»i~;vendor/symfony/config/Exception/FileLoaderLoadException.php¡<00>'êW¡´Iî¶%vendor/symfony/config/FileLocator.php!<00>'êW!j䋶.vendor/symfony/config/FileLocatorInterface.php©<00>'êW©3Ë5>¶1vendor/symfony/config/Loader/DelegatingLoader.php`<00>'êW` åˆÞ¶+vendor/symfony/config/Loader/FileLoader.phpƒ<00>'êWƒý<>0'vendor/symfony/config/Loader/Loader.php<00>'êWÂÇ(¶0vendor/symfony/config/Loader/LoaderInterface.php=<00>'êW=‰n+<2B>/vendor/symfony/config/Loader/LoaderResolver.php}<00>'êW}èpݶ8vendor/symfony/config/Loader/LoaderResolverInterface.php¡<00>'êW¡˜Kjï¶4vendor/symfony/config/Resource/DirectoryResource.php°<00>'êW°!ÂÅÔ¶8vendor/symfony/config/Resource/FileExistenceResource.phpï<00>'êWï'¡À/vendor/symfony/config/Resource/FileResource.phpt<00>'êWt¿R\¶4vendor/symfony/config/Resource/ResourceInterface.phpŒ<00>'êWŒe±ü©¶>vendor/symfony/config/Resource/SelfCheckingResourceChecker.php«<00>'êW«¢ÕŒg¶@vendor/symfony/config/Resource/SelfCheckingResourceInterface.php¶<00>'êW¶‘üê[¶4vendor/symfony/config/ResourceCheckerConfigCache.php8<00>'êW8.ÎM«¶;vendor/symfony/config/ResourceCheckerConfigCacheFactory.phpž<00>'êWžrc<72>¹¶2vendor/symfony/config/ResourceCheckerInterface.php+<00>'êW+Œ±d¶'vendor/symfony/config/Util/XmlUtils.php2<00>'êW2á¥Ýš¶Avendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.phpî <00>'êWî 0¦a¶Bvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php3<00>'êW3ë[œ¶Kvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php3<00>'êW3ç€[
9vendor/symfony/event-dispatcher/Debug/WrappedListener.phpÕ<00>'êWÕWnü¶Mvendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php <00>'êW '[ë)vendor/symfony/event-dispatcher/Event.php)<00>'êW)@ƒÙB¶3vendor/symfony/event-dispatcher/EventDispatcher.php# <00>'êW# 9,»Z¶<vendor/symfony/event-dispatcher/EventDispatcherInterface.php<00>'êWÓÿú¶<vendor/symfony/event-dispatcher/EventSubscriberInterface.php°<00>'êW°Œo;y¶0vendor/symfony/event-dispatcher/GenericEvent.php€<00>'êW€<13>:•¶<vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php{<00>'êW{%&'vendor/composer/autoload_namespaces.php<00>'êWWOǶ!vendor/composer/autoload_psr4.php<00>'êW$|ìX¶%vendor/composer/autoload_classmap.phpIñ<00>'êWIñÌÑr¶"vendor/composer/autoload_files.phpÃ<00>'êWÃÒÂür¶#vendor/composer/autoload_static.php|#<00>'êW|#„Çè^¶!vendor/composer/autoload_real.php><00>'êW>ÂE>>¶vendor/composer/ClassLoader.php<00>'êW k€¶(vendor/sebastian/version/src/Version.phpu<00>'êWuÉ*>¶7vendor/sebastian/resource-operations/build/generate.phpô<00>'êWô{ÌK(¶?vendor/sebastian/resource-operations/src/ResourceOperations.php6<00>'êW6
2vendor/sebastian/recursion-context/src/Context.php4<00>'êW4ÏY5ï¶4vendor/sebastian/recursion-context/src/Exception.phpX<00>'êWXNÈé3¶Cvendor/sebastian/recursion-context/src/InvalidArgumentException.php <00>'êW >_ÎF¶5vendor/sebastian/object-enumerator/src/Enumerator.phpu<00>'êWu4vendor/sebastian/object-enumerator/src/Exception.phpV<00>'êWVcá¶Cvendor/sebastian/object-enumerator/src/InvalidArgumentException.php˜<00>'êW˜‘þš¯¶/vendor/sebastian/global-state/src/Blacklist.phpÊ<00>'êWÊnº| ¶2vendor/sebastian/global-state/src/CodeExporter.php²<00>'êW²4R /vendor/sebastian/global-state/src/Exception.phpS<00>'êWSC)Á¶.vendor/sebastian/global-state/src/Restorer.php?
<00>'êW?
±n̦¶6vendor/sebastian/global-state/src/RuntimeException.php…<00>'êW…5©~®¶.vendor/sebastian/global-state/src/Snapshot.phpU<00>'êWU©Ö X¶*vendor/sebastian/exporter/src/Exporter.php¥<00>'êW¥üÀj̶,vendor/sebastian/environment/src/Console.php><00>'êW>É/Z°¶,vendor/sebastian/environment/src/Runtime.php6 <00>'êW6 y=j¶#vendor/sebastian/diff/src/Chunk.php#<00>'êW#h­<68>Ž¶"vendor/sebastian/diff/src/Diff.phpñ<00>'êWñnÖ@ä¶$vendor/sebastian/diff/src/Differ.php <00>'êW 38<̶:vendor/sebastian/diff/src/LCS/LongestCommonSubsequence.php<00>'êW(ƒUþ¶Wvendor/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php<00>'êW´½<C2B4>Uvendor/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.phpÓ<00>'êWÓùÜIã¶"vendor/sebastian/diff/src/Line.php”<00>'êW”64/F¶$vendor/sebastian/diff/src/Parser.php…<00>'êW…$ ©¶3vendor/sebastian/comparator/src/ArrayComparator.php<00>'êWÀW§6¶.vendor/sebastian/comparator/src/Comparator.php <00>'êW ƒ2¤é¶5vendor/sebastian/comparator/src/ComparisonFailure.php®<00>'êW®Çeê¶5vendor/sebastian/comparator/src/DOMNodeComparator.phpJ<00>'êWJÏ\Ãg¶6vendor/sebastian/comparator/src/DateTimeComparator.php<00>'êW”yèI¶4vendor/sebastian/comparator/src/DoubleComparator.php+<00>'êW+‹¶Š‹¶7vendor/sebastian/comparator/src/ExceptionComparator.php¼<00>'êW¼`.cG¶+vendor/sebastian/comparator/src/Factory.php'<00>'êW'ïKW8vendor/sebastian/comparator/src/MockObjectComparator.php¿<00>'êW¿­5vendor/sebastian/comparator/src/NumericComparator.phpP<00>'êWPËV½¶4vendor/sebastian/comparator/src/ObjectComparator.php|<00>'êW|¿N6vendor/sebastian/comparator/src/ResourceComparator.phpï<00>'êWï¡Š\±¶4vendor/sebastian/comparator/src/ScalarComparator.phpf<00>'êWfº9ÛŠ¶>vendor/sebastian/comparator/src/SplObjectStorageComparator.phpq<00>'êWqy#ñë¶2vendor/sebastian/comparator/src/TypeComparator.php<00>'êWêe]·¶8vendor/sebastian/code-unit-reverse-lookup/src/Wizard.phpZ<00>'êWZÜ÷çWvendor/doctrine/instantiator/src/Doctrine/Instantiator/Exception/ExceptionInterface.phpj<00>'êWjŸøßζ]vendor/doctrine/instantiator/src/Doctrine/Instantiator/Exception/InvalidArgumentException.php <00>'êW üŸp¶]vendor/doctrine/instantiator/src/Doctrine/Instantiator/Exception/UnexpectedValueException.phpÉ<00>'êWÉxiÕî¶Gvendor/doctrine/instantiator/src/Doctrine/Instantiator/Instantiator.phpÃ<00>'êWÃy—Pvendor/doctrine/instantiator/src/Doctrine/Instantiator/InstantiatorInterface.php“<00>'êW“,A¶1vendor/phpunit/php-text-template/src/Template.phpŒ<00>'êWŒ²Iû¶Qvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Identity.phpu<00>'êWudSÖ¶Yvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/InvocationMocker.phpÝ<00>'êWÝŸø¤¶Nvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Match.php£<00>'êW£¯S»¶Xvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/MethodNameMatch.php»<00>'êW»Ž‰¶Rvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Namespace.phpØ<00>'êW؉g¶Xvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/ParametersMatch.phpñ<00>'êWñY2Ýñ¶Mvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Stub.phpÉ<00>'êWÉQPQd¶avendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/BadMethodCallException.php¡<00>'êW¡½Ë¥¶Tvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/Exception.phpI<00>'êWIø[vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/RuntimeException.php•<00>'êW•Ë¹} Jvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.phpÁ^<00>'êWÁ^´kü±¶Kvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation.phpt<00>'êWt" ö”¶Rvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Object.phpŠ<00>'êWŠçBdRvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Static.php>
<00>'êW>
UÅÙ¶Qvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/InvocationMocker.phpµ<00>'êWµÞÒ<C39E>Jvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invokable.php'<00>'êW'<10>·É¶Hvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher.php·<00>'êW·ƒ—_©¶Xvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyInvokedCount.phpø<00>'êWøÁópÀ¶Vvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyParameters.php6<00>'êW6xp«â¶^vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/ConsecutiveParameters.php <00>'êW ;ðMX¶Svendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Invocation.phpZ<00>'êWZxZã3¶Wvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtIndex.phpr<00>'êWrúÝñ¶\vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastCount.php­<00>'êW­~i[vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastOnce.php­<00>'êW­0©S¶[vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtMostCount.php£<00>'êW£#_?6¶Uvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedCount.php"<00>'êW"ªü9 Xvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedRecorder.phpz<00>'êWz1äI¸Svendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/MethodName.phpõ<00>'êWõ3vÁ¶Svendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Parameters.phph <00>'êWh ߀d9¶\vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/StatelessInvocation.php'<00>'êW'Zy²Ã¶Lvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockBuilder.php,<00>'êW,8I¢¶Kvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockObject.phpz<00>'êWzLs`t¶Evendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub.phpÅ<00>'êWÅEC<43>Vvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ConsecutiveCalls.php£<00>'êW£®$鬶Ovendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Exception.phpÚ<00>'êWÚÅk1±¶Wvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/MatcherCollection.php²<00>'êW²¶*Ûà¶Lvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Return.phpæ<00>'êWæjPy@¶Tvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnArgument.php%<00>'êW%0Û]’¶Tvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnCallback.php8<00>'êW8?'™F¶Uvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnReference.phpÂ<00>'êWÂ%óé¶Pvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnSelf.php<00>'êWõ+<2B>߶Tvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnValueMap.phpt<00>'êWteJåL¶Kvendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Verifiable.phpj<00>'êWj ý³¿¶&vendor/phpunit/php-timer/src/Timer.phpÈ<00>'êWÈÓî[<5B>/vendor/phpunit/php-file-iterator/src/Facade.php<68><00>'êW<C3AA>?µ-ɶ0vendor/phpunit/php-file-iterator/src/Factory.phpd<00>'êWdmèpŠ¶1vendor/phpunit/php-file-iterator/src/Iterator.phpÒ<00>'êWÒ†Ÿ-vendor/phpunit/php-token-stream/src/Token.php[H<00>'êW[HgªË¨¶4vendor/phpunit/php-token-stream/src/Token/Stream.php "<00>'êW "æ»{{¶Cvendor/phpunit/php-token-stream/src/Token/Stream/CachingFactory.php²<00>'êW²|cŠ¶5vendor/phpunit/php-code-coverage/src/CodeCoverage.phpQ?<00>'êWQ?<00>Vܶ6vendor/phpunit/php-code-coverage/src/Driver/Driver.php<00>'êWó+\4vendor/phpunit/php-code-coverage/src/Driver/HHVM.phpÁ<00>'êWÁ ùe¶6vendor/phpunit/php-code-coverage/src/Driver/PHPDBG.php³<00>'êW³%µ½¶6vendor/phpunit/php-code-coverage/src/Driver/Xdebug.phpß<00>'êWßH(#ê¶Rvendor/phpunit/php-code-coverage/src/Exception/CoveredCodeNotExecutedException.php€<00>'êW€<53>©¶<vendor/phpunit/php-code-coverage/src/Exception/Exception.phpU<00>'êWU³Sw^¶Kvendor/phpunit/php-code-coverage/src/Exception/InvalidArgumentException.phpÑ<00>'êWÑÊ(ú¶Svendor/phpunit/php-code-coverage/src/Exception/MissingCoversAnnotationException.php<68><00>'êW<C3AA>lÕ”Cvendor/phpunit/php-code-coverage/src/Exception/RuntimeException.php„<00>'êW„¬KÁ¶Vvendor/phpunit/php-code-coverage/src/Exception/UnintentionallyCoveredCodeException.phpk<00>'êWk A/vendor/phpunit/php-code-coverage/src/Filter.phpí<00>'êWí<<3C>37¶:vendor/phpunit/php-code-coverage/src/Node/AbstractNode.phpÛ <00>'êWÛ XA²5vendor/phpunit/php-code-coverage/src/Node/Builder.phpë <00>'êWë ™Ní'¶7vendor/phpunit/php-code-coverage/src/Node/Directory.php¢<00>'êW¢K½¶2vendor/phpunit/php-code-coverage/src/Node/File.php (<00>'êW (646vendor/phpunit/php-code-coverage/src/Node/Iterator.php<00>'êW΄Б¶6vendor/phpunit/php-code-coverage/src/Report/Clover.php£<00>'êW£Æ6vendor/phpunit/php-code-coverage/src/Report/Crap4j.phpw<00>'êWwˆ«o¶;vendor/phpunit/php-code-coverage/src/Report/Html/Facade.php(<00>'êW(ÃßD=vendor/phpunit/php-code-coverage/src/Report/Html/Renderer.phpé<00>'êWéiŠ-Gvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Dashboard.php<00>'êW½F¶Gvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Directory.php2<00>'êW2 ‚¶Bvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/File.php;$<00>'êW;$vm€R¶3vendor/phpunit/php-code-coverage/src/Report/PHP.php­<00>'êW­4““x¶4vendor/phpunit/php-code-coverage/src/Report/Text.php˜<00>'êW˜£î.¶<vendor/phpunit/php-code-coverage/src/Report/Xml/Coverage.php<00>'êW™ÏÚ¢¶=vendor/phpunit/php-code-coverage/src/Report/Xml/Directory.phpf<00>'êWfkž%a¶:vendor/phpunit/php-code-coverage/src/Report/Xml/Facade.php^<00>'êW^mBÐ{¶8vendor/phpunit/php-code-coverage/src/Report/Xml/File.phpø<00>'êWøÀoŸˆ:vendor/phpunit/php-code-coverage/src/Report/Xml/Method.php<00>'êWE@ƒ¶8vendor/phpunit/php-code-coverage/src/Report/Xml/Node.php(<00>'êW(ËãÑ´¶;vendor/phpunit/php-code-coverage/src/Report/Xml/Project.phpË<00>'êWË ê}¶:vendor/phpunit/php-code-coverage/src/Report/Xml/Report.php†<00>'êW†YÆó 9vendor/phpunit/php-code-coverage/src/Report/Xml/Tests.phpí<00>'êWí[ã잶:vendor/phpunit/php-code-coverage/src/Report/Xml/Totals.php
<00>'êW
AzU¶8vendor/phpunit/php-code-coverage/src/Report/Xml/Unit.phpº<00>'êWº¢q-vendor/phpunit/php-code-coverage/src/Util.php¥<00>'êW¥X ³l¶(vendor/phpunit/phpunit/src/Exception.php4<00>'êW4ð¶Ó+¶8vendor/phpunit/phpunit/src/Extensions/GroupTestSuite.php=<00>'êW=Ÿô1@¶6vendor/phpunit/phpunit/src/Extensions/PhptTestCase.phpÚ<00>'êWÚÑêɶ7vendor/phpunit/phpunit/src/Extensions/PhptTestSuite.phpÏ<00>'êWÏI¹0b¶6vendor/phpunit/phpunit/src/Extensions/RepeatedTest.phpô<00>'êWô¾¶7vendor/phpunit/phpunit/src/Extensions/TestDecorator.phpH<00>'êWHHïù/¶8vendor/phpunit/phpunit/src/Extensions/TicketListener.php
<00>'êW
_,Ïž¶<vendor/phpunit/phpunit/src/ForwardCompatibility/TestCase.php„<00>'êW„ë¾0þ¶/vendor/phpunit/phpunit/src/Framework/Assert.phpH§<00>'êWH§fCÃb¶9vendor/phpunit/phpunit/src/Framework/Assert/Functions.phpÇ`<00>'êWÇ`S_³¶=vendor/phpunit/phpunit/src/Framework/AssertionFailedError.phpÕ<00>'êWÕ£@9vendor/phpunit/phpunit/src/Framework/BaseTestListener.php¬<00>'êW¬¿àå\¶>vendor/phpunit/phpunit/src/Framework/CodeCoverageException.phph<00>'êWhÞýׄ¶3vendor/phpunit/phpunit/src/Framework/Constraint.php£<00>'êW£ÇE¼æ¶7vendor/phpunit/phpunit/src/Framework/Constraint/And.php¹<00>'êW¹Á<>Te¶?vendor/phpunit/phpunit/src/Framework/Constraint/ArrayHasKey.phpv<00>'êWvÒ÷Z¶?vendor/phpunit/phpunit/src/Framework/Constraint/ArraySubset.php´<00>'êW´·9"¶=vendor/phpunit/phpunit/src/Framework/Constraint/Attribute.phpð<00>'êWð}Gƒû¶<vendor/phpunit/phpunit/src/Framework/Constraint/Callback.php÷<00>'êW÷ïX`l¶Evendor/phpunit/phpunit/src/Framework/Constraint/ClassHasAttribute.php¼<00>'êW¼m<>§P¶Kvendor/phpunit/phpunit/src/Framework/Constraint/ClassHasStaticAttribute.phpñ<00>'êWñ1Fƒ¶=vendor/phpunit/phpunit/src/Framework/Constraint/Composite.php†<00>'êW†Ä“6•¶9vendor/phpunit/phpunit/src/Framework/Constraint/Count.phpG<00>'êWGç<><C3A7>¹¶=vendor/phpunit/phpunit/src/Framework/Constraint/Exception.php<68><00>'êW<C3AA>üœØU¶Avendor/phpunit/phpunit/src/Framework/Constraint/ExceptionCode.phpx<00>'êWxƒ ‰[¶Dvendor/phpunit/phpunit/src/Framework/Constraint/ExceptionMessage.php]<00>'êW]w€k¶Jvendor/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegExp.php:<00>'êW:)PáH¶>vendor/phpunit/phpunit/src/Framework/Constraint/FileExists.php^<00>'êW^=ärô¶?vendor/phpunit/phpunit/src/Framework/Constraint/GreaterThan.php<00>'êWÅóƒ6¶>vendor/phpunit/phpunit/src/Framework/Constraint/IsAnything.phpY<00>'êWY;¸È@¶;vendor/phpunit/phpunit/src/Framework/Constraint/IsEmpty.phpç<00>'êWç3!òt¶;vendor/phpunit/phpunit/src/Framework/Constraint/IsEqual.phpØ<00>'êWØ“§l(¶;vendor/phpunit/phpunit/src/Framework/Constraint/IsFalse.phpè<00>'êWès~)à¶<vendor/phpunit/phpunit/src/Framework/Constraint/IsFinite.phpë<00>'êWë"Vq7¶?vendor/phpunit/phpunit/src/Framework/Constraint/IsIdentical.php€<00>'êW€3Œ//¶>vendor/phpunit/phpunit/src/Framework/Constraint/IsInfinite.phpñ<00>'êWñ­¬•/¶@vendor/phpunit/phpunit/src/Framework/Constraint/IsInstanceOf.phpG<00>'êWG2AUɶ:vendor/phpunit/phpunit/src/Framework/Constraint/IsJson.php¦<00>'êW¦öú¼*¶9vendor/phpunit/phpunit/src/Framework/Constraint/IsNan.phpâ<00>'êWâÉQ :vendor/phpunit/phpunit/src/Framework/Constraint/IsNull.phpå<00>'êWå®pË:vendor/phpunit/phpunit/src/Framework/Constraint/IsTrue.phpå<00>'êWåîâSƒ¶:vendor/phpunit/phpunit/src/Framework/Constraint/IsType.phpÈ<00>'êWÈN
?vendor/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php;<00>'êW;¾[A¶Tvendor/phpunit/phpunit/src/Framework/Constraint/JsonMatches/ErrorMessageProvider.php»<00>'êW»Þ7Ô¶<vendor/phpunit/phpunit/src/Framework/Constraint/LessThan.phpŒ<00>'êWŒïˆs4¶7vendor/phpunit/phpunit/src/Framework/Constraint/Not.phpâ<00>'êWâÞHSFvendor/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php<00>'êW|~$߶6vendor/phpunit/phpunit/src/Framework/Constraint/Or.phph<00>'êWh,?îѶ=vendor/phpunit/phpunit/src/Framework/Constraint/PCREMatch.phpª<00>'êWª_Y<5F>¯¶<vendor/phpunit/phpunit/src/Framework/Constraint/SameSize.phpì<00>'êWìgSAH¶Bvendor/phpunit/phpunit/src/Framework/Constraint/StringContains.php¤<00>'êW¤ß9U×Bvendor/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.php§<00>'êW§Š<_¦¶Avendor/phpunit/phpunit/src/Framework/Constraint/StringMatches.phpQ<00>'êWQ"Î/G¶Dvendor/phpunit/phpunit/src/Framework/Constraint/StringStartsWith.php”<00>'êW”6Ùß̶Gvendor/phpunit/phpunit/src/Framework/Constraint/TraversableContains.php<68><00>'êW<C3AA>øÂH<C382>Kvendor/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.phpl<00>'êWl ³r7vendor/phpunit/phpunit/src/Framework/Constraint/Xor.phpº<00>'êWºàÿ
.vendor/phpunit/phpunit/src/Framework/Error.php<00>'êWØS9vendor/phpunit/phpunit/src/Framework/Error/Deprecated.php…<00>'êW…rC‰r¶5vendor/phpunit/phpunit/src/Framework/Error/Notice.php<68><00>'êW<C3AA>¤"´6vendor/phpunit/phpunit/src/Framework/Error/Warning.php<00>'êWA¥~2vendor/phpunit/phpunit/src/Framework/Exception.php/<00>'êW/žƒ„P¶9vendor/phpunit/phpunit/src/Framework/ExceptionWrapper.phpâ<00>'êWâCvendor/phpunit/phpunit/src/Framework/ExpectationFailedException.phpÝ<00>'êWÝ°7<¶7vendor/phpunit/phpunit/src/Framework/IncompleteTest.phpD<00>'êWD;vendor/phpunit/phpunit/src/Framework/IncompleteTestCase.phpÄ<00>'êWÄòg<vendor/phpunit/phpunit/src/Framework/IncompleteTestError.php <00>'êW ù¹²Ñ¶Evendor/phpunit/phpunit/src/Framework/InvalidCoversTargetException.php{<00>'êW{´+½ì¶4vendor/phpunit/phpunit/src/Framework/OutputError.phpl<00>'êWlt4•¶Zvendor/phpunit/phpunit/src/Framework/PHPUnit_Framework_CoveredCodeNotExecutedException.phpz<00>'êWz[X“¶[vendor/phpunit/phpunit/src/Framework/PHPUnit_Framework_MissingCoversAnnotationException.php{<00>'êW{†ö.=¶2vendor/phpunit/phpunit/src/Framework/RiskyTest.php?<00>'êW?,×홶7vendor/phpunit/phpunit/src/Framework/RiskyTestError.php<00>'êWM©ÈÒ¶7vendor/phpunit/phpunit/src/Framework/SelfDescribing.phpd<00>'êWdcö!¶4vendor/phpunit/phpunit/src/Framework/SkippedTest.php@<00>'êW@7¸w8vendor/phpunit/phpunit/src/Framework/SkippedTestCase.php¼<00>'êW¼Ž<>9vendor/phpunit/phpunit/src/Framework/SkippedTestError.phpš<00>'êWšMJŽq¶>vendor/phpunit/phpunit/src/Framework/SkippedTestSuiteError.phpŸ<00>'êWŸï`¡Ê¶7vendor/phpunit/phpunit/src/Framework/SyntheticError.phpŠ<00>'êWŠ¤~Z)¶-vendor/phpunit/phpunit/src/Framework/Test.php”<00>'êW”þ¨ 1vendor/phpunit/phpunit/src/Framework/TestCase.php,<2C><00>'êW,<2C>ÿÕ-G¶4vendor/phpunit/phpunit/src/Framework/TestFailure.php<<00>'êW<ˆM5vendor/phpunit/phpunit/src/Framework/TestListener.phpH<00>'êWHE»ì¨¶3vendor/phpunit/phpunit/src/Framework/TestResult.phpÆE<00>'êWÆEŸÇ2vendor/phpunit/phpunit/src/Framework/TestSuite.php<68>8<00>'êW<C3AA>8L9x¢¶?vendor/phpunit/phpunit/src/Framework/TestSuite/DataProvider.phpò<00>'êWò ݶHvendor/phpunit/phpunit/src/Framework/UnintentionallyCoveredCodeError.phpz<00>'êWzÜœù¶0vendor/phpunit/phpunit/src/Framework/Warning.phpÈ<00>'êWÈ8vendor/phpunit/phpunit/src/Framework/WarningTestCase.phpl<00>'êWly‡ÿV¶4vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php(<00>'êW(Ç¢à/vendor/phpunit/phpunit/src/Runner/Exception.phpk<00>'êWkçˆ÷¶4vendor/phpunit/phpunit/src/Runner/Filter/Factory.php[<00>'êW[¨Ÿ2vendor/phpunit/phpunit/src/Runner/Filter/Group.php<00>'êWé¢(¶:vendor/phpunit/phpunit/src/Runner/Filter/Group/Exclude.phpÅ<00>'êWÅÆT¤:vendor/phpunit/phpunit/src/Runner/Filter/Group/Include.phpÄ<00>'êWÄ1fB1vendor/phpunit/phpunit/src/Runner/Filter/Test.phpÆ<00>'êWÆõL8ð¶=vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.phpÍ<00>'êWÍŠ;‰¥¶5vendor/phpunit/phpunit/src/Runner/TestSuiteLoader.php»<00>'êW»Ô­¶#¶-vendor/phpunit/phpunit/src/Runner/Version.php\<00>'êW\¨€¨í¶-vendor/phpunit/phpunit/src/TextUI/Command.phpéb<00>'êWébŸS‡3vendor/phpunit/phpunit/src/TextUI/ResultPrinter.php¸(<00>'êW¸(†üÕ 0vendor/phpunit/phpunit/src/TextUI/TestRunner.phpÉz<00>'êWÉzOYåé¶-vendor/phpunit/phpunit/src/Util/Blacklist.phpð<00>'êWðÛ¥q1vendor/phpunit/phpunit/src/Util/Configuration.php¡J<00>'êW¡Jâ6õ¾¶:vendor/phpunit/phpunit/src/Util/ConfigurationGenerator.php¿<00>'êW¿ª-b+¶0vendor/phpunit/phpunit/src/Util/ErrorHandler.php<00>'êW!¡Wµ¶.vendor/phpunit/phpunit/src/Util/Fileloader.php8<00>'êW8ØÕ<C398>°¶.vendor/phpunit/phpunit/src/Util/Filesystem.phpì<00>'êWìÅZðf¶*vendor/phpunit/phpunit/src/Util/Filter.phpl<00>'êWlb„a¶*vendor/phpunit/phpunit/src/Util/Getopt.phpÁ
<00>'êWÁ
{0* ¶/vendor/phpunit/phpunit/src/Util/GlobalState.phpÚ <00>'êWÚ Ø»«¶9vendor/phpunit/phpunit/src/Util/InvalidArgumentHelper.php<00>'êW|A`¥¶,vendor/phpunit/phpunit/src/Util/Log/JSON.php<68> <00>'êW<C3AA> -vendor/phpunit/phpunit/src/Util/Log/JUnit.phpô<00>'êWôÕ*œ¶+vendor/phpunit/phpunit/src/Util/Log/TAP.phpY <00>'êWY Ê.c1¶0vendor/phpunit/phpunit/src/Util/Log/TeamCity.phpY<00>'êWYUÿ¬¶'vendor/phpunit/phpunit/src/Util/PHP.phpÈ<00>'êWÈŠ(¾…¶/vendor/phpunit/phpunit/src/Util/PHP/Default.phpë
<00>'êWë
/vendor/phpunit/phpunit/src/Util/PHP/Windows.phpñ<00>'êWñÜæ˜\¶2vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php6<00>'êW6ÍŒG¶+vendor/phpunit/phpunit/src/Util/Printer.phpë<00>'êWë½(Wç¶)vendor/phpunit/phpunit/src/Util/Regex.phpQ<00>'êWQ2Ûãã¶*vendor/phpunit/phpunit/src/Util/String.php<00>'êW²¢‚\¶(vendor/phpunit/phpunit/src/Util/Test.php R<00>'êW R&Š¶:vendor/phpunit/phpunit/src/Util/TestDox/NamePrettifier.php<68><00>'êW<C3AA>¢ ›Ò¶9vendor/phpunit/phpunit/src/Util/TestDox/ResultPrinter.phpÑ<00>'êWÑ<>Ö¶>vendor/phpunit/phpunit/src/Util/TestDox/ResultPrinter/HTML.php³<00>'êW³^˶>vendor/phpunit/phpunit/src/Util/TestDox/ResultPrinter/Text.php»<00>'êW»!m<>=vendor/phpunit/phpunit/src/Util/TestDox/ResultPrinter/XML.phpÜ <00>'êWÜ Iô=Ѷ5vendor/phpunit/phpunit/src/Util/TestSuiteIterator.php<00>'êWêaw ¶(vendor/phpunit/phpunit/src/Util/Type.phpë<00>'êW륶'vendor/phpunit/phpunit/src/Util/XML.phpã <00>'êWã %-Ƕ&vendor/webmozart/assert/src/Assert.php|B<00>'êW|B ð‡û¶6vendor/phpdocumentor/reflection-common/src/Element.php<68><00>'êW<C3AA>†©#¥¶3vendor/phpdocumentor/reflection-common/src/File.php«<00>'êW«¡Ï6Þ¶4vendor/phpdocumentor/reflection-common/src/Fqsen.php¤<00>'êW¤+¯§Ú¶7vendor/phpdocumentor/reflection-common/src/Location.php¢<00>'êW¢òµ¥@¶6vendor/phpdocumentor/reflection-common/src/Project.phpn<00>'êWnÄjí¶=vendor/phpdocumentor/reflection-common/src/ProjectFactory.php‰<00>'êW‰ì{ƒ¶Ivendor/phpdocumentor/type-resolver/examples/01-resolving-simple-types.phpð<00>'êWðÓ§5¶Dvendor/phpdocumentor/type-resolver/examples/02-resolving-classes.php><00>'êW>ζIvendor/phpdocumentor/type-resolver/examples/03-resolving-all-elements.phpˆ<00>'êWˆ¦¨Xä¶avendor/phpdocumentor/type-resolver/examples/04-discovering-the-context-using-class-reflection.php¼<00>'êW¼F·}`¶bvendor/phpdocumentor/type-resolver/examples/05-discovering-the-context-using-method-reflection.phpÌ<00>'êWÌ=Iöݶ^vendor/phpdocumentor/type-resolver/examples/06-discovering-the-context-using-file-contents.phpc<00>'êWcøŸ½ö¶6vendor/phpdocumentor/type-resolver/examples/Classy.php“<00>'êW“9ëÚi¶8vendor/phpdocumentor/type-resolver/src/FqsenResolver.php2<00>'êW2h™E¶/vendor/phpdocumentor/type-resolver/src/Type.phpg<00>'êWgGF:ñ¶7vendor/phpdocumentor/type-resolver/src/TypeResolver.php<00>'êW¶`“¶7vendor/phpdocumentor/type-resolver/src/Types/Array_.phpý<00>'êWý€¢K1¶8vendor/phpdocumentor/type-resolver/src/Types/Boolean.phpÀ<00>'êWÀŒâ:vendor/phpdocumentor/type-resolver/src/Types/Callable_.phpÆ<00>'êWÆŠ%G{¶9vendor/phpdocumentor/type-resolver/src/Types/Compound.php”<00>'êW”*&ÆÒ¶8vendor/phpdocumentor/type-resolver/src/Types/Context.phpô<00>'êWô=]?vendor/phpdocumentor/type-resolver/src/Types/ContextFactory.php; <00>'êW; ô`¶7vendor/phpdocumentor/type-resolver/src/Types/Float_.phpÀ<00>'êWÀ×ÅW¼¶8vendor/phpdocumentor/type-resolver/src/Types/Integer.php¼<00>'êW¼ƒt`9¶6vendor/phpdocumentor/type-resolver/src/Types/Mixed.php¿<00>'êW¿÷6vendor/phpdocumentor/type-resolver/src/Types/Null_.php¾<00>'êW¾Jìå¶8vendor/phpdocumentor/type-resolver/src/Types/Object_.phpÎ<00>'êWÎyö™9vendor/phpdocumentor/type-resolver/src/Types/Resource.phpÅ<00>'êWÅü¤À<C2A4>7vendor/phpdocumentor/type-resolver/src/Types/Scalar.phpÁ<00>'êWÁD,6¶6vendor/phpdocumentor/type-resolver/src/Types/Self_.phpÀ<00>'êWÀ¡{«Ä¶8vendor/phpdocumentor/type-resolver/src/Types/Static_.phpÉ<00>'êWÉÙA•5¶8vendor/phpdocumentor/type-resolver/src/Types/String_.phpÂ<00>'êWÂwÔ.ü¶5vendor/phpdocumentor/type-resolver/src/Types/This.phpÁ<00>'êWÁóV5å¶6vendor/phpdocumentor/type-resolver/src/Types/Void_.phpÁ<00>'êWÁ%2Û¶Wvendor/phpdocumentor/reflection-docblock/examples/01-interpreting-a-simple-docblock.phpc<00>'êWc¯{§·¶Jvendor/phpdocumentor/reflection-docblock/examples/02-interpreting-tags.phpÏ<00>'êWÏ‚úªÆ¶Rvendor/phpdocumentor/reflection-docblock/examples/03-reconstituting-a-docblock.phpQ<00>'êWQñ²xU¶Lvendor/phpdocumentor/reflection-docblock/examples/04-adding-your-own-tag.php²<00>'êW²á4ä¶[vendor/phpdocumentor/reflection-docblock/examples/playing-with-descriptions/02-escaping.php<00>'êWNïz¶9vendor/phpdocumentor/reflection-docblock/src/DocBlock.phpŒ<00>'êWŒo@<ƒ¶Evendor/phpdocumentor/reflection-docblock/src/DocBlock/Description.php1<00>'êW1 Ï1¶Lvendor/phpdocumentor/reflection-docblock/src/DocBlock/DescriptionFactory.php¯ <00>'êW¯ ™"þx¶Gvendor/phpdocumentor/reflection-docblock/src/DocBlock/ExampleFinder.phpC<00>'êWCdò€¶Dvendor/phpdocumentor/reflection-docblock/src/DocBlock/Serializer.phpß<00>'êWß|UyQ¶Lvendor/phpdocumentor/reflection-docblock/src/DocBlock/StandardTagFactory.phpK<00>'êWK<ñ†¶=vendor/phpdocumentor/reflection-docblock/src/DocBlock/Tag.php<00>'êW¬KxˆDvendor/phpdocumentor/reflection-docblock/src/DocBlock/TagFactory.php¤<00>'êW¤Ëfd¶Evendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Author.php”<00>'êW”‡&@{¶Fvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/BaseTag.php+<00>'êW+ÁG9œ¶Evendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Covers.php©<00>'êW©µ€ïIvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Deprecated.phpJ<00>'êWJûHFvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Example.phpR<00>'êWR<00>¼ún¶Svendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Factory/StaticMethod.php<68><00>'êW<C3AA>
Š¶Ovendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Factory/Strategy.php<00>'êWµjÉo¶Hvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Formatter.php±<00>'êW±…1D¶]vendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Formatter/PassthroughFormatter.phpC<00>'êWCì`„x¶Fvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Generic.php8<00>'êW8ûžÑ¶Cvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Link.php><00>'êW>ÜJEvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Method.php<00>'êWWP<57>¶¶Dvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Param.phpø<00>'êWøÇ"ѶGvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Property.phpj<00>'êWjÂ{ÿñ¶Kvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/PropertyRead.phps<00>'êWsF`%C¶Lvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/PropertyWrite.phpu<00>'êWu¨xFvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Return_.phpÉ<00>'êWÉeíýŒ¶Bvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/See.phpÙ<00>'êWÙïÉlî¶Dvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Since.phpA<00>'êWAÍP4G¶Evendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Source.phpm<00>'êWm·æ¹W¶Evendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Throws.phpÈ<00>'êWÈ¥¢`Cvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Uses.php¨<00>'êW¨îñ¨¶Cvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Var_.phpa<00>'êWa±’å¶Fvendor/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Version.phpD<00>'êWDÜ™Zñ¶@vendor/phpdocumentor/reflection-docblock/src/DocBlockFactory.php!<00>'êW!h~o ¶Ivendor/phpdocumentor/reflection-docblock/src/DocBlockFactoryInterface.php<00>'êW]F¾ Hvendor/phpspec/prophecy/spec/Prophecy/Argument/ArgumentsWildcardSpec.phpr<00>'êWr {Iþ¶Jvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/AnyValueTokenSpec.phpÝ<00>'êWÝ€¿1_¶Kvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/AnyValuesTokenSpec.phpí<00>'êWí¥G±I¶Rvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ApproximateValueTokenSpec.phpQ<00>'êWQ&U¶Lvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ArrayCountTokenSpec.phpô<00>'êWôÀûÇÚ¶Lvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ArrayEntryTokenSpec.php<00>'êWæ/A¶Qvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ArrayEveryEntryTokenSpec.php<68> <00>'êW<C3AA> ©z¡Jvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/CallbackTokenSpec.phpR<00>'êWRú™„жLvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ExactValueTokenSpec.php<00>'êWÏp„¶Pvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/IdenticalValueTokenSpec.phpD<00>'êWDùi1Lvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/LogicalAndTokenSpec.php<00>'êWg0¤¶Lvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/LogicalNotTokenSpec.php•<00>'êW•SŸàŶMvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ObjectStateTokenSpec.php<00>'êW{Zƒ¶Pvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/StringContainsTokenSpec.phpÓ<00>'êWÓŸ*&=¶Fvendor/phpspec/prophecy/spec/Prophecy/Argument/Token/TypeTokenSpec.php|<00>'êW|£dRQ¶6vendor/phpspec/prophecy/spec/Prophecy/ArgumentSpec.php <00>'êW ç9Ÿ¶=vendor/phpspec/prophecy/spec/Prophecy/Call/CallCenterSpec.php}<00>'êW}xÎ"7vendor/phpspec/prophecy/spec/Prophecy/Call/CallSpec.php@<00>'êW@_Jvendor/phpspec/prophecy/spec/Prophecy/Comparator/ClosureComparatorSpec.php/<00>'êW/šx,u¶@vendor/phpspec/prophecy/spec/Prophecy/Comparator/FactorySpec.php×<00>'êW×*Sjü¶Kvendor/phpspec/prophecy/spec/Prophecy/Comparator/ProphecyComparatorSpec.phpw<00>'êWwŸšüs¶Xvendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/DisableConstructorPatchSpec.php`<00>'êW`Òmüç¶Svendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/HhvmExceptionPatchSpec.php<00>'êW")ÈMvendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/KeywordPatchSpec.phpD<00>'êWDÔ„X§¶Ovendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/MagicCallPatchSpec.php <00>'êW Ì拸¶Uvendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/ProphecySubjectPatchSpec.phpý<00>'êWý±cˆ`vendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/ReflectionClassNewInstancePatchSpec.phpÅ<00>'êWÅ÷×Øq¶Qvendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/SplFileInfoPatchSpec.phpb<00>'êWbµ|ˆ¶Qvendor/phpspec/prophecy/spec/Prophecy/Doubler/ClassPatch/TraversablePatchSpec.phpŒ<00>'êWŒ°ø8š¶=vendor/phpspec/prophecy/spec/Prophecy/Doubler/DoublerSpec.php <00>'êW S,?ͶRvendor/phpspec/prophecy/spec/Prophecy/Doubler/Generator/ClassCodeGeneratorSpec.phpE&<00>'êWE&_)º¶Lvendor/phpspec/prophecy/spec/Prophecy/Doubler/Generator/ClassCreatorSpec.phpW<00>'êWW¼¿Ù¶Kvendor/phpspec/prophecy/spec/Prophecy/Doubler/Generator/ClassMirrorSpec.phpû`<00>'êWû`¼®Œ6¶Qvendor/phpspec/prophecy/spec/Prophecy/Doubler/Generator/Node/ArgumentNodeSpec.php†<00>'êW†•ËȶNvendor/phpspec/prophecy/spec/Prophecy/Doubler/Generator/Node/ClassNodeSpec.phpˆ<00>'êWˆܲ4f¶Ovendor/phpspec/prophecy/spec/Prophecy/Doubler/Generator/Node/MethodNodeSpec.php„ <00>'êW„ ªôO€¶@vendor/phpspec/prophecy/spec/Prophecy/Doubler/LazyDoubleSpec.phpR<00>'êWR>ÿ¹Cvendor/phpspec/prophecy/spec/Prophecy/Doubler/NameGeneratorSpec.php<00>'êW9B:~¶Tvendor/phpspec/prophecy/spec/Prophecy/Exception/Call/UnexpectedCallExceptionSpec.php†<00>'êW†eÊA¶Uvendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/ClassCreatorExceptionSpec.php<00>'êW$4Tvendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/ClassMirrorExceptionSpec.phpë<00>'êWëWÊÕ%¶Vvendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/ClassNotFoundExceptionSpec.php<00>'êWñ„¹ð¶Ovendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/DoubleExceptionSpec.php*<00>'êW*üº¿<¶Zvendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/InterfaceNotFoundExceptionSpec.phpì<00>'êWì\vendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/MethodNotExtendableExceptionSpec.php<00>'êW™¶Wvendor/phpspec/prophecy/spec/Prophecy/Exception/Doubler/MethodNotFoundExceptionSpec.php<00>'êWŸ³Ó¶Uvendor/phpspec/prophecy/spec/Prophecy/Exception/Prediction/AggregateExceptionSpec.php<00>'êWÔ_ĶSvendor/phpspec/prophecy/spec/Prophecy/Exception/Prediction/NoCallsExceptionSpec.php1<00>'êW1°<þè¶`vendor/phpspec/prophecy/spec/Prophecy/Exception/Prediction/UnexpectedCallsCountExceptionSpec.phph<00>'êWh<00>A§k¶[vendor/phpspec/prophecy/spec/Prophecy/Exception/Prediction/UnexpectedCallsExceptionSpec.phpã<00>'êWã"ÃnXvendor/phpspec/prophecy/spec/Prophecy/Exception/Prophecy/MethodProphecyExceptionSpec.phpX<00>'êWXïIÃâ¶Xvendor/phpspec/prophecy/spec/Prophecy/Exception/Prophecy/ObjectProphecyExceptionSpec.php<00>'êWvMGvendor/phpspec/prophecy/spec/Prophecy/Prediction/CallPredictionSpec.php¸<00>'êW¸ýkïLvendor/phpspec/prophecy/spec/Prophecy/Prediction/CallTimesPredictionSpec.php,<00>'êW,Ðdiá¶Kvendor/phpspec/prophecy/spec/Prophecy/Prediction/CallbackPredictionSpec.phph<00>'êWhwÔÄñ¶Jvendor/phpspec/prophecy/spec/Prophecy/Prediction/NoCallsPredictionSpec.php¶<00>'êW¶­pE¶Evendor/phpspec/prophecy/spec/Prophecy/Promise/CallbackPromiseSpec.phpr<00>'êWr
ùï׶Kvendor/phpspec/prophecy/spec/Prophecy/Promise/ReturnArgumentPromiseSpec.phpÅ<00>'êWÅûà~_¶Cvendor/phpspec/prophecy/spec/Prophecy/Promise/ReturnPromiseSpec.phpp<00>'êWpuGBvendor/phpspec/prophecy/spec/Prophecy/Promise/ThrowPromiseSpec.phpa<00>'êWa<C2A7>Evendor/phpspec/prophecy/spec/Prophecy/Prophecy/MethodProphecySpec.php(<00>'êW('Æ”9¶Evendor/phpspec/prophecy/spec/Prophecy/Prophecy/ObjectProphecySpec.phpŠ<00>'êWŠšµ?vendor/phpspec/prophecy/spec/Prophecy/Prophecy/RevealerSpec.php6<00>'êW6Œ®bµ¶5vendor/phpspec/prophecy/spec/Prophecy/ProphetSpec.phpä<00>'êWäÙœ…¡¶=vendor/phpspec/prophecy/spec/Prophecy/Util/StringUtilSpec.phpL <00>'êWL âÞg‰¶1vendor/phpspec/prophecy/src/Prophecy/Argument.phpp<00>'êWpm?+ Cvendor/phpspec/prophecy/src/Prophecy/Argument/ArgumentsWildcard.phpp<00>'êWpƒ˶Evendor/phpspec/prophecy/src/Prophecy/Argument/Token/AnyValueToken.php <00>'êW %&³|¶Fvendor/phpspec/prophecy/src/Prophecy/Argument/Token/AnyValuesToken.php<00>'êWóaÑN¶Mvendor/phpspec/prophecy/src/Prophecy/Argument/Token/ApproximateValueToken.php/<00>'êW/{Nà&¶Gvendor/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayCountToken.php¤<00>'êW¤ß–Gvendor/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayEntryToken.php÷<00>'êW÷>v¡[¶Lvendor/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayEveryEntryToken.php[<00>'êW[æòÇj¶Evendor/phpspec/prophecy/src/Prophecy/Argument/Token/CallbackToken.phpˆ<00>'êWˆòÀŽÇ¶Gvendor/phpspec/prophecy/src/Prophecy/Argument/Token/ExactValueToken.php=<00>'êW=ŠŒðW¶Kvendor/phpspec/prophecy/src/Prophecy/Argument/Token/IdenticalValueToken.phpŒ<00>'êWŒA ÑGvendor/phpspec/prophecy/src/Prophecy/Argument/Token/LogicalAndToken.php<00>'êW»ºÐ¶Gvendor/phpspec/prophecy/src/Prophecy/Argument/Token/LogicalNotToken.phpR<00>'êWR<10>Hvendor/phpspec/prophecy/src/Prophecy/Argument/Token/ObjectStateToken.php=<00>'êW=
8Kvendor/phpspec/prophecy/src/Prophecy/Argument/Token/StringContainsToken.phpô<00>'êWôæM&¶Fvendor/phpspec/prophecy/src/Prophecy/Argument/Token/TokenInterface.phpË<00>'êWËV]稶Avendor/phpspec/prophecy/src/Prophecy/Argument/Token/TypeToken.php><00>'êW>¶ðmÓ¶2vendor/phpspec/prophecy/src/Prophecy/Call/Call.php<00>'êWÐŽg8vendor/phpspec/prophecy/src/Prophecy/Call/CallCenter.php‰ <00>'êW‰ ŽEvendor/phpspec/prophecy/src/Prophecy/Comparator/ClosureComparator.phpF<00>'êWFYŠÉ_¶;vendor/phpspec/prophecy/src/Prophecy/Comparator/Factory.phpÏ<00>'êWÏ÷L×Fvendor/phpspec/prophecy/src/Prophecy/Comparator/ProphecyComparator.php?<00>'êW?²…gD¶>vendor/phpspec/prophecy/src/Prophecy/Doubler/CachedDoubler.phpu<00>'êWuê/*Œ¶Ovendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ClassPatchInterface.php<00>'êWË ¸Ÿ¶Svendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/DisableConstructorPatch.php<00>'êW©àgNvendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/HhvmExceptionPatch.php¢<00>'êW¢À6§Ç¶Hvendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/KeywordPatch.phpê<00>'êWê•sqŠ¶Jvendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/MagicCallPatch.phpq<00>'êWqi ¤A¶Pvendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ProphecySubjectPatch.php¨<00>'êW¨±¨‹¶[vendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ReflectionClassNewInstancePatch.phpî<00>'êWîõkS¤¶Lvendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/SplFileInfoPatch.phpY<00>'êWYóo?ѶLvendor/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/TraversablePatch.phpk<00>'êWk«á~ó¶@vendor/phpspec/prophecy/src/Prophecy/Doubler/DoubleInterface.phpQ<00>'êWQo̊ʶ8vendor/phpspec/prophecy/src/Prophecy/Doubler/Doubler.phpù<00>'êWù2BMvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCodeGenerator.phpˆ<00>'êWˆH©IȶGvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCreator.php8<00>'êW8cÒ1·¶Fvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassMirror.php}<00>'êW}ž&Wj¶Lvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/ArgumentNode.phpK<00>'êWK{FݶIvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/ClassNode.php»<00>'êW»îïi«¶Jvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/MethodNode.phpÒ <00>'êWÒ gÄNvendor/phpspec/prophecy/src/Prophecy/Doubler/Generator/ReflectionInterface.php_<00>'êW_”~–¶;vendor/phpspec/prophecy/src/Prophecy/Doubler/LazyDouble.php—<00>'êW—˜lE5¶>vendor/phpspec/prophecy/src/Prophecy/Doubler/NameGenerator.phpï<00>'êWï•[KOvendor/phpspec/prophecy/src/Prophecy/Exception/Call/UnexpectedCallException.phpV<00>'êWVh0J+¶Pvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassCreatorException.phpu<00>'êWu˜Ð¢y¶Ovendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassMirrorException.phpj<00>'êWjgö&¶Qvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassNotFoundException.php;<00>'êW;ÍÓI}¶Jvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/DoubleException.php<68><00>'êW<C3AA> ¶'}¶Kvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/DoublerException.php<00>'êWmïUvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/InterfaceNotFoundException.phpÀ<00>'êWÀ
l Wvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/MethodNotExtendableException.phpÄ<00>'êWÄ ø Rvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/MethodNotFoundException.phpN<00>'êWNáK]Uvendor/phpspec/prophecy/src/Prophecy/Exception/Doubler/ReturnByReferenceException.phpÂ<00>'êW€²<vendor/phpspec/prophecy/src/Prophecy/Exception/Exception.phpn<00>'êWn…*$»¶Kvendor/phpspec/prophecy/src/Prophecy/Exception/InvalidArgumentException.php‰<00>'êW‰È˜hµ¶Pvendor/phpspec/prophecy/src/Prophecy/Exception/Prediction/AggregateException.phpÝ<00>'êWÝsšÓͶWvendor/phpspec/prophecy/src/Prophecy/Exception/Prediction/FailedPredictionException.php³<00>'êW³Ó|DNvendor/phpspec/prophecy/src/Prophecy/Exception/Prediction/NoCallsException.phpÎ<00>'êWÎwši@¶Qvendor/phpspec/prophecy/src/Prophecy/Exception/Prediction/PredictionException.php<00>'êW ûµ¶[vendor/phpspec/prophecy/src/Prophecy/Exception/Prediction/UnexpectedCallsCountException.phpÈ<00>'êWÈŽRVvendor/phpspec/prophecy/src/Prophecy/Exception/Prediction/UnexpectedCallsException.phpì<00>'êWìôf~¨¶Svendor/phpspec/prophecy/src/Prophecy/Exception/Prophecy/MethodProphecyException.php¾<00>'êW¾¢@<40>½¶Svendor/phpspec/prophecy/src/Prophecy/Exception/Prophecy/ObjectProphecyException.php¯<00>'êW¯ Mvendor/phpspec/prophecy/src/Prophecy/Exception/Prophecy/ProphecyException.php<68><00>'êW<C3AA>Ó_Än¶Tvendor/phpspec/prophecy/src/Prophecy/PhpDocumentor/ClassAndInterfaceTagRetriever.php<00>'êWiM:c¶Hvendor/phpspec/prophecy/src/Prophecy/PhpDocumentor/ClassTagRetriever.php<00>'êWmNvendor/phpspec/prophecy/src/Prophecy/PhpDocumentor/LegacyClassTagRetriever.php£<00>'êW£Ó¥¦q¶Rvendor/phpspec/prophecy/src/Prophecy/PhpDocumentor/MethodTagRetrieverInterface.php"<00>'êW"¶!]•¶Bvendor/phpspec/prophecy/src/Prophecy/Prediction/CallPrediction.php<<00>'êW<BÍ<>Gvendor/phpspec/prophecy/src/Prophecy/Prediction/CallTimesPrediction.phpó<00>'êWó'Bû¶Fvendor/phpspec/prophecy/src/Prophecy/Prediction/CallbackPrediction.phpP<00>'êWP<00>¿0¶Evendor/phpspec/prophecy/src/Prophecy/Prediction/NoCallsPrediction.phpv<00>'êWvç"dp¶Gvendor/phpspec/prophecy/src/Prophecy/Prediction/PredictionInterface.php<00>'êW¶;êí¶@vendor/phpspec/prophecy/src/Prophecy/Promise/CallbackPromise.php5<00>'êW5þ6˜Avendor/phpspec/prophecy/src/Prophecy/Promise/PromiseInterface.phpþ<00>'êWþ×ê/c¶Fvendor/phpspec/prophecy/src/Prophecy/Promise/ReturnArgumentPromise.php<00>'êW”\€>vendor/phpspec/prophecy/src/Prophecy/Promise/ReturnPromise.php<00>'êW^-5¶=vendor/phpspec/prophecy/src/Prophecy/Promise/ThrowPromise.phpÅ<00>'êWÅâèd¶@vendor/phpspec/prophecy/src/Prophecy/Prophecy/MethodProphecy.phpA<00>'êWAHçi¶@vendor/phpspec/prophecy/src/Prophecy/Prophecy/ObjectProphecy.php¥<00>'êW¥‡ï©Q¶Cvendor/phpspec/prophecy/src/Prophecy/Prophecy/ProphecyInterface.phpr<00>'êWr+h¡Ú¶Jvendor/phpspec/prophecy/src/Prophecy/Prophecy/ProphecySubjectInterface.php¾<00>'êW¾ÐŠ/ô¶:vendor/phpspec/prophecy/src/Prophecy/Prophecy/Revealer.phpb<00>'êWbÁZ„ ¶Cvendor/phpspec/prophecy/src/Prophecy/Prophecy/RevealerInterface.phpz<00>'êWzŠÒ0vendor/phpspec/prophecy/src/Prophecy/Prophet.phpÍ<00>'êWÍüÌÞ¾¶8vendor/phpspec/prophecy/src/Prophecy/Util/ExportUtil.php† <00>'êW† ƒÑ8vendor/phpspec/prophecy/src/Prophecy/Util/StringUtil.php°<00>'êW°8>Nø¶2vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.php` <00>'êW` 'Õlî¶Bvendor/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php`<00>'êW`<>ü¶Rvendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineCollectionFilter.php(<00>'êW(«®ê¶Wvendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php¥<00>'êW¥è <0A><>7vendor/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php{<00>'êW{¹U겶;vendor/myclabs/deep-copy/src/DeepCopy/Filter/KeepFilter.php<68><00>'êW<C3AA>ú‘;>vendor/myclabs/deep-copy/src/DeepCopy/Filter/ReplaceFilter.phpï<00>'êWïø¶>vendor/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.phpD<00>'êWDvŠÞ9vendor/myclabs/deep-copy/src/DeepCopy/Matcher/Matcher.phpo<00>'êWo,êeÕ¶Avendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyMatcher.phpj<00>'êWj<00>ÅoL¶Evendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php<00>'êWµá¶Evendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.phpÕ<00>'êWÕ31âë¶Evendor/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.phpß<00>'êWß<19>‰¶Bvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php<00>'êW'w%é¶Fvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php—<00>'êW—‹Šùµ¶?vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.phpe<00>'êWeSú<_¶Avendor/myclabs/deep-copy/src/DeepCopy/TypeMatcher/TypeMatcher.php<00>'êW„@PG¶)vendor/psr/log/Psr/Log/AbstractLogger.php;<00>'êW;ñ>3[¶3vendor/psr/log/Psr/Log/InvalidArgumentException.php`<00>'êW` ˆX1¶#vendor/psr/log/Psr/Log/LogLevel.phpû<00>'êWûjðñ8¶/vendor/psr/log/Psr/Log/LoggerAwareInterface.php|<00>'êW|$£ˆ¶+vendor/psr/log/Psr/Log/LoggerAwareTrait.php§<00>'êW§T½úB¶*vendor/psr/log/Psr/Log/LoggerInterface.phpÆ<00>'êWÆ»sg¶&vendor/psr/log/Psr/Log/LoggerTrait.phpi<00>'êWi35§Þ¶%vendor/psr/log/Psr/Log/NullLogger.phpž<00>'êWžÇÃ3vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.phpî <00>'êWî "vendor/guzzle/guzzle/phar-stub.phpA<00>'êWA¤Þ‰G¶5vendor/guzzle/guzzle/phing/tasks/ComposerLintTask.php9<00>'êW9¸ƒ;u¶>vendor/guzzle/guzzle/phing/tasks/GuzzlePearPharPackageTask.php4"<00>'êW4"@ÜÇ7vendor/guzzle/guzzle/phing/tasks/GuzzleSubSplitTask.phpë<00>'êWë]H¶@vendor/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php*<00>'êW*àÂýG¶/vendor/guzzle/guzzle/src/Guzzle/Batch/Batch.phpð<00>'êWðü46vendor/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.phpè<00>'êWè¬é5߶=vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php<00>'êWSf桶>vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php*<00>'êW*È›É>vendor/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php”<00>'êW”v¯8Z¶?vendor/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php<00>'êWn+‰£¶8vendor/guzzle/guzzle/src/Guzzle/Batch/BatchInterface.php£<00>'êW£Pؽ>vendor/guzzle/guzzle/src/Guzzle/Batch/BatchRequestTransfer.phpi<00>'êWi]« »¶:vendor/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php®<00>'êW®ö6-j¶@vendor/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.phpu<00>'êWu™Õ…Jvendor/guzzle/guzzle/src/Guzzle/Batch/Exception/BatchTransferException.phpš<00>'êWšI—$ö¶Avendor/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php<68><00>'êW<C3AA>; ^h¶7vendor/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php‰<00>'êW‰ ùš6vendor/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.phpd<00>'êWd¸ŽÛM¶8vendor/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php)<00>'êW)¹¶>vendor/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php¾<00>'êW¾nÇŒÀ¶=vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php¦ <00>'êW¦ "5)¶?vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.phpY<00>'êWY¶„W¤¶=vendor/guzzle/guzzle/src/Guzzle/Cache/ClosureCacheAdapter.phpÔ<00>'êWÔk®é¶>vendor/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.php]<00>'êW];ËŒQ¶:vendor/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php«<00>'êW«Š<0E>9vendor/guzzle/guzzle/src/Guzzle/Cache/Zf1CacheAdapter.phpº<00>'êWº»µã`¶9vendor/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.phph<00>'êWh!ÄP¶@vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.phpÂ<00>'êWÂB»vܶ5vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php[<00>'êW[u'Û;¶0vendor/guzzle/guzzle/src/Guzzle/Common/Event.php<00>'êW<4&x¶Kvendor/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php†<00>'êW†qS”¶Hvendor/guzzle/guzzle/src/Guzzle/Common/Exception/ExceptionCollection.php¬<00>'êW¬dÓN¶Dvendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.phpK<00>'êWK¹ññ¶Mvendor/guzzle/guzzle/src/Guzzle/Common/Exception/InvalidArgumentException.phpŠ<00>'êWŠùVǶEvendor/guzzle/guzzle/src/Guzzle/Common/Exception/RuntimeException.phpz<00>'êWzh^Üw¶Mvendor/guzzle/guzzle/src/Guzzle/Common/Exception/UnexpectedValueException.phpŠ<00>'êWŠ¢eˆ£¶>vendor/guzzle/guzzle/src/Guzzle/Common/FromConfigInterface.php€<00>'êW€ï"­Avendor/guzzle/guzzle/src/Guzzle/Common/HasDispatcherInterface.php<00>'êW ¦?J¶;vendor/guzzle/guzzle/src/Guzzle/Common/ToArrayInterface.phpc<00>'êWc`¦ˆ÷¶2vendor/guzzle/guzzle/src/Guzzle/Common/Version.php <00>'êW VJ8­Dvendor/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.phpÿ <00>'êWÿ úúÝí¶:vendor/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.phpF <00>'êWF Å<>™¶/vendor/guzzle/guzzle/src/Guzzle/Http/Client.php<68>)<00>'êW<C3AA>)b?§¶8vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php<68><00>'êW<C3AA>©¬vz¶8vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlHandle.php2<00>'êW2߈3ù¶7vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php~<00>'êW~ù¬©@vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.phpÃ<00>'êWÃ÷_½¶<vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiProxy.phpÊ<00>'êWÊë¼³ƒ¶9vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php<00>'êWä ñ‡¶=vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.phpž<00>'êWžîèÉ3vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php© <00>'êW© åù.=¶<vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php<00>'êWH—ƒGvendor/guzzle/guzzle/src/Guzzle/Http/Exception/BadResponseException.php<00>'êW%ö倶Ovendor/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.phpo<00>'êWoÒ'‰ó¶Pvendor/guzzle/guzzle/src/Guzzle/Http/Exception/CouldNotRewindStreamException.php±<00>'êW±„n—ð¶@vendor/guzzle/guzzle/src/Guzzle/Http/Exception/CurlException.php<00>'êW3‡ô@vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php<68><00>'êW<C3AA> n8­Ivendor/guzzle/guzzle/src/Guzzle/Http/Exception/MultiTransferException.php¬<00>'êW¬ÄCvendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php<00>'êW»LXò¶Ovendor/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.phpo<00>'êWo¥ˆLvendor/guzzle/guzzle/src/Guzzle/Http/Exception/TooManyRedirectsException.phpi<00>'êWiǸ–¶=vendor/guzzle/guzzle/src/Guzzle/Http/IoEmittingEntityBody.phpË<00>'êWËŸ<E28098>@vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.phpñ<00>'êWñSJ0¼¶Gvendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.phpF<00>'êWFòB`¶Pvendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php<00>'êW dâ¶7vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php
<00>'êW
ÕmDvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.phpÌ<00>'êWÌIÇcu¶Hvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.phpW<00>'êWW<šÀ:¶Evendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.phpî<00>'êWî¼ Nvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php”<00>'êW”ÍïÀã¶Gvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderInterface.php<00>'êWƒ²gÖ¶<vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/Link.php<00>'êW
<EFBFBD>˜´Avendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php7<00>'êW7®ª£f¶9vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFile.php”<00>'êW”€ž¶Bvendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.phpó<00>'êWó<00>38vendor/guzzle/guzzle/src/Guzzle/Http/Message/Request.phpO.<00>'êWO.{—<>‡¶?vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.phpc!<00>'êWc!A噶Hvendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php©<00>'êW©,êtÞ¶Avendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestInterface.php…<00>'êW…ž‹%4¶9vendor/guzzle/guzzle/src/Guzzle/Http/Message/Response.phpZ.<00>'êWZ.½(Α¶2vendor/guzzle/guzzle/src/Guzzle/Http/Mimetypes.phpl…<00>'êWl…Ð~‚¶Hvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.phpŽ<00>'êWŽ3"Lvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.phpx<00>'êWxkgB€¶Fvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php´<00>'êW´—’¹¶Qvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php½<00>'êW½±×E4vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.phpë <00>'êWë É”<ó¶<vendor/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php<00>'êW!\¦¶7vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php<68><00>'êW<C3AA>îî<C3AE>϶5vendor/guzzle/guzzle/src/Guzzle/Http/StaticClient.phpÑ<00>'êWÑE„g,vendor/guzzle/guzzle/src/Guzzle/Http/Url.phpK<00>'êWKn{ùY¶8vendor/guzzle/guzzle/src/Guzzle/Inflection/Inflector.phpï<00>'êWï*üŒé¶Avendor/guzzle/guzzle/src/Guzzle/Inflection/InflectorInterface.php”<00>'êW”¦Å*‰¶Avendor/guzzle/guzzle/src/Guzzle/Inflection/MemoizingInflector.php<00>'êWšõð¶Cvendor/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.phpo<00>'êWoFK†B¶;vendor/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.phpº<00>'êWº«{Ø <vendor/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php<00>'êWóX˶;vendor/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.phpè<00>'êWèÆØEŸ¶8vendor/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.phpê<00>'êWê¹Ìå@vendor/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php2<00>'êW2@!L1¶:vendor/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php­<00>'êW­À-k¶7vendor/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php<68><00>'êW<C3AA><00>91f¶9vendor/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php†<00>'êW†ã½1Ѷ;vendor/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php<00>'êW6/ö8vendor/guzzle/guzzle/src/Guzzle/Log/MessageFormatter.phpý <00>'êWý šð‰Î¶9vendor/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php<00>'êWRí²*¶5vendor/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.phpG<00>'êWGÂ輶5vendor/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.phpi<00>'êWi¾7cã¶5vendor/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php1<00>'êW1«¿å¶>vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php<00>'êW­;2(¶Gvendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php¸<00>'êW¸øð¡!¶Hvendor/guzzle/guzzle/src/Guzzle/Parser/Message/AbstractMessageParser.phpÛ<00>'êWÛ{^"X¶@vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.phpë<00>'êWë¡÷m]¶Ivendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php±<00>'êW±
sú³¶Hvendor/guzzle/guzzle/src/Guzzle/Parser/Message/PeclHttpMessageParser.phpN<00>'êWN^¿#¶9vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.phpà<00>'êWàß5&d¶Fvendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php²<00>'êW²ídŸ¶Bvendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplate.phpz<00>'êWzß>Ék¶Kvendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php<00>'êW'JÜŒ¶8vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParser.php<00>'êW(yËá¶Avendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.phpq<00>'êWqV³ý:¶<vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php'<00>'êW'MA"Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.phpü<00>'êWüm]<ζSvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php<00>'êWðîÍy¶@vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.phps<00>'êWsT©.ö@vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php² <00>'êW² ±gí¶Kvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.phpP<00>'êWPJ=,—¶Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.phpj<00>'êWjB}}2¶Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.phpü<00>'êWü¤…ÿ8¶Fvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php<00>'êWåÃJ™¶Mvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php´<00>'êW´x¬&9¶Fvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php7<00>'êW7ú¥NG¶Hvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php<00>'êWSºÞNvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.phpü<00>'êWüž̶Kvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.phpW<00>'êWW,ÙR{¶Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php´<00>'êW´=Ú8Ö¶<vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CachePlugin.phpŸ<00>'êWŸ³3®Fvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php}<00>'êW}
‚²ï¶Ivendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.phpC<00>'êWC‹íç-¶Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php <00>'êW ýââv¶Hvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.phpË<00>'êWËZʉɶDvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php¹<00>'êW¹??ô¶Hvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php|<00>'êW|€‰¼ô¶Dvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php= <00>'êW= ¸Å¶Avendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php,<00>'êW,-NLݶFvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/RevalidationInterface.phpH<00>'êWH&!z¨¶Avendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/SkipRevalidation.php+<00>'êW+¾$ô 8vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php<00>'êW¢p<70>Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.phpœ<00>'êWœTJNvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.phpå<00>'êWå<57>ò¶Ivendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php÷<00>'êW÷}²4Û¶>vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.phpt<00>'êWt^¡_®¶Rvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.phpª<00>'êWª!m|€¶Bvendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.phpM<00>'êWM8^ÿ¶Xvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php <00>'êW ÁIF¶Lvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.phpó<00>'êWó+A²Ü¶Yvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php¡<00>'êW¡«ÔÒ™¶@vendor/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.phpó<00>'êWóuïñ8vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.phpR <00>'êWR  ÄɶFvendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php¨<00>'êW¨¢­Avendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.phpÇ<00>'êWÇ<>:vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.php <00>'êW ç…D“¶<vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php<68><00>'êW<C3AA>ž\Þ¼¶@vendor/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php@ <00>'êW@ <ðJ¶Bvendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.phpH <00>'êWH µ‹ç¶Kvendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.phpú<00>'êWú2ÍÈ•¶Hvendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderLoader.php.<00>'êW.xÊÜݶ?vendor/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php<68><00>'êW<C3AA>d¯¶2vendor/guzzle/guzzle/src/Guzzle/Service/Client.php$<00>'êW$re‡¶;vendor/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php:<00>'êW:ÜîÇm¶Cvendor/guzzle/guzzle/src/Guzzle/Service/Command/AbstractCommand.php<00>'êW<00>+6J¶Bvendor/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php«<00>'êW«Ñé›Ü¶Dvendor/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.phpè<00>'êWè:wª¶Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/CreateResponseClassEvent.php<00>'êW€Ì<E282AC>Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.phpÞ <00>'êWÞ F<
Ivendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.phpÈ<00>'êWȈ2<CB86>Hvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.phpM<00>'êWM³<>¬¶Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.phpŠ<00>'êWŠÊáT¶Pvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php“<00>'êW“Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.phpÁ<00>'êWÁÏTO¶Fvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/MapFactory.phpL<00>'êWLód=I¶Uvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.phpJ<00>'êWJÅÚH'¶bvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.phpØ<00>'êWØŠÿ´²¶Wvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php¹<00>'êW¹eÌ9¶Yvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php <00>'êW <00>Æs¶¶Wvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php<68><00>'êW<C3AA>×Á¶\vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php¿<00>'êW¿Þ†uª¶[vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.phpA<00>'êWAã¶*£¶Xvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php¾<00>'êW¾Ô§!¶cvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php°<00>'êW°c`7ƶ_vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.php<00>'êWü… Vvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php%<00>'êW%ßò¶dvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php<00>'êWçXþ¶Xvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php¯<00>'êW¯Zvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php<00>'êW²¬ 2¶Xvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php<00>'êWêÓN¬¶`vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php¯<00>'êW¯ùMµÁ¶evendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.phpç<00>'êWçbZ!ض^vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.php«<00>'êW«V÷NWvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.phpQ
<00>'êWQ
Й%ð¶Tvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.phpú
<00>'êWú
LÕ啶Dvendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php-<00>'êW-ç¨Äw¶Kvendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.phpÃ<00>'êWÃíã<C3AD>Nvendor/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.phpé<00>'êWé㜇¶Jvendor/guzzle/guzzle/src/Guzzle/Service/Command/ResponseClassInterface.php˜<00>'êW˜XsÆM¶Kvendor/guzzle/guzzle/src/Guzzle/Service/Command/ResponseParserInterface.phpŒ<00>'êWŒÖo¥¶Avendor/guzzle/guzzle/src/Guzzle/Service/ConfigLoaderInterface.php<68><00>'êW<C3AA>Vqq Avendor/guzzle/guzzle/src/Guzzle/Service/Description/Operation.php”<00>'êW”k¹É¶Jvendor/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php3<00>'êW3ÒŠA9¶Avendor/guzzle/guzzle/src/Guzzle/Service/Description/Parameter.phpý"<00>'êWý"¡M¹­Gvendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.phpR<00>'êWR«<>”¶Gvendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php*<00>'êW*|Ë»Jvendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php=<00>'êW=us<75>°¶Svendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.phpM<00>'êWM4r϶Pvendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionLoader.phpÇ<00>'êWÇî¶Jvendor/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php´<00>'êW´ÎA0¶Fvendor/guzzle/guzzle/src/Guzzle/Service/Exception/CommandException.phpŽ<00>'êWŽ<00>£Õ¯¶Nvendor/guzzle/guzzle/src/Guzzle/Service/Exception/CommandTransferException.phpF<00>'êWFÂQvendor/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php™<00>'êW™Æ£Ñï¶Yvendor/guzzle/guzzle/src/Guzzle/Service/Exception/InconsistentClientTransferException.php0<00>'êW0¢
Ò´¶Lvendor/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php•<00>'êW•#ìíN¶Mvendor/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceBuilderException.php•<00>'êW•ïèNζNvendor/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceNotFoundException.phpn<00>'êWn¼S¬h¶Ivendor/guzzle/guzzle/src/Guzzle/Service/Exception/ValidationException.php7<00>'êW7!ù3Tvendor/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.phpÉ<00>'êWÉk4 ‹¶Uvendor/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.phpù<00>'êWùœ\åζOvendor/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.phpí<00>'êWíõ´·¶:vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php_<00>'êW_58Ô¶Evendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php <00>'êW ß¾¶¶Qvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php×<00>'êW×Qvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php¯<00>'êW¯Ä“e¹¶Uvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php<00>'êW.½—׶Nvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorInterface.phpÀ<00>'êWÀQíÝ-¶Bvendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.phpY<00>'êWYø:*z¶1vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.phpK<00>'êWK8€ÿ¶:vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.phpl<00>'êWlÛ§Hvendor/guzzle/guzzle/src/Guzzle/Stream/StreamRequestFactoryInterface.phpë<00>'êWëÜ÷ݶYvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Console/Application.php-<00>'êW-<00>½Û*¶Uvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/CoverallsBundle.php<00>'êWz—òO¶]vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Entity/ArrayConvertable.php~<00>'êW~ò2œ&¶Xvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/CoverallsApi.phpR<00>'êWRO®òþ¶Pvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/Jobs.phpû<00>'êWû8gÍì¶dvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CiEnvVarsCollector.phpð
<00>'êWð
mL ™¶lvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CloverXmlCoverageCollector.php¯<00>'êW¯í<1D> bvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/GitInfoCollector.phpÖ<00>'êWÖ5ÒŠŠ¶fvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Command/CoverallsV1JobsCommand.phpZ <00>'êWZ 3ïɪ¶\vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configuration.phpÙ <00>'êWÙ ›¶¶[vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configurator.php<00>'êW>|˜Ž¶evendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/CoverallsConfiguration.phpI<00>'êWI`Šâ¶Yvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/CoverallsV1Bundle.php<00>'êWøáñX¶Xvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Coveralls.php<00>'êWyö@zvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Exception/RequirementsNotSatisfiedException.php <00>'êW ¿ªĶYvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Commit.phpC<00>'êWC<4D>Vvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Git.php/<00>'êW/Ui `¶Yvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Remote.phpƒ<00>'êWƒ%r¿¶Wvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/JsonFile.phpÈ<00>'êWÈŠòÚ¶Vvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Metrics.phpv<00>'êWv¤
ʶYvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/SourceFile.phpV<00>'êWVuÑf½¶avendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Repository/JobsRepository.php<68><00>'êW<C3AA>›üͶOvendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Version.phpp<00>'êWpY9å¶Bvendor/satooshi/php-coveralls/src/Satooshi/Component/File/Path.phpp<00>'êWp<00>YçM¶Jvendor/satooshi/php-coveralls/src/Satooshi/Component/Log/ConsoleLogger.phpŽ<00>'êWŽòjÚA¶Nvendor/satooshi/php-coveralls/src/Satooshi/Component/System/Git/GitCommand.php[<00>'êW[t§qF¶Mvendor/satooshi/php-coveralls/src/Satooshi/Component/System/SystemCommand.php<00>'êWÞvendor/autoload.php<00>'êWúáb¶Symfony/CS/Config/Config.php<68><00>'êW<C3AA>[s#ó¶#Symfony/CS/Config/MagentoConfig.php6<00>'êW6zÒ¼µ¶%Symfony/CS/Config/Symfony23Config.php;<00>'êW;1*’¶)Symfony/CS/Console/Command/FixCommand.php˜D<00>'êW˜D.¹bÛ¶,Symfony/CS/Console/Command/ReadmeCommand.phpÑ<00>'êWÑ|™§¶0Symfony/CS/Console/Command/SelfUpdateCommand.php6
<00>'êW6
Û
"Symfony/CS/Console/Application.phpO<00>'êWO,™"Symfony/CS/DocBlock/Annotation.php)<00>'êW)Àñ«„¶ Symfony/CS/DocBlock/DocBlock.phpJ<00>'êWJå§Ý—¶Symfony/CS/DocBlock/Line.phpÑ<00>'êWѾ›ó¶Symfony/CS/DocBlock/Tag.php<00>'êWàä׶%Symfony/CS/DocBlock/TagComparator.php‡<00>'êW‡ˆãHð¶#Symfony/CS/Finder/DefaultFinder.php <00>'êW Æ=æF¶#Symfony/CS/Finder/MagentoFinder.phpH<00>'êWH FF¶%Symfony/CS/Finder/Symfony23Finder.phpi<00>'êWiö ¬1¶2Symfony/CS/Fixer/Contrib/AlignDoubleArrowFixer.php” <00>'êW” -Œ0Ž¶-Symfony/CS/Fixer/Contrib/AlignEqualsFixer.phpÞ<00>'êWÞíMJ¾¶4Symfony/CS/Fixer/Contrib/ClassKeywordRemoveFixer.php<<00>'êW<m$Ãh¶:Symfony/CS/Fixer/Contrib/CombineConsecutiveUnsetsFixer.phpû <00>'êWû Ê<>2Symfony/CS/Fixer/Contrib/ConcatWithSpacesFixer.php¢<00>'êW¢µ¸×̶-Symfony/CS/Fixer/Contrib/EchoToPrintFixer.php&<00>'êW&Š˜ž¶-Symfony/CS/Fixer/Contrib/EmptyReturnFixer.phpp<00>'êWpâ¶,Symfony/CS/Fixer/Contrib/EregToPregFixer.phpÒ <00>'êWÒ X¹3<C2B9>/Symfony/CS/Fixer/Contrib/HeaderCommentFixer.phpH <00>'êWH Ä3¼Y¶?Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixer.php™<00>'êW™„Â*8¶GSymfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixer.phpX<00>'êWX Üm­1Symfony/CS/Fixer/Contrib/LongArraySyntaxFixer.phpï<00>'êWï<00>©0Symfony/CS/Fixer/Contrib/MbStrFunctionsFixer.phpH<00>'êWHÑ@Symfony/CS/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixer.php<68><00>'êW<C3AA>¢oR¶5Symfony/CS/Fixer/Contrib/NewlineAfterOpenTagFixer.php!<00>'êW!E.ᬶ=Symfony/CS/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixer.php]<00>'êW]û ÏW¶/Symfony/CS/Fixer/Contrib/NoUselessElseFixer.phpa<00>'êWaMé2t¶1Symfony/CS/Fixer/Contrib/NoUselessReturnFixer.phpc<00>'êWcA<º¶,Symfony/CS/Fixer/Contrib/OrderedUseFixer.php¾ <00>'êW¾ ǃé¶1Symfony/CS/Fixer/Contrib/Php4ConstructorFixer.php<00>'êWè¶2Symfony/CS/Fixer/Contrib/PhpUnitConstructFixer.php! <00>'êW! æ µj¶7Symfony/CS/Fixer/Contrib/PhpUnitDedicateAssertFixer.php
<00>'êW
%¸Î/Symfony/CS/Fixer/Contrib/PhpUnitStrictFixer.phpB<00>'êWB¯V-Symfony/CS/Fixer/Contrib/PhpdocOrderFixer.phpd<00>'êWd4Ìæÿ¶1Symfony/CS/Fixer/Contrib/PhpdocVarToTypeFixer.php9<00>'êW9_òÐã¶2Symfony/CS/Fixer/Contrib/ShortArraySyntaxFixer.php&<00>'êW&^ ¶.Symfony/CS/Fixer/Contrib/ShortEchoTagFixer.php™<00>'êW™ÝVsŠ¶:Symfony/CS/Fixer/Contrib/SilencedDeprecationErrorFixer.php¬<00>'êW¬ÀC€¶(Symfony/CS/Fixer/Contrib/StrictFixer.php<00>'êWä2ªÔ¶-Symfony/CS/Fixer/Contrib/StrictParamFixer.phpA
<00>'êWA
tTr#Symfony/CS/Fixer/PSR0/Psr0Fixer.php¿ <00>'êW¿ q“<`¶'Symfony/CS/Fixer/PSR1/EncodingFixer.php<00>'êWçü¦ù¶'Symfony/CS/Fixer/PSR1/ShortTagFixer.php¡<00>'êW¡¡Ž¢l¶%Symfony/CS/Fixer/PSR2/BracesFixer.phpê8<00>'êWê8~xùn¶.Symfony/CS/Fixer/PSR2/ClassDefinitionFixer.php¨<00>'êW¨ôxAî¶%Symfony/CS/Fixer/PSR2/ElseifFixer.php…<00>'êW…%›Ü]¶(Symfony/CS/Fixer/PSR2/EofEndingFixer.phpe<00>'êWež¶0Symfony/CS/Fixer/PSR2/FunctionCallSpaceFixer.phpP<00>'êWPÓ§[2Symfony/CS/Fixer/PSR2/FunctionDeclarationFixer.phpÕ <00>'êWÕ ÔŽÛž¶*Symfony/CS/Fixer/PSR2/IndentationFixer.php™<00>'êW™nuõ¶1Symfony/CS/Fixer/PSR2/LineAfterNamespaceFixer.php <00>'êW ½ÊÈ'Symfony/CS/Fixer/PSR2/LinefeedFixer.php<00>'êW¤Åâ,¶1Symfony/CS/Fixer/PSR2/LowercaseConstantsFixer.php<00>'êWØ45w¶0Symfony/CS/Fixer/PSR2/LowercaseKeywordsFixer.phpc<00>'êWcÔ¬°“¶2Symfony/CS/Fixer/PSR2/MethodArgumentSpaceFixer.php<00>'êW$B*Symfony/CS/Fixer/PSR2/MultipleUseFixer.php§<00>'êW§€G˶<Symfony/CS/Fixer/PSR2/NoTrailingWhitespaceInCommentFixer.php:<00>'êW:ÔC<l¶*Symfony/CS/Fixer/PSR2/ParenthesisFixer.php…<00>'êW…ñšÅ¶,Symfony/CS/Fixer/PSR2/PhpClosingTagFixer.phpz<00>'êWz'1¹7¶5Symfony/CS/Fixer/PSR2/SingleLineAfterImportsFixer.phpò <00>'êWò R±¶Å¶9Symfony/CS/Fixer/PSR2/SwitchCaseSemicolonToColonFixer.phpj<00>'êWjG6.Symfony/CS/Fixer/PSR2/SwitchCaseSpaceFixer.phpŒ<00>'êWŒ9ì3U¶-Symfony/CS/Fixer/PSR2/TrailingSpacesFixer.php¨<00>'êW¨<00><>_!¶)Symfony/CS/Fixer/PSR2/VisibilityFixer.phpf <00>'êWf ôºÔª¶@Symfony/CS/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixer.php¸<00>'êW¸¬ÞBSymfony/CS/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixer.phpŠ<00>'êWŠë¶7Symfony/CS/Fixer/Symfony/BlanklineAfterOpenTagFixer.phpe<00>'êWeÓf_¶5Symfony/CS/Fixer/Symfony/ConcatWithoutSpacesFixer.phpà<00>'êWà?3ðð¶7Symfony/CS/Fixer/Symfony/DeclareEqualNormalizeFixer.php¹<00>'êW¹lþàASymfony/CS/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixer.php<00>'êW…p  ¶4Symfony/CS/Fixer/Symfony/DuplicateSemicolonFixer.phpf<00>'êWf$;w_¶1Symfony/CS/Fixer/Symfony/ExtraEmptyLinesFixer.phpõ<00>'êWõ½)ƒU¶7Symfony/CS/Fixer/Symfony/FunctionTypehintSpaceFixer.php,<00>'êW,=ºÀ=¶4Symfony/CS/Fixer/Symfony/HashToSlashCommentFixer.php—<00>'êW—|U#n¶1Symfony/CS/Fixer/Symfony/HeredocToNowdocFixer.phpà<00>'êWà»âö)Symfony/CS/Fixer/Symfony/IncludeFixer.php
<00>'êW
-kh¶.Symfony/CS/Fixer/Symfony/JoinFunctionFixer.phpy<00>'êWyD¬ú¿¶,Symfony/CS/Fixer/Symfony/ListCommasFixer.phpä<00>'êWäÓ%\¶/Symfony/CS/Fixer/Symfony/LowercaseCastFixer.phpN<00>'êWNÜ<>˶<Symfony/CS/Fixer/Symfony/MethodArgumentDefaultValueFixer.php <00>'êW …Ý=Symfony/CS/Fixer/Symfony/MultilineArrayTrailingCommaFixer.php—<00>'êW—®ÌÓ>Symfony/CS/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixer.phpH<00>'êWHv<>¥¶¶6Symfony/CS/Fixer/Symfony/NativeFunctionCasingFixer.phpc<00>'êWcÄA>ñ¶/Symfony/CS/Fixer/Symfony/NewWithBracesFixer.phpO<00>'êWO𹎶?Symfony/CS/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixer.phpÀ<00>'êWÀÂ<1D>0Symfony/CS/Fixer/Symfony/NoEmptyCommentFixer.php
<00>'êW
xcð¶:Symfony/CS/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixer.phpD<00>'êWD {]¶/Symfony/CS/Fixer/Symfony/NoEmptyPhpdocFixer.php <00>'êW ¤¶2Symfony/CS/Fixer/Symfony/NoEmptyStatementFixer.php <00>'êW Úÿºä¶0Symfony/CS/Fixer/Symfony/ObjectOperatorFixer.php<00>'êW¨8èU¶1Symfony/CS/Fixer/Symfony/OperatorsSpacesFixer.phpo<00>'êWoƶ<Symfony/CS/Fixer/Symfony/PhpdocAnnotationWithoutDotFixer.php×<00>'êW×ÐHÍÿ¶.Symfony/CS/Fixer/Symfony/PhpdocIndentFixer.phpÎ<00>'êWÎ5<E28098>1Symfony/CS/Fixer/Symfony/PhpdocInlineTagFixer.phpÙ<00>'êWÙÎ •À¶0Symfony/CS/Fixer/Symfony/PhpdocNoAccessFixer.phpë<00>'êWëÿ| ¶5Symfony/CS/Fixer/Symfony/PhpdocNoEmptyReturnFixer.phpE<00>'êWE†@ 1Symfony/CS/Fixer/Symfony/PhpdocNoPackageFixer.php <00>'êW CEž¶.Symfony/CS/Fixer/Symfony/PhpdocParamsFixer.php <00>'êW .Symfony/CS/Fixer/Symfony/PhpdocScalarFixer.phpŽ<00>'êWŽMÈkѶ2Symfony/CS/Fixer/Symfony/PhpdocSeparationFixer.phpl<00>'êWl,28Symfony/CS/Fixer/Symfony/PhpdocShortDescriptionFixer.php«<00>'êW«¢ä<Symfony/CS/Fixer/Symfony/PhpdocSingleLineVarSpacingFixer.php<00>'êWQ(64¶1Symfony/CS/Fixer/Symfony/PhpdocToCommentFixer.php§ <00>'êW§ “F_¶,Symfony/CS/Fixer/Symfony/PhpdocTrimFixer.phpm<00>'êWm‡¶1Symfony/CS/Fixer/Symfony/PhpdocTypeToVarFixer.php<00>'êW6-Symfony/CS/Fixer/Symfony/PhpdocTypesFixer.phpÐ<00>'êWФ$v¿¶6Symfony/CS/Fixer/Symfony/PhpdocVarWithoutNameFixer.php»<00>'êW»zžØÔ¶.Symfony/CS/Fixer/Symfony/PreIncrementFixer.phpC<00>'êWCÒª-Symfony/CS/Fixer/Symfony/PrintToEchoFixer.phpÖ<00>'êWÖÿžk+¶7Symfony/CS/Fixer/Symfony/RemoveLeadingSlashUseFixer.phpt<00>'êWt<00>·P1¶8Symfony/CS/Fixer/Symfony/RemoveLinesBetweenUsesFixer.phpf<00>'êWf­8Á1¶(Symfony/CS/Fixer/Symfony/ReturnFixer.phpÁ<00>'êWÁ°<.Symfony/CS/Fixer/Symfony/SelfAccessorFixer.phpô<00>'êWôiC½1¶/Symfony/CS/Fixer/Symfony/ShortBoolCastFixer.php<68><00>'êW<C3AA>´³(϶1Symfony/CS/Fixer/Symfony/ShortScalarCastFixer.phpÞ<00>'êWÞÆ œ<Symfony/CS/Fixer/Symfony/SingleArrayNoTrailingCommaFixer.php¶<00>'êW¶Lv_˶@Symfony/CS/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixer.phph<00>'êWhÿ¡2v¶-Symfony/CS/Fixer/Symfony/SingleQuoteFixer.php;<00>'êW;jÔµ·¶6Symfony/CS/Fixer/Symfony/SpacesAfterSemicolonFixer.phpò<00>'êWò9äS7Symfony/CS/Fixer/Symfony/SpacesBeforeSemicolonFixer.php
<00>'êW
<76>Ͷ,Symfony/CS/Fixer/Symfony/SpacesCastFixer.phpÛ<00>'êWÛ…iy¡¶5Symfony/CS/Fixer/Symfony/StandardizeNotEqualFixer.phpø<00>'êWøšp¼=¶/Symfony/CS/Fixer/Symfony/TernarySpacesFixer.phpã<00>'êWãèŒѶ1Symfony/CS/Fixer/Symfony/TrimArraySpacesFixer.phpJ<00>'êWJbƒ¦š¶4Symfony/CS/Fixer/Symfony/UnalignDoubleArrowFixer.phpé<00>'êWéh¦Ê/Symfony/CS/Fixer/Symfony/UnalignEqualsFixer.phpÎ<00>'êWÎr2Ò¶6Symfony/CS/Fixer/Symfony/UnaryOperatorsSpacesFixer.php´<00>'êW´] ¥À¶<Symfony/CS/Fixer/Symfony/UnneededControlParenthesesFixer.php”
<00>'êW”
Ìé +Symfony/CS/Fixer/Symfony/UnusedUseFixer.phpH<00>'êWH¡âÍ®¶1Symfony/CS/Fixer/Symfony/WhitespacyLinesFixer.phpF<00>'êWF1o>¶"Symfony/CS/Resources/phar-stub.php<00>'êW<00>7G°¶2Symfony/CS/Tokenizer/Transformer/ArrayTypehint.phpY<00>'êWY#<E28093>2Symfony/CS/Tokenizer/Transformer/ClassConstant.php»<00>'êW»àƒ¯¶/Symfony/CS/Tokenizer/Transformer/CurlyClose.phpµ<00>'êWµ‰Mo<4D>;Symfony/CS/Tokenizer/Transformer/DollarCloseCurlyBraces.php<00>'êWQв~¶5Symfony/CS/Tokenizer/Transformer/DynamicPropBrace.phpd<00>'êWd?‡.g¶4Symfony/CS/Tokenizer/Transformer/DynamicVarBrace.phpÆ<00>'êWÆ/þ®Â¶,Symfony/CS/Tokenizer/AbstractTransformer.phpN<00>'êWNÚÆ-p¶Symfony/CS/Tokenizer/Token.php#<00>'êW#ÿµu}¶Symfony/CS/Tokenizer/Tokens.phpO<00>'êWOg-Symfony/CS/Tokenizer/TransformerInterface.php0<00>'êW0•`ÔL¶%Symfony/CS/Tokenizer/Transformers.phpR<00>'êWR¡Õ¶Û¶!Symfony/CS/AbstractAlignFixer.php<00>'êWëDNï¶-Symfony/CS/AbstractAnnotationRemovalFixer.php<00>'êW¦ãŸã¶Symfony/CS/AbstractFixer.phpc<00>'êWc
á3í¶0Symfony/CS/AbstractLinesBeforeNamespaceFixer.phpq<00>'êWq £z'Symfony/CS/AbstractPhpdocTypesFixer.php„<00>'êW„íX$i¶Symfony/CS/Config.php <00>'êW #Symfony/CS/ConfigAwareInterface.php‡<00>'êW‡£·Symfony/CS/ConfigInterface.php§<00>'êW§GM³Î¶CSymfony/CS/ConfigurationException/InvalidConfigurationException.phpa<00>'êWaæAHSymfony/CS/ConfigurationException/InvalidFixerConfigurationException.phpu<00>'êWu<13>e
$Symfony/CS/ConfigurationResolver.php  <00>'êW  ¤F³,¶Symfony/CS/ErrorsManager.phpº<00>'êWºõ‰™¶Symfony/CS/FileCacheManager.phpT <00>'êWT Symfony/CS/FileRemoval.php6<00>'êW6<00>¶ìö¶Symfony/CS/Finder.php-<00>'êW-ySymfony/CS/FinderInterface.phpg<00>'êWg+0`Symfony/CS/Fixer.phpõ<00>'êWõÙ¦ùz¶&Symfony/CS/FixerFileProcessedEvent.phpb<00>'êWbx¶Í
Symfony/CS/FixerInterface.phpß<00>'êWߥ¾5¶Symfony/CS/LintManager.phpê<00>'êWêDúËöSymfony/CS/StdinFileInfo.phpò<00>'êWòUÀ+*¶#Symfony/CS/Test/IntegrationCase.php<68><00>'êW<C3AA>€«M*Symfony/CS/Test/IntegrationCaseFactory.php&<00>'êW&&]úk¶Symfony/CS/ToolInfo.php;<00>'êW;fªÊʶ!Symfony/CS/UniqueFileIterator.php <00>'êW Ë0‰9¶Symfony/CS/Utils.php`<00>'êW`â~É‘¶LICENSES<00>'êWSöØæ&¶<?php
namespace Symfony\Component\Finder\Comparator;
class Comparator
{
private $target;
private $operator = '==';
public function getTarget()
{
return $this->target;
}
public function setTarget($target)
{
$this->target = $target;
}
public function getOperator()
{
return $this->operator;
}
public function setOperator($operator)
{
if (!$operator) {
$operator = '==';
}
if (!in_array($operator, array('>', '<', '>=', '<=', '==', '!='))) {
throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator));
}
$this->operator = $operator;
}
public function test($test)
{
switch ($this->operator) {
case '>':
return $test > $this->target;
case '>=':
return $test >= $this->target;
case '<':
return $test < $this->target;
case '<=':
return $test <= $this->target;
case '!=':
return $test != $this->target;
}
return $test == $this->target;
}
}
<?php
namespace Symfony\Component\Finder\Comparator;
class DateComparator extends Comparator
{
public function __construct($test)
{
if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) {
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test));
}
try {
$date = new \DateTime($matches[2]);
$target = $date->format('U');
} catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2]));
}
$operator = isset($matches[1]) ? $matches[1] : '==';
if ('since' === $operator || 'after' === $operator) {
$operator = '>';
}
if ('until' === $operator || 'before' === $operator) {
$operator = '<';
}
$this->setOperator($operator);
$this->setTarget($target);
}
}
<?php
namespace Symfony\Component\Finder\Comparator;
class NumberComparator extends Comparator
{
public function __construct($test)
{
if (!preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test));
}
$target = $matches[2];
if (!is_numeric($target)) {
throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target));
}
if (isset($matches[3])) {
switch (strtolower($matches[3])) {
case 'k':
$target *= 1000;
break;
case 'ki':
$target *= 1024;
break;
case 'm':
$target *= 1000000;
break;
case 'mi':
$target *= 1024 * 1024;
break;
case 'g':
$target *= 1000000000;
break;
case 'gi':
$target *= 1024 * 1024 * 1024;
break;
}
}
$this->setTarget($target);
$this->setOperator(isset($matches[1]) ? $matches[1] : '==');
}
}
<?php
namespace Symfony\Component\Finder\Exception;
class AccessDeniedException extends \UnexpectedValueException
{
}
<?php
namespace Symfony\Component\Finder\Exception;
interface ExceptionInterface
{
public function getAdapter();
}
<?php
namespace Symfony\Component\Finder;
use Symfony\Component\Finder\Comparator\DateComparator;
use Symfony\Component\Finder\Comparator\NumberComparator;
use Symfony\Component\Finder\Iterator\CustomFilterIterator;
use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
use Symfony\Component\Finder\Iterator\SortableIterator;
class Finder implements \IteratorAggregate, \Countable
{
const IGNORE_VCS_FILES = 1;
const IGNORE_DOT_FILES = 2;
private $mode = 0;
private $names = array();
private $notNames = array();
private $exclude = array();
private $filters = array();
private $depths = array();
private $sizes = array();
private $followLinks = false;
private $sort = false;
private $ignore = 0;
private $dirs = array();
private $dates = array();
private $iterators = array();
private $contains = array();
private $notContains = array();
private $paths = array();
private $notPaths = array();
private $ignoreUnreadableDirs = false;
private static $vcsPatterns = array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg');
public function __construct()
{
$this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
}
public static function create()
{
return new static();
}
public function directories()
{
$this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
return $this;
}
public function files()
{
$this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
return $this;
}
public function depth($level)
{
$this->depths[] = new Comparator\NumberComparator($level);
return $this;
}
public function date($date)
{
$this->dates[] = new Comparator\DateComparator($date);
return $this;
}
public function name($pattern)
{
$this->names[] = $pattern;
return $this;
}
public function notName($pattern)
{
$this->notNames[] = $pattern;
return $this;
}
public function contains($pattern)
{
$this->contains[] = $pattern;
return $this;
}
public function notContains($pattern)
{
$this->notContains[] = $pattern;
return $this;
}
public function path($pattern)
{
$this->paths[] = $pattern;
return $this;
}
public function notPath($pattern)
{
$this->notPaths[] = $pattern;
return $this;
}
public function size($size)
{
$this->sizes[] = new Comparator\NumberComparator($size);
return $this;
}
public function exclude($dirs)
{
$this->exclude = array_merge($this->exclude, (array) $dirs);
return $this;
}
public function ignoreDotFiles($ignoreDotFiles)
{
if ($ignoreDotFiles) {
$this->ignore |= static::IGNORE_DOT_FILES;
} else {
$this->ignore &= ~static::IGNORE_DOT_FILES;
}
return $this;
}
public function ignoreVCS($ignoreVCS)
{
if ($ignoreVCS) {
$this->ignore |= static::IGNORE_VCS_FILES;
} else {
$this->ignore &= ~static::IGNORE_VCS_FILES;
}
return $this;
}
public static function addVCSPattern($pattern)
{
foreach ((array) $pattern as $p) {
self::$vcsPatterns[] = $p;
}
self::$vcsPatterns = array_unique(self::$vcsPatterns);
}
public function sort(\Closure $closure)
{
$this->sort = $closure;
return $this;
}
public function sortByName()
{
$this->sort = Iterator\SortableIterator::SORT_BY_NAME;
return $this;
}
public function sortByType()
{
$this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
return $this;
}
public function sortByAccessedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
return $this;
}
public function sortByChangedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
return $this;
}
public function sortByModifiedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
return $this;
}
public function filter(\Closure $closure)
{
$this->filters[] = $closure;
return $this;
}
public function followLinks()
{
$this->followLinks = true;
return $this;
}
public function ignoreUnreadableDirs($ignore = true)
{
$this->ignoreUnreadableDirs = (bool) $ignore;
return $this;
}
public function in($dirs)
{
$resolvedDirs = array();
foreach ((array) $dirs as $dir) {
if (is_dir($dir)) {
$resolvedDirs[] = $dir;
} elseif ($glob = glob($dir, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
$resolvedDirs = array_merge($resolvedDirs, $glob);
} else {
throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
}
}
$this->dirs = array_merge($this->dirs, $resolvedDirs);
return $this;
}
public function getIterator()
{
if (0 === count($this->dirs) && 0 === count($this->iterators)) {
throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
}
if (1 === count($this->dirs) && 0 === count($this->iterators)) {
return $this->searchInDirectory($this->dirs[0]);
}
$iterator = new \AppendIterator();
foreach ($this->dirs as $dir) {
$iterator->append($this->searchInDirectory($dir));
}
foreach ($this->iterators as $it) {
$iterator->append($it);
}
return $iterator;
}
public function append($iterator)
{
if ($iterator instanceof \IteratorAggregate) {
$this->iterators[] = $iterator->getIterator();
} elseif ($iterator instanceof \Iterator) {
$this->iterators[] = $iterator;
} elseif ($iterator instanceof \Traversable || is_array($iterator)) {
$it = new \ArrayIterator();
foreach ($iterator as $file) {
$it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
}
$this->iterators[] = $it;
} else {
throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
}
return $this;
}
public function count()
{
return iterator_count($this->getIterator());
}
private function searchInDirectory($dir)
{
if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
$this->exclude = array_merge($this->exclude, self::$vcsPatterns);
}
if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
$this->notPaths[] = '#(^|/)\..+(/|$)#';
}
$minDepth = 0;
$maxDepth = PHP_INT_MAX;
foreach ($this->depths as $comparator) {
switch ($comparator->getOperator()) {
case '>':
$minDepth = $comparator->getTarget() + 1;
break;
case '>=':
$minDepth = $comparator->getTarget();
break;
case '<':
$maxDepth = $comparator->getTarget() - 1;
break;
case '<=':
$maxDepth = $comparator->getTarget();
break;
default:
$minDepth = $maxDepth = $comparator->getTarget();
}
}
$flags = \RecursiveDirectoryIterator::SKIP_DOTS;
if ($this->followLinks) {
$flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
}
$iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
if ($this->exclude) {
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
}
$iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
if ($minDepth > 0 || $maxDepth < PHP_INT_MAX) {
$iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
}
if ($this->mode) {
$iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
}
if ($this->names || $this->notNames) {
$iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
}
if ($this->contains || $this->notContains) {
$iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
}
if ($this->sizes) {
$iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
}
if ($this->dates) {
$iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
}
if ($this->filters) {
$iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
}
if ($this->paths || $this->notPaths) {
$iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
}
if ($this->sort) {
$iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
$iterator = $iteratorAggregate->getIterator();
}
return $iterator;
}
}
<?php
namespace Symfony\Component\Finder;
class Glob
{
public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true, $delimiter = '#')
{
$firstByte = true;
$escaping = false;
$inCurlies = 0;
$regex = '';
$sizeGlob = strlen($glob);
for ($i = 0; $i < $sizeGlob; ++$i) {
$car = $glob[$i];
if ($firstByte) {
if ($strictLeadingDot && '.' !== $car) {
$regex .= '(?=[^\.])';
}
$firstByte = false;
}
if ('/' === $car) {
$firstByte = true;
}
if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
$regex .= "\\$car";
} elseif ('*' === $car) {
$regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
} elseif ('?' === $car) {
$regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
} elseif ('{' === $car) {
$regex .= $escaping ? '\\{' : '(';
if (!$escaping) {
++$inCurlies;
}
} elseif ('}' === $car && $inCurlies) {
$regex .= $escaping ? '}' : ')';
if (!$escaping) {
--$inCurlies;
}
} elseif (',' === $car && $inCurlies) {
$regex .= $escaping ? ',' : '|';
} elseif ('\\' === $car) {
if ($escaping) {
$regex .= '\\\\';
$escaping = false;
} else {
$escaping = true;
}
continue;
} else {
$regex .= $car;
}
$escaping = false;
}
return $delimiter.'^'.$regex.'$'.$delimiter;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class CustomFilterIterator extends FilterIterator
{
private $filters = array();
public function __construct(\Iterator $iterator, array $filters)
{
foreach ($filters as $filter) {
if (!is_callable($filter)) {
throw new \InvalidArgumentException('Invalid PHP callback.');
}
}
$this->filters = $filters;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
foreach ($this->filters as $filter) {
if (false === call_user_func($filter, $fileinfo)) {
return false;
}
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Comparator\DateComparator;
class DateRangeFilterIterator extends FilterIterator
{
private $comparators = array();
public function __construct(\Iterator $iterator, array $comparators)
{
$this->comparators = $comparators;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
if (!file_exists($fileinfo->getRealPath())) {
return false;
}
$filedate = $fileinfo->getMTime();
foreach ($this->comparators as $compare) {
if (!$compare->test($filedate)) {
return false;
}
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class DepthRangeFilterIterator extends FilterIterator
{
private $minDepth = 0;
public function __construct(\RecursiveIteratorIterator $iterator, $minDepth = 0, $maxDepth = PHP_INT_MAX)
{
$this->minDepth = $minDepth;
$iterator->setMaxDepth(PHP_INT_MAX === $maxDepth ? -1 : $maxDepth);
parent::__construct($iterator);
}
public function accept()
{
return $this->getInnerIterator()->getDepth() >= $this->minDepth;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class ExcludeDirectoryFilterIterator extends FilterIterator implements \RecursiveIterator
{
private $iterator;
private $isRecursive;
private $excludedDirs = array();
private $excludedPattern;
public function __construct(\Iterator $iterator, array $directories)
{
$this->iterator = $iterator;
$this->isRecursive = $iterator instanceof \RecursiveIterator;
$patterns = array();
foreach ($directories as $directory) {
if (!$this->isRecursive || false !== strpos($directory, '/')) {
$patterns[] = preg_quote($directory, '#');
} else {
$this->excludedDirs[$directory] = true;
}
}
if ($patterns) {
$this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#';
}
parent::__construct($iterator);
}
public function accept()
{
if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) {
return false;
}
if ($this->excludedPattern) {
$path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
$path = str_replace('\\', '/', $path);
return !preg_match($this->excludedPattern, $path);
}
return true;
}
public function hasChildren()
{
return $this->isRecursive && $this->iterator->hasChildren();
}
public function getChildren()
{
$children = new self($this->iterator->getChildren(), array());
$children->excludedDirs = $this->excludedDirs;
$children->excludedPattern = $this->excludedPattern;
return $children;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class FileTypeFilterIterator extends FilterIterator
{
const ONLY_FILES = 1;
const ONLY_DIRECTORIES = 2;
private $mode;
public function __construct(\Iterator $iterator, $mode)
{
$this->mode = $mode;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) {
return false;
} elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) {
return false;
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class FilecontentFilterIterator extends MultiplePcreFilterIterator
{
public function accept()
{
if (!$this->matchRegexps && !$this->noMatchRegexps) {
return true;
}
$fileinfo = $this->current();
if ($fileinfo->isDir() || !$fileinfo->isReadable()) {
return false;
}
$content = $fileinfo->getContents();
if (!$content) {
return false;
}
return $this->isAccepted($content);
}
protected function toRegex($str)
{
return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Glob;
class FilenameFilterIterator extends MultiplePcreFilterIterator
{
public function accept()
{
return $this->isAccepted($this->current()->getFilename());
}
protected function toRegex($str)
{
return $this->isRegex($str) ? $str : Glob::toRegex($str);
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
abstract class FilterIterator extends \FilterIterator
{
public function rewind()
{
if (PHP_VERSION_ID > 50607 || (PHP_VERSION_ID > 50523 && PHP_VERSION_ID < 50600)) {
parent::rewind();
return;
}
$iterator = $this;
while ($iterator instanceof \OuterIterator) {
$innerIterator = $iterator->getInnerIterator();
if ($innerIterator instanceof RecursiveDirectoryIterator) {
if ($innerIterator->isRewindable()) {
$innerIterator->next();
$innerIterator->rewind();
}
} elseif ($innerIterator instanceof \FilesystemIterator) {
$innerIterator->next();
$innerIterator->rewind();
}
$iterator = $innerIterator;
}
parent::rewind();
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
abstract class MultiplePcreFilterIterator extends FilterIterator
{
protected $matchRegexps = array();
protected $noMatchRegexps = array();
public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
{
foreach ($matchPatterns as $pattern) {
$this->matchRegexps[] = $this->toRegex($pattern);
}
foreach ($noMatchPatterns as $pattern) {
$this->noMatchRegexps[] = $this->toRegex($pattern);
}
parent::__construct($iterator);
}
protected function isAccepted($string)
{
foreach ($this->noMatchRegexps as $regex) {
if (preg_match($regex, $string)) {
return false;
}
}
if ($this->matchRegexps) {
foreach ($this->matchRegexps as $regex) {
if (preg_match($regex, $string)) {
return true;
}
}
return false;
}
return true;
}
protected function isRegex($str)
{
if (preg_match('/^(.{3,}?)[imsxuADU]*$/', $str, $m)) {
$start = substr($m[1], 0, 1);
$end = substr($m[1], -1);
if ($start === $end) {
return !preg_match('/[*?[:alnum:] \\\\]/', $start);
}
foreach (array(array('{', '}'), array('(', ')'), array('[', ']'), array('<', '>')) as $delimiters) {
if ($start === $delimiters[0] && $end === $delimiters[1]) {
return true;
}
}
}
return false;
}
abstract protected function toRegex($str);
}
<?php
namespace Symfony\Component\Finder\Iterator;
class PathFilterIterator extends MultiplePcreFilterIterator
{
public function accept()
{
$filename = $this->current()->getRelativePathname();
if ('\\' === DIRECTORY_SEPARATOR) {
$filename = str_replace('\\', '/', $filename);
}
return $this->isAccepted($filename);
}
protected function toRegex($str)
{
return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\Finder\SplFileInfo;
class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
{
private $ignoreUnreadableDirs;
private $rewindable;
private $rootPath;
private $subPath;
private $directorySeparator = '/';
public function __construct($path, $flags, $ignoreUnreadableDirs = false)
{
if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) {
throw new \RuntimeException('This iterator only support returning current as fileinfo.');
}
parent::__construct($path, $flags);
$this->ignoreUnreadableDirs = $ignoreUnreadableDirs;
$this->rootPath = $path;
if ('/' !== DIRECTORY_SEPARATOR && !($flags & self::UNIX_PATHS)) {
$this->directorySeparator = DIRECTORY_SEPARATOR;
}
}
public function current()
{
if (null === $subPathname = $this->subPath) {
$subPathname = $this->subPath = (string) $this->getSubPath();
}
if ('' !== $subPathname) {
$subPathname .= $this->directorySeparator;
}
$subPathname .= $this->getFilename();
return new SplFileInfo($this->rootPath.$this->directorySeparator.$subPathname, $this->subPath, $subPathname);
}
public function getChildren()
{
try {
$children = parent::getChildren();
if ($children instanceof self) {
$children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
$children->rewindable = &$this->rewindable;
$children->rootPath = $this->rootPath;
}
return $children;
} catch (\UnexpectedValueException $e) {
if ($this->ignoreUnreadableDirs) {
return new \RecursiveArrayIterator(array());
} else {
throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e);
}
}
}
public function rewind()
{
if (false === $this->isRewindable()) {
return;
}
if (PHP_VERSION_ID < 50523 || PHP_VERSION_ID >= 50600 && PHP_VERSION_ID < 50607) {
parent::next();
}
parent::rewind();
}
public function isRewindable()
{
if (null !== $this->rewindable) {
return $this->rewindable;
}
if (false !== $stream = @opendir($this->getPath())) {
$infos = stream_get_meta_data($stream);
closedir($stream);
if ($infos['seekable']) {
return $this->rewindable = true;
}
}
return $this->rewindable = false;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Comparator\NumberComparator;
class SizeRangeFilterIterator extends FilterIterator
{
private $comparators = array();
public function __construct(\Iterator $iterator, array $comparators)
{
$this->comparators = $comparators;
parent::__construct($iterator);
}
public function accept()
{
$fileinfo = $this->current();
if (!$fileinfo->isFile()) {
return true;
}
$filesize = $fileinfo->getSize();
foreach ($this->comparators as $compare) {
if (!$compare->test($filesize)) {
return false;
}
}
return true;
}
}
<?php
namespace Symfony\Component\Finder\Iterator;
class SortableIterator implements \IteratorAggregate
{
const SORT_BY_NAME = 1;
const SORT_BY_TYPE = 2;
const SORT_BY_ACCESSED_TIME = 3;
const SORT_BY_CHANGED_TIME = 4;
const SORT_BY_MODIFIED_TIME = 5;
private $iterator;
private $sort;
public function __construct(\Traversable $iterator, $sort)
{
$this->iterator = $iterator;
if (self::SORT_BY_NAME === $sort) {
$this->sort = function ($a, $b) {
return strcmp($a->getRealpath(), $b->getRealpath());
};
} elseif (self::SORT_BY_TYPE === $sort) {
$this->sort = function ($a, $b) {
if ($a->isDir() && $b->isFile()) {
return -1;
} elseif ($a->isFile() && $b->isDir()) {
return 1;
}
return strcmp($a->getRealpath(), $b->getRealpath());
};
} elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
$this->sort = function ($a, $b) {
return $a->getATime() - $b->getATime();
};
} elseif (self::SORT_BY_CHANGED_TIME === $sort) {
$this->sort = function ($a, $b) {
return $a->getCTime() - $b->getCTime();
};
} elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
$this->sort = function ($a, $b) {
return $a->getMTime() - $b->getMTime();
};
} elseif (is_callable($sort)) {
$this->sort = $sort;
} else {
throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
}
}
public function getIterator()
{
$array = iterator_to_array($this->iterator, true);
uasort($array, $this->sort);
return new \ArrayIterator($array);
}
}
<?php
namespace Symfony\Component\Finder;
class SplFileInfo extends \SplFileInfo
{
private $relativePath;
private $relativePathname;
public function __construct($file, $relativePath, $relativePathname)
{
parent::__construct($file);
$this->relativePath = $relativePath;
$this->relativePathname = $relativePathname;
}
public function getRelativePath()
{
return $this->relativePath;
}
public function getRelativePathname()
{
return $this->relativePathname;
}
public function getContents()
{
$level = error_reporting(0);
$content = file_get_contents($this->getPathname());
error_reporting($level);
if (false === $content) {
$error = error_get_last();
throw new \RuntimeException($error['message']);
}
return $content;
}
}
<?php
namespace Symfony\Component\Process\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process\Exception;
class LogicException extends \LogicException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process\Exception;
use Symfony\Component\Process\Process;
class ProcessFailedException extends RuntimeException
{
private $process;
public function __construct(Process $process)
{
if ($process->isSuccessful()) {
throw new InvalidArgumentException('Expected a failed process, but the given process was successful.');
}
$error = sprintf('The command "%s" failed.'."\n\nExit Code: %s(%s)\n\nWorking directory: %s",
$process->getCommandLine(),
$process->getExitCode(),
$process->getExitCodeText(),
$process->getWorkingDirectory()
);
if (!$process->isOutputDisabled()) {
$error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s",
$process->getOutput(),
$process->getErrorOutput()
);
}
parent::__construct($error);
$this->process = $process;
}
public function getProcess()
{
return $this->process;
}
}
<?php
namespace Symfony\Component\Process\Exception;
use Symfony\Component\Process\Process;
class ProcessTimedOutException extends RuntimeException
{
const TYPE_GENERAL = 1;
const TYPE_IDLE = 2;
private $process;
private $timeoutType;
public function __construct(Process $process, $timeoutType)
{
$this->process = $process;
$this->timeoutType = $timeoutType;
parent::__construct(sprintf(
'The process "%s" exceeded the timeout of %s seconds.',
$process->getCommandLine(),
$this->getExceededTimeout()
));
}
public function getProcess()
{
return $this->process;
}
public function isGeneralTimeout()
{
return $this->timeoutType === self::TYPE_GENERAL;
}
public function isIdleTimeout()
{
return $this->timeoutType === self::TYPE_IDLE;
}
public function getExceededTimeout()
{
switch ($this->timeoutType) {
case self::TYPE_GENERAL:
return $this->process->getTimeout();
case self::TYPE_IDLE:
return $this->process->getIdleTimeout();
default:
throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType));
}
}
}
<?php
namespace Symfony\Component\Process\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Process;
class ExecutableFinder
{
private $suffixes = array('.exe', '.bat', '.cmd', '.com');
public function setSuffixes(array $suffixes)
{
$this->suffixes = $suffixes;
}
public function addSuffix($suffix)
{
$this->suffixes[] = $suffix;
}
public function find($name, $default = null, array $extraDirs = array())
{
if (ini_get('open_basedir')) {
$searchPath = explode(PATH_SEPARATOR, ini_get('open_basedir'));
$dirs = array();
foreach ($searchPath as $path) {
if (@is_dir($path)) {
$dirs[] = $path;
} else {
if (basename($path) == $name && @is_executable($path)) {
return $path;
}
}
}
} else {
$dirs = array_merge(
explode(PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')),
$extraDirs
);
}
$suffixes = array('');
if ('\\' === DIRECTORY_SEPARATOR) {
$pathExt = getenv('PATHEXT');
$suffixes = $pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes;
}
foreach ($suffixes as $suffix) {
foreach ($dirs as $dir) {
if (is_file($file = $dir.DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === DIRECTORY_SEPARATOR || is_executable($file))) {
return $file;
}
}
}
return $default;
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\RuntimeException;
class InputStream implements \IteratorAggregate
{
private $onEmpty = null;
private $input = array();
private $open = true;
public function onEmpty(callable $onEmpty = null)
{
$this->onEmpty = $onEmpty;
}
public function write($input)
{
if (null === $input) {
return;
}
if ($this->isClosed()) {
throw new RuntimeException(sprintf('%s is closed', static::class));
}
$this->input[] = ProcessUtils::validateInput(__METHOD__, $input);
}
public function close()
{
$this->open = false;
}
public function isClosed()
{
return !$this->open;
}
public function getIterator()
{
$this->open = true;
while ($this->open || $this->input) {
if (!$this->input) {
yield '';
continue;
}
$current = array_shift($this->input);
if ($current instanceof \Iterator) {
foreach ($current as $cur) {
yield $cur;
}
} else {
yield $current;
}
if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) {
$this->write($onEmpty($this));
}
}
}
}
<?php
namespace Symfony\Component\Process;
class PhpExecutableFinder
{
private $executableFinder;
public function __construct()
{
$this->executableFinder = new ExecutableFinder();
}
public function find($includeArgs = true)
{
$args = $this->findArguments();
$args = $includeArgs && $args ? ' '.implode(' ', $args) : '';
if (defined('HHVM_VERSION')) {
return (getenv('PHP_BINARY') ?: PHP_BINARY).$args;
}
if (PHP_BINARY && in_array(PHP_SAPI, array('cli', 'cli-server', 'phpdbg')) && is_file(PHP_BINARY)) {
return PHP_BINARY.$args;
}
if ($php = getenv('PHP_PATH')) {
if (!is_executable($php)) {
return false;
}
return $php;
}
if ($php = getenv('PHP_PEAR_PHP_BIN')) {
if (is_executable($php)) {
return $php;
}
}
$dirs = array(PHP_BINDIR);
if ('\\' === DIRECTORY_SEPARATOR) {
$dirs[] = 'C:\xampp\php\\';
}
return $this->executableFinder->find('php', false, $dirs);
}
public function findArguments()
{
$arguments = array();
if (defined('HHVM_VERSION')) {
$arguments[] = '--php';
} elseif ('phpdbg' === PHP_SAPI) {
$arguments[] = '-qrr';
}
return $arguments;
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\RuntimeException;
class PhpProcess extends Process
{
public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = array())
{
$executableFinder = new PhpExecutableFinder();
if (false === $php = $executableFinder->find()) {
$php = null;
}
if ('phpdbg' === PHP_SAPI) {
$file = tempnam(sys_get_temp_dir(), 'dbg');
file_put_contents($file, $script);
register_shutdown_function('unlink', $file);
$php .= ' '.ProcessUtils::escapeArgument($file);
$script = null;
}
if ('\\' !== DIRECTORY_SEPARATOR && null !== $php) {
$php = 'exec '.$php;
}
parent::__construct($php, $cwd, $env, $script, $timeout, $options);
}
public function setPhpBinary($php)
{
$this->setCommandLine($php);
}
public function start(callable $callback = null)
{
if (null === $this->getCommandLine()) {
throw new RuntimeException('Unable to find the PHP executable.');
}
parent::start($callback);
}
}
<?php
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Exception\InvalidArgumentException;
abstract class AbstractPipes implements PipesInterface
{
public $pipes = array();
private $inputBuffer = '';
private $input;
private $blocked = true;
public function __construct($input)
{
if (is_resource($input) || $input instanceof \Iterator) {
$this->input = $input;
} elseif (is_string($input)) {
$this->inputBuffer = $input;
} else {
$this->inputBuffer = (string) $input;
}
}
public function close()
{
foreach ($this->pipes as $pipe) {
fclose($pipe);
}
$this->pipes = array();
}
protected function hasSystemCallBeenInterrupted()
{
$lastError = error_get_last();
return isset($lastError['message']) && false !== stripos($lastError['message'], 'interrupted system call');
}
protected function unblock()
{
if (!$this->blocked) {
return;
}
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, 0);
}
if (is_resource($this->input)) {
stream_set_blocking($this->input, 0);
}
$this->blocked = false;
}
protected function write()
{
if (!isset($this->pipes[0])) {
return;
}
$input = $this->input;
if ($input instanceof \Iterator) {
if (!$input->valid()) {
$input = null;
} elseif (is_resource($input = $input->current())) {
stream_set_blocking($input, 0);
} elseif (!isset($this->inputBuffer[0])) {
if (!is_string($input)) {
if (!is_scalar($input)) {
throw new InvalidArgumentException(sprintf('%s yielded a value of type "%s", but only scalars and stream resources are supported', get_class($this->input), gettype($input)));
}
$input = (string) $input;
}
$this->inputBuffer = $input;
$this->input->next();
$input = null;
} else {
$input = null;
}
}
$r = $e = array();
$w = array($this->pipes[0]);
if (false === $n = @stream_select($r, $w, $e, 0, 0)) {
return;
}
foreach ($w as $stdin) {
if (isset($this->inputBuffer[0])) {
$written = fwrite($stdin, $this->inputBuffer);
$this->inputBuffer = substr($this->inputBuffer, $written);
if (isset($this->inputBuffer[0])) {
return array($this->pipes[0]);
}
}
if ($input) {
for (;;) {
$data = fread($input, self::CHUNK_SIZE);
if (!isset($data[0])) {
break;
}
$written = fwrite($stdin, $data);
$data = substr($data, $written);
if (isset($data[0])) {
$this->inputBuffer = $data;
return array($this->pipes[0]);
}
}
if (feof($input)) {
if ($this->input instanceof \Iterator) {
$this->input->next();
} else {
$this->input = null;
}
}
}
}
if (!isset($this->inputBuffer[0]) && !($this->input instanceof \Iterator ? $this->input->valid() : $this->input)) {
$this->input = null;
fclose($this->pipes[0]);
unset($this->pipes[0]);
} elseif (!$w) {
return array($this->pipes[0]);
}
}
}
<?php
namespace Symfony\Component\Process\Pipes;
interface PipesInterface
{
const CHUNK_SIZE = 16384;
public function getDescriptors();
public function getFiles();
public function readAndWrite($blocking, $close = false);
public function areOpen();
public function haveReadSupport();
public function close();
}
<?php
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Process;
class UnixPipes extends AbstractPipes
{
private $ttyMode;
private $ptyMode;
private $haveReadSupport;
public function __construct($ttyMode, $ptyMode, $input, $haveReadSupport)
{
$this->ttyMode = (bool) $ttyMode;
$this->ptyMode = (bool) $ptyMode;
$this->haveReadSupport = (bool) $haveReadSupport;
parent::__construct($input);
}
public function __destruct()
{
$this->close();
}
public function getDescriptors()
{
if (!$this->haveReadSupport) {
$nullstream = fopen('/dev/null', 'c');
return array(
array('pipe', 'r'),
$nullstream,
$nullstream,
);
}
if ($this->ttyMode) {
return array(
array('file', '/dev/tty', 'r'),
array('file', '/dev/tty', 'w'),
array('file', '/dev/tty', 'w'),
);
}
if ($this->ptyMode && Process::isPtySupported()) {
return array(
array('pty'),
array('pty'),
array('pty'),
);
}
return array(
array('pipe', 'r'),
array('pipe', 'w'),
array('pipe', 'w'),
);
}
public function getFiles()
{
return array();
}
public function readAndWrite($blocking, $close = false)
{
$this->unblock();
$w = $this->write();
$read = $e = array();
$r = $this->pipes;
unset($r[0]);
if (($r || $w) && false === $n = @stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
if (!$this->hasSystemCallBeenInterrupted()) {
$this->pipes = array();
}
return $read;
}
foreach ($r as $pipe) {
$read[$type = array_search($pipe, $this->pipes, true)] = '';
do {
$data = fread($pipe, self::CHUNK_SIZE);
$read[$type] .= $data;
} while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1])));
if (!isset($read[$type][0])) {
unset($read[$type]);
}
if ($close && feof($pipe)) {
fclose($pipe);
unset($this->pipes[$type]);
}
}
return $read;
}
public function haveReadSupport()
{
return $this->haveReadSupport;
}
public function areOpen()
{
return (bool) $this->pipes;
}
}
<?php
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\RuntimeException;
class WindowsPipes extends AbstractPipes
{
private $files = array();
private $fileHandles = array();
private $readBytes = array(
Process::STDOUT => 0,
Process::STDERR => 0,
);
private $haveReadSupport;
public function __construct($input, $haveReadSupport)
{
$this->haveReadSupport = (bool) $haveReadSupport;
if ($this->haveReadSupport) {
$pipes = array(
Process::STDOUT => Process::OUT,
Process::STDERR => Process::ERR,
);
$tmpCheck = false;
$tmpDir = sys_get_temp_dir();
$lastError = 'unknown reason';
set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; });
for ($i = 0;; ++$i) {
foreach ($pipes as $pipe => $name) {
$file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name);
if (file_exists($file) && !unlink($file)) {
continue 2;
}
$h = fopen($file, 'xb');
if (!$h) {
$error = $lastError;
if ($tmpCheck || $tmpCheck = unlink(tempnam(false, 'sf_check_'))) {
continue;
}
restore_error_handler();
throw new RuntimeException(sprintf('A temporary file could not be opened to write the process output: %s', $error));
}
if (!$h || !$this->fileHandles[$pipe] = fopen($file, 'rb')) {
continue 2;
}
if (isset($this->files[$pipe])) {
unlink($this->files[$pipe]);
}
$this->files[$pipe] = $file;
}
break;
}
restore_error_handler();
}
parent::__construct($input);
}
public function __destruct()
{
$this->close();
$this->removeFiles();
}
public function getDescriptors()
{
if (!$this->haveReadSupport) {
$nullstream = fopen('NUL', 'c');
return array(
array('pipe', 'r'),
$nullstream,
$nullstream,
);
}
return array(
array('pipe', 'r'),
array('file', 'NUL', 'w'),
array('file', 'NUL', 'w'),
);
}
public function getFiles()
{
return $this->files;
}
public function readAndWrite($blocking, $close = false)
{
$this->unblock();
$w = $this->write();
$read = $r = $e = array();
if ($blocking) {
if ($w) {
@stream_select($r, $w, $e, 0, Process::TIMEOUT_PRECISION * 1E6);
} elseif ($this->fileHandles) {
usleep(Process::TIMEOUT_PRECISION * 1E6);
}
}
foreach ($this->fileHandles as $type => $fileHandle) {
$data = stream_get_contents($fileHandle, -1, $this->readBytes[$type]);
if (isset($data[0])) {
$this->readBytes[$type] += strlen($data);
$read[$type] = $data;
}
if ($close) {
fclose($fileHandle);
unset($this->fileHandles[$type]);
}
}
return $read;
}
public function haveReadSupport()
{
return $this->haveReadSupport;
}
public function areOpen()
{
return $this->pipes && $this->fileHandles;
}
public function close()
{
parent::close();
foreach ($this->fileHandles as $handle) {
fclose($handle);
}
$this->fileHandles = array();
}
private function removeFiles()
{
foreach ($this->files as $filename) {
if (file_exists($filename)) {
@unlink($filename);
}
}
$this->files = array();
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Exception\LogicException;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\Pipes\PipesInterface;
use Symfony\Component\Process\Pipes\UnixPipes;
use Symfony\Component\Process\Pipes\WindowsPipes;
class Process implements \IteratorAggregate
{
const ERR = 'err';
const OUT = 'out';
const STATUS_READY = 'ready';
const STATUS_STARTED = 'started';
const STATUS_TERMINATED = 'terminated';
const STDIN = 0;
const STDOUT = 1;
const STDERR = 2;
const TIMEOUT_PRECISION = 0.2;
const ITER_NON_BLOCKING = 1;
const ITER_KEEP_OUTPUT = 2;
const ITER_SKIP_OUT = 4;
const ITER_SKIP_ERR = 8;
private $callback;
private $hasCallback = false;
private $commandline;
private $cwd;
private $env;
private $input;
private $starttime;
private $lastOutputTime;
private $timeout;
private $idleTimeout;
private $options;
private $exitcode;
private $fallbackStatus = array();
private $processInformation;
private $outputDisabled = false;
private $stdout;
private $stderr;
private $enhanceWindowsCompatibility = true;
private $enhanceSigchildCompatibility;
private $process;
private $status = self::STATUS_READY;
private $incrementalOutputOffset = 0;
private $incrementalErrorOutputOffset = 0;
private $tty;
private $pty;
private $useFileHandles = false;
private $processPipes;
private $latestSignal;
private static $sigchild;
public static $exitCodes = array(
0 => 'OK',
1 => 'General error',
2 => 'Misuse of shell builtins',
126 => 'Invoked command cannot execute',
127 => 'Command not found',
128 => 'Invalid exit argument',
129 => 'Hangup',
130 => 'Interrupt',
131 => 'Quit and dump core',
132 => 'Illegal instruction',
133 => 'Trace/breakpoint trap',
134 => 'Process aborted',
135 => 'Bus error: "access to undefined portion of memory object"',
136 => 'Floating point exception: "erroneous arithmetic operation"',
137 => 'Kill (terminate immediately)',
138 => 'User-defined 1',
139 => 'Segmentation violation',
140 => 'User-defined 2',
141 => 'Write to pipe with no one reading',
142 => 'Signal raised by alarm',
143 => 'Termination (request to terminate)',
145 => 'Child process terminated, stopped (or continued*)',
146 => 'Continue if stopped',
147 => 'Stop executing temporarily',
148 => 'Terminal stop signal',
149 => 'Background process attempting to read from tty ("in")',
150 => 'Background process attempting to write to tty ("out")',
151 => 'Urgent data available on socket',
152 => 'CPU time limit exceeded',
153 => 'File size limit exceeded',
154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
155 => 'Profiling timer expired',
157 => 'Pollable event',
159 => 'Bad syscall',
);
public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
{
if (!function_exists('proc_open')) {
throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
}
$this->commandline = $commandline;
$this->cwd = $cwd;
if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
$this->cwd = getcwd();
}
if (null !== $env) {
$this->setEnv($env);
}
$this->setInput($input);
$this->setTimeout($timeout);
$this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
$this->pty = false;
$this->enhanceWindowsCompatibility = true;
$this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
$this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
}
public function __destruct()
{
$this->stop(0);
}
public function __clone()
{
$this->resetProcessData();
}
public function run($callback = null)
{
$this->start($callback);
return $this->wait();
}
public function mustRun(callable $callback = null)
{
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
if (0 !== $this->run($callback)) {
throw new ProcessFailedException($this);
}
return $this;
}
public function start(callable $callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}
$this->resetProcessData();
$this->starttime = $this->lastOutputTime = microtime(true);
$this->callback = $this->buildCallback($callback);
$this->hasCallback = null !== $callback;
$descriptors = $this->getDescriptors();
$commandline = $this->commandline;
if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
$commandline = 'cmd /V:ON /E:ON /D /C "('.$commandline.')';
foreach ($this->processPipes->getFiles() as $offset => $filename) {
$commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
}
$commandline .= '"';
if (!isset($this->options['bypass_shell'])) {
$this->options['bypass_shell'] = true;
}
} elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$descriptors[3] = array('pipe', 'w');
$commandline = '{ ('.$this->commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
$commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
$ptsWorkaround = fopen(__FILE__, 'r');
}
$this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
if (!is_resource($this->process)) {
throw new RuntimeException('Unable to launch a new process.');
}
$this->status = self::STATUS_STARTED;
if (isset($descriptors[3])) {
$this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
}
if ($this->tty) {
return;
}
$this->updateStatus(false);
$this->checkTimeout();
}
public function restart(callable $callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}
$process = clone $this;
$process->start($callback);
return $process;
}
public function wait(callable $callback = null)
{
$this->requireProcessIsStarted(__FUNCTION__);
$this->updateStatus(false);
if (null !== $callback) {
if (!$this->processPipes->haveReadSupport()) {
$this->stop(0);
throw new \LogicException('Pass the callback to the Process:start method or enableOutput to use a callback with Process::wait');
}
$this->callback = $this->buildCallback($callback);
}
do {
$this->checkTimeout();
$running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$this->readPipes($running, '\\' !== DIRECTORY_SEPARATOR || !$running);
} while ($running);
while ($this->isRunning()) {
usleep(1000);
}
if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
}
return $this->exitcode;
}
public function getPid()
{
return $this->isRunning() ? $this->processInformation['pid'] : null;
}
public function signal($signal)
{
$this->doSignal($signal, true);
return $this;
}
public function disableOutput()
{
if ($this->isRunning()) {
throw new RuntimeException('Disabling output while the process is running is not possible.');
}
if (null !== $this->idleTimeout) {
throw new LogicException('Output can not be disabled while an idle timeout is set.');
}
$this->outputDisabled = true;
return $this;
}
public function enableOutput()
{
if ($this->isRunning()) {
throw new RuntimeException('Enabling output while the process is running is not possible.');
}
$this->outputDisabled = false;
return $this;
}
public function isOutputDisabled()
{
return $this->outputDisabled;
}
public function getOutput()
{
$this->readPipesForOutput(__FUNCTION__);
if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
return '';
}
return $ret;
}
public function getIncrementalOutput()
{
$this->readPipesForOutput(__FUNCTION__);
$latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
$this->incrementalOutputOffset = ftell($this->stdout);
if (false === $latest) {
return '';
}
return $latest;
}
public function getIterator($flags = 0)
{
$this->readPipesForOutput(__FUNCTION__, false);
$clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
$blocking = !(self::ITER_NON_BLOCKING & $flags);
$yieldOut = !(self::ITER_SKIP_OUT & $flags);
$yieldErr = !(self::ITER_SKIP_ERR & $flags);
while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
if ($yieldOut) {
$out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
if (isset($out[0])) {
if ($clearOutput) {
$this->clearOutput();
} else {
$this->incrementalOutputOffset = ftell($this->stdout);
}
yield self::OUT => $out;
}
}
if ($yieldErr) {
$err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
if (isset($err[0])) {
if ($clearOutput) {
$this->clearErrorOutput();
} else {
$this->incrementalErrorOutputOffset = ftell($this->stderr);
}
yield self::ERR => $err;
}
}
if (!$blocking && !isset($out[0]) && !isset($err[0])) {
yield self::OUT => '';
}
$this->readPipesForOutput(__FUNCTION__, $blocking);
}
}
public function clearOutput()
{
ftruncate($this->stdout, 0);
fseek($this->stdout, 0);
$this->incrementalOutputOffset = 0;
return $this;
}
public function getErrorOutput()
{
$this->readPipesForOutput(__FUNCTION__);
if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
return '';
}
return $ret;
}
public function getIncrementalErrorOutput()
{
$this->readPipesForOutput(__FUNCTION__);
$latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
$this->incrementalErrorOutputOffset = ftell($this->stderr);
if (false === $latest) {
return '';
}
return $latest;
}
public function clearErrorOutput()
{
ftruncate($this->stderr, 0);
fseek($this->stderr, 0);
$this->incrementalErrorOutputOffset = 0;
return $this;
}
public function getExitCode()
{
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
$this->updateStatus(false);
return $this->exitcode;
}
public function getExitCodeText()
{
if (null === $exitcode = $this->getExitCode()) {
return;
}
return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
}
public function isSuccessful()
{
return 0 === $this->getExitCode();
}
public function hasBeenSignaled()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
return $this->processInformation['signaled'];
}
public function getTermSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if ($this->isSigchildEnabled() && (!$this->enhanceSigchildCompatibility || -1 === $this->processInformation['termsig'])) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
return $this->processInformation['termsig'];
}
public function hasBeenStopped()
{
$this->requireProcessIsTerminated(__FUNCTION__);
return $this->processInformation['stopped'];
}
public function getStopSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);
return $this->processInformation['stopsig'];
}
public function isRunning()
{
if (self::STATUS_STARTED !== $this->status) {
return false;
}
$this->updateStatus(false);
return $this->processInformation['running'];
}
public function isStarted()
{
return $this->status != self::STATUS_READY;
}
public function isTerminated()
{
$this->updateStatus(false);
return $this->status == self::STATUS_TERMINATED;
}
public function getStatus()
{
$this->updateStatus(false);
return $this->status;
}
public function stop($timeout = 10, $signal = null)
{
$timeoutMicro = microtime(true) + $timeout;
if ($this->isRunning()) {
$this->doSignal(15, false);
do {
usleep(1000);
} while ($this->isRunning() && microtime(true) < $timeoutMicro);
if ($this->isRunning()) {
$this->doSignal($signal ?: 9, false);
}
}
if ($this->isRunning()) {
if (isset($this->fallbackStatus['pid'])) {
unset($this->fallbackStatus['pid']);
return $this->stop(0, $signal);
}
$this->close();
}
return $this->exitcode;
}
public function addOutput($line)
{
$this->lastOutputTime = microtime(true);
fseek($this->stdout, 0, SEEK_END);
fwrite($this->stdout, $line);
fseek($this->stdout, $this->incrementalOutputOffset);
}
public function addErrorOutput($line)
{
$this->lastOutputTime = microtime(true);
fseek($this->stderr, 0, SEEK_END);
fwrite($this->stderr, $line);
fseek($this->stderr, $this->incrementalErrorOutputOffset);
}
public function getCommandLine()
{
return $this->commandline;
}
public function setCommandLine($commandline)
{
$this->commandline = $commandline;
return $this;
}
public function getTimeout()
{
return $this->timeout;
}
public function getIdleTimeout()
{
return $this->idleTimeout;
}
public function setTimeout($timeout)
{
$this->timeout = $this->validateTimeout($timeout);
return $this;
}
public function setIdleTimeout($timeout)
{
if (null !== $timeout && $this->outputDisabled) {
throw new LogicException('Idle timeout can not be set while the output is disabled.');
}
$this->idleTimeout = $this->validateTimeout($timeout);
return $this;
}
public function setTty($tty)
{
if ('\\' === DIRECTORY_SEPARATOR && $tty) {
throw new RuntimeException('TTY mode is not supported on Windows platform.');
}
if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
throw new RuntimeException('TTY mode requires /dev/tty to be readable.');
}
$this->tty = (bool) $tty;
return $this;
}
public function isTty()
{
return $this->tty;
}
public function setPty($bool)
{
$this->pty = (bool) $bool;
return $this;
}
public function isPty()
{
return $this->pty;
}
public function getWorkingDirectory()
{
if (null === $this->cwd) {
return getcwd() ?: null;
}
return $this->cwd;
}
public function setWorkingDirectory($cwd)
{
$this->cwd = $cwd;
return $this;
}
public function getEnv()
{
return $this->env;
}
public function setEnv(array $env)
{
$env = array_filter($env, function ($value) {
return !is_array($value);
});
$this->env = array();
foreach ($env as $key => $value) {
$this->env[$key] = (string) $value;
}
return $this;
}
public function getInput()
{
return $this->input;
}
public function setInput($input)
{
if ($this->isRunning()) {
throw new LogicException('Input can not be set while the process is running.');
}
$this->input = ProcessUtils::validateInput(__METHOD__, $input);
return $this;
}
public function getOptions()
{
return $this->options;
}
public function setOptions(array $options)
{
$this->options = $options;
return $this;
}
public function getEnhanceWindowsCompatibility()
{
return $this->enhanceWindowsCompatibility;
}
public function setEnhanceWindowsCompatibility($enhance)
{
$this->enhanceWindowsCompatibility = (bool) $enhance;
return $this;
}
public function getEnhanceSigchildCompatibility()
{
return $this->enhanceSigchildCompatibility;
}
public function setEnhanceSigchildCompatibility($enhance)
{
$this->enhanceSigchildCompatibility = (bool) $enhance;
return $this;
}
public function checkTimeout()
{
if ($this->status !== self::STATUS_STARTED) {
return;
}
if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
$this->stop(0);
throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
}
if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
$this->stop(0);
throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
}
}
public static function isPtySupported()
{
static $result;
if (null !== $result) {
return $result;
}
if ('\\' === DIRECTORY_SEPARATOR) {
return $result = false;
}
return $result = (bool) @proc_open('echo 1', array(array('pty'), array('pty'), array('pty')), $pipes);
}
private function getDescriptors()
{
if ($this->input instanceof \Iterator) {
$this->input->rewind();
}
if ('\\' === DIRECTORY_SEPARATOR) {
$this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
} else {
$this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
}
return $this->processPipes->getDescriptors();
}
protected function buildCallback(callable $callback = null)
{
if ($this->outputDisabled) {
return function ($type, $data) use ($callback) {
if (null !== $callback) {
call_user_func($callback, $type, $data);
}
};
}
$out = self::OUT;
return function ($type, $data) use ($callback, $out) {
if ($out == $type) {
$this->addOutput($data);
} else {
$this->addErrorOutput($data);
}
if (null !== $callback) {
call_user_func($callback, $type, $data);
}
};
}
protected function updateStatus($blocking)
{
if (self::STATUS_STARTED !== $this->status) {
return;
}
$this->processInformation = proc_get_status($this->process);
$running = $this->processInformation['running'];
$this->readPipes($running && $blocking, '\\' !== DIRECTORY_SEPARATOR || !$running);
if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$this->processInformation = $this->fallbackStatus + $this->processInformation;
}
if (!$running) {
$this->close();
}
}
protected function isSigchildEnabled()
{
if (null !== self::$sigchild) {
return self::$sigchild;
}
if (!function_exists('phpinfo') || defined('HHVM_VERSION')) {
return self::$sigchild = false;
}
ob_start();
phpinfo(INFO_GENERAL);
return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
}
private function readPipesForOutput($caller, $blocking = false)
{
if ($this->outputDisabled) {
throw new LogicException('Output has been disabled.');
}
$this->requireProcessIsStarted($caller);
$this->updateStatus($blocking);
}
private function validateTimeout($timeout)
{
$timeout = (float) $timeout;
if (0.0 === $timeout) {
$timeout = null;
} elseif ($timeout < 0) {
throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
}
return $timeout;
}
private function readPipes($blocking, $close)
{
$result = $this->processPipes->readAndWrite($blocking, $close);
$callback = $this->callback;
foreach ($result as $type => $data) {
if (3 !== $type) {
$callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
} elseif (!isset($this->fallbackStatus['signaled'])) {
$this->fallbackStatus['exitcode'] = (int) $data;
}
}
}
private function close()
{
$this->processPipes->close();
if (is_resource($this->process)) {
proc_close($this->process);
}
$this->exitcode = $this->processInformation['exitcode'];
$this->status = self::STATUS_TERMINATED;
if (-1 === $this->exitcode) {
if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
$this->exitcode = 128 + $this->processInformation['termsig'];
} elseif ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$this->processInformation['signaled'] = true;
$this->processInformation['termsig'] = -1;
}
}
$this->callback = null;
return $this->exitcode;
}
private function resetProcessData()
{
$this->starttime = null;
$this->callback = null;
$this->exitcode = null;
$this->fallbackStatus = array();
$this->processInformation = null;
$this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
$this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
$this->process = null;
$this->latestSignal = null;
$this->status = self::STATUS_READY;
$this->incrementalOutputOffset = 0;
$this->incrementalErrorOutputOffset = 0;
}
private function doSignal($signal, $throwException)
{
if (null === $pid = $this->getPid()) {
if ($throwException) {
throw new LogicException('Can not send signal on a non running process.');
}
return false;
}
if ('\\' === DIRECTORY_SEPARATOR) {
exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
if ($exitCode && $this->isRunning()) {
if ($throwException) {
throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
}
return false;
}
} else {
if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) {
$ok = @proc_terminate($this->process, $signal);
} elseif (function_exists('posix_kill')) {
$ok = @posix_kill($pid, $signal);
} elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) {
$ok = false === fgets($pipes[2]);
}
if (!$ok) {
if ($throwException) {
throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
}
return false;
}
}
$this->latestSignal = (int) $signal;
$this->fallbackStatus['signaled'] = true;
$this->fallbackStatus['exitcode'] = -1;
$this->fallbackStatus['termsig'] = $this->latestSignal;
return true;
}
private function requireProcessIsStarted($functionName)
{
if (!$this->isStarted()) {
throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
}
}
private function requireProcessIsTerminated($functionName)
{
if (!$this->isTerminated()) {
throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
}
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Exception\LogicException;
class ProcessBuilder
{
private $arguments;
private $cwd;
private $env = array();
private $input;
private $timeout = 60;
private $options = array();
private $inheritEnv = true;
private $prefix = array();
private $outputDisabled = false;
public function __construct(array $arguments = array())
{
$this->arguments = $arguments;
}
public static function create(array $arguments = array())
{
return new static($arguments);
}
public function add($argument)
{
$this->arguments[] = $argument;
return $this;
}
public function setPrefix($prefix)
{
$this->prefix = is_array($prefix) ? $prefix : array($prefix);
return $this;
}
public function setArguments(array $arguments)
{
$this->arguments = $arguments;
return $this;
}
public function setWorkingDirectory($cwd)
{
$this->cwd = $cwd;
return $this;
}
public function inheritEnvironmentVariables($inheritEnv = true)
{
$this->inheritEnv = $inheritEnv;
return $this;
}
public function setEnv($name, $value)
{
$this->env[$name] = $value;
return $this;
}
public function addEnvironmentVariables(array $variables)
{
$this->env = array_replace($this->env, $variables);
return $this;
}
public function setInput($input)
{
$this->input = ProcessUtils::validateInput(__METHOD__, $input);
return $this;
}
public function setTimeout($timeout)
{
if (null === $timeout) {
$this->timeout = null;
return $this;
}
$timeout = (float) $timeout;
if ($timeout < 0) {
throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
}
$this->timeout = $timeout;
return $this;
}
public function setOption($name, $value)
{
$this->options[$name] = $value;
return $this;
}
public function disableOutput()
{
$this->outputDisabled = true;
return $this;
}
public function enableOutput()
{
$this->outputDisabled = false;
return $this;
}
public function getProcess()
{
if (0 === count($this->prefix) && 0 === count($this->arguments)) {
throw new LogicException('You must add() command arguments before calling getProcess().');
}
$options = $this->options;
$arguments = array_merge($this->prefix, $this->arguments);
$script = implode(' ', array_map(array(__NAMESPACE__.'\\ProcessUtils', 'escapeArgument'), $arguments));
if ($this->inheritEnv) {
$env = array_replace($_ENV, $_SERVER, $this->env);
} else {
$env = $this->env;
}
$process = new Process($script, $this->cwd, $env, $this->input, $this->timeout, $options);
if ($this->outputDisabled) {
$process->disableOutput();
}
return $process;
}
}
<?php
namespace Symfony\Component\Process;
use Symfony\Component\Process\Exception\InvalidArgumentException;
class ProcessUtils
{
private function __construct()
{
}
public static function escapeArgument($argument)
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('' === $argument) {
return escapeshellarg($argument);
}
$escapedArgument = '';
$quote = false;
foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
if ('"' === $part) {
$escapedArgument .= '\\"';
} elseif (self::isSurroundedBy($part, '%')) {
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
} else {
if ('\\' === substr($part, -1)) {
$part .= '\\';
}
$quote = true;
$escapedArgument .= $part;
}
}
if ($quote) {
$escapedArgument = '"'.$escapedArgument.'"';
}
return $escapedArgument;
}
return escapeshellarg($argument);
}
public static function validateInput($caller, $input)
{
if (null !== $input) {
if (is_resource($input)) {
return $input;
}
if (is_string($input)) {
return $input;
}
if (is_scalar($input)) {
return (string) $input;
}
if ($input instanceof Process) {
return $input->getIterator($input::ITER_SKIP_ERR);
}
if ($input instanceof \Iterator) {
return $input;
}
if ($input instanceof \Traversable) {
return new \IteratorIterator($input);
}
throw new InvalidArgumentException(sprintf('%s only accepts strings, Traversable objects or stream resources.', $caller));
}
return $input;
}
private static function isSurroundedBy($arg, $char)
{
return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
}
}
<?php
namespace Symfony\Component\Yaml;
class Dumper
{
protected $indentation;
public function __construct($indentation = 4)
{
if ($indentation < 1) {
throw new \InvalidArgumentException('The indentation must be greater than zero.');
}
$this->indentation = $indentation;
}
public function setIndentation($num)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 3.1 and will be removed in 4.0. Pass the indentation to the constructor instead.', E_USER_DEPRECATED);
$this->indentation = (int) $num;
}
public function dump($input, $inline = 0, $indent = 0, $flags = 0)
{
if (is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (func_num_args() >= 5) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(4)) {
$flags |= Yaml::DUMP_OBJECT;
}
}
$output = '';
$prefix = $indent ? str_repeat(' ', $indent) : '';
if ($inline <= 0 || !is_array($input) || empty($input)) {
$output .= $prefix.Inline::dump($input, $flags);
} else {
$isAHash = Inline::isHash($input);
foreach ($input as $key => $value) {
if ($inline > 1 && Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && is_string($value) && false !== strpos($value, "\n")) {
$output .= sprintf("%s%s%s |\n", $prefix, $isAHash ? Inline::dump($key, $flags).':' : '-', '');
foreach (preg_split('/\n|\r\n/', $value) as $row) {
$output .= sprintf("%s%s%s\n", $prefix, str_repeat(' ', $this->indentation), $row);
}
continue;
}
$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
$output .= sprintf('%s%s%s%s',
$prefix,
$isAHash ? Inline::dump($key, $flags).':' : '-',
$willBeInlined ? ' ' : "\n",
$this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $flags)
).($willBeInlined ? "\n" : '');
}
}
return $output;
}
}
<?php
namespace Symfony\Component\Yaml;
class Escaper
{
const REGEX_CHARACTER_TO_ESCAPE = "[\\x00-\\x1f]|\xc2\x85|\xc2\xa0|\xe2\x80\xa8|\xe2\x80\xa9";
private static $escapees = array('\\', '\\\\', '\\"', '"',
"\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
"\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f",
"\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
"\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f",
"\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9");
private static $escaped = array('\\\\', '\\"', '\\\\', '\\"',
'\\0', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\a',
'\\b', '\\t', '\\n', '\\v', '\\f', '\\r', '\\x0e', '\\x0f',
'\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17',
'\\x18', '\\x19', '\\x1a', '\\e', '\\x1c', '\\x1d', '\\x1e', '\\x1f',
'\\N', '\\_', '\\L', '\\P');
public static function requiresDoubleQuoting($value)
{
return preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value);
}
public static function escapeWithDoubleQuotes($value)
{
return sprintf('"%s"', str_replace(self::$escapees, self::$escaped, $value));
}
public static function requiresSingleQuoting($value)
{
if (in_array(strtolower($value), array('null', '~', 'true', 'false', 'y', 'n', 'yes', 'no', 'on', 'off'))) {
return true;
}
return preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ \- ? | < > = ! % @ ` ]/x', $value);
}
public static function escapeWithSingleQuotes($value)
{
return sprintf("'%s'", str_replace('\'', '\'\'', $value));
}
}
<?php
namespace Symfony\Component\Yaml\Exception;
class DumpException extends RuntimeException
{
}
<?php
namespace Symfony\Component\Yaml\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Yaml\Exception;
class ParseException extends RuntimeException
{
private $parsedFile;
private $parsedLine;
private $snippet;
private $rawMessage;
public function __construct($message, $parsedLine = -1, $snippet = null, $parsedFile = null, \Exception $previous = null)
{
$this->parsedFile = $parsedFile;
$this->parsedLine = $parsedLine;
$this->snippet = $snippet;
$this->rawMessage = $message;
$this->updateRepr();
parent::__construct($this->message, 0, $previous);
}
public function getSnippet()
{
return $this->snippet;
}
public function setSnippet($snippet)
{
$this->snippet = $snippet;
$this->updateRepr();
}
public function getParsedFile()
{
return $this->parsedFile;
}
public function setParsedFile($parsedFile)
{
$this->parsedFile = $parsedFile;
$this->updateRepr();
}
public function getParsedLine()
{
return $this->parsedLine;
}
public function setParsedLine($parsedLine)
{
$this->parsedLine = $parsedLine;
$this->updateRepr();
}
private function updateRepr()
{
$this->message = $this->rawMessage;
$dot = false;
if ('.' === substr($this->message, -1)) {
$this->message = substr($this->message, 0, -1);
$dot = true;
}
if (null !== $this->parsedFile) {
$this->message .= sprintf(' in %s', json_encode($this->parsedFile, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}
if ($this->parsedLine >= 0) {
$this->message .= sprintf(' at line %d', $this->parsedLine);
}
if ($this->snippet) {
$this->message .= sprintf(' (near "%s")', $this->snippet);
}
if ($dot) {
$this->message .= '.';
}
}
}
<?php
namespace Symfony\Component\Yaml\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Exception\DumpException;
class Inline
{
const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')';
private static $exceptionOnInvalidType = false;
private static $objectSupport = false;
private static $objectForMap = false;
public static function parse($value, $flags = 0, $references = array())
{
if (is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (func_num_args() >= 3 && !is_array($references)) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if ($references) {
$flags |= Yaml::PARSE_OBJECT;
}
if (func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= Yaml::PARSE_OBJECT_FOR_MAP;
}
}
if (func_num_args() >= 5) {
$references = func_get_arg(4);
} else {
$references = array();
}
}
self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags);
$value = trim($value);
if ('' === $value) {
return '';
}
if (2 & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
}
$i = 0;
switch ($value[0]) {
case '[':
$result = self::parseSequence($value, $flags, $i, $references);
++$i;
break;
case '{':
$result = self::parseMapping($value, $flags, $i, $references);
++$i;
break;
default:
$result = self::parseScalar($value, $flags, null, array('"', "'"), $i, true, $references);
}
if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
}
if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
return $result;
}
public static function dump($value, $flags = 0)
{
if (is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (func_num_args() >= 3) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(2)) {
$flags |= Yaml::DUMP_OBJECT;
}
}
switch (true) {
case is_resource($value):
if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
}
return 'null';
case $value instanceof \DateTimeInterface:
return $value->format('c');
case is_object($value):
if (Yaml::DUMP_OBJECT & $flags) {
return '!php/object:'.serialize($value);
}
if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
return self::dumpArray((array) $value, $flags);
}
if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
throw new DumpException('Object support when dumping a YAML file has been disabled.');
}
return 'null';
case is_array($value):
return self::dumpArray($value, $flags);
case null === $value:
return 'null';
case true === $value:
return 'true';
case false === $value:
return 'false';
case ctype_digit($value):
return is_string($value) ? "'$value'" : (int) $value;
case is_numeric($value):
$locale = setlocale(LC_NUMERIC, 0);
if (false !== $locale) {
setlocale(LC_NUMERIC, 'C');
}
if (is_float($value)) {
$repr = (string) $value;
if (is_infinite($value)) {
$repr = str_ireplace('INF', '.Inf', $repr);
} elseif (floor($value) == $value && $repr == $value) {
$repr = '!!float '.$repr;
}
} else {
$repr = is_string($value) ? "'$value'" : (string) $value;
}
if (false !== $locale) {
setlocale(LC_NUMERIC, $locale);
}
return $repr;
case '' == $value:
return "''";
case self::isBinaryString($value):
return '!!binary '.base64_encode($value);
case Escaper::requiresDoubleQuoting($value):
return Escaper::escapeWithDoubleQuotes($value);
case Escaper::requiresSingleQuoting($value):
case preg_match(self::getHexRegex(), $value):
case preg_match(self::getTimestampRegex(), $value):
return Escaper::escapeWithSingleQuotes($value);
default:
return $value;
}
}
public static function isHash(array $value)
{
$expectedKey = 0;
foreach ($value as $key => $val) {
if ($key !== $expectedKey++) {
return true;
}
}
return false;
}
private static function dumpArray($value, $flags)
{
if ($value && !self::isHash($value)) {
$output = array();
foreach ($value as $val) {
$output[] = self::dump($val, $flags);
}
return sprintf('[%s]', implode(', ', $output));
}
$output = array();
foreach ($value as $key => $val) {
$output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
}
return sprintf('{ %s }', implode(', ', $output));
}
public static function parseScalar($scalar, $flags = 0, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
{
if (in_array($scalar[$i], $stringDelimiters)) {
$output = self::parseQuotedScalar($scalar, $i);
if (null !== $delimiters) {
$tmp = ltrim(substr($scalar, $i), ' ');
if (!in_array($tmp[0], $delimiters)) {
throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
}
}
} else {
if (!$delimiters) {
$output = substr($scalar, $i);
$i += strlen($output);
if (preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) {
$output = substr($output, 0, $match[0][1]);
}
} elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
$output = $match[1];
$i += strlen($output);
} else {
throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar));
}
if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) {
throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]));
}
if ($output && '%' === $output[0]) {
@trigger_error(sprintf('Not quoting the scalar "%s" starting with the "%%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0.' , $output), E_USER_DEPRECATED);
}
if ($evaluate) {
$output = self::evaluateScalar($output, $flags, $references);
}
}
return $output;
}
private static function parseQuotedScalar($scalar, &$i)
{
if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
}
$output = substr($match[0], 1, strlen($match[0]) - 2);
$unescaper = new Unescaper();
if ('"' == $scalar[$i]) {
$output = $unescaper->unescapeDoubleQuotedString($output);
} else {
$output = $unescaper->unescapeSingleQuotedString($output);
}
$i += strlen($match[0]);
return $output;
}
private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
{
$output = array();
$len = strlen($sequence);
++$i;
while ($i < $len) {
switch ($sequence[$i]) {
case '[':
$output[] = self::parseSequence($sequence, $flags, $i, $references);
break;
case '{':
$output[] = self::parseMapping($sequence, $flags, $i, $references);
break;
case ']':
return $output;
case ',':
case ' ':
break;
default:
$isQuoted = in_array($sequence[$i], array('"', "'"));
$value = self::parseScalar($sequence, $flags, array(',', ']'), array('"', "'"), $i, true, $references);
if (is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
try {
$pos = 0;
$value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
} catch (\InvalidArgumentException $e) {
}
}
$output[] = $value;
--$i;
}
++$i;
}
throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
}
private static function parseMapping($mapping, $flags, &$i = 0, $references = array())
{
$output = array();
$len = strlen($mapping);
++$i;
while ($i < $len) {
switch ($mapping[$i]) {
case ' ':
case ',':
++$i;
continue 2;
case '}':
if (self::$objectForMap) {
return (object) $output;
}
return $output;
}
$key = self::parseScalar($mapping, $flags, array(':', ' '), array('"', "'"), $i, false);
$done = false;
while ($i < $len) {
switch ($mapping[$i]) {
case '[':
$value = self::parseSequence($mapping, $flags, $i, $references);
if (!isset($output[$key])) {
$output[$key] = $value;
}
$done = true;
break;
case '{':
$value = self::parseMapping($mapping, $flags, $i, $references);
if (!isset($output[$key])) {
$output[$key] = $value;
}
$done = true;
break;
case ':':
case ' ':
break;
default:
$value = self::parseScalar($mapping, $flags, array(',', '}'), array('"', "'"), $i, true, $references);
if (!isset($output[$key])) {
$output[$key] = $value;
}
$done = true;
--$i;
}
++$i;
if ($done) {
continue 2;
}
}
}
throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping));
}
private static function evaluateScalar($scalar, $flags, $references = array())
{
$scalar = trim($scalar);
$scalarLower = strtolower($scalar);
if (0 === strpos($scalar, '*')) {
if (false !== $pos = strpos($scalar, '#')) {
$value = substr($scalar, 1, $pos - 2);
} else {
$value = substr($scalar, 1);
}
if (false === $value || '' === $value) {
throw new ParseException('A reference must contain at least one character.');
}
if (!array_key_exists($value, $references)) {
throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
}
return $references[$value];
}
switch (true) {
case 'null' === $scalarLower:
case '' === $scalar:
case '~' === $scalar:
return;
case 'true' === $scalarLower:
return true;
case 'false' === $scalarLower:
return false;
case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
switch (true) {
case 0 === strpos($scalar, '!str'):
return (string) substr($scalar, 5);
case 0 === strpos($scalar, '! '):
return (int) self::parseScalar(substr($scalar, 2), $flags);
case 0 === strpos($scalar, '!php/object:'):
if (self::$objectSupport) {
return unserialize(substr($scalar, 12));
}
if (self::$exceptionOnInvalidType) {
throw new ParseException('Object support when parsing a YAML file has been disabled.');
}
return;
case 0 === strpos($scalar, '!!php/object:'):
if (self::$objectSupport) {
@trigger_error('The !!php/object tag to indicate dumped PHP objects is deprecated since version 3.1 and will be removed in 4.0. Use the !php/object tag instead.', E_USER_DEPRECATED);
return unserialize(substr($scalar, 13));
}
if (self::$exceptionOnInvalidType) {
throw new ParseException('Object support when parsing a YAML file has been disabled.');
}
return;
case 0 === strpos($scalar, '!!float '):
return (float) substr($scalar, 8);
case ctype_digit($scalar):
$raw = $scalar;
$cast = (int) $scalar;
return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
$raw = $scalar;
$cast = (int) $scalar;
return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
case is_numeric($scalar):
case preg_match(self::getHexRegex(), $scalar):
return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
case '.inf' === $scalarLower:
case '.nan' === $scalarLower:
return -log(0);
case '-.inf' === $scalarLower:
return log(0);
case 0 === strpos($scalar, '!!binary '):
return self::evaluateBinaryScalar(substr($scalar, 9));
case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
return (float) str_replace(',', '', $scalar);
case preg_match(self::getTimestampRegex(), $scalar):
if (Yaml::PARSE_DATETIME & $flags) {
return new \DateTime($scalar, new \DateTimeZone('UTC'));
}
$timeZone = date_default_timezone_get();
date_default_timezone_set('UTC');
$time = strtotime($scalar);
date_default_timezone_set($timeZone);
return $time;
}
default:
return (string) $scalar;
}
}
public static function evaluateBinaryScalar($scalar)
{
$parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
if (0 !== (strlen($parsedBinaryData) % 4)) {
throw new ParseException(sprintf('The normalized base64 encoded data (data without whitespace characters) length must be a multiple of four (%d bytes given).', strlen($parsedBinaryData)));
}
if (!preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData));
}
return base64_decode($parsedBinaryData, true);
}
private static function isBinaryString($value)
{
return !preg_match('//u', $value) || preg_match('/[^\x09-\x0d\x20-\xff]/', $value);
}
private static function getTimestampRegex()
{
return <<<EOF
~^
(?P<year>[0-9][0-9][0-9][0-9])
-(?P<month>[0-9][0-9]?)
-(?P<day>[0-9][0-9]?)
(?:(?:[Tt]|[ \t]+)
(?P<hour>[0-9][0-9]?)
:(?P<minute>[0-9][0-9])
:(?P<second>[0-9][0-9])
(?:\.(?P<fraction>[0-9]*))?
(?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
(?::(?P<tz_minute>[0-9][0-9]))?))?)?
$~x
EOF;
}
private static function getHexRegex()
{
return '~^0x[0-9a-f]++$~i';
}
}
<?php
namespace Symfony\Component\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
class Parser
{
const TAG_PATTERN = '((?P<tag>![\w!.\/:-]+) +)?';
const BLOCK_SCALAR_HEADER_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
private $offset = 0;
private $totalNumberOfLines;
private $lines = array();
private $currentLineNb = -1;
private $currentLine = '';
private $refs = array();
private $skippedLineNumbers = array();
private $locallySkippedLineNumbers = array();
public function __construct($offset = 0, $totalNumberOfLines = null, array $skippedLineNumbers = array())
{
$this->offset = $offset;
$this->totalNumberOfLines = $totalNumberOfLines;
$this->skippedLineNumbers = $skippedLineNumbers;
}
public function parse($value, $flags = 0)
{
if (is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (func_num_args() >= 3) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(2)) {
$flags |= Yaml::PARSE_OBJECT;
}
}
if (func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= Yaml::PARSE_OBJECT_FOR_MAP;
}
}
if (!preg_match('//u', $value)) {
throw new ParseException('The YAML value does not appear to be valid UTF-8.');
}
$this->currentLineNb = -1;
$this->currentLine = '';
$value = $this->cleanup($value);
$this->lines = explode("\n", $value);
if (null === $this->totalNumberOfLines) {
$this->totalNumberOfLines = count($this->lines);
}
if (2 & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8');
}
$data = array();
$context = null;
$allowOverwrite = false;
while ($this->moveToNextLine()) {
if ($this->isCurrentLineEmpty()) {
continue;
}
if ("\t" === $this->currentLine[0]) {
throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
$isRef = $mergeNode = false;
if (preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) {
if ($context && 'mapping' == $context) {
throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
$context = 'sequence';
if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
$isRef = $matches['ref'];
$values['value'] = $matches['value'];
}
if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
$data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags);
} else {
if (isset($values['leadspaces'])
&& preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
) {
$block = $values['value'];
if ($this->isNextLineIndented()) {
$block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1);
}
$data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags);
} else {
$data[] = $this->parseValue($values['value'], $flags, $context);
}
}
if ($isRef) {
$this->refs[$isRef] = end($data);
}
} elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'")))) {
if ($context && 'sequence' == $context) {
throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine);
}
$context = 'mapping';
Inline::parse(null, $flags, $this->refs);
try {
$key = Inline::parseScalar($values['key']);
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);
throw $e;
}
if (is_float($key)) {
$key = (string) $key;
}
if ('<<' === $key) {
$mergeNode = true;
$allowOverwrite = true;
if (isset($values['value']) && 0 === strpos($values['value'], '*')) {
$refName = substr($values['value'], 1);
if (!array_key_exists($refName, $this->refs)) {
throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
$refValue = $this->refs[$refName];
if (!is_array($refValue)) {
throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
foreach ($refValue as $key => $value) {
if (!isset($data[$key])) {
$data[$key] = $value;
}
}
} else {
if (isset($values['value']) && $values['value'] !== '') {
$value = $values['value'];
} else {
$value = $this->getNextEmbedBlock();
}
$parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags);
if (!is_array($parsed)) {
throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
if (isset($parsed[0])) {
foreach ($parsed as $parsedItem) {
if (!is_array($parsedItem)) {
throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem);
}
foreach ($parsedItem as $key => $value) {
if (!isset($data[$key])) {
$data[$key] = $value;
}
}
}
} else {
foreach ($parsed as $key => $value) {
if (!isset($data[$key])) {
$data[$key] = $value;
}
}
}
}
} elseif (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
$isRef = $matches['ref'];
$values['value'] = $matches['value'];
}
if ($mergeNode) {
} elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
if ($allowOverwrite || !isset($data[$key])) {
$data[$key] = null;
}
} else {
$value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
if ($allowOverwrite || !isset($data[$key])) {
$data[$key] = $value;
}
}
} else {
$value = $this->parseValue($values['value'], $flags, $context);
if ($allowOverwrite || !isset($data[$key])) {
$data[$key] = $value;
}
}
if ($isRef) {
$this->refs[$isRef] = $data[$key];
}
} else {
if ('---' === $this->currentLine) {
throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine);
}
if (is_string($value) && $this->lines[0] === trim($value)) {
try {
$value = Inline::parse($this->lines[0], $flags, $this->refs);
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);
throw $e;
}
if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
return $value;
}
switch (preg_last_error()) {
case PREG_INTERNAL_ERROR:
$error = 'Internal PCRE error.';
break;
case PREG_BACKTRACK_LIMIT_ERROR:
$error = 'pcre.backtrack_limit reached.';
break;
case PREG_RECURSION_LIMIT_ERROR:
$error = 'pcre.recursion_limit reached.';
break;
case PREG_BAD_UTF8_ERROR:
$error = 'Malformed UTF-8 data.';
break;
case PREG_BAD_UTF8_OFFSET_ERROR:
$error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
break;
default:
$error = 'Unable to parse.';
}
throw new ParseException($error, $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
}
if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && !is_object($data) && 'mapping' === $context) {
$object = new \stdClass();
foreach ($data as $key => $value) {
$object->$key = $value;
}
$data = $object;
}
return empty($data) ? null : $data;
}
private function parseBlock($offset, $yaml, $flags)
{
$skippedLineNumbers = $this->skippedLineNumbers;
foreach ($this->locallySkippedLineNumbers as $lineNumber) {
if ($lineNumber < $offset) {
continue;
}
$skippedLineNumbers[] = $lineNumber;
}
$parser = new self($offset, $this->totalNumberOfLines, $skippedLineNumbers);
$parser->refs = &$this->refs;
return $parser->parse($yaml, $flags);
}
private function getRealCurrentLineNb()
{
$realCurrentLineNumber = $this->currentLineNb + $this->offset;
foreach ($this->skippedLineNumbers as $skippedLineNumber) {
if ($skippedLineNumber > $realCurrentLineNumber) {
break;
}
++$realCurrentLineNumber;
}
return $realCurrentLineNumber;
}
private function getCurrentLineIndentation()
{
return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
}
private function getNextEmbedBlock($indentation = null, $inSequence = false)
{
$oldLineIndentation = $this->getCurrentLineIndentation();
$blockScalarIndentations = array();
if ($this->isBlockScalarHeader()) {
$blockScalarIndentations[] = $this->getCurrentLineIndentation();
}
if (!$this->moveToNextLine()) {
return;
}
if (null === $indentation) {
$newIndent = $this->getCurrentLineIndentation();
$unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
} else {
$newIndent = $indentation;
}
$data = array();
if ($this->getCurrentLineIndentation() >= $newIndent) {
$data[] = substr($this->currentLine, $newIndent);
} else {
$this->moveToPreviousLine();
return;
}
if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
$this->moveToPreviousLine();
return;
}
$isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
if (empty($blockScalarIndentations) && $this->isBlockScalarHeader()) {
$blockScalarIndentations[] = $this->getCurrentLineIndentation();
}
$previousLineIndentation = $this->getCurrentLineIndentation();
while ($this->moveToNextLine()) {
$indent = $this->getCurrentLineIndentation();
if (!empty($blockScalarIndentations) && $indent < $previousLineIndentation && trim($this->currentLine) !== '') {
foreach ($blockScalarIndentations as $key => $blockScalarIndentation) {
if ($blockScalarIndentation >= $this->getCurrentLineIndentation()) {
unset($blockScalarIndentations[$key]);
}
}
}
if (empty($blockScalarIndentations) && !$this->isCurrentLineComment() && $this->isBlockScalarHeader()) {
$blockScalarIndentations[] = $this->getCurrentLineIndentation();
}
$previousLineIndentation = $indent;
if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
$this->moveToPreviousLine();
break;
}
if ($this->isCurrentLineBlank()) {
$data[] = substr($this->currentLine, $newIndent);
continue;
}
if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) {
$this->locallySkippedLineNumbers[] = $this->getRealCurrentLineNb();
continue;
}
if ($indent >= $newIndent) {
$data[] = substr($this->currentLine, $newIndent);
} elseif (0 == $indent) {
$this->moveToPreviousLine();
break;
} else {
throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
}
}
return implode("\n", $data);
}
private function moveToNextLine()
{
if ($this->currentLineNb >= count($this->lines) - 1) {
return false;
}
$this->currentLine = $this->lines[++$this->currentLineNb];
return true;
}
private function moveToPreviousLine()
{
if ($this->currentLineNb < 1) {
return false;
}
$this->currentLine = $this->lines[--$this->currentLineNb];
return true;
}
private function parseValue($value, $flags, $context)
{
if (0 === strpos($value, '*')) {
if (false !== $pos = strpos($value, '#')) {
$value = substr($value, 1, $pos - 2);
} else {
$value = substr($value, 1);
}
if (!array_key_exists($value, $this->refs)) {
throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine);
}
return $this->refs[$value];
}
if (preg_match('/^'.self::TAG_PATTERN.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
$data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
if (isset($matches['tag']) && '!!binary' === $matches['tag']) {
return Inline::evaluateBinaryScalar($data);
}
return $data;
}
try {
$parsedValue = Inline::parse($value, $flags, $this->refs);
if ('mapping' === $context && is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
throw new ParseException('A colon cannot be used in an unquoted mapping value.');
}
return $parsedValue;
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);
throw $e;
}
}
private function parseBlockScalar($style, $chomping = '', $indentation = 0)
{
$notEOF = $this->moveToNextLine();
if (!$notEOF) {
return '';
}
$isCurrentLineBlank = $this->isCurrentLineBlank();
$blockLines = array();
while ($notEOF && $isCurrentLineBlank) {
if ($notEOF = $this->moveToNextLine()) {
$blockLines[] = '';
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
if (0 === $indentation) {
if (preg_match('/^ +/', $this->currentLine, $matches)) {
$indentation = strlen($matches[0]);
}
}
if ($indentation > 0) {
$pattern = sprintf('/^ {%d}(.*)$/', $indentation);
while (
$notEOF && (
$isCurrentLineBlank ||
preg_match($pattern, $this->currentLine, $matches)
)
) {
if ($isCurrentLineBlank && strlen($this->currentLine) > $indentation) {
$blockLines[] = substr($this->currentLine, $indentation);
} elseif ($isCurrentLineBlank) {
$blockLines[] = '';
} else {
$blockLines[] = $matches[1];
}
if ($notEOF = $this->moveToNextLine()) {
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
} elseif ($notEOF) {
$blockLines[] = '';
}
if ($notEOF) {
$blockLines[] = '';
$this->moveToPreviousLine();
} elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
$blockLines[] = '';
}
if ('>' === $style) {
$text = '';
$previousLineIndented = false;
$previousLineBlank = false;
for ($i = 0; $i < count($blockLines); ++$i) {
if ('' === $blockLines[$i]) {
$text .= "\n";
$previousLineIndented = false;
$previousLineBlank = true;
} elseif (' ' === $blockLines[$i][0]) {
$text .= "\n".$blockLines[$i];
$previousLineIndented = true;
$previousLineBlank = false;
} elseif ($previousLineIndented) {
$text .= "\n".$blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
} elseif ($previousLineBlank || 0 === $i) {
$text .= $blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
} else {
$text .= ' '.$blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
}
}
} else {
$text = implode("\n", $blockLines);
}
if ('' === $chomping) {
$text = preg_replace('/\n+$/', "\n", $text);
} elseif ('-' === $chomping) {
$text = preg_replace('/\n+$/', '', $text);
}
return $text;
}
private function isNextLineIndented()
{
$currentIndentation = $this->getCurrentLineIndentation();
$EOF = !$this->moveToNextLine();
while (!$EOF && $this->isCurrentLineEmpty()) {
$EOF = !$this->moveToNextLine();
}
if ($EOF) {
return false;
}
$ret = false;
if ($this->getCurrentLineIndentation() > $currentIndentation) {
$ret = true;
}
$this->moveToPreviousLine();
return $ret;
}
private function isCurrentLineEmpty()
{
return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
}
private function isCurrentLineBlank()
{
return '' == trim($this->currentLine, ' ');
}
private function isCurrentLineComment()
{
$ltrimmedLine = ltrim($this->currentLine, ' ');
return '' !== $ltrimmedLine && $ltrimmedLine[0] === '#';
}
private function isCurrentLineLastLineInDocument()
{
return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
}
private function cleanup($value)
{
$value = str_replace(array("\r\n", "\r"), "\n", $value);
$count = 0;
$value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
$this->offset += $count;
$trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
if ($count == 1) {
$this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
$value = $trimmedValue;
}
$trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
if ($count == 1) {
$this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
$value = $trimmedValue;
$value = preg_replace('#\.\.\.\s*$#', '', $value);
}
return $value;
}
private function isNextLineUnIndentedCollection()
{
$currentIndentation = $this->getCurrentLineIndentation();
$notEOF = $this->moveToNextLine();
while ($notEOF && $this->isCurrentLineEmpty()) {
$notEOF = $this->moveToNextLine();
}
if (false === $notEOF) {
return false;
}
$ret = false;
if (
$this->getCurrentLineIndentation() == $currentIndentation
&&
$this->isStringUnIndentedCollectionItem()
) {
$ret = true;
}
$this->moveToPreviousLine();
return $ret;
}
private function isStringUnIndentedCollectionItem()
{
return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- ');
}
private function isBlockScalarHeader()
{
return (bool) preg_match('~'.self::BLOCK_SCALAR_HEADER_PATTERN.'$~', $this->currentLine);
}
}
<?php
namespace Symfony\Component\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
class Unescaper
{
const REGEX_ESCAPED_CHARACTER = '\\\\(x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)';
public function unescapeSingleQuotedString($value)
{
return str_replace('\'\'', '\'', $value);
}
public function unescapeDoubleQuotedString($value)
{
$callback = function ($match) {
return $this->unescapeCharacter($match[0]);
};
return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value);
}
private function unescapeCharacter($value)
{
switch ($value[1]) {
case '0':
return "\x0";
case 'a':
return "\x7";
case 'b':
return "\x8";
case 't':
return "\t";
case "\t":
return "\t";
case 'n':
return "\n";
case 'v':
return "\xB";
case 'f':
return "\xC";
case 'r':
return "\r";
case 'e':
return "\x1B";
case ' ':
return ' ';
case '"':
return '"';
case '/':
return '/';
case '\\':
return '\\';
case 'N':
return "\xC2\x85";
case '_':
return "\xC2\xA0";
case 'L':
return "\xE2\x80\xA8";
case 'P':
return "\xE2\x80\xA9";
case 'x':
return self::utf8chr(hexdec(substr($value, 2, 2)));
case 'u':
return self::utf8chr(hexdec(substr($value, 2, 4)));
case 'U':
return self::utf8chr(hexdec(substr($value, 2, 8)));
default:
throw new ParseException(sprintf('Found unknown escape character "%s".', $value));
}
}
private static function utf8chr($c)
{
if (0x80 > $c %= 0x200000) {
return chr($c);
}
if (0x800 > $c) {
return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
}
if (0x10000 > $c) {
return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
}
return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
}
}
<?php
namespace Symfony\Component\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
class Yaml
{
const DUMP_OBJECT = 1;
const PARSE_EXCEPTION_ON_INVALID_TYPE = 2;
const PARSE_OBJECT = 4;
const PARSE_OBJECT_FOR_MAP = 8;
const DUMP_EXCEPTION_ON_INVALID_TYPE = 16;
const PARSE_DATETIME = 32;
const DUMP_OBJECT_AS_MAP = 64;
const DUMP_MULTI_LINE_LITERAL_BLOCK = 128;
public static function parse($input, $flags = 0)
{
if (is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = self::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (func_num_args() >= 3) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(2)) {
$flags |= self::PARSE_OBJECT;
}
}
if (func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= self::PARSE_OBJECT_FOR_MAP;
}
}
$yaml = new Parser();
return $yaml->parse($input, $flags);
}
public static function dump($input, $inline = 2, $indent = 4, $flags = 0)
{
if (is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = self::DUMP_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (func_num_args() >= 5) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(4)) {
$flags |= self::DUMP_OBJECT;
}
}
$yaml = new Dumper($indent);
return $yaml->dump($input, $inline, 0, $flags);
}
}
<?php
namespace Symfony\Component\Stopwatch;
class Section
{
private $events = array();
private $origin;
private $id;
private $children = array();
public function __construct($origin = null)
{
$this->origin = is_numeric($origin) ? $origin : null;
}
public function get($id)
{
foreach ($this->children as $child) {
if ($id === $child->getId()) {
return $child;
}
}
}
public function open($id)
{
if (null === $session = $this->get($id)) {
$session = $this->children[] = new self(microtime(true) * 1000);
}
return $session;
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function startEvent($name, $category)
{
if (!isset($this->events[$name])) {
$this->events[$name] = new StopwatchEvent($this->origin ?: microtime(true) * 1000, $category);
}
return $this->events[$name]->start();
}
public function isEventStarted($name)
{
return isset($this->events[$name]) && $this->events[$name]->isStarted();
}
public function stopEvent($name)
{
if (!isset($this->events[$name])) {
throw new \LogicException(sprintf('Event "%s" is not started.', $name));
}
return $this->events[$name]->stop();
}
public function lap($name)
{
return $this->stopEvent($name)->start();
}
public function getEvent($name)
{
if (!isset($this->events[$name])) {
throw new \LogicException(sprintf('Event "%s" is not known.', $name));
}
return $this->events[$name];
}
public function getEvents()
{
return $this->events;
}
}
<?php
namespace Symfony\Component\Stopwatch;
class Stopwatch
{
private $sections;
private $activeSections;
public function __construct()
{
$this->sections = $this->activeSections = array('__root__' => new Section('__root__'));
}
public function getSections()
{
return $this->sections;
}
public function openSection($id = null)
{
$current = end($this->activeSections);
if (null !== $id && null === $current->get($id)) {
throw new \LogicException(sprintf('The section "%s" has been started at an other level and can not be opened.', $id));
}
$this->start('__section__.child', 'section');
$this->activeSections[] = $current->open($id);
$this->start('__section__');
}
public function stopSection($id)
{
$this->stop('__section__');
if (1 == count($this->activeSections)) {
throw new \LogicException('There is no started section to stop.');
}
$this->sections[$id] = array_pop($this->activeSections)->setId($id);
$this->stop('__section__.child');
}
public function start($name, $category = null)
{
return end($this->activeSections)->startEvent($name, $category);
}
public function isStarted($name)
{
return end($this->activeSections)->isEventStarted($name);
}
public function stop($name)
{
return end($this->activeSections)->stopEvent($name);
}
public function lap($name)
{
return end($this->activeSections)->stopEvent($name)->start();
}
public function getEvent($name)
{
return end($this->activeSections)->getEvent($name);
}
public function getSectionEvents($id)
{
return isset($this->sections[$id]) ? $this->sections[$id]->getEvents() : array();
}
}
<?php
namespace Symfony\Component\Stopwatch;
class StopwatchEvent
{
private $periods = array();
private $origin;
private $category;
private $started = array();
public function __construct($origin, $category = null)
{
$this->origin = $this->formatTime($origin);
$this->category = is_string($category) ? $category : 'default';
}
public function getCategory()
{
return $this->category;
}
public function getOrigin()
{
return $this->origin;
}
public function start()
{
$this->started[] = $this->getNow();
return $this;
}
public function stop()
{
if (!count($this->started)) {
throw new \LogicException('stop() called but start() has not been called before.');
}
$this->periods[] = new StopwatchPeriod(array_pop($this->started), $this->getNow());
return $this;
}
public function isStarted()
{
return !empty($this->started);
}
public function lap()
{
return $this->stop()->start();
}
public function ensureStopped()
{
while (count($this->started)) {
$this->stop();
}
}
public function getPeriods()
{
return $this->periods;
}
public function getStartTime()
{
return isset($this->periods[0]) ? $this->periods[0]->getStartTime() : 0;
}
public function getEndTime()
{
$count = count($this->periods);
return $count ? $this->periods[$count - 1]->getEndTime() : 0;
}
public function getDuration()
{
$periods = $this->periods;
$stopped = count($periods);
$left = count($this->started) - $stopped;
for ($i = 0; $i < $left; ++$i) {
$index = $stopped + $i;
$periods[] = new StopwatchPeriod($this->started[$index], $this->getNow());
}
$total = 0;
foreach ($periods as $period) {
$total += $period->getDuration();
}
return $total;
}
public function getMemory()
{
$memory = 0;
foreach ($this->periods as $period) {
if ($period->getMemory() > $memory) {
$memory = $period->getMemory();
}
}
return $memory;
}
protected function getNow()
{
return $this->formatTime(microtime(true) * 1000 - $this->origin);
}
private function formatTime($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('The time must be a numerical value');
}
return round($time, 1);
}
public function __toString()
{
return sprintf('%s: %.2F MiB - %d ms', $this->getCategory(), $this->getMemory() / 1024 / 1024, $this->getDuration());
}
}
<?php
namespace Symfony\Component\Stopwatch;
class StopwatchPeriod
{
private $start;
private $end;
private $memory;
public function __construct($start, $end)
{
$this->start = (int) $start;
$this->end = (int) $end;
$this->memory = memory_get_usage(true);
}
public function getStartTime()
{
return $this->start;
}
public function getEndTime()
{
return $this->end;
}
public function getDuration()
{
return $this->end - $this->start;
}
public function getMemory()
{
return $this->memory;
}
}
<?php
namespace Symfony\Polyfill\Mbstring;
final class Mbstring
{
const MB_CASE_FOLD = PHP_INT_MAX;
private static $encodingList = array('ASCII', 'UTF-8');
private static $language = 'neutral';
private static $internalEncoding = 'UTF-8';
private static $caseFold = array(
array('µ','ſ',"\xCD\x85",'ς',"\xCF\x90","\xCF\x91","\xCF\x95","\xCF\x96","\xCF\xB0","\xCF\xB1","\xCF\xB5","\xE1\xBA\x9B","\xE1\xBE\xBE"),
array('μ','s','ι', 'σ','β', 'θ', 'φ', 'Ï€', 'κ', 'Ï<>', 'ε', "\xE1\xB9\xA1",'ι'),
);
public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null)
{
if (is_array($fromEncoding) || false !== strpos($fromEncoding, ',')) {
$fromEncoding = self::mb_detect_encoding($s, $fromEncoding);
} else {
$fromEncoding = self::getEncoding($fromEncoding);
}
$toEncoding = self::getEncoding($toEncoding);
if ('BASE64' === $fromEncoding) {
$s = base64_decode($s);
$fromEncoding = $toEncoding;
}
if ('BASE64' === $toEncoding) {
return base64_encode($s);
}
if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) {
if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) {
$fromEncoding = 'Windows-1252';
}
if ('UTF-8' !== $fromEncoding) {
$s = iconv($fromEncoding, 'UTF-8', $s);
}
return preg_replace_callback('/[\x80-\xFF]+/', array(__CLASS__, 'html_encoding_callback'), $s);
}
if ('HTML-ENTITIES' === $fromEncoding) {
$s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
$fromEncoding = 'UTF-8';
}
return iconv($fromEncoding, $toEncoding, $s);
}
public static function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null)
{
$vars = array(&$a, &$b, &$c, &$d, &$e, &$f);
$ok = true;
array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) {
if (false === $v = Mbstring::mb_convert_encoding($v, $toEncoding, $fromEncoding)) {
$ok = false;
}
});
return $ok ? $fromEncoding : false;
}
public static function mb_decode_mimeheader($s)
{
return iconv_mime_decode($s, 2, self::$internalEncoding);
}
public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null)
{
trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', E_USER_WARNING);
}
public static function mb_convert_case($s, $mode, $encoding = null)
{
if ('' === $s .= '') {
return '';
}
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
$encoding = null;
} else {
$s = iconv($encoding, 'UTF-8', $s);
}
if (MB_CASE_TITLE == $mode) {
$s = preg_replace_callback('/\b\p{Ll}/u', array(__CLASS__, 'title_case_upper'), $s);
$s = preg_replace_callback('/\B[\p{Lu}\p{Lt}]+/u', array(__CLASS__, 'title_case_lower'), $s);
} else {
if (MB_CASE_UPPER == $mode) {
static $upper = null;
if (null === $upper) {
$upper = self::getData('upperCase');
}
$map = $upper;
} else {
if (self::MB_CASE_FOLD === $mode) {
$s = str_replace(self::$caseFold[0], self::$caseFold[1], $s);
}
static $lower = null;
if (null === $lower) {
$lower = self::getData('lowerCase');
}
$map = $lower;
}
static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4);
$i = 0;
$len = strlen($s);
while ($i < $len) {
$ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
$uchr = substr($s, $i, $ulen);
$i += $ulen;
if (isset($map[$uchr])) {
$uchr = $map[$uchr];
$nlen = strlen($uchr);
if ($nlen == $ulen) {
$nlen = $i;
do {
$s[--$nlen] = $uchr[--$ulen];
} while ($ulen);
} else {
$s = substr_replace($s, $uchr, $i - $ulen, $ulen);
$len += $nlen - $ulen;
$i += $nlen - $ulen;
}
}
}
}
if (null === $encoding) {
return $s;
}
return iconv('UTF-8', $encoding, $s);
}
public static function mb_internal_encoding($encoding = null)
{
if (null === $encoding) {
return self::$internalEncoding;
}
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding || false !== @iconv($encoding, $encoding, ' ')) {
self::$internalEncoding = $encoding;
return true;
}
return false;
}
public static function mb_language($lang = null)
{
if (null === $lang) {
return self::$language;
}
switch ($lang = strtolower($lang)) {
case 'uni':
case 'neutral':
self::$language = $lang;
return true;
}
return false;
}
public static function mb_list_encodings()
{
return array('UTF-8');
}
public static function mb_encoding_aliases($encoding)
{
switch (strtoupper($encoding)) {
case 'UTF8':
case 'UTF-8':
return array('utf8');
}
return false;
}
public static function mb_check_encoding($var = null, $encoding = null)
{
if (null === $encoding) {
if (null === $var) {
return false;
}
$encoding = self::$internalEncoding;
}
return self::mb_detect_encoding($var, array($encoding)) || false !== @iconv($encoding, $encoding, $var);
}
public static function mb_detect_encoding($str, $encodingList = null, $strict = false)
{
if (null === $encodingList) {
$encodingList = self::$encodingList;
} else {
if (!is_array($encodingList)) {
$encodingList = array_map('trim', explode(',', $encodingList));
}
$encodingList = array_map('strtoupper', $encodingList);
}
foreach ($encodingList as $enc) {
switch ($enc) {
case 'ASCII':
if (!preg_match('/[\x80-\xFF]/', $str)) {
return $enc;
}
break;
case 'UTF8':
case 'UTF-8':
if (preg_match('//u', $str)) {
return 'UTF-8';
}
break;
default:
if (0 === strncmp($enc, 'ISO-8859-', 9)) {
return $enc;
}
}
}
return false;
}
public static function mb_detect_order($encodingList = null)
{
if (null === $encodingList) {
return self::$encodingList;
}
if (!is_array($encodingList)) {
$encodingList = array_map('trim', explode(',', $encodingList));
}
$encodingList = array_map('strtoupper', $encodingList);
foreach ($encodingList as $enc) {
switch ($enc) {
default:
if (strncmp($enc, 'ISO-8859-', 9)) {
return false;
}
case 'ASCII':
case 'UTF8':
case 'UTF-8':
}
}
self::$encodingList = $encodingList;
return true;
}
public static function mb_strlen($s, $encoding = null)
{
$encoding = self::getEncoding($encoding);
return iconv_strlen($s, $encoding);
}
public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('' === $needle .= '') {
trigger_error(__METHOD__.': Empty delimiter', E_USER_WARNING);
return false;
}
return iconv_strpos($haystack, $needle, $offset, $encoding);
}
public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ($offset != (int) $offset) {
$offset = 0;
} elseif ($offset = (int) $offset) {
if ($offset < 0) {
$haystack = self::mb_substr($haystack, 0, $offset, $encoding);
$offset = 0;
} else {
$haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding);
}
}
$pos = iconv_strrpos($haystack, $needle, $encoding);
return false !== $pos ? $offset + $pos : false;
}
public static function mb_strtolower($s, $encoding = null)
{
return self::mb_convert_case($s, MB_CASE_LOWER, $encoding);
}
public static function mb_strtoupper($s, $encoding = null)
{
return self::mb_convert_case($s, MB_CASE_UPPER, $encoding);
}
public static function mb_substitute_character($c = null)
{
if (0 === strcasecmp($c, 'none')) {
return true;
}
return null !== $c ? false : 'none';
}
public static function mb_substr($s, $start, $length = null, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ($start < 0) {
$start = iconv_strlen($s, $encoding) + $start;
if ($start < 0) {
$start = 0;
}
}
if (null === $length) {
$length = 2147483647;
} elseif ($length < 0) {
$length = iconv_strlen($s, $encoding) + $length - $start;
if ($length < 0) {
return '';
}
}
return iconv_substr($s, $start, $length, $encoding).'';
}
public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null)
{
$haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding);
$needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding);
return self::mb_strpos($haystack, $needle, $offset, $encoding);
}
public static function mb_stristr($haystack, $needle, $part = false, $encoding = null)
{
$pos = self::mb_stripos($haystack, $needle, 0, $encoding);
return self::getSubpart($pos, $part, $haystack, $encoding);
}
public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null)
{
$encoding = self::getEncoding($encoding);
$needle = self::mb_substr($needle, 0, 1, $encoding);
$pos = iconv_strrpos($haystack, $needle, $encoding);
return self::getSubpart($pos, $part, $haystack, $encoding);
}
public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null)
{
$needle = self::mb_substr($needle, 0, 1, $encoding);
$pos = self::mb_strripos($haystack, $needle, $encoding);
return self::getSubpart($pos, $part, $haystack, $encoding);
}
public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null)
{
$haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding);
$needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding);
return self::mb_strrpos($haystack, $needle, $offset, $encoding);
}
public static function mb_strstr($haystack, $needle, $part = false, $encoding = null)
{
$pos = strpos($haystack, $needle);
if (false === $pos) {
return false;
}
if ($part) {
return substr($haystack, 0, $pos);
}
return substr($haystack, $pos);
}
public static function mb_get_info($type = 'all')
{
$info = array(
'internal_encoding' => self::$internalEncoding,
'http_output' => 'pass',
'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)',
'func_overload' => 0,
'func_overload_list' => 'no overload',
'mail_charset' => 'UTF-8',
'mail_header_encoding' => 'BASE64',
'mail_body_encoding' => 'BASE64',
'illegal_chars' => 0,
'encoding_translation' => 'Off',
'language' => self::$language,
'detect_order' => self::$encodingList,
'substitute_character' => 'none',
'strict_detection' => 'Off',
);
if ('all' === $type) {
return $info;
}
if (isset($info[$type])) {
return $info[$type];
}
return false;
}
public static function mb_http_input($type = '')
{
return false;
}
public static function mb_http_output($encoding = null)
{
return null !== $encoding ? 'pass' === $encoding : 'pass';
}
public static function mb_strwidth($s, $encoding = null)
{
$encoding = self::getEncoding($encoding);
if ('UTF-8' !== $encoding) {
$s = iconv($encoding, 'UTF-8', $s);
}
$s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide);
return ($wide << 1) + iconv_strlen($s, 'UTF-8');
}
public static function mb_substr_count($haystack, $needle, $encoding = null)
{
return substr_count($haystack, $needle);
}
public static function mb_output_handler($contents, $status)
{
return $contents;
}
private static function getSubpart($pos, $part, $haystack, $encoding)
{
if (false === $pos) {
return false;
}
if ($part) {
return self::mb_substr($haystack, 0, $pos, $encoding);
}
return self::mb_substr($haystack, $pos, null, $encoding);
}
private static function html_encoding_callback($m)
{
$i = 1;
$entities = '';
$m = unpack('C*', htmlentities($m[0], ENT_COMPAT, 'UTF-8'));
while (isset($m[$i])) {
if (0x80 > $m[$i]) {
$entities .= chr($m[$i++]);
continue;
}
if (0xF0 <= $m[$i]) {
$c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
} elseif (0xE0 <= $m[$i]) {
$c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
} else {
$c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80;
}
$entities .= '&#'.$c.';';
}
return $entities;
}
private static function title_case_lower($s)
{
return self::mb_convert_case($s[0], MB_CASE_LOWER, 'UTF-8');
}
private static function title_case_upper($s)
{
return self::mb_convert_case($s[0], MB_CASE_UPPER, 'UTF-8');
}
private static function getData($file)
{
if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) {
return require $file;
}
return false;
}
private static function getEncoding($encoding)
{
if (null === $encoding) {
return self::$internalEncoding;
}
$encoding = strtoupper($encoding);
if ('8BIT' === $encoding || 'BINARY' === $encoding) {
return 'CP850';
}
if ('UTF8' === $encoding) {
return 'UTF-8';
}
return $encoding;
}
}
<?php
static $data = array (
'A' => 'a',
'B' => 'b',
'C' => 'c',
'D' => 'd',
'E' => 'e',
'F' => 'f',
'G' => 'g',
'H' => 'h',
'I' => 'i',
'J' => 'j',
'K' => 'k',
'L' => 'l',
'M' => 'm',
'N' => 'n',
'O' => 'o',
'P' => 'p',
'Q' => 'q',
'R' => 'r',
'S' => 's',
'T' => 't',
'U' => 'u',
'V' => 'v',
'W' => 'w',
'X' => 'x',
'Y' => 'y',
'Z' => 'z',
'À' => 'à',
<>' => 'á',
'Â' => 'â',
'Ã' => 'ã',
'Ä' => 'ä',
'Ã…' => 'Ã¥',
'Æ' => 'æ',
'Ç' => 'ç',
'È' => 'è',
'É' => 'é',
'Ê' => 'ê',
'Ë' => 'ë',
'Ì' => 'ì',
<>' => 'í',
'Î' => 'î',
<>' => 'ï',
<>' => 'ð',
'Ñ' => 'ñ',
'Ò' => 'ò',
'Ó' => 'ó',
'Ô' => 'ô',
'Õ' => 'õ',
'Ö' => 'ö',
'Ø' => 'ø',
'Ù' => 'ù',
'Ú' => 'ú',
'Û' => 'û',
'Ü' => 'ü',
<>' => 'ý',
'Þ' => 'þ',
'Ä€' => 'Ä<>',
'Ă' => 'ă',
'Ä„' => 'Ä…',
'Ć' => 'ć',
'Ĉ' => 'ĉ',
'ÄŠ' => 'Ä‹',
'ÄŒ' => 'Ä<>',
'ÄŽ' => 'Ä<>',
<>' => 'Ä‘',
'Ä’' => 'Ä“',
'Ä”' => 'Ä•',
'Ä–' => 'Ä—',
'Ę' => 'ę',
'Äš' => 'Ä›',
'Äœ' => 'Ä<>',
'Äž' => 'ÄŸ',
'Ä ' => 'Ä¡',
'Ä¢' => 'Ä£',
'Ĥ' => 'ĥ',
'Ħ' => 'ħ',
'Ĩ' => 'ĩ',
'Ī' => 'ī',
'Ĭ' => 'ĭ',
'Į' => 'į',
'Ä°' => 'i',
'IJ' => 'ij',
'Ĵ' => 'ĵ',
'Ķ' => 'ķ',
'Ĺ' => 'ĺ',
'Ļ' => 'ļ',
'Ľ' => 'ľ',
'Ä¿' => 'Å€',
<>' => 'Å‚',
'Ń' => 'ń',
'Ņ' => 'ņ',
'Ň' => 'ň',
'ÅŠ' => 'Å‹',
'ÅŒ' => 'Å<>',
'ÅŽ' => 'Å<>',
<>' => 'Å‘',
'Å’' => 'Å“',
'Å”' => 'Å•',
'Å–' => 'Å—',
'Ř' => 'ř',
'Åš' => 'Å›',
'Åœ' => 'Å<>',
'Åž' => 'ÅŸ',
'Å ' => 'Å¡',
'Å¢' => 'Å£',
'Ť' => 'ť',
'Ŧ' => 'ŧ',
'Ũ' => 'ũ',
'Ū' => 'ū',
'Ŭ' => 'ŭ',
'Ů' => 'ů',
'Ű' => 'ű',
'Ų' => 'ų',
'Ŵ' => 'ŵ',
'Ŷ' => 'ŷ',
'Ÿ' => 'ÿ',
'Ź' => 'ź',
'Ż' => 'ż',
'Ž' => 'ž',
<>' => 'É“',
'Ƃ' => 'ƃ',
'Æ„' => 'Æ…',
'Ɔ' => 'ɔ',
'Ƈ' => 'ƈ',
'Ɖ' => 'ɖ',
'ÆŠ' => 'É—',
'Ƌ' => 'ƌ',
'ÆŽ' => 'Ç<>',
<>' => 'É™',
<>' => 'É›',
'Æ‘' => 'Æ’',
'Æ“' => 'É ',
'Æ”' => 'É£',
'Æ–' => 'É©',
'Ɨ' => 'ɨ',
'Ƙ' => 'ƙ',
'Ɯ' => 'ɯ',
<>' => 'ɲ',
'Ɵ' => 'ɵ',
'Æ ' => 'Æ¡',
'Æ¢' => 'Æ£',
'Ƥ' => 'ƥ',
'Ʀ' => 'ʀ',
'Ƨ' => 'ƨ',
'Ʃ' => 'ʃ',
'Ƭ' => 'ƭ',
'Ʈ' => 'ʈ',
'Ư' => 'ư',
'Ʊ' => 'ʊ',
'Ʋ' => 'ʋ',
'Ƴ' => 'ƴ',
'Ƶ' => 'ƶ',
'Æ·' => 'Ê’',
'Ƹ' => 'ƹ',
'Ƽ' => 'ƽ',
'DŽ' => 'dž',
'Dž' => 'dž',
'LJ' => 'lj',
'Lj' => 'lj',
'NJ' => 'nj',
'Nj' => 'nj',
<>' => 'ÇŽ',
<>' => 'Ç<>',
'Ç‘' => 'Ç’',
'Ç“' => 'Ç”',
'Ç•' => 'Ç–',
'Ǘ' => 'ǘ',
'Ç™' => 'Çš',
'Ǜ' => 'ǜ',
'Çž' => 'ÇŸ',
'Ç ' => 'Ç¡',
'Ç¢' => 'Ç£',
'Ǥ' => 'ǥ',
'Ǧ' => 'ǧ',
'Ǩ' => 'ǩ',
'Ǫ' => 'ǫ',
'Ǭ' => 'ǭ',
'Ǯ' => 'ǯ',
'DZ' => 'dz',
'Dz' => 'dz',
'Ǵ' => 'ǵ',
'Ƕ' => 'ƕ',
'Ç·' => 'Æ¿',
'Ǹ' => 'ǹ',
'Ǻ' => 'ǻ',
'Ǽ' => 'ǽ',
'Ǿ' => 'ǿ',
'È€' => 'È<>',
'Ȃ' => 'ȃ',
'È„' => 'È…',
'Ȇ' => 'ȇ',
'Ȉ' => 'ȉ',
'ÈŠ' => 'È‹',
'ÈŒ' => 'È<>',
'ÈŽ' => 'È<>',
<>' => 'È‘',
'È’' => 'È“',
'È”' => 'È•',
'È–' => 'È—',
'Ș' => 'ș',
'Èš' => 'È›',
'Èœ' => 'È<>',
'Èž' => 'ÈŸ',
'È ' => 'Æž',
'È¢' => 'È£',
'Ȥ' => 'ȥ',
'Ȧ' => 'ȧ',
'Ȩ' => 'ȩ',
'Ȫ' => 'ȫ',
'Ȭ' => 'ȭ',
'Ȯ' => 'ȯ',
'Ȱ' => 'ȱ',
'Ȳ' => 'ȳ',
'Ⱥ' => 'ⱥ',
'Ȼ' => 'ȼ',
'Ƚ' => 'ƚ',
'Ⱦ' => 'ⱦ',
<>' => 'É‚',
'Ƀ' => 'ƀ',
'Ʉ' => 'ʉ',
'Ʌ' => 'ʌ',
'Ɇ' => 'ɇ',
'Ɉ' => 'ɉ',
'ÉŠ' => 'É‹',
'ÉŒ' => 'É<>',
'ÉŽ' => 'É<>',
'Ͱ' => 'ͱ',
'Ͳ' => 'ͳ',
'Ͷ' => 'ͷ',
'Ϳ' => 'ϳ',
'Ά' => 'ά',
'Έ' => 'έ',
'Ή' => 'ή',
'Ί' => 'ί',
'Ό' => 'ό',
'ÎŽ' => 'Ï<>',
<>' => 'ÏŽ',
'Α' => 'α',
'Β' => 'β',
'Γ' => 'γ',
'Δ' => 'δ',
'Ε' => 'ε',
'Ζ' => 'ζ',
'Η' => 'η',
'Θ' => 'θ',
'Ι' => 'ι',
'Κ' => 'κ',
'Λ' => 'λ',
'Μ' => 'μ',
<>' => 'ν',
'Ξ' => 'ξ',
'Ο' => 'ο',
'Π' => 'π',
'Ρ' => 'Ï<>',
'Σ' => 'σ',
'Τ' => 'τ',
'Î¥' => 'Ï…',
'Φ' => 'φ',
'Χ' => 'χ',
'Ψ' => 'ψ',
'Ω' => 'ω',
'Ϊ' => 'ϊ',
'Ϋ' => 'ϋ',
<>' => 'Ï—',
'Ϙ' => 'ϙ',
'Ïš' => 'Ï›',
'Ïœ' => 'Ï<>',
'Ïž' => 'ÏŸ',
'Ï ' => 'Ï¡',
'Ï¢' => 'Ï£',
'Ϥ' => 'ϥ',
'Ϧ' => 'ϧ',
'Ϩ' => 'ϩ',
'Ϫ' => 'ϫ',
'Ϭ' => 'ϭ',
'Ϯ' => 'ϯ',
'ϴ' => 'θ',
'Ϸ' => 'ϸ',
'Ϲ' => 'ϲ',
'Ϻ' => 'ϻ',
'Ͻ' => 'ͻ',
'Ͼ' => 'ͼ',
'Ͽ' => 'ͽ',
'Ѐ' => 'Ñ<>',
<>' => 'Ñ‘',
'Ђ' => 'ђ',
'Ѓ' => 'ѓ',
'Є' => 'є',
'Ð…' => 'Ñ•',
'І' => 'і',
'Ї' => 'ї',
'Ј' => 'ј',
'Љ' => 'љ',
'Њ' => 'њ',
'Ћ' => 'ћ',
'Ќ' => 'ќ',
<>' => 'Ñ<>',
'ÐŽ' => 'Ñž',
<>' => 'ÑŸ',
<>' => 'а',
'Б' => 'б',
'В' => 'в',
'Г' => 'г',
'Д' => 'д',
'Е' => 'е',
'Ж' => 'ж',
'З' => 'з',
'И' => 'и',
'Й' => 'й',
'К' => 'к',
'Л' => 'л',
'М' => 'м',
<>' => 'н',
'О' => 'о',
'П' => 'п',
'Р' => 'р',
'С' => 'Ñ<>',
'Т' => 'т',
'У' => 'у',
'Ф' => 'ф',
'Ð¥' => 'Ñ…',
'Ц' => 'ц',
'Ч' => 'ч',
'Ш' => 'ш',
'Щ' => 'щ',
'Ъ' => 'ъ',
'Ы' => 'ы',
'Ь' => 'ь',
'Э' => 'Ñ<>',
'Ю' => 'ю',
'Я' => 'Ñ<>',
'Ñ ' => 'Ñ¡',
'Ñ¢' => 'Ñ£',
'Ѥ' => 'ѥ',
'Ѧ' => 'ѧ',
'Ѩ' => 'ѩ',
'Ѫ' => 'ѫ',
'Ѭ' => 'ѭ',
'Ѯ' => 'ѯ',
'Ѱ' => 'ѱ',
'Ѳ' => 'ѳ',
'Ѵ' => 'ѵ',
'Ѷ' => 'ѷ',
'Ѹ' => 'ѹ',
'Ѻ' => 'ѻ',
'Ѽ' => 'ѽ',
'Ѿ' => 'ѿ',
'Ò€' => 'Ò<>',
'ÒŠ' => 'Ò‹',
'ÒŒ' => 'Ò<>',
'ÒŽ' => 'Ò<>',
<>' => 'Ò‘',
'Ò’' => 'Ò“',
'Ò”' => 'Ò•',
'Ò–' => 'Ò—',
'Ò˜' => 'Ò™',
'Òš' => 'Ò›',
'Òœ' => 'Ò<>',
'Òž' => 'ÒŸ',
'Ò ' => 'Ò¡',
'Ò¢' => 'Ò£',
'Ò¤' => 'Ò¥',
'Ò¦' => 'Ò§',
'Ò¨' => 'Ò©',
'Òª' => 'Ò«',
'Ò¬' => 'Ò­',
'Ò®' => 'Ò¯',
'Ò°' => 'Ò±',
'Ò²' => 'Ò³',
'Ò´' => 'Òµ',
'Ò¶' => 'Ò·',
'Ò¸' => 'Ò¹',
'Òº' => 'Ò»',
'Ò¼' => 'Ò½',
'Ò¾' => 'Ò¿',
'Ó€' => 'Ó<>',
<>' => 'Ó‚',
'Óƒ' => 'Ó„',
'Ó…' => 'Ó†',
'Ó‡' => 'Óˆ',
'Ó‰' => 'ÓŠ',
'Ӌ' => 'ӌ',
<>' => 'ÓŽ',
<>' => 'Ó‘',
'Ó’' => 'Ó“',
'Ó”' => 'Ó•',
'Ó–' => 'Ó—',
'Ó˜' => 'Ó™',
'Óš' => 'Ó›',
'Óœ' => 'Ó<>',
'Óž' => 'ÓŸ',
'Ó ' => 'Ó¡',
'Ó¢' => 'Ó£',
'Ó¤' => 'Ó¥',
'Ó¦' => 'Ó§',
'Ó¨' => 'Ó©',
'Óª' => 'Ó«',
'Ó¬' => 'Ó­',
'Ó®' => 'Ó¯',
'Ó°' => 'Ó±',
'Ó²' => 'Ó³',
'Ó´' => 'Óµ',
'Ó¶' => 'Ó·',
'Ó¸' => 'Ó¹',
'Óº' => 'Ó»',
'Ó¼' => 'Ó½',
'Ó¾' => 'Ó¿',
'Ô€' => 'Ô<>',
'Ô‚' => 'Ôƒ',
'Ô„' => 'Ô…',
'Ô†' => 'Ô‡',
'Ôˆ' => 'Ô‰',
'ÔŠ' => 'Ô‹',
'ÔŒ' => 'Ô<>',
'ÔŽ' => 'Ô<>',
<>' => 'Ô‘',
'Ô’' => 'Ô“',
'Ô”' => 'Ô•',
'Ô–' => 'Ô—',
'Ô˜' => 'Ô™',
'Ôš' => 'Ô›',
'Ôœ' => 'Ô<>',
'Ôž' => 'ÔŸ',
'Ô ' => 'Ô¡',
'Ô¢' => 'Ô£',
'Ô¤' => 'Ô¥',
'Ô¦' => 'Ô§',
'Ô¨' => 'Ô©',
'Ôª' => 'Ô«',
'Ô¬' => 'Ô­',
'Ô®' => 'Ô¯',
'Ô±' => 'Õ¡',
'Ô²' => 'Õ¢',
'Ô³' => 'Õ£',
'Ô´' => 'Õ¤',
'Ôµ' => 'Õ¥',
'Ô¶' => 'Õ¦',
'Ô·' => 'Õ§',
'Ô¸' => 'Õ¨',
'Ô¹' => 'Õ©',
'Ôº' => 'Õª',
'Ô»' => 'Õ«',
'Ô¼' => 'Õ¬',
'Ô½' => 'Õ­',
'Ô¾' => 'Õ®',
'Ô¿' => 'Õ¯',
'Õ€' => 'Õ°',
<>' => 'Õ±',
'Õ‚' => 'Õ²',
'Õƒ' => 'Õ³',
'Õ„' => 'Õ´',
'Õ…' => 'Õµ',
'Õ†' => 'Õ¶',
'Õ‡' => 'Õ·',
'Õˆ' => 'Õ¸',
'Õ‰' => 'Õ¹',
'ÕŠ' => 'Õº',
'Õ‹' => 'Õ»',
'Ռ' => 'ռ',
<>' => 'Õ½',
'ÕŽ' => 'Õ¾',
<>' => 'Õ¿',
<>' => 'Ö€',
'Õ‘' => 'Ö<>',
'Õ’' => 'Ö‚',
'Õ“' => 'Öƒ',
'Õ”' => 'Ö„',
'Õ•' => 'Ö…',
'Õ–' => 'Ö†',
'á‚ ' => 'â´€',
'á‚¡' => 'â´<C3A2>',
'á‚¢' => 'â´‚',
'á‚£' => 'â´ƒ',
'Ⴄ' => 'ⴄ',
'á‚¥' => 'â´…',
'Ⴆ' => 'ⴆ',
'Ⴇ' => 'ⴇ',
'Ⴈ' => 'ⴈ',
'á‚©' => 'â´‰',
'Ⴊ' => 'ⴊ',
'á‚«' => 'â´‹',
'Ⴌ' => 'ⴌ',
'á‚­' => 'â´<C3A2>',
'á‚®' => 'â´Ž',
'Ⴏ' => 'â´<C3A2>',
'á‚°' => 'â´<C3A2>',
'Ⴑ' => 'ⴑ',
'Ⴒ' => 'ⴒ',
'Ⴓ' => 'ⴓ',
'á‚´' => 'â´”',
'Ⴕ' => 'ⴕ',
'Ⴖ' => 'ⴖ',
'á‚·' => 'â´—',
'Ⴘ' => 'ⴘ',
'Ⴙ' => 'ⴙ',
'Ⴚ' => 'ⴚ',
'á‚»' => 'â´›',
'Ⴜ' => 'ⴜ',
'Ⴝ' => 'â´<C3A2>',
'Ⴞ' => 'ⴞ',
'á‚¿' => 'â´Ÿ',
'Ⴠ' => 'ⴠ',
'áƒ<C3A1>' => 'â´¡',
'Ⴢ' => 'ⴢ',
'Ⴣ' => 'ⴣ',
'Ⴤ' => 'ⴤ',
'Ⴥ' => 'ⴥ',
'Ⴧ' => 'ⴧ',
'áƒ<C3A1>' => 'â´­',
'Ḁ' => 'á¸<C3A1>',
'Ḃ' => 'ḃ',
'Ḅ' => 'ḅ',
'Ḇ' => 'ḇ',
'Ḉ' => 'ḉ',
'Ḋ' => 'ḋ',
'Ḍ' => 'á¸<C3A1>',
'Ḏ' => 'á¸<C3A1>',
¸<C3A1>' => 'ḑ',
'Ḓ' => 'ḓ',
'Ḕ' => 'ḕ',
'Ḗ' => 'ḗ',
'Ḙ' => 'ḙ',
'Ḛ' => 'ḛ',
'Ḝ' => 'á¸<C3A1>',
'Ḟ' => 'ḟ',
'Ḡ' => 'ḡ',
'Ḣ' => 'ḣ',
'Ḥ' => 'ḥ',
'Ḧ' => 'ḧ',
'Ḩ' => 'ḩ',
'Ḫ' => 'ḫ',
'Ḭ' => 'ḭ',
'Ḯ' => 'ḯ',
'Ḱ' => 'ḱ',
'Ḳ' => 'ḳ',
'Ḵ' => 'ḵ',
'Ḷ' => 'ḷ',
'Ḹ' => 'ḹ',
'Ḻ' => 'ḻ',
'Ḽ' => 'ḽ',
'Ḿ' => 'ḿ',
'á¹€' => 'á¹<C3A1>',
'Ṃ' => 'ṃ',
'Ṅ' => 'ṅ',
'Ṇ' => 'ṇ',
'Ṉ' => 'ṉ',
'Ṋ' => 'ṋ',
'Ṍ' => 'á¹<C3A1>',
'Ṏ' => 'á¹<C3A1>',
'á¹<C3A1>' => 'ṑ',
'Ṓ' => 'ṓ',
'Ṕ' => 'ṕ',
'á¹–' => 'á¹—',
'Ṙ' => 'ṙ',
'Ṛ' => 'ṛ',
'Ṝ' => 'á¹<C3A1>',
'Ṟ' => 'ṟ',
'Ṡ' => 'ṡ',
'á¹¢' => 'á¹£',
'Ṥ' => 'ṥ',
'Ṧ' => 'ṧ',
'Ṩ' => 'ṩ',
'Ṫ' => 'ṫ',
'Ṭ' => 'ṭ',
'Ṯ' => 'ṯ',
'á¹°' => 'á¹±',
'á¹²' => 'á¹³',
'á¹´' => 'á¹µ',
'Ṷ' => 'ṷ',
'Ṹ' => 'ṹ',
'Ṻ' => 'ṻ',
'á¹¼' => 'á¹½',
'Ṿ' => 'ṿ',
'Ẁ' => 'áº<C3A1>',
'Ẃ' => 'ẃ',
'Ẅ' => 'ẅ',
'Ẇ' => 'ẇ',
'Ẉ' => 'ẉ',
'Ẋ' => 'ẋ',
'Ẍ' => 'áº<C3A1>',
'Ẏ' => 'áº<C3A1>',
'áº<C3A1>' => 'ẑ',
'Ẓ' => 'ẓ',
'Ẕ' => 'ẕ',
'ẞ' => 'ß',
'Ạ' => 'ạ',
'Ả' => 'ả',
'Ấ' => 'ấ',
'Ầ' => 'ầ',
'Ẩ' => 'ẩ',
'Ẫ' => 'ẫ',
'Ậ' => 'ậ',
'Ắ' => 'ắ',
'Ằ' => 'ằ',
'Ẳ' => 'ẳ',
'Ẵ' => 'ẵ',
'Ặ' => 'ặ',
'Ẹ' => 'ẹ',
'Ẻ' => 'ẻ',
'Ẽ' => 'ẽ',
'Ế' => 'ế',
'Ề' => 'á»<C3A1>',
'Ể' => 'ể',
'Ễ' => 'ễ',
'Ệ' => 'ệ',
'Ỉ' => 'ỉ',
'Ị' => 'ị',
'Ọ' => 'á»<C3A1>',
'Ỏ' => 'á»<C3A1>',
'á»<C3A1>' => 'ố',
'Ồ' => 'ồ',
'Ổ' => 'ổ',
'á»–' => 'á»—',
'Ộ' => 'ộ',
'Ớ' => 'ớ',
'Ờ' => 'á»<C3A1>',
'Ở' => 'ở',
'Ỡ' => 'ỡ',
'Ợ' => 'ợ',
'Ụ' => 'ụ',
'Ủ' => 'ủ',
'Ứ' => 'ứ',
'Ừ' => 'ừ',
'Ử' => 'ử',
'Ữ' => 'ữ',
'á»°' => 'á»±',
'Ỳ' => 'ỳ',
'Ỵ' => 'ỵ',
'Ỷ' => 'ỷ',
'Ỹ' => 'ỹ',
'Ỻ' => 'ỻ',
'Ỽ' => 'ỽ',
'Ỿ' => 'ỿ',
'Ἀ' => 'ἀ',
'Ἁ' => 'á¼<C3A1>',
'Ἂ' => 'ἂ',
'Ἃ' => 'ἃ',
'Ἄ' => 'ἄ',
'á¼<C3A1>' => 'á¼…',
'Ἆ' => 'ἆ',
'á¼<C3A1>' => 'ἇ',
'Ἐ' => 'á¼<C3A1>',
'Ἑ' => 'ἑ',
'Ἒ' => 'ἒ',
'Ἓ' => 'ἓ',
'Ἔ' => 'ἔ',
'á¼<C3A1>' => 'ἕ',
'Ἠ' => 'ἠ',
'Ἡ' => 'ἡ',
'Ἢ' => 'ἢ',
'Ἣ' => 'ἣ',
'Ἤ' => 'ἤ',
'á¼­' => 'á¼¥',
'Ἦ' => 'ἦ',
'Ἧ' => 'ἧ',
'Ἰ' => 'ἰ',
'á¼¹' => 'á¼±',
'Ἲ' => 'ἲ',
'á¼»' => 'á¼³',
'á¼¼' => 'á¼´',
'á¼½' => 'á¼µ',
'Ἶ' => 'ἶ',
'Ἷ' => 'ἷ',
'Ὀ' => 'ὀ',
'Ὁ' => 'á½<C3A1>',
'Ὂ' => 'ὂ',
'Ὃ' => 'ὃ',
'Ὄ' => 'ὄ',
'á½<C3A1>' => 'á½…',
'Ὑ' => 'ὑ',
'Ὓ' => 'ὓ',
'á½<C3A1>' => 'ὕ',
'Ὗ' => 'ὗ',
'Ὠ' => 'ὠ',
'Ὡ' => 'ὡ',
'Ὢ' => 'ὢ',
'Ὣ' => 'ὣ',
'Ὤ' => 'ὤ',
'á½­' => 'á½¥',
'Ὦ' => 'ὦ',
'Ὧ' => 'ὧ',
'ᾈ' => 'ᾀ',
'ᾉ' => 'á¾<C3A1>',
'ᾊ' => 'ᾂ',
'ᾋ' => 'ᾃ',
'ᾌ' => 'ᾄ',
'á¾<C3A1>' => 'á¾…',
'ᾎ' => 'ᾆ',
'á¾<C3A1>' => 'ᾇ',
'ᾘ' => 'á¾<C3A1>',
'ᾙ' => 'ᾑ',
'ᾚ' => 'ᾒ',
'ᾛ' => 'ᾓ',
'ᾜ' => 'ᾔ',
'á¾<C3A1>' => 'ᾕ',
'ᾞ' => 'ᾖ',
'ᾟ' => 'ᾗ',
'ᾨ' => 'ᾠ',
'ᾩ' => 'ᾡ',
'ᾪ' => 'ᾢ',
'ᾫ' => 'ᾣ',
'ᾬ' => 'ᾤ',
'á¾­' => 'á¾¥',
'ᾮ' => 'ᾦ',
'ᾯ' => 'ᾧ',
'Ᾰ' => 'ᾰ',
'á¾¹' => 'á¾±',
'Ὰ' => 'ὰ',
'á¾»' => 'á½±',
'á¾¼' => 'á¾³',
'Ὲ' => 'ὲ',
'Έ' => 'έ',
'á¿Š' => 'á½´',
'á¿‹' => 'á½µ',
'ῌ' => 'ῃ',
'Ῐ' => 'á¿<C3A1>',
'á¿™' => 'á¿‘',
'Ὶ' => 'ὶ',
'á¿›' => 'á½·',
'Ῠ' => 'ῠ',
'á¿©' => 'á¿¡',
'Ὺ' => 'ὺ',
'á¿«' => 'á½»',
'Ῥ' => 'ῥ',
'Ὸ' => 'ὸ',
'Ό' => 'ό',
'Ὼ' => 'ὼ',
'á¿»' => 'á½½',
'ῼ' => 'ῳ',
'Ω' => 'ω',
'K' => 'k',
'â„«' => 'Ã¥',
'Ⅎ' => 'ⅎ',
'â… ' => 'â…°',
'â…¡' => 'â…±',
'â…¢' => 'â…²',
'â…£' => 'â…³',
'â…¤' => 'â…´',
'â…¥' => 'â…µ',
'â…¦' => 'â…¶',
'â…§' => 'â…·',
'â…¨' => 'â…¸',
'â…©' => 'â…¹',
'â…ª' => 'â…º',
'â…«' => 'â…»',
'â…¬' => 'â…¼',
'â…­' => 'â…½',
'â…®' => 'â…¾',
'â…¯' => 'â…¿',
'Ↄ' => 'ↄ',
'â’¶' => 'â“<C3A2>',
'â’·' => 'â“‘',
'â’¸' => 'â“’',
'â’¹' => 'â““',
'â’º' => 'â“”',
'â’»' => 'â“•',
'â’¼' => 'â“–',
'â’½' => 'â“—',
'Ⓘ' => 'ⓘ',
'â’¿' => 'â“™',
'â“€' => 'â“š',
'â“<C3A2>' => 'â“›',
'Ⓜ' => 'ⓜ',
'Ⓝ' => 'â“<C3A2>',
'â“„' => 'â“ž',
'â“…' => 'â“Ÿ',
'Ⓠ' => 'ⓠ',
'Ⓡ' => 'ⓡ',
'Ⓢ' => 'ⓢ',
'Ⓣ' => 'ⓣ',
'Ⓤ' => 'ⓤ',
'â“‹' => 'â“¥',
'Ⓦ' => 'ⓦ',
'â“<C3A2>' => 'ⓧ',
'Ⓨ' => 'ⓨ',
'â“<C3A2>' => 'â“©',
'â°€' => 'â°°',
'â°<C3A2>' => 'â°±',
'â°‚' => 'â°²',
'â°ƒ' => 'â°³',
'â°„' => 'â°´',
'â°…' => 'â°µ',
'â°†' => 'â°¶',
'â°‡' => 'â°·',
'â°ˆ' => 'â°¸',
'â°‰' => 'â°¹',
'â°Š' => 'â°º',
'â°‹' => 'â°»',
'Ⰼ' => 'ⰼ',
'â°<C3A2>' => 'â°½',
'â°Ž' => 'â°¾',
'â°<C3A2>' => 'â°¿',
'â°<C3A2>' => 'â±€',
'â°‘' => 'â±<C3A2>',
'Ⱂ' => 'ⱂ',
'Ⱃ' => 'ⱃ',
'Ⱄ' => 'ⱄ',
'â°•' => 'â±…',
'Ⱆ' => 'ⱆ',
'Ⱇ' => 'ⱇ',
'Ⱈ' => 'ⱈ',
'Ⱉ' => 'ⱉ',
'Ⱊ' => 'ⱊ',
'Ⱋ' => 'ⱋ',
'Ⱌ' => 'ⱌ',
'â°<C3A2>' => 'â±<C3A2>',
'Ⱎ' => 'ⱎ',
'â°Ÿ' => 'â±<C3A2>',
'â° ' => 'â±<C3A2>',
'Ⱑ' => 'ⱑ',
'â°¢' => 'â±’',
'Ⱓ' => 'ⱓ',
'â°¤' => 'â±”',
'Ⱕ' => 'ⱕ',
'â°¦' => 'â±–',
'â°§' => 'â±—',
'Ⱘ' => 'ⱘ',
'â°©' => 'â±™',
'Ⱚ' => 'ⱚ',
'â°«' => 'â±›',
'Ⱜ' => 'ⱜ',
'â°­' => 'â±<C3A2>',
'Ⱞ' => 'ⱞ',
'Ⱡ' => 'ⱡ',
'â±¢' => 'É«',
'â±£' => 'áµ½',
'Ɽ' => 'ɽ',
'Ⱨ' => 'ⱨ',
'Ⱪ' => 'ⱪ',
'Ⱬ' => 'ⱬ',
'â±­' => 'É‘',
'Ɱ' => 'ɱ',
'Ɐ' => 'É<>',
'â±°' => 'É’',
'â±²' => 'â±³',
'Ⱶ' => 'ⱶ',
'â±¾' => 'È¿',
'Ɀ' => 'ɀ',
'â²€' => 'â²<C3A2>',
'Ⲃ' => 'ⲃ',
'Ⲅ' => 'ⲅ',
'Ⲇ' => 'ⲇ',
'Ⲉ' => 'ⲉ',
'Ⲋ' => 'ⲋ',
'Ⲍ' => 'â²<C3A2>',
'Ⲏ' => 'â²<C3A2>',
'â²<C3A2>' => 'ⲑ',
'Ⲓ' => 'ⲓ',
'Ⲕ' => 'ⲕ',
'â²–' => 'â²—',
'Ⲙ' => 'ⲙ',
'Ⲛ' => 'ⲛ',
'Ⲝ' => 'â²<C3A2>',
'Ⲟ' => 'ⲟ',
'Ⲡ' => 'ⲡ',
'â²¢' => 'â²£',
'Ⲥ' => 'ⲥ',
'Ⲧ' => 'ⲧ',
'Ⲩ' => 'ⲩ',
'Ⲫ' => 'ⲫ',
'Ⲭ' => 'ⲭ',
'Ⲯ' => 'ⲯ',
'â²°' => 'â²±',
'â²²' => 'â²³',
'â²´' => 'â²µ',
'Ⲷ' => 'ⲷ',
'Ⲹ' => 'ⲹ',
'Ⲻ' => 'ⲻ',
'â²¼' => 'â²½',
'Ⲿ' => 'ⲿ',
'â³€' => 'â³<C3A2>',
'Ⳃ' => 'ⳃ',
'Ⳅ' => 'ⳅ',
'Ⳇ' => 'ⳇ',
'Ⳉ' => 'ⳉ',
'Ⳋ' => 'ⳋ',
'Ⳍ' => 'â³<C3A2>',
'Ⳏ' => 'â³<C3A2>',
'â³<C3A2>' => 'ⳑ',
'Ⳓ' => 'ⳓ',
'Ⳕ' => 'ⳕ',
'â³–' => 'â³—',
'Ⳙ' => 'ⳙ',
'Ⳛ' => 'ⳛ',
'Ⳝ' => 'â³<C3A2>',
'Ⳟ' => 'ⳟ',
'Ⳡ' => 'ⳡ',
'â³¢' => 'â³£',
'Ⳬ' => 'ⳬ',
'â³­' => 'â³®',
'â³²' => 'â³³',
'Ꙁ' => 'ê™<C3AA>',
'Ꙃ' => 'ꙃ',
'Ꙅ' => 'ꙅ',
'Ꙇ' => 'ꙇ',
'Ꙉ' => 'ꙉ',
'Ꙋ' => 'ꙋ',
'Ꙍ' => 'ê™<C3AA>',
'Ꙏ' => 'ê™<C3AA>',
'ê™<C3AA>' => 'ꙑ',
'Ꙓ' => 'ꙓ',
'Ꙕ' => 'ꙕ',
'ê™–' => 'ê™—',
'Ꙙ' => 'ꙙ',
'Ꙛ' => 'ꙛ',
'Ꙝ' => 'ê™<C3AA>',
'Ꙟ' => 'ꙟ',
'Ꙡ' => 'ꙡ',
'Ꙣ' => 'ꙣ',
'Ꙥ' => 'ꙥ',
'Ꙧ' => 'ꙧ',
'Ꙩ' => 'ꙩ',
'Ꙫ' => 'ꙫ',
'Ꙭ' => 'ꙭ',
'Ꚁ' => 'êš<C3AA>',
'Ꚃ' => 'ꚃ',
'êš„' => 'êš…',
'Ꚇ' => 'ꚇ',
'Ꚉ' => 'ꚉ',
'Ꚋ' => 'ꚋ',
'Ꚍ' => 'êš<C3AA>',
'Ꚏ' => 'êš<C3AA>',
'êš<C3AA>' => 'êš‘',
'êš’' => 'êš“',
'êš”' => 'êš•',
'êš–' => 'êš—',
'Ꚙ' => 'ꚙ',
'êšš' => 'êš›',
'Ꜣ' => 'ꜣ',
'Ꜥ' => 'ꜥ',
'Ꜧ' => 'ꜧ',
'Ꜩ' => 'ꜩ',
'Ꜫ' => 'ꜫ',
'Ꜭ' => 'ꜭ',
'Ꜯ' => 'ꜯ',
'Ꜳ' => 'ꜳ',
'Ꜵ' => 'ꜵ',
'Ꜷ' => 'ꜷ',
'Ꜹ' => 'ꜹ',
'Ꜻ' => 'ꜻ',
'Ꜽ' => 'ꜽ',
'Ꜿ' => 'ꜿ',
<>€' => 'ê<><C3AA>',
<>' => 'ê<>ƒ',
<>„' => 'ê<>…',
<>†' => 'ê<>‡',
<>ˆ' => 'ê<>‰',
<>Š' => 'ê<>',
<>Œ' => 'ê<><C3AA>',
<>Ž' => 'ê<><C3AA>',
<><C3AA>' => 'ê<>',
<>' => 'ê<>“',
<>”' => 'ê<>•',
<>' => 'ê<>—',
<>˜' => 'ê<>™',
<>š' => 'ê<>',
<>œ' => 'ê<><C3AA>',
<>ž' => 'ê<>Ÿ',
<> ' => 'ê<>¡',
<>¢' => 'ê<>£',
<>¤' => 'ê<>¥',
<>¦' => 'ê<>§',
<>¨' => 'ê<>©',
<>ª' => 'ê<>«',
<>¬' => 'ê<>­',
<>®' => 'ê<>¯',
<>¹' => 'ê<>º',
<>»' => 'ê<>¼',
<>½' => 'áµ¹',
<>¾' => 'ê<>¿',
'Ꞁ' => 'êž<C3AA>',
'Ꞃ' => 'ꞃ',
'êž„' => 'êž…',
'Ꞇ' => 'ꞇ',
'Ꞌ' => 'ꞌ',
'êž<C3AA>' => 'É¥',
'êž<C3AA>' => 'êž‘',
'êž’' => 'êž“',
'êž–' => 'êž—',
'Ꞙ' => 'ꞙ',
'êžš' => 'êž›',
'êžœ' => 'êž<C3AA>',
'Ꞟ' => 'ꞟ',
'êž ' => 'êž¡',
'Ꞣ' => 'ꞣ',
'Ꞥ' => 'ꞥ',
'Ꞧ' => 'ꞧ',
'Ꞩ' => 'ꞩ',
'Ɦ' => 'ɦ',
'Ɜ' => 'ɜ',
'Ɡ' => 'ɡ',
'Ɬ' => 'ɬ',
'êž°' => 'Êž',
'Ʇ' => 'ʇ',
'A' => 'ï½<C3AF>',
'B' => 'b',
'C' => 'c',
'D' => 'd',
'ï¼¥' => 'ï½…',
'F' => 'f',
'G' => 'g',
'H' => 'h',
'I' => 'i',
'J' => 'j',
'K' => 'k',
'L' => 'l',
'ï¼­' => 'ï½<C3AF>',
'N' => 'n',
'O' => 'ï½<C3AF>',
'ï¼°' => 'ï½<C3AF>',
'Q' => 'q',
'ï¼²' => 'ï½’',
'S' => 's',
'ï¼´' => 'ï½”',
'U' => 'u',
'V' => 'v',
'ï¼·' => 'ï½—',
'X' => 'x',
'ï¼¹' => 'ï½™',
'Z' => 'z',
<><C3B0>€' => 'ð<><C3B0>¨',
<><C3B0><EFBFBD>' => 'ð<><C3B0>©',
<><C3B0>' => 'ð<><C3B0>ª',
<><C3B0>ƒ' => 'ð<><C3B0>«',
<><C3B0>„' => 'ð<><C3B0>¬',
<><C3B0>…' => 'ð<><C3B0>­',
<><C3B0>†' => 'ð<><C3B0>®',
<><C3B0>‡' => 'ð<><C3B0>¯',
<><C3B0>ˆ' => 'ð<><C3B0>°',
<><C3B0>‰' => 'ð<><C3B0>±',
<><C3B0>Š' => 'ð<><C3B0>²',
<><C3B0>' => 'ð<><C3B0>³',
<><C3B0>Œ' => 'ð<><C3B0>´',
<><C3B0><EFBFBD>' => 'ð<><C3B0>µ',
<><C3B0>Ž' => 'ð<><C3B0>¶',
<><C3B0><EFBFBD>' => 'ð<><C3B0>·',
<><C3B0><EFBFBD>' => 'ð<><C3B0>¸',
<><C3B0>' => 'ð<><C3B0>¹',
<><C3B0>' => 'ð<><C3B0>º',
<><C3B0>“' => 'ð<><C3B0>»',
<><C3B0>”' => 'ð<><C3B0>¼',
<><C3B0>•' => 'ð<><C3B0>½',
<><C3B0>' => 'ð<><C3B0>¾',
<><C3B0>—' => 'ð<><C3B0>¿',
<><C3B0>˜' => 'ð<>€',
<><C3B0>™' => 'ð<><EFBFBD>',
<><C3B0>š' => 'ð<>',
<><C3B0>' => 'ð<>ƒ',
<><C3B0>œ' => 'ð<>„',
<><C3B0><EFBFBD>' => 'ð<>…',
<><C3B0>ž' => 'ð<>†',
<><C3B0>Ÿ' => 'ð<>‡',
<><C3B0> ' => 'ð<>ˆ',
<><C3B0>¡' => 'ð<>‰',
<><C3B0>¢' => 'ð<>Š',
<><C3B0>£' => 'ð<>',
<><C3B0>¤' => 'ð<>Œ',
<><C3B0>¥' => 'ð<><EFBFBD>',
<><C3B0>¦' => 'ð<>Ž',
<><C3B0>§' => 'ð<><EFBFBD>',
'ð‘¢ ' => 'ð‘£€',
'𑢡' => 'ð£<E28098>',
'𑢢' => '𑣂',
'𑢣' => '𑣃',
'𑢤' => '𑣄',
'ð‘¢¥' => 'ð‘£…',
'𑢦' => '𑣆',
'𑢧' => '𑣇',
'𑢨' => '𑣈',
'𑢩' => '𑣉',
'𑢪' => '𑣊',
'𑢫' => '𑣋',
'𑢬' => '𑣌',
'ð‘¢­' => 'ð£<E28098>',
'𑢮' => '𑣎',
'𑢯' => 'ð£<E28098>',
'ð‘¢°' => 'ð£<E28098>',
'𑢱' => '𑣑',
'ð‘¢²' => 'ð‘£’',
'𑢳' => '𑣓',
'ð‘¢´' => 'ð‘£”',
'𑢵' => '𑣕',
'𑢶' => '𑣖',
'ð‘¢·' => 'ð‘£—',
'𑢸' => '𑣘',
'ð‘¢¹' => 'ð‘£™',
'𑢺' => '𑣚',
'ð‘¢»' => 'ð‘£›',
'𑢼' => '𑣜',
'ð‘¢½' => 'ð£<E28098>',
'𑢾' => '𑣞',
'𑢿' => '𑣟',
);
$result =& $data;
unset($data);
return $result;
<?php
static $data = array (
'a' => 'A',
'b' => 'B',
'c' => 'C',
'd' => 'D',
'e' => 'E',
'f' => 'F',
'g' => 'G',
'h' => 'H',
'i' => 'I',
'j' => 'J',
'k' => 'K',
'l' => 'L',
'm' => 'M',
'n' => 'N',
'o' => 'O',
'p' => 'P',
'q' => 'Q',
'r' => 'R',
's' => 'S',
't' => 'T',
'u' => 'U',
'v' => 'V',
'w' => 'W',
'x' => 'X',
'y' => 'Y',
'z' => 'Z',
'µ' => 'Μ',
'à' => 'À',
'á' => 'Ã<>',
'â' => 'Â',
'ã' => 'Ã',
'ä' => 'Ä',
'Ã¥' => 'Ã…',
'æ' => 'Æ',
'ç' => 'Ç',
'è' => 'È',
'é' => 'É',
'ê' => 'Ê',
'ë' => 'Ë',
'ì' => 'Ì',
'í' => 'Ã<>',
'î' => 'Î',
'ï' => 'Ã<>',
'ð' => 'Ã<>',
'ñ' => 'Ñ',
'ò' => 'Ò',
'ó' => 'Ó',
'ô' => 'Ô',
'õ' => 'Õ',
'ö' => 'Ö',
'ø' => 'Ø',
'ù' => 'Ù',
'ú' => 'Ú',
'û' => 'Û',
'ü' => 'Ü',
'ý' => 'Ã<>',
'þ' => 'Þ',
'ÿ' => 'Ÿ',
<>' => 'Ä€',
'ă' => 'Ă',
'Ä…' => 'Ä„',
'ć' => 'Ć',
'ĉ' => 'Ĉ',
'Ä‹' => 'ÄŠ',
<>' => 'Č',
<>' => 'ÄŽ',
'Ä‘' => 'Ä<>',
'Ä“' => 'Ä’',
'Ä•' => 'Ä”',
'Ä—' => 'Ä–',
'ę' => 'Ę',
'Ä›' => 'Äš',
<>' => 'Ĝ',
'ÄŸ' => 'Äž',
'Ä¡' => 'Ä ',
'Ä£' => 'Ä¢',
'ĥ' => 'Ĥ',
'ħ' => 'Ħ',
'ĩ' => 'Ĩ',
'ī' => 'Ī',
'ĭ' => 'Ĭ',
'į' => 'Į',
'ı' => 'I',
'ij' => 'IJ',
'ĵ' => 'Ĵ',
'ķ' => 'Ķ',
'ĺ' => 'Ĺ',
'ļ' => 'Ļ',
'ľ' => 'Ľ',
'Å€' => 'Ä¿',
'Å‚' => 'Å<>',
'ń' => 'Ń',
'ņ' => 'Ņ',
'ň' => 'Ň',
'Å‹' => 'ÅŠ',
<>' => 'Ō',
<>' => 'ÅŽ',
'Å‘' => 'Å<>',
'Å“' => 'Å’',
'Å•' => 'Å”',
'Å—' => 'Å–',
'ř' => 'Ř',
'Å›' => 'Åš',
<>' => 'Ŝ',
'ÅŸ' => 'Åž',
'Å¡' => 'Å ',
'Å£' => 'Å¢',
'ť' => 'Ť',
'ŧ' => 'Ŧ',
'ũ' => 'Ũ',
'ū' => 'Ū',
'ŭ' => 'Ŭ',
'ů' => 'Ů',
'ű' => 'Ű',
'ų' => 'Ų',
'ŵ' => 'Ŵ',
'ŷ' => 'Ŷ',
'ź' => 'Ź',
'ż' => 'Ż',
'ž' => 'Ž',
'Å¿' => 'S',
'ƀ' => 'Ƀ',
'ƃ' => 'Ƃ',
'Æ…' => 'Æ„',
'ƈ' => 'Ƈ',
'ƌ' => 'Ƌ',
'Æ’' => 'Æ‘',
'ƕ' => 'Ƕ',
'ƙ' => 'Ƙ',
'ƚ' => 'Ƚ',
'Æž' => 'È ',
'Æ¡' => 'Æ ',
'Æ£' => 'Æ¢',
'ƥ' => 'Ƥ',
'ƨ' => 'Ƨ',
'ƭ' => 'Ƭ',
'ư' => 'Ư',
'ƴ' => 'Ƴ',
'ƶ' => 'Ƶ',
'ƹ' => 'Ƹ',
'ƽ' => 'Ƽ',
'Æ¿' => 'Ç·',
'Ç…' => 'Ç„',
'dž' => 'DŽ',
'Lj' => 'LJ',
'lj' => 'LJ',
'Ç‹' => 'ÇŠ',
'nj' => 'NJ',
'ÇŽ' => 'Ç<>',
<>' => 'Ç<>',
'Ç’' => 'Ç‘',
'Ç”' => 'Ç“',
'Ç–' => 'Ç•',
'ǘ' => 'Ǘ',
'Çš' => 'Ç™',
'ǜ' => 'Ǜ',
<>' => 'ÆŽ',
'ÇŸ' => 'Çž',
'Ç¡' => 'Ç ',
'Ç£' => 'Ç¢',
'ǥ' => 'Ǥ',
'ǧ' => 'Ǧ',
'ǩ' => 'Ǩ',
'ǫ' => 'Ǫ',
'ǭ' => 'Ǭ',
'ǯ' => 'Ǯ',
'Dz' => 'DZ',
'dz' => 'DZ',
'ǵ' => 'Ǵ',
'ǹ' => 'Ǹ',
'ǻ' => 'Ǻ',
'ǽ' => 'Ǽ',
'ǿ' => 'Ǿ',
<>' => 'È€',
'ȃ' => 'Ȃ',
'È…' => 'È„',
'ȇ' => 'Ȇ',
'ȉ' => 'Ȉ',
'È‹' => 'ÈŠ',
<>' => 'Ȍ',
<>' => 'ÈŽ',
'È‘' => 'È<>',
'È“' => 'È’',
'È•' => 'È”',
'È—' => 'È–',
'ș' => 'Ș',
'È›' => 'Èš',
<>' => 'Ȝ',
'ÈŸ' => 'Èž',
'È£' => 'È¢',
'ȥ' => 'Ȥ',
'ȧ' => 'Ȧ',
'ȩ' => 'Ȩ',
'ȫ' => 'Ȫ',
'ȭ' => 'Ȭ',
'ȯ' => 'Ȯ',
'ȱ' => 'Ȱ',
'ȳ' => 'Ȳ',
'ȼ' => 'Ȼ',
'È¿' => 'â±¾',
'ɀ' => 'Ɀ',
'É‚' => 'É<>',
'ɇ' => 'Ɇ',
'ɉ' => 'Ɉ',
'É‹' => 'ÉŠ',
<>' => 'Ɍ',
<>' => 'ÉŽ',
<>' => 'Ɐ',
'É‘' => 'â±­',
'É’' => 'â±°',
'É“' => 'Æ<>',
'ɔ' => 'Ɔ',
'ɖ' => 'Ɖ',
'É—' => 'ÆŠ',
'É™' => 'Æ<>',
'É›' => 'Æ<>',
'ɜ' => 'Ɜ',
'É ' => 'Æ“',
'ɡ' => 'Ɡ',
'É£' => 'Æ”',
'É¥' => 'êž<C3AA>',
'ɦ' => 'Ɦ',
'ɨ' => 'Ɨ',
'É©' => 'Æ–',
'É«' => 'â±¢',
'ɬ' => 'Ɬ',
'ɯ' => 'Ɯ',
'ɱ' => 'Ɱ',
'ɲ' => 'Æ<>',
'ɵ' => 'Ɵ',
'ɽ' => 'Ɽ',
'ʀ' => 'Ʀ',
'ʃ' => 'Ʃ',
'ʇ' => 'Ʇ',
'ʈ' => 'Ʈ',
'ʉ' => 'Ʉ',
'ʊ' => 'Ʊ',
'ʋ' => 'Ʋ',
'ʌ' => 'Ʌ',
'Ê’' => 'Æ·',
'Êž' => 'êž°',
'ͅ' => 'Ι',
'ͱ' => 'Ͱ',
'ͳ' => 'Ͳ',
'ͷ' => 'Ͷ',
'ͻ' => 'Ͻ',
'ͼ' => 'Ͼ',
'ͽ' => 'Ͽ',
'ά' => 'Ά',
'έ' => 'Έ',
'ή' => 'Ή',
'ί' => 'Ί',
'α' => 'Α',
'β' => 'Β',
'γ' => 'Γ',
'δ' => 'Δ',
'ε' => 'Ε',
'ζ' => 'Ζ',
'η' => 'Η',
'θ' => 'Θ',
'ι' => 'Ι',
'κ' => 'Κ',
'λ' => 'Λ',
'μ' => 'Μ',
'ν' => 'Î<>',
'ξ' => 'Ξ',
'ο' => 'Ο',
'π' => 'Π',
<>' => 'Ρ',
'ς' => 'Σ',
'σ' => 'Σ',
'τ' => 'Τ',
'Ï…' => 'Î¥',
'φ' => 'Φ',
'χ' => 'Χ',
'ψ' => 'Ψ',
'ω' => 'Ω',
'ϊ' => 'Ϊ',
'ϋ' => 'Ϋ',
'ό' => 'Ό',
<>' => 'ÎŽ',
'ÏŽ' => 'Î<>',
<>' => 'Î’',
'ϑ' => 'Θ',
'ϕ' => 'Φ',
'ϖ' => 'Π',
'Ï—' => 'Ï<>',
'ϙ' => 'Ϙ',
'Ï›' => 'Ïš',
<>' => 'Ϝ',
'ÏŸ' => 'Ïž',
'Ï¡' => 'Ï ',
'Ï£' => 'Ï¢',
'ϥ' => 'Ϥ',
'ϧ' => 'Ϧ',
'ϩ' => 'Ϩ',
'ϫ' => 'Ϫ',
'ϭ' => 'Ϭ',
'ϯ' => 'Ϯ',
'ϰ' => 'Κ',
'ϱ' => 'Ρ',
'ϲ' => 'Ϲ',
'ϳ' => 'Ϳ',
'ϵ' => 'Ε',
'ϸ' => 'Ϸ',
'ϻ' => 'Ϻ',
'а' => 'Ð<>',
'б' => 'Б',
'в' => 'В',
'г' => 'Г',
'д' => 'Д',
'е' => 'Е',
'ж' => 'Ж',
'з' => 'З',
'и' => 'И',
'й' => 'Й',
'к' => 'К',
'л' => 'Л',
'м' => 'М',
'н' => 'Ð<>',
'о' => 'О',
'п' => 'П',
'р' => 'Р',
<>' => 'С',
'т' => 'Т',
'у' => 'У',
'ф' => 'Ф',
'Ñ…' => 'Ð¥',
'ц' => 'Ц',
'ч' => 'Ч',
'ш' => 'Ш',
'щ' => 'Щ',
'ъ' => 'Ъ',
'ы' => 'Ы',
'ь' => 'Ь',
<>' => 'Э',
'ю' => 'Ю',
<>' => 'Я',
<>' => 'Ѐ',
'Ñ‘' => 'Ð<>',
'ђ' => 'Ђ',
'ѓ' => 'Ѓ',
'є' => 'Є',
'Ñ•' => 'Ð…',
'і' => 'І',
'ї' => 'Ї',
'ј' => 'Ј',
'љ' => 'Љ',
'њ' => 'Њ',
'ћ' => 'Ћ',
'ќ' => 'Ќ',
<>' => 'Ð<>',
'Ñž' => 'ÐŽ',
'ÑŸ' => 'Ð<>',
'Ñ¡' => 'Ñ ',
'Ñ£' => 'Ñ¢',
'ѥ' => 'Ѥ',
'ѧ' => 'Ѧ',
'ѩ' => 'Ѩ',
'ѫ' => 'Ѫ',
'ѭ' => 'Ѭ',
'ѯ' => 'Ѯ',
'ѱ' => 'Ѱ',
'ѳ' => 'Ѳ',
'ѵ' => 'Ѵ',
'ѷ' => 'Ѷ',
'ѹ' => 'Ѹ',
'ѻ' => 'Ѻ',
'ѽ' => 'Ѽ',
'ѿ' => 'Ѿ',
<>' => 'Ò€',
'Ò‹' => 'ÒŠ',
<>' => 'Ҍ',
<>' => 'ÒŽ',
'Ò‘' => 'Ò<>',
'Ò“' => 'Ò’',
'Ò•' => 'Ò”',
'Ò—' => 'Ò–',
'Ò™' => 'Ò˜',
'Ò›' => 'Òš',
<>' => 'Ҝ',
'ÒŸ' => 'Òž',
'Ò¡' => 'Ò ',
'Ò£' => 'Ò¢',
'Ò¥' => 'Ò¤',
'Ò§' => 'Ò¦',
'Ò©' => 'Ò¨',
'Ò«' => 'Òª',
'Ò­' => 'Ò¬',
'Ò¯' => 'Ò®',
'Ò±' => 'Ò°',
'Ò³' => 'Ò²',
'Òµ' => 'Ò´',
'Ò·' => 'Ò¶',
'Ò¹' => 'Ò¸',
'Ò»' => 'Òº',
'Ò½' => 'Ò¼',
'Ò¿' => 'Ò¾',
'Ó‚' => 'Ó<>',
'Ó„' => 'Óƒ',
'Ó†' => 'Ó…',
'Óˆ' => 'Ó‡',
'ÓŠ' => 'Ó‰',
'ӌ' => 'Ӌ',
'ÓŽ' => 'Ó<>',
<>' => 'Ó€',
'Ó‘' => 'Ó<>',
'Ó“' => 'Ó’',
'Ó•' => 'Ó”',
'Ó—' => 'Ó–',
'Ó™' => 'Ó˜',
'Ó›' => 'Óš',
<>' => 'Ӝ',
'ÓŸ' => 'Óž',
'Ó¡' => 'Ó ',
'Ó£' => 'Ó¢',
'Ó¥' => 'Ó¤',
'Ó§' => 'Ó¦',
'Ó©' => 'Ó¨',
'Ó«' => 'Óª',
'Ó­' => 'Ó¬',
'Ó¯' => 'Ó®',
'Ó±' => 'Ó°',
'Ó³' => 'Ó²',
'Óµ' => 'Ó´',
'Ó·' => 'Ó¶',
'Ó¹' => 'Ó¸',
'Ó»' => 'Óº',
'Ó½' => 'Ó¼',
'Ó¿' => 'Ó¾',
<>' => 'Ô€',
'Ôƒ' => 'Ô‚',
'Ô…' => 'Ô„',
'Ô‡' => 'Ô†',
'Ô‰' => 'Ôˆ',
'Ô‹' => 'ÔŠ',
<>' => 'Ԍ',
<>' => 'ÔŽ',
'Ô‘' => 'Ô<>',
'Ô“' => 'Ô’',
'Ô•' => 'Ô”',
'Ô—' => 'Ô–',
'Ô™' => 'Ô˜',
'Ô›' => 'Ôš',
<>' => 'Ԝ',
'ÔŸ' => 'Ôž',
'Ô¡' => 'Ô ',
'Ô£' => 'Ô¢',
'Ô¥' => 'Ô¤',
'Ô§' => 'Ô¦',
'Ô©' => 'Ô¨',
'Ô«' => 'Ôª',
'Ô­' => 'Ô¬',
'Ô¯' => 'Ô®',
'Õ¡' => 'Ô±',
'Õ¢' => 'Ô²',
'Õ£' => 'Ô³',
'Õ¤' => 'Ô´',
'Õ¥' => 'Ôµ',
'Õ¦' => 'Ô¶',
'Õ§' => 'Ô·',
'Õ¨' => 'Ô¸',
'Õ©' => 'Ô¹',
'Õª' => 'Ôº',
'Õ«' => 'Ô»',
'Õ¬' => 'Ô¼',
'Õ­' => 'Ô½',
'Õ®' => 'Ô¾',
'Õ¯' => 'Ô¿',
'Õ°' => 'Õ€',
'Õ±' => 'Õ<>',
'Õ²' => 'Õ‚',
'Õ³' => 'Õƒ',
'Õ´' => 'Õ„',
'Õµ' => 'Õ…',
'Õ¶' => 'Õ†',
'Õ·' => 'Õ‡',
'Õ¸' => 'Õˆ',
'Õ¹' => 'Õ‰',
'Õº' => 'ÕŠ',
'Õ»' => 'Õ‹',
'ռ' => 'Ռ',
'Õ½' => 'Õ<>',
'Õ¾' => 'ÕŽ',
'Õ¿' => 'Õ<>',
'Ö€' => 'Õ<>',
<>' => 'Õ‘',
'Ö‚' => 'Õ’',
'Öƒ' => 'Õ“',
'Ö„' => 'Õ”',
'Ö…' => 'Õ•',
'Ö†' => 'Õ–',
'áµ¹' => 'ê<>½',
'áµ½' => 'â±£',
¸<C3A1>' => 'Ḁ',
'ḃ' => 'Ḃ',
'ḅ' => 'Ḅ',
'ḇ' => 'Ḇ',
'ḉ' => 'Ḉ',
'ḋ' => 'Ḋ',
¸<C3A1>' => 'Ḍ',
¸<C3A1>' => 'Ḏ',
'ḑ' => 'á¸<C3A1>',
'ḓ' => 'Ḓ',
'ḕ' => 'Ḕ',
'ḗ' => 'Ḗ',
'ḙ' => 'Ḙ',
'ḛ' => 'Ḛ',
¸<C3A1>' => 'Ḝ',
'ḟ' => 'Ḟ',
'ḡ' => 'Ḡ',
'ḣ' => 'Ḣ',
'ḥ' => 'Ḥ',
'ḧ' => 'Ḧ',
'ḩ' => 'Ḩ',
'ḫ' => 'Ḫ',
'ḭ' => 'Ḭ',
'ḯ' => 'Ḯ',
'ḱ' => 'Ḱ',
'ḳ' => 'Ḳ',
'ḵ' => 'Ḵ',
'ḷ' => 'Ḷ',
'ḹ' => 'Ḹ',
'ḻ' => 'Ḻ',
'ḽ' => 'Ḽ',
'ḿ' => 'Ḿ',
'á¹<C3A1>' => 'á¹€',
'ṃ' => 'Ṃ',
'ṅ' => 'Ṅ',
'ṇ' => 'Ṇ',
'ṉ' => 'Ṉ',
'ṋ' => 'Ṋ',
'á¹<C3A1>' => 'Ṍ',
'á¹<C3A1>' => 'Ṏ',
'ṑ' => 'á¹<C3A1>',
'ṓ' => 'Ṓ',
'ṕ' => 'Ṕ',
'á¹—' => 'á¹–',
'ṙ' => 'Ṙ',
'ṛ' => 'Ṛ',
'á¹<C3A1>' => 'Ṝ',
'ṟ' => 'Ṟ',
'ṡ' => 'Ṡ',
'á¹£' => 'á¹¢',
'ṥ' => 'Ṥ',
'ṧ' => 'Ṧ',
'ṩ' => 'Ṩ',
'ṫ' => 'Ṫ',
'ṭ' => 'Ṭ',
'ṯ' => 'Ṯ',
'á¹±' => 'á¹°',
'á¹³' => 'á¹²',
'á¹µ' => 'á¹´',
'ṷ' => 'Ṷ',
'ṹ' => 'Ṹ',
'ṻ' => 'Ṻ',
'á¹½' => 'á¹¼',
'ṿ' => 'Ṿ',
'áº<C3A1>' => 'Ẁ',
'ẃ' => 'Ẃ',
'ẅ' => 'Ẅ',
'ẇ' => 'Ẇ',
'ẉ' => 'Ẉ',
'ẋ' => 'Ẋ',
'áº<C3A1>' => 'Ẍ',
'áº<C3A1>' => 'Ẏ',
'ẑ' => 'áº<C3A1>',
'ẓ' => 'Ẓ',
'ẕ' => 'Ẕ',
'ẛ' => 'Ṡ',
'ạ' => 'Ạ',
'ả' => 'Ả',
'ấ' => 'Ấ',
'ầ' => 'Ầ',
'ẩ' => 'Ẩ',
'ẫ' => 'Ẫ',
'ậ' => 'Ậ',
'ắ' => 'Ắ',
'ằ' => 'Ằ',
'ẳ' => 'Ẳ',
'ẵ' => 'Ẵ',
'ặ' => 'Ặ',
'ẹ' => 'Ẹ',
'ẻ' => 'Ẻ',
'ẽ' => 'Ẽ',
'ế' => 'Ế',
'á»<C3A1>' => 'Ề',
'ể' => 'Ể',
'ễ' => 'Ễ',
'ệ' => 'Ệ',
'ỉ' => 'Ỉ',
'ị' => 'Ị',
'á»<C3A1>' => 'Ọ',
'á»<C3A1>' => 'Ỏ',
'ố' => 'á»<C3A1>',
'ồ' => 'Ồ',
'ổ' => 'Ổ',
'á»—' => 'á»–',
'ộ' => 'Ộ',
'ớ' => 'Ớ',
'á»<C3A1>' => 'Ờ',
'ở' => 'Ở',
'ỡ' => 'Ỡ',
'ợ' => 'Ợ',
'ụ' => 'Ụ',
'ủ' => 'Ủ',
'ứ' => 'Ứ',
'ừ' => 'Ừ',
'ử' => 'Ử',
'ữ' => 'Ữ',
'á»±' => 'á»°',
'ỳ' => 'Ỳ',
'ỵ' => 'Ỵ',
'ỷ' => 'Ỷ',
'ỹ' => 'Ỹ',
'ỻ' => 'Ỻ',
'ỽ' => 'Ỽ',
'ỿ' => 'Ỿ',
'ἀ' => 'Ἀ',
'á¼<C3A1>' => 'Ἁ',
'ἂ' => 'Ἂ',
'ἃ' => 'Ἃ',
'ἄ' => 'Ἄ',
'á¼…' => 'á¼<C3A1>',
'ἆ' => 'Ἆ',
'ἇ' => 'á¼<C3A1>',
'á¼<C3A1>' => 'Ἐ',
'ἑ' => 'Ἑ',
'ἒ' => 'Ἒ',
'ἓ' => 'Ἓ',
'ἔ' => 'Ἔ',
'ἕ' => 'á¼<C3A1>',
'ἠ' => 'Ἠ',
'ἡ' => 'Ἡ',
'ἢ' => 'Ἢ',
'ἣ' => 'Ἣ',
'ἤ' => 'Ἤ',
'á¼¥' => 'á¼­',
'ἦ' => 'Ἦ',
'ἧ' => 'Ἧ',
'ἰ' => 'Ἰ',
'á¼±' => 'á¼¹',
'ἲ' => 'Ἲ',
'á¼³' => 'á¼»',
'á¼´' => 'á¼¼',
'á¼µ' => 'á¼½',
'ἶ' => 'Ἶ',
'ἷ' => 'Ἷ',
'ὀ' => 'Ὀ',
'á½<C3A1>' => 'Ὁ',
'ὂ' => 'Ὂ',
'ὃ' => 'Ὃ',
'ὄ' => 'Ὄ',
'á½…' => 'á½<C3A1>',
'ὑ' => 'Ὑ',
'ὓ' => 'Ὓ',
'ὕ' => 'á½<C3A1>',
'ὗ' => 'Ὗ',
'ὠ' => 'Ὠ',
'ὡ' => 'Ὡ',
'ὢ' => 'Ὢ',
'ὣ' => 'Ὣ',
'ὤ' => 'Ὤ',
'á½¥' => 'á½­',
'ὦ' => 'Ὦ',
'ὧ' => 'Ὧ',
'ὰ' => 'Ὰ',
'á½±' => 'á¾»',
'ὲ' => 'Ὲ',
'έ' => 'Έ',
'á½´' => 'á¿Š',
'á½µ' => 'á¿‹',
'ὶ' => 'Ὶ',
'á½·' => 'á¿›',
'ὸ' => 'Ὸ',
'ό' => 'Ό',
'ὺ' => 'Ὺ',
'á½»' => 'á¿«',
'ὼ' => 'Ὼ',
'á½½' => 'á¿»',
'ᾀ' => 'ᾈ',
'á¾<C3A1>' => 'ᾉ',
'ᾂ' => 'ᾊ',
'ᾃ' => 'ᾋ',
'ᾄ' => 'ᾌ',
'á¾…' => 'á¾<C3A1>',
'ᾆ' => 'ᾎ',
'ᾇ' => 'á¾<C3A1>',
'á¾<C3A1>' => 'ᾘ',
'ᾑ' => 'ᾙ',
'ᾒ' => 'ᾚ',
'ᾓ' => 'ᾛ',
'ᾔ' => 'ᾜ',
'ᾕ' => 'á¾<C3A1>',
'ᾖ' => 'ᾞ',
'ᾗ' => 'ᾟ',
'ᾠ' => 'ᾨ',
'ᾡ' => 'ᾩ',
'ᾢ' => 'ᾪ',
'ᾣ' => 'ᾫ',
'ᾤ' => 'ᾬ',
'á¾¥' => 'á¾­',
'ᾦ' => 'ᾮ',
'ᾧ' => 'ᾯ',
'ᾰ' => 'Ᾰ',
'á¾±' => 'á¾¹',
'á¾³' => 'á¾¼',
'ι' => 'Ι',
'ῃ' => 'ῌ',
'á¿<C3A1>' => 'Ῐ',
'á¿‘' => 'á¿™',
'ῠ' => 'Ῠ',
'á¿¡' => 'á¿©',
'ῥ' => 'Ῥ',
'ῳ' => 'ῼ',
'ⅎ' => 'Ⅎ',
'â…°' => 'â… ',
'â…±' => 'â…¡',
'â…²' => 'â…¢',
'â…³' => 'â…£',
'â…´' => 'â…¤',
'â…µ' => 'â…¥',
'â…¶' => 'â…¦',
'â…·' => 'â…§',
'â…¸' => 'â…¨',
'â…¹' => 'â…©',
'â…º' => 'â…ª',
'â…»' => 'â…«',
'â…¼' => 'â…¬',
'â…½' => 'â…­',
'â…¾' => 'â…®',
'â…¿' => 'â…¯',
'ↄ' => 'Ↄ',
'â“<C3A2>' => 'â’¶',
'â“‘' => 'â’·',
'â“’' => 'â’¸',
'â““' => 'â’¹',
'â“”' => 'â’º',
'â“•' => 'â’»',
'â“–' => 'â’¼',
'â“—' => 'â’½',
'ⓘ' => 'Ⓘ',
'â“™' => 'â’¿',
'â“š' => 'â“€',
'â“›' => 'â“<C3A2>',
'ⓜ' => 'Ⓜ',
'â“<C3A2>' => 'Ⓝ',
'â“ž' => 'â“„',
'â“Ÿ' => 'â“…',
'ⓠ' => 'Ⓠ',
'ⓡ' => 'Ⓡ',
'ⓢ' => 'Ⓢ',
'ⓣ' => 'Ⓣ',
'ⓤ' => 'Ⓤ',
'â“¥' => 'â“‹',
'ⓦ' => 'Ⓦ',
'ⓧ' => 'â“<C3A2>',
'ⓨ' => 'Ⓨ',
'â“©' => 'â“<C3A2>',
'â°°' => 'â°€',
'â°±' => 'â°<C3A2>',
'â°²' => 'â°‚',
'â°³' => 'â°ƒ',
'â°´' => 'â°„',
'â°µ' => 'â°…',
'â°¶' => 'â°†',
'â°·' => 'â°‡',
'â°¸' => 'â°ˆ',
'â°¹' => 'â°‰',
'â°º' => 'â°Š',
'â°»' => 'â°‹',
'ⰼ' => 'Ⰼ',
'â°½' => 'â°<C3A2>',
'â°¾' => 'â°Ž',
'â°¿' => 'â°<C3A2>',
'â±€' => 'â°<C3A2>',
'â±<C3A2>' => 'â°‘',
'ⱂ' => 'Ⱂ',
'ⱃ' => 'Ⱃ',
'ⱄ' => 'Ⱄ',
'â±…' => 'â°•',
'ⱆ' => 'Ⱆ',
'ⱇ' => 'Ⱇ',
'ⱈ' => 'Ⱈ',
'ⱉ' => 'Ⱉ',
'ⱊ' => 'Ⱊ',
'ⱋ' => 'Ⱋ',
'ⱌ' => 'Ⱌ',
'â±<C3A2>' => 'â°<C3A2>',
'ⱎ' => 'Ⱎ',
'â±<C3A2>' => 'â°Ÿ',
'â±<C3A2>' => 'â° ',
'ⱑ' => 'Ⱑ',
'â±’' => 'â°¢',
'ⱓ' => 'Ⱓ',
'â±”' => 'â°¤',
'ⱕ' => 'Ⱕ',
'â±–' => 'â°¦',
'â±—' => 'â°§',
'ⱘ' => 'Ⱘ',
'â±™' => 'â°©',
'ⱚ' => 'Ⱚ',
'â±›' => 'â°«',
'ⱜ' => 'Ⱜ',
'â±<C3A2>' => 'â°­',
'ⱞ' => 'Ⱞ',
'ⱡ' => 'Ⱡ',
'ⱥ' => 'Ⱥ',
'ⱦ' => 'Ⱦ',
'ⱨ' => 'Ⱨ',
'ⱪ' => 'Ⱪ',
'ⱬ' => 'Ⱬ',
'â±³' => 'â±²',
'ⱶ' => 'Ⱶ',
'â²<C3A2>' => 'â²€',
'ⲃ' => 'Ⲃ',
'ⲅ' => 'Ⲅ',
'ⲇ' => 'Ⲇ',
'ⲉ' => 'Ⲉ',
'ⲋ' => 'Ⲋ',
'â²<C3A2>' => 'Ⲍ',
'â²<C3A2>' => 'Ⲏ',
'ⲑ' => 'â²<C3A2>',
'ⲓ' => 'Ⲓ',
'ⲕ' => 'Ⲕ',
'â²—' => 'â²–',
'ⲙ' => 'Ⲙ',
'ⲛ' => 'Ⲛ',
'â²<C3A2>' => 'Ⲝ',
'ⲟ' => 'Ⲟ',
'ⲡ' => 'Ⲡ',
'â²£' => 'â²¢',
'ⲥ' => 'Ⲥ',
'ⲧ' => 'Ⲧ',
'ⲩ' => 'Ⲩ',
'ⲫ' => 'Ⲫ',
'ⲭ' => 'Ⲭ',
'ⲯ' => 'Ⲯ',
'â²±' => 'â²°',
'â²³' => 'â²²',
'â²µ' => 'â²´',
'ⲷ' => 'Ⲷ',
'ⲹ' => 'Ⲹ',
'ⲻ' => 'Ⲻ',
'â²½' => 'â²¼',
'ⲿ' => 'Ⲿ',
'â³<C3A2>' => 'â³€',
'ⳃ' => 'Ⳃ',
'ⳅ' => 'Ⳅ',
'ⳇ' => 'Ⳇ',
'ⳉ' => 'Ⳉ',
'ⳋ' => 'Ⳋ',
'â³<C3A2>' => 'Ⳍ',
'â³<C3A2>' => 'Ⳏ',
'ⳑ' => 'â³<C3A2>',
'ⳓ' => 'Ⳓ',
'ⳕ' => 'Ⳕ',
'â³—' => 'â³–',
'ⳙ' => 'Ⳙ',
'ⳛ' => 'Ⳛ',
'â³<C3A2>' => 'Ⳝ',
'ⳟ' => 'Ⳟ',
'ⳡ' => 'Ⳡ',
'â³£' => 'â³¢',
'ⳬ' => 'Ⳬ',
'â³®' => 'â³­',
'â³³' => 'â³²',
'â´€' => 'á‚ ',
´<C3A2>' => 'á‚¡',
'â´‚' => 'á‚¢',
'â´ƒ' => 'á‚£',
'ⴄ' => 'Ⴄ',
'â´…' => 'á‚¥',
'ⴆ' => 'Ⴆ',
'ⴇ' => 'Ⴇ',
'ⴈ' => 'Ⴈ',
'â´‰' => 'á‚©',
'ⴊ' => 'Ⴊ',
'â´‹' => 'á‚«',
'ⴌ' => 'Ⴌ',
´<C3A2>' => 'á‚­',
'â´Ž' => 'á‚®',
´<C3A2>' => 'Ⴏ',
´<C3A2>' => 'á‚°',
'ⴑ' => 'Ⴑ',
'ⴒ' => 'Ⴒ',
'ⴓ' => 'Ⴓ',
'â´”' => 'á‚´',
'ⴕ' => 'Ⴕ',
'ⴖ' => 'Ⴖ',
'â´—' => 'á‚·',
'ⴘ' => 'Ⴘ',
'ⴙ' => 'Ⴙ',
'ⴚ' => 'Ⴚ',
'â´›' => 'á‚»',
'ⴜ' => 'Ⴜ',
´<C3A2>' => 'Ⴝ',
'ⴞ' => 'Ⴞ',
'â´Ÿ' => 'á‚¿',
'ⴠ' => 'Ⴠ',
'â´¡' => 'áƒ<C3A1>',
'ⴢ' => 'Ⴢ',
'ⴣ' => 'Ⴣ',
'ⴤ' => 'Ⴤ',
'ⴥ' => 'Ⴥ',
'ⴧ' => 'Ⴧ',
'â´­' => 'áƒ<C3A1>',
'ê™<C3AA>' => 'Ꙁ',
'ꙃ' => 'Ꙃ',
'ꙅ' => 'Ꙅ',
'ꙇ' => 'Ꙇ',
'ꙉ' => 'Ꙉ',
'ꙋ' => 'Ꙋ',
'ê™<C3AA>' => 'Ꙍ',
'ê™<C3AA>' => 'Ꙏ',
'ꙑ' => 'ê™<C3AA>',
'ꙓ' => 'Ꙓ',
'ꙕ' => 'Ꙕ',
'ê™—' => 'ê™–',
'ꙙ' => 'Ꙙ',
'ꙛ' => 'Ꙛ',
'ê™<C3AA>' => 'Ꙝ',
'ꙟ' => 'Ꙟ',
'ꙡ' => 'Ꙡ',
'ꙣ' => 'Ꙣ',
'ꙥ' => 'Ꙥ',
'ꙧ' => 'Ꙧ',
'ꙩ' => 'Ꙩ',
'ꙫ' => 'Ꙫ',
'ꙭ' => 'Ꙭ',
'êš<C3AA>' => 'Ꚁ',
'ꚃ' => 'Ꚃ',
'êš…' => 'êš„',
'ꚇ' => 'Ꚇ',
'ꚉ' => 'Ꚉ',
'ꚋ' => 'Ꚋ',
'êš<C3AA>' => 'Ꚍ',
'êš<C3AA>' => 'Ꚏ',
'êš‘' => 'êš<C3AA>',
'êš“' => 'êš’',
'êš•' => 'êš”',
'êš—' => 'êš–',
'ꚙ' => 'Ꚙ',
'êš›' => 'êšš',
'ꜣ' => 'Ꜣ',
'ꜥ' => 'Ꜥ',
'ꜧ' => 'Ꜧ',
'ꜩ' => 'Ꜩ',
'ꜫ' => 'Ꜫ',
'ꜭ' => 'Ꜭ',
'ꜯ' => 'Ꜯ',
'ꜳ' => 'Ꜳ',
'ꜵ' => 'Ꜵ',
'ꜷ' => 'Ꜷ',
'ꜹ' => 'Ꜹ',
'ꜻ' => 'Ꜻ',
'ꜽ' => 'Ꜽ',
'ꜿ' => 'Ꜿ',
<><C3AA>' => 'ê<>€',
<>ƒ' => 'ê<>',
<>…' => 'ê<>„',
<>‡' => 'ê<>†',
<>‰' => 'ê<>ˆ',
<>' => 'ê<>Š',
<><C3AA>' => 'ê<>Œ',
<><C3AA>' => 'ê<>Ž',
<>' => 'ê<><C3AA>',
<>“' => 'ê<>',
<>•' => 'ê<>”',
<>—' => 'ê<>',
<>™' => 'ê<>˜',
<>' => 'ê<>š',
<><C3AA>' => 'ê<>œ',
<>Ÿ' => 'ê<>ž',
<>¡' => 'ê<> ',
<>£' => 'ê<>¢',
<>¥' => 'ê<>¤',
<>§' => 'ê<>¦',
<>©' => 'ê<>¨',
<>«' => 'ê<>ª',
<>­' => 'ê<>¬',
<>¯' => 'ê<>®',
<>º' => 'ê<>¹',
<>¼' => 'ê<>»',
<>¿' => 'ê<>¾',
'êž<C3AA>' => 'Ꞁ',
'ꞃ' => 'Ꞃ',
'êž…' => 'êž„',
'ꞇ' => 'Ꞇ',
'ꞌ' => 'Ꞌ',
'êž‘' => 'êž<C3AA>',
'êž“' => 'êž’',
'êž—' => 'êž–',
'ꞙ' => 'Ꞙ',
'êž›' => 'êžš',
'êž<C3AA>' => 'êžœ',
'ꞟ' => 'Ꞟ',
'êž¡' => 'êž ',
'ꞣ' => 'Ꞣ',
'ꞥ' => 'Ꞥ',
'ꞧ' => 'Ꞧ',
'ꞩ' => 'Ꞩ',
'ï½<C3AF>' => 'A',
'b' => 'B',
'c' => 'C',
'd' => 'D',
'ï½…' => 'ï¼¥',
'f' => 'F',
'g' => 'G',
'h' => 'H',
'i' => 'I',
'j' => 'J',
'k' => 'K',
'l' => 'L',
'ï½<C3AF>' => 'ï¼­',
'n' => 'N',
'ï½<C3AF>' => 'O',
'ï½<C3AF>' => 'ï¼°',
'q' => 'Q',
'ï½’' => 'ï¼²',
's' => 'S',
'ï½”' => 'ï¼´',
'u' => 'U',
'v' => 'V',
'ï½—' => 'ï¼·',
'x' => 'X',
'ï½™' => 'ï¼¹',
'z' => 'Z',
<><C3B0>¨' => 'ð<><C3B0>€',
<><C3B0>©' => 'ð<><C3B0><EFBFBD>',
<><C3B0>ª' => 'ð<><C3B0>',
<><C3B0>«' => 'ð<><C3B0>ƒ',
<><C3B0>¬' => 'ð<><C3B0>„',
<><C3B0>­' => 'ð<><C3B0>…',
<><C3B0>®' => 'ð<><C3B0>†',
<><C3B0>¯' => 'ð<><C3B0>‡',
<><C3B0>°' => 'ð<><C3B0>ˆ',
<><C3B0>±' => 'ð<><C3B0>‰',
<><C3B0>²' => 'ð<><C3B0>Š',
<><C3B0>³' => 'ð<><C3B0>',
<><C3B0>´' => 'ð<><C3B0>Œ',
<><C3B0>µ' => 'ð<><C3B0><EFBFBD>',
<><C3B0>¶' => 'ð<><C3B0>Ž',
<><C3B0>·' => 'ð<><C3B0><EFBFBD>',
<><C3B0>¸' => 'ð<><C3B0><EFBFBD>',
<><C3B0>¹' => 'ð<><C3B0>',
<><C3B0>º' => 'ð<><C3B0>',
<><C3B0>»' => 'ð<><C3B0>“',
<><C3B0>¼' => 'ð<><C3B0>”',
<><C3B0>½' => 'ð<><C3B0>•',
<><C3B0>¾' => 'ð<><C3B0>',
<><C3B0>¿' => 'ð<><C3B0>—',
<>€' => 'ð<><C3B0>˜',
<><EFBFBD>' => 'ð<><C3B0>™',
<>' => 'ð<><C3B0>š',
<>ƒ' => 'ð<><C3B0>',
<>„' => 'ð<><C3B0>œ',
<>…' => 'ð<><C3B0><EFBFBD>',
<>†' => 'ð<><C3B0>ž',
<>‡' => 'ð<><C3B0>Ÿ',
<>ˆ' => 'ð<><C3B0> ',
<>‰' => 'ð<><C3B0>¡',
<>Š' => 'ð<><C3B0>¢',
<>' => 'ð<><C3B0>£',
<>Œ' => 'ð<><C3B0>¤',
<><EFBFBD>' => 'ð<><C3B0>¥',
<>Ž' => 'ð<><C3B0>¦',
<><EFBFBD>' => 'ð<><C3B0>§',
'ð‘£€' => 'ð‘¢ ',
£<E28098>' => '𑢡',
'𑣂' => '𑢢',
'𑣃' => '𑢣',
'𑣄' => '𑢤',
'ð‘£…' => 'ð‘¢¥',
'𑣆' => '𑢦',
'𑣇' => '𑢧',
'𑣈' => '𑢨',
'𑣉' => '𑢩',
'𑣊' => '𑢪',
'𑣋' => '𑢫',
'𑣌' => '𑢬',
£<E28098>' => 'ð‘¢­',
'𑣎' => '𑢮',
£<E28098>' => '𑢯',
£<E28098>' => 'ð‘¢°',
'𑣑' => '𑢱',
'ð‘£’' => 'ð‘¢²',
'𑣓' => '𑢳',
'ð‘£”' => 'ð‘¢´',
'𑣕' => '𑢵',
'𑣖' => '𑢶',
'ð‘£—' => 'ð‘¢·',
'𑣘' => '𑢸',
'ð‘£™' => 'ð‘¢¹',
'𑣚' => '𑢺',
'ð‘£›' => 'ð‘¢»',
'𑣜' => '𑢼',
£<E28098>' => 'ð‘¢½',
'𑣞' => '𑢾',
'𑣟' => '𑢿',
);
$result =& $data;
unset($data);
return $result;
<?php
use Symfony\Polyfill\Mbstring as p;
if (!function_exists('mb_strlen')) {
define('MB_CASE_UPPER', 0);
define('MB_CASE_LOWER', 1);
define('MB_CASE_TITLE', 2);
function mb_convert_encoding($s, $to, $from = null) { return p\Mbstring::mb_convert_encoding($s, $to, $from); }
function mb_decode_mimeheader($s) { return p\Mbstring::mb_decode_mimeheader($s); }
function mb_encode_mimeheader($s, $charset = null, $transferEnc = null, $lf = null, $indent = null) { return p\Mbstring::mb_encode_mimeheader($s, $charset, $transferEnc, $lf, $indent); }
function mb_convert_case($s, $mode, $enc = null) { return p\Mbstring::mb_convert_case($s, $mode, $enc); }
function mb_internal_encoding($enc = null) { return p\Mbstring::mb_internal_encoding($enc); }
function mb_language($lang = null) { return p\Mbstring::mb_language($lang); }
function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); }
function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); }
function mb_check_encoding($var = null, $encoding = null) { return p\Mbstring::mb_check_encoding($var, $encoding); }
function mb_detect_encoding($str, $encodingList = null, $strict = false) { return p\Mbstring::mb_detect_encoding($str, $encodingList, $strict); }
function mb_detect_order($encodingList = null) { return p\Mbstring::mb_detect_order($encodingList); }
function mb_parse_str($s, &$result = array()) { parse_str($s, $result); }
function mb_strlen($s, $enc = null) { return p\Mbstring::mb_strlen($s, $enc); }
function mb_strpos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strpos($s, $needle, $offset, $enc); }
function mb_strtolower($s, $enc = null) { return p\Mbstring::mb_strtolower($s, $enc); }
function mb_strtoupper($s, $enc = null) { return p\Mbstring::mb_strtoupper($s, $enc); }
function mb_substitute_character($char = null) { return p\Mbstring::mb_substitute_character($char); }
function mb_substr($s, $start, $length = 2147483647, $enc = null) { return p\Mbstring::mb_substr($s, $start, $length, $enc); }
function mb_stripos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_stripos($s, $needle, $offset, $enc); }
function mb_stristr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_stristr($s, $needle, $part, $enc); }
function mb_strrchr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strrchr($s, $needle, $part, $enc); }
function mb_strrichr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strrichr($s, $needle, $part, $enc); }
function mb_strripos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strripos($s, $needle, $offset, $enc); }
function mb_strrpos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strrpos($s, $needle, $offset, $enc); }
function mb_strstr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strstr($s, $needle, $part, $enc); }
function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); }
function mb_http_output($enc = null) { return p\Mbstring::mb_http_output($enc); }
function mb_strwidth($s, $enc = null) { return p\Mbstring::mb_strwidth($s, $enc); }
function mb_substr_count($haystack, $needle, $enc = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $enc); }
function mb_output_handler($contents, $status) { return p\Mbstring::mb_output_handler($contents, $status); }
function mb_http_input($type = '') { return p\Mbstring::mb_http_input($type); }
function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null) { return p\Mbstring::mb_convert_variables($toEncoding, $fromEncoding, $v0, $a, $b, $c, $d, $e, $f); }
}
<?php
namespace Symfony\Component\Console;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Helper\DebugFormatterHelper;
use Symfony\Component\Console\Helper\ProcessHelper;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputAwareInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\HelpCommand;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class Application
{
private $commands = array();
private $wantHelps = false;
private $runningCommand;
private $name;
private $version;
private $catchExceptions = true;
private $autoExit = true;
private $definition;
private $helperSet;
private $dispatcher;
private $terminalDimensions;
private $defaultCommand;
public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
{
$this->name = $name;
$this->version = $version;
$this->defaultCommand = 'list';
$this->helperSet = $this->getDefaultHelperSet();
$this->definition = $this->getDefaultInputDefinition();
foreach ($this->getDefaultCommands() as $command) {
$this->add($command);
}
}
public function setDispatcher(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function run(InputInterface $input = null, OutputInterface $output = null)
{
if (null === $input) {
$input = new ArgvInput();
}
if (null === $output) {
$output = new ConsoleOutput();
}
$this->configureIO($input, $output);
try {
$exitCode = $this->doRun($input, $output);
} catch (\Exception $e) {
if (!$this->catchExceptions) {
throw $e;
}
if ($output instanceof ConsoleOutputInterface) {
$this->renderException($e, $output->getErrorOutput());
} else {
$this->renderException($e, $output);
}
$exitCode = $e->getCode();
if (is_numeric($exitCode)) {
$exitCode = (int) $exitCode;
if (0 === $exitCode) {
$exitCode = 1;
}
} else {
$exitCode = 1;
}
}
if ($this->autoExit) {
if ($exitCode > 255) {
$exitCode = 255;
}
exit($exitCode);
}
return $exitCode;
}
public function doRun(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(array('--version', '-V'), true)) {
$output->writeln($this->getLongVersion());
return 0;
}
$name = $this->getCommandName($input);
if (true === $input->hasParameterOption(array('--help', '-h'), true)) {
if (!$name) {
$name = 'help';
$input = new ArrayInput(array('command' => 'help'));
} else {
$this->wantHelps = true;
}
}
if (!$name) {
$name = $this->defaultCommand;
$input = new ArrayInput(array('command' => $this->defaultCommand));
}
$command = $this->find($name);
$this->runningCommand = $command;
$exitCode = $this->doRunCommand($command, $input, $output);
$this->runningCommand = null;
return $exitCode;
}
public function setHelperSet(HelperSet $helperSet)
{
$this->helperSet = $helperSet;
}
public function getHelperSet()
{
return $this->helperSet;
}
public function setDefinition(InputDefinition $definition)
{
$this->definition = $definition;
}
public function getDefinition()
{
return $this->definition;
}
public function getHelp()
{
return $this->getLongVersion();
}
public function areExceptionsCaught()
{
return $this->catchExceptions;
}
public function setCatchExceptions($boolean)
{
$this->catchExceptions = (bool) $boolean;
}
public function isAutoExitEnabled()
{
return $this->autoExit;
}
public function setAutoExit($boolean)
{
$this->autoExit = (bool) $boolean;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getVersion()
{
return $this->version;
}
public function setVersion($version)
{
$this->version = $version;
}
public function getLongVersion()
{
if ('UNKNOWN' !== $this->getName()) {
if ('UNKNOWN' !== $this->getVersion()) {
return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
}
return sprintf('<info>%s</info>', $this->getName());
}
return '<info>Console Tool</info>';
}
public function register($name)
{
return $this->add(new Command($name));
}
public function addCommands(array $commands)
{
foreach ($commands as $command) {
$this->add($command);
}
}
public function add(Command $command)
{
$command->setApplication($this);
if (!$command->isEnabled()) {
$command->setApplication(null);
return;
}
if (null === $command->getDefinition()) {
throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
}
$this->commands[$command->getName()] = $command;
foreach ($command->getAliases() as $alias) {
$this->commands[$alias] = $command;
}
return $command;
}
public function get($name)
{
if (!isset($this->commands[$name])) {
throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
}
$command = $this->commands[$name];
if ($this->wantHelps) {
$this->wantHelps = false;
$helpCommand = $this->get('help');
$helpCommand->setCommand($command);
return $helpCommand;
}
return $command;
}
public function has($name)
{
return isset($this->commands[$name]);
}
public function getNamespaces()
{
$namespaces = array();
foreach ($this->all() as $command) {
$namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
foreach ($command->getAliases() as $alias) {
$namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
}
}
return array_values(array_unique(array_filter($namespaces)));
}
public function findNamespace($namespace)
{
$allNamespaces = $this->getNamespaces();
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
$namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
if (empty($namespaces)) {
$message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
if (1 == count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}
$message .= implode("\n ", $alternatives);
}
throw new CommandNotFoundException($message, $alternatives);
}
$exact = in_array($namespace, $namespaces, true);
if (count($namespaces) > 1 && !$exact) {
throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
}
return $exact ? $namespace : reset($namespaces);
}
public function find($name)
{
$allCommands = array_keys($this->commands);
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
$commands = preg_grep('{^'.$expr.'}', $allCommands);
if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) {
if (false !== $pos = strrpos($name, ':')) {
$this->findNamespace(substr($name, 0, $pos));
}
$message = sprintf('Command "%s" is not defined.', $name);
if ($alternatives = $this->findAlternatives($name, $allCommands)) {
if (1 == count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}
$message .= implode("\n ", $alternatives);
}
throw new CommandNotFoundException($message, $alternatives);
}
if (count($commands) > 1) {
$commandList = $this->commands;
$commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) {
$commandName = $commandList[$nameOrAlias]->getName();
return $commandName === $nameOrAlias || !in_array($commandName, $commands);
});
}
$exact = in_array($name, $commands, true);
if (count($commands) > 1 && !$exact) {
$suggestions = $this->getAbbreviationSuggestions(array_values($commands));
throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands));
}
return $this->get($exact ? $name : reset($commands));
}
public function all($namespace = null)
{
if (null === $namespace) {
return $this->commands;
}
$commands = array();
foreach ($this->commands as $name => $command) {
if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
$commands[$name] = $command;
}
}
return $commands;
}
public static function getAbbreviations($names)
{
$abbrevs = array();
foreach ($names as $name) {
for ($len = strlen($name); $len > 0; --$len) {
$abbrev = substr($name, 0, $len);
$abbrevs[$abbrev][] = $name;
}
}
return $abbrevs;
}
public function renderException(\Exception $e, OutputInterface $output)
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
do {
$title = sprintf(
' [%s%s] ',
get_class($e),
$output->isVerbose() && 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''
);
$len = $this->stringWidth($title);
$width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
if (defined('HHVM_VERSION') && $width > 1 << 31) {
$width = 1 << 31;
}
$formatter = $output->getFormatter();
$lines = array();
foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
$lineLength = $this->stringWidth(preg_replace('/\[[^m]*m/', '', $formatter->format($line))) + 4;
$lines[] = array($line, $lineLength);
$len = max($lineLength, $len);
}
}
$messages = array();
$messages[] = $emptyLine = $formatter->format(sprintf('<error>%s</error>', str_repeat(' ', $len)));
$messages[] = $formatter->format(sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title)))));
foreach ($lines as $line) {
$messages[] = $formatter->format(sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1])));
}
$messages[] = $emptyLine;
$messages[] = '';
$output->writeln($messages, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET);
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
$trace = $e->getTrace();
array_unshift($trace, array(
'function' => '',
'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
'args' => array(),
));
for ($i = 0, $count = count($trace); $i < $count; ++$i) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function'];
$file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
$line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
$output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
}
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} while ($e = $e->getPrevious());
if (null !== $this->runningCommand) {
$output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
}
protected function getTerminalWidth()
{
$dimensions = $this->getTerminalDimensions();
return $dimensions[0];
}
protected function getTerminalHeight()
{
$dimensions = $this->getTerminalDimensions();
return $dimensions[1];
}
public function getTerminalDimensions()
{
if ($this->terminalDimensions) {
return $this->terminalDimensions;
}
if ('\\' === DIRECTORY_SEPARATOR) {
if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
return array((int) $matches[1], (int) $matches[2]);
}
if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) {
return array((int) $matches[1], (int) $matches[2]);
}
}
if ($sttyString = $this->getSttyColumns()) {
if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
return array((int) $matches[2], (int) $matches[1]);
}
if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
return array((int) $matches[2], (int) $matches[1]);
}
}
return array(null, null);
}
public function setTerminalDimensions($width, $height)
{
$this->terminalDimensions = array($width, $height);
return $this;
}
protected function configureIO(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(array('--ansi'), true)) {
$output->setDecorated(true);
} elseif (true === $input->hasParameterOption(array('--no-ansi'), true)) {
$output->setDecorated(false);
}
if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) {
$input->setInteractive(false);
} elseif (function_exists('posix_isatty') && $this->getHelperSet()->has('question')) {
$inputStream = $this->getHelperSet()->get('question')->getInputStream();
if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
$input->setInteractive(false);
}
}
if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
} else {
if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || $input->getParameterOption('--verbose', false, true) === 3) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
} elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || $input->getParameterOption('--verbose', false, true) === 2) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
} elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
}
}
}
protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
{
foreach ($command->getHelperSet() as $helper) {
if ($helper instanceof InputAwareInterface) {
$helper->setInput($input);
}
}
if (null === $this->dispatcher) {
return $command->run($input, $output);
}
try {
$command->mergeApplicationDefinition();
$input->bind($command->getDefinition());
} catch (ExceptionInterface $e) {
}
$event = new ConsoleCommandEvent($command, $input, $output);
$this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
if ($event->commandShouldRun()) {
try {
$exitCode = $command->run($input, $output);
} catch (\Exception $e) {
$event = new ConsoleExceptionEvent($command, $input, $output, $e, $e->getCode());
$this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
$e = $event->getException();
$event = new ConsoleTerminateEvent($command, $input, $output, $e->getCode());
$this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
throw $e;
}
} else {
$exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
}
$event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
$this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
return $event->getExitCode();
}
protected function getCommandName(InputInterface $input)
{
return $input->getFirstArgument();
}
protected function getDefaultInputDefinition()
{
return new InputDefinition(array(
new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
));
}
protected function getDefaultCommands()
{
return array(new HelpCommand(), new ListCommand());
}
protected function getDefaultHelperSet()
{
return new HelperSet(array(
new FormatterHelper(),
new DebugFormatterHelper(),
new ProcessHelper(),
new QuestionHelper(),
));
}
private function getSttyColumns()
{
if (!function_exists('proc_open')) {
return;
}
$descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
$process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
if (is_resource($process)) {
$info = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $info;
}
}
private function getConsoleMode()
{
if (!function_exists('proc_open')) {
return;
}
$descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
$process = proc_open('mode CON', $descriptorspec, $pipes, null, null, array('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)) {
return $matches[2].'x'.$matches[1];
}
}
}
private function getAbbreviationSuggestions($abbrevs)
{
return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
}
public function extractNamespace($name, $limit = null)
{
$parts = explode(':', $name);
array_pop($parts);
return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
}
private function findAlternatives($name, $collection)
{
$threshold = 1e3;
$alternatives = array();
$collectionParts = array();
foreach ($collection as $item) {
$collectionParts[$item] = explode(':', $item);
}
foreach (explode(':', $name) as $i => $subname) {
foreach ($collectionParts as $collectionName => $parts) {
$exists = isset($alternatives[$collectionName]);
if (!isset($parts[$i]) && $exists) {
$alternatives[$collectionName] += $threshold;
continue;
} elseif (!isset($parts[$i])) {
continue;
}
$lev = levenshtein($subname, $parts[$i]);
if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
$alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
} elseif ($exists) {
$alternatives[$collectionName] += $threshold;
}
}
}
foreach ($collection as $item) {
$lev = levenshtein($name, $item);
if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}
$alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
asort($alternatives);
return array_keys($alternatives);
}
public function setDefaultCommand($commandName)
{
$this->defaultCommand = $commandName;
}
private function stringWidth($string)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return strlen($string);
}
return mb_strwidth($string, $encoding);
}
private function splitStringByWidth($string, $width)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return str_split($string, $width);
}
$utf8String = mb_convert_encoding($string, 'utf8', $encoding);
$lines = array();
$line = '';
foreach (preg_split('//u', $utf8String) as $char) {
if (mb_strwidth($line.$char, 'utf8') <= $width) {
$line .= $char;
continue;
}
$lines[] = str_pad($line, $width);
$line = $char;
}
if ('' !== $line) {
$lines[] = count($lines) ? str_pad($line, $width) : $line;
}
mb_convert_variables($encoding, 'utf8', $lines);
return $lines;
}
private function extractAllNamespaces($name)
{
$parts = explode(':', $name, -1);
$namespaces = array();
foreach ($parts as $part) {
if (count($namespaces)) {
$namespaces[] = end($namespaces).':'.$part;
} else {
$namespaces[] = $part;
}
}
return $namespaces;
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class Command
{
private $application;
private $name;
private $processTitle;
private $aliases = array();
private $definition;
private $help;
private $description;
private $ignoreValidationErrors = false;
private $applicationDefinitionMerged = false;
private $applicationDefinitionMergedWithArgs = false;
private $code;
private $synopsis = array();
private $usages = array();
private $helperSet;
public function __construct($name = null)
{
$this->definition = new InputDefinition();
if (null !== $name) {
$this->setName($name);
}
$this->configure();
if (!$this->name) {
throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_class($this)));
}
}
public function ignoreValidationErrors()
{
$this->ignoreValidationErrors = true;
}
public function setApplication(Application $application = null)
{
$this->application = $application;
if ($application) {
$this->setHelperSet($application->getHelperSet());
} else {
$this->helperSet = null;
}
}
public function setHelperSet(HelperSet $helperSet)
{
$this->helperSet = $helperSet;
}
public function getHelperSet()
{
return $this->helperSet;
}
public function getApplication()
{
return $this->application;
}
public function isEnabled()
{
return true;
}
protected function configure()
{
}
protected function execute(InputInterface $input, OutputInterface $output)
{
throw new LogicException('You must override the execute() method in the concrete command class.');
}
protected function interact(InputInterface $input, OutputInterface $output)
{
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
}
public function run(InputInterface $input, OutputInterface $output)
{
$this->getSynopsis(true);
$this->getSynopsis(false);
$this->mergeApplicationDefinition();
try {
$input->bind($this->definition);
} catch (ExceptionInterface $e) {
if (!$this->ignoreValidationErrors) {
throw $e;
}
}
$this->initialize($input, $output);
if (null !== $this->processTitle) {
if (function_exists('cli_set_process_title')) {
cli_set_process_title($this->processTitle);
} elseif (function_exists('setproctitle')) {
setproctitle($this->processTitle);
} elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
$output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
}
}
if ($input->isInteractive()) {
$this->interact($input, $output);
}
if ($input->hasArgument('command') && null === $input->getArgument('command')) {
$input->setArgument('command', $this->getName());
}
$input->validate();
if ($this->code) {
$statusCode = call_user_func($this->code, $input, $output);
} else {
$statusCode = $this->execute($input, $output);
}
return is_numeric($statusCode) ? (int) $statusCode : 0;
}
public function setCode(callable $code)
{
if ($code instanceof \Closure) {
$r = new \ReflectionFunction($code);
if (null === $r->getClosureThis()) {
$code = \Closure::bind($code, $this);
}
}
$this->code = $code;
return $this;
}
public function mergeApplicationDefinition($mergeArgs = true)
{
if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
return;
}
$this->definition->addOptions($this->application->getDefinition()->getOptions());
if ($mergeArgs) {
$currentArguments = $this->definition->getArguments();
$this->definition->setArguments($this->application->getDefinition()->getArguments());
$this->definition->addArguments($currentArguments);
}
$this->applicationDefinitionMerged = true;
if ($mergeArgs) {
$this->applicationDefinitionMergedWithArgs = true;
}
}
public function setDefinition($definition)
{
if ($definition instanceof InputDefinition) {
$this->definition = $definition;
} else {
$this->definition->setDefinition($definition);
}
$this->applicationDefinitionMerged = false;
return $this;
}
public function getDefinition()
{
return $this->definition;
}
public function getNativeDefinition()
{
return $this->getDefinition();
}
public function addArgument($name, $mode = null, $description = '', $default = null)
{
$this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
return $this;
}
public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
{
$this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
return $this;
}
public function setName($name)
{
$this->validateName($name);
$this->name = $name;
return $this;
}
public function setProcessTitle($title)
{
$this->processTitle = $title;
return $this;
}
public function getName()
{
return $this->name;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function setHelp($help)
{
$this->help = $help;
return $this;
}
public function getHelp()
{
return $this->help;
}
public function getProcessedHelp()
{
$name = $this->name;
$placeholders = array(
'%command.name%',
'%command.full_name%',
);
$replacements = array(
$name,
$_SERVER['PHP_SELF'].' '.$name,
);
return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
}
public function setAliases($aliases)
{
if (!is_array($aliases) && !$aliases instanceof \Traversable) {
throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
}
foreach ($aliases as $alias) {
$this->validateName($alias);
}
$this->aliases = $aliases;
return $this;
}
public function getAliases()
{
return $this->aliases;
}
public function getSynopsis($short = false)
{
$key = $short ? 'short' : 'long';
if (!isset($this->synopsis[$key])) {
$this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
}
return $this->synopsis[$key];
}
public function addUsage($usage)
{
if (0 !== strpos($usage, $this->name)) {
$usage = sprintf('%s %s', $this->name, $usage);
}
$this->usages[] = $usage;
return $this;
}
public function getUsages()
{
return $this->usages;
}
public function getHelper($name)
{
if (null === $this->helperSet) {
throw new LogicException(sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', $name));
}
return $this->helperSet->get($name);
}
private function validateName($name)
{
if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
}
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HelpCommand extends Command
{
private $command;
protected function configure()
{
$this->ignoreValidationErrors();
$this
->setName('help')
->setDefinition(array(
new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
))
->setDescription('Displays help for a command')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command displays help for a given command:
<info>php %command.full_name% list</info>
You can also output the help in other formats by using the <comment>--format</comment> option:
<info>php %command.full_name% --format=xml list</info>
To display the list of available commands, please use the <info>list</info> command.
EOF
)
;
}
public function setCommand(Command $command)
{
$this->command = $command;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (null === $this->command) {
$this->command = $this->getApplication()->find($input->getArgument('command_name'));
}
$helper = new DescriptorHelper();
$helper->describe($output, $this->command, array(
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
));
$this->command = null;
}
}
<?php
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputDefinition;
class ListCommand extends Command
{
protected function configure()
{
$this
->setName('list')
->setDefinition($this->createDefinition())
->setDescription('Lists commands')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command lists all commands:
<info>php %command.full_name%</info>
You can also display the commands for a specific namespace:
<info>php %command.full_name% test</info>
You can also output the information in other formats by using the <comment>--format</comment> option:
<info>php %command.full_name% --format=xml</info>
It's also possible to get raw list of commands (useful for embedding command runner):
<info>php %command.full_name% --raw</info>
EOF
)
;
}
public function getNativeDefinition()
{
return $this->createDefinition();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$helper = new DescriptorHelper();
$helper->describe($output, $this->getApplication(), array(
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
'namespace' => $input->getArgument('namespace'),
));
}
private function createDefinition()
{
return new InputDefinition(array(
new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),
));
}
}
<?php
namespace Symfony\Component\Console;
final class ConsoleEvents
{
const COMMAND = 'console.command';
const TERMINATE = 'console.terminate';
const EXCEPTION = 'console.exception';
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\CommandNotFoundException;
class ApplicationDescription
{
const GLOBAL_NAMESPACE = '_global';
private $application;
private $namespace;
private $namespaces;
private $commands;
private $aliases;
public function __construct(Application $application, $namespace = null)
{
$this->application = $application;
$this->namespace = $namespace;
}
public function getNamespaces()
{
if (null === $this->namespaces) {
$this->inspectApplication();
}
return $this->namespaces;
}
public function getCommands()
{
if (null === $this->commands) {
$this->inspectApplication();
}
return $this->commands;
}
public function getCommand($name)
{
if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
throw new CommandNotFoundException(sprintf('Command %s does not exist.', $name));
}
return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
}
private function inspectApplication()
{
$this->commands = array();
$this->namespaces = array();
$all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null);
foreach ($this->sortCommands($all) as $namespace => $commands) {
$names = array();
foreach ($commands as $name => $command) {
if (!$command->getName()) {
continue;
}
if ($command->getName() === $name) {
$this->commands[$name] = $command;
} else {
$this->aliases[$name] = $command;
}
$names[] = $name;
}
$this->namespaces[$namespace] = array('id' => $namespace, 'commands' => $names);
}
}
private function sortCommands(array $commands)
{
$namespacedCommands = array();
$globalCommands = array();
foreach ($commands as $name => $command) {
$key = $this->application->extractNamespace($name, 1);
if (!$key) {
$globalCommands['_global'][$name] = $command;
} else {
$namespacedCommands[$key][$name] = $command;
}
}
ksort($namespacedCommands);
$namespacedCommands = array_merge($globalCommands, $namespacedCommands);
foreach ($namespacedCommands as &$commandsSet) {
ksort($commandsSet);
}
unset($commandsSet);
return $namespacedCommands;
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Exception\InvalidArgumentException;
abstract class Descriptor implements DescriptorInterface
{
protected $output;
public function describe(OutputInterface $output, $object, array $options = array())
{
$this->output = $output;
switch (true) {
case $object instanceof InputArgument:
$this->describeInputArgument($object, $options);
break;
case $object instanceof InputOption:
$this->describeInputOption($object, $options);
break;
case $object instanceof InputDefinition:
$this->describeInputDefinition($object, $options);
break;
case $object instanceof Command:
$this->describeCommand($object, $options);
break;
case $object instanceof Application:
$this->describeApplication($object, $options);
break;
default:
throw new InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_class($object)));
}
}
protected function write($content, $decorated = false)
{
$this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW);
}
abstract protected function describeInputArgument(InputArgument $argument, array $options = array());
abstract protected function describeInputOption(InputOption $option, array $options = array());
abstract protected function describeInputDefinition(InputDefinition $definition, array $options = array());
abstract protected function describeCommand(Command $command, array $options = array());
abstract protected function describeApplication(Application $application, array $options = array());
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Output\OutputInterface;
interface DescriptorInterface
{
public function describe(OutputInterface $output, $object, array $options = array());
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class JsonDescriptor extends Descriptor
{
protected function describeInputArgument(InputArgument $argument, array $options = array())
{
$this->writeData($this->getInputArgumentData($argument), $options);
}
protected function describeInputOption(InputOption $option, array $options = array())
{
$this->writeData($this->getInputOptionData($option), $options);
}
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
{
$this->writeData($this->getInputDefinitionData($definition), $options);
}
protected function describeCommand(Command $command, array $options = array())
{
$this->writeData($this->getCommandData($command), $options);
}
protected function describeApplication(Application $application, array $options = array())
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
$commands = array();
foreach ($description->getCommands() as $command) {
$commands[] = $this->getCommandData($command);
}
$data = $describedNamespace
? array('commands' => $commands, 'namespace' => $describedNamespace)
: array('commands' => $commands, 'namespaces' => array_values($description->getNamespaces()));
$this->writeData($data, $options);
}
private function writeData(array $data, array $options)
{
$this->write(json_encode($data, isset($options['json_encoding']) ? $options['json_encoding'] : 0));
}
private function getInputArgumentData(InputArgument $argument)
{
return array(
'name' => $argument->getName(),
'is_required' => $argument->isRequired(),
'is_array' => $argument->isArray(),
'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()),
'default' => $argument->getDefault(),
);
}
private function getInputOptionData(InputOption $option)
{
return array(
'name' => '--'.$option->getName(),
'shortcut' => $option->getShortcut() ? '-'.implode('|-', explode('|', $option->getShortcut())) : '',
'accept_value' => $option->acceptValue(),
'is_value_required' => $option->isValueRequired(),
'is_multiple' => $option->isArray(),
'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()),
'default' => $option->getDefault(),
);
}
private function getInputDefinitionData(InputDefinition $definition)
{
$inputArguments = array();
foreach ($definition->getArguments() as $name => $argument) {
$inputArguments[$name] = $this->getInputArgumentData($argument);
}
$inputOptions = array();
foreach ($definition->getOptions() as $name => $option) {
$inputOptions[$name] = $this->getInputOptionData($option);
}
return array('arguments' => $inputArguments, 'options' => $inputOptions);
}
private function getCommandData(Command $command)
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
return array(
'name' => $command->getName(),
'usage' => array_merge(array($command->getSynopsis()), $command->getUsages(), $command->getAliases()),
'description' => $command->getDescription(),
'help' => $command->getProcessedHelp(),
'definition' => $this->getInputDefinitionData($command->getNativeDefinition()),
);
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class MarkdownDescriptor extends Descriptor
{
protected function describeInputArgument(InputArgument $argument, array $options = array())
{
$this->write(
'**'.$argument->getName().':**'."\n\n"
.'* Name: '.($argument->getName() ?: '<none>')."\n"
.'* Is required: '.($argument->isRequired() ? 'yes' : 'no')."\n"
.'* Is array: '.($argument->isArray() ? 'yes' : 'no')."\n"
.'* Description: '.preg_replace('/\s*[\r\n]\s*/', "\n ", $argument->getDescription() ?: '<none>')."\n"
.'* Default: `'.str_replace("\n", '', var_export($argument->getDefault(), true)).'`'
);
}
protected function describeInputOption(InputOption $option, array $options = array())
{
$this->write(
'**'.$option->getName().':**'."\n\n"
.'* Name: `--'.$option->getName().'`'."\n"
.'* Shortcut: '.($option->getShortcut() ? '`-'.implode('|-', explode('|', $option->getShortcut())).'`' : '<none>')."\n"
.'* Accept value: '.($option->acceptValue() ? 'yes' : 'no')."\n"
.'* Is value required: '.($option->isValueRequired() ? 'yes' : 'no')."\n"
.'* Is multiple: '.($option->isArray() ? 'yes' : 'no')."\n"
.'* Description: '.preg_replace('/\s*[\r\n]\s*/', "\n ", $option->getDescription() ?: '<none>')."\n"
.'* Default: `'.str_replace("\n", '', var_export($option->getDefault(), true)).'`'
);
}
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
{
if ($showArguments = count($definition->getArguments()) > 0) {
$this->write('### Arguments:');
foreach ($definition->getArguments() as $argument) {
$this->write("\n\n");
$this->write($this->describeInputArgument($argument));
}
}
if (count($definition->getOptions()) > 0) {
if ($showArguments) {
$this->write("\n\n");
}
$this->write('### Options:');
foreach ($definition->getOptions() as $option) {
$this->write("\n\n");
$this->write($this->describeInputOption($option));
}
}
}
protected function describeCommand(Command $command, array $options = array())
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
$this->write(
$command->getName()."\n"
.str_repeat('-', strlen($command->getName()))."\n\n"
.'* Description: '.($command->getDescription() ?: '<none>')."\n"
.'* Usage:'."\n\n"
.array_reduce(array_merge(array($command->getSynopsis()), $command->getAliases(), $command->getUsages()), function ($carry, $usage) {
return $carry .= ' * `'.$usage.'`'."\n";
})
);
if ($help = $command->getProcessedHelp()) {
$this->write("\n");
$this->write($help);
}
if ($command->getNativeDefinition()) {
$this->write("\n\n");
$this->describeInputDefinition($command->getNativeDefinition());
}
}
protected function describeApplication(Application $application, array $options = array())
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
$this->write($application->getName()."\n".str_repeat('=', strlen($application->getName())));
foreach ($description->getNamespaces() as $namespace) {
if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
$this->write("\n\n");
$this->write('**'.$namespace['id'].':**');
}
$this->write("\n\n");
$this->write(implode("\n", array_map(function ($commandName) {
return '* '.$commandName;
}, $namespace['commands'])));
}
foreach ($description->getCommands() as $command) {
$this->write("\n\n");
$this->write($this->describeCommand($command));
}
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class TextDescriptor extends Descriptor
{
protected function describeInputArgument(InputArgument $argument, array $options = array())
{
if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
} else {
$default = '';
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : strlen($argument->getName());
$spacingWidth = $totalWidth - strlen($argument->getName()) + 2;
$this->writeText(sprintf(' <info>%s</info>%s%s%s',
$argument->getName(),
str_repeat(' ', $spacingWidth),
preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 17), $argument->getDescription()),
$default
), $options);
}
protected function describeInputOption(InputOption $option, array $options = array())
{
if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
} else {
$default = '';
}
$value = '';
if ($option->acceptValue()) {
$value = '='.strtoupper($option->getName());
if ($option->isValueOptional()) {
$value = '['.$value.']';
}
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions(array($option));
$synopsis = sprintf('%s%s',
$option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ',
sprintf('--%s%s', $option->getName(), $value)
);
$spacingWidth = $totalWidth - strlen($synopsis) + 2;
$this->writeText(sprintf(' <info>%s</info>%s%s%s%s',
$synopsis,
str_repeat(' ', $spacingWidth),
preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 17), $option->getDescription()),
$default,
$option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
), $options);
}
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
{
$totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
foreach ($definition->getArguments() as $argument) {
$totalWidth = max($totalWidth, strlen($argument->getName()));
}
if ($definition->getArguments()) {
$this->writeText('<comment>Arguments:</comment>', $options);
$this->writeText("\n");
foreach ($definition->getArguments() as $argument) {
$this->describeInputArgument($argument, array_merge($options, array('total_width' => $totalWidth)));
$this->writeText("\n");
}
}
if ($definition->getArguments() && $definition->getOptions()) {
$this->writeText("\n");
}
if ($definition->getOptions()) {
$laterOptions = array();
$this->writeText('<comment>Options:</comment>', $options);
foreach ($definition->getOptions() as $option) {
if (strlen($option->getShortcut()) > 1) {
$laterOptions[] = $option;
continue;
}
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, array('total_width' => $totalWidth)));
}
foreach ($laterOptions as $option) {
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, array('total_width' => $totalWidth)));
}
}
}
protected function describeCommand(Command $command, array $options = array())
{
$command->getSynopsis(true);
$command->getSynopsis(false);
$command->mergeApplicationDefinition(false);
$this->writeText('<comment>Usage:</comment>', $options);
foreach (array_merge(array($command->getSynopsis(true)), $command->getAliases(), $command->getUsages()) as $usage) {
$this->writeText("\n");
$this->writeText(' '.$usage, $options);
}
$this->writeText("\n");
$definition = $command->getNativeDefinition();
if ($definition->getOptions() || $definition->getArguments()) {
$this->writeText("\n");
$this->describeInputDefinition($definition, $options);
$this->writeText("\n");
}
if ($help = $command->getProcessedHelp()) {
$this->writeText("\n");
$this->writeText('<comment>Help:</comment>', $options);
$this->writeText("\n");
$this->writeText(' '.str_replace("\n", "\n ", $help), $options);
$this->writeText("\n");
}
}
protected function describeApplication(Application $application, array $options = array())
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
if (isset($options['raw_text']) && $options['raw_text']) {
$width = $this->getColumnWidth($description->getCommands());
foreach ($description->getCommands() as $command) {
$this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options);
$this->writeText("\n");
}
} else {
if ('' != $help = $application->getHelp()) {
$this->writeText("$help\n\n", $options);
}
$this->writeText("<comment>Usage:</comment>\n", $options);
$this->writeText(" command [options] [arguments]\n\n", $options);
$this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options);
$this->writeText("\n");
$this->writeText("\n");
$width = $this->getColumnWidth($description->getCommands());
if ($describedNamespace) {
$this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options);
} else {
$this->writeText('<comment>Available commands:</comment>', $options);
}
foreach ($description->getNamespaces() as $namespace) {
if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
$this->writeText("\n");
$this->writeText(' <comment>'.$namespace['id'].'</comment>', $options);
}
foreach ($namespace['commands'] as $name) {
$this->writeText("\n");
$spacingWidth = $width - strlen($name);
$this->writeText(sprintf(' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $description->getCommand($name)->getDescription()), $options);
}
}
$this->writeText("\n");
}
}
private function writeText($content, array $options = array())
{
$this->write(
isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
isset($options['raw_output']) ? !$options['raw_output'] : true
);
}
private function formatDefaultValue($default)
{
return str_replace('\\\\', '\\', json_encode($default, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}
private function getColumnWidth(array $commands)
{
$widths = array();
foreach ($commands as $command) {
$widths[] = strlen($command->getName());
foreach ($command->getAliases() as $alias) {
$widths[] = strlen($alias);
}
}
return max($widths) + 2;
}
private function calculateTotalWidthForOptions($options)
{
$totalWidth = 0;
foreach ($options as $option) {
$nameLength = 1 + max(strlen($option->getShortcut()), 1) + 4 + strlen($option->getName());
if ($option->acceptValue()) {
$valueLength = 1 + strlen($option->getName());
$valueLength += $option->isValueOptional() ? 2 : 0;
$nameLength += $valueLength;
}
$totalWidth = max($totalWidth, $nameLength);
}
return $totalWidth;
}
}
<?php
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class XmlDescriptor extends Descriptor
{
public function getInputDefinitionDocument(InputDefinition $definition)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($definitionXML = $dom->createElement('definition'));
$definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
foreach ($definition->getArguments() as $argument) {
$this->appendDocument($argumentsXML, $this->getInputArgumentDocument($argument));
}
$definitionXML->appendChild($optionsXML = $dom->createElement('options'));
foreach ($definition->getOptions() as $option) {
$this->appendDocument($optionsXML, $this->getInputOptionDocument($option));
}
return $dom;
}
public function getCommandDocument(Command $command)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($commandXML = $dom->createElement('command'));
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
$commandXML->setAttribute('id', $command->getName());
$commandXML->setAttribute('name', $command->getName());
$commandXML->appendChild($usagesXML = $dom->createElement('usages'));
foreach (array_merge(array($command->getSynopsis()), $command->getAliases(), $command->getUsages()) as $usage) {
$usagesXML->appendChild($dom->createElement('usage', $usage));
}
$commandXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getDescription())));
$commandXML->appendChild($helpXML = $dom->createElement('help'));
$helpXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getProcessedHelp())));
$definitionXML = $this->getInputDefinitionDocument($command->getNativeDefinition());
$this->appendDocument($commandXML, $definitionXML->getElementsByTagName('definition')->item(0));
return $dom;
}
public function getApplicationDocument(Application $application, $namespace = null)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($rootXml = $dom->createElement('symfony'));
if ($application->getName() !== 'UNKNOWN') {
$rootXml->setAttribute('name', $application->getName());
if ($application->getVersion() !== 'UNKNOWN') {
$rootXml->setAttribute('version', $application->getVersion());
}
}
$rootXml->appendChild($commandsXML = $dom->createElement('commands'));
$description = new ApplicationDescription($application, $namespace);
if ($namespace) {
$commandsXML->setAttribute('namespace', $namespace);
}
foreach ($description->getCommands() as $command) {
$this->appendDocument($commandsXML, $this->getCommandDocument($command));
}
if (!$namespace) {
$rootXml->appendChild($namespacesXML = $dom->createElement('namespaces'));
foreach ($description->getNamespaces() as $namespaceDescription) {
$namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace'));
$namespaceArrayXML->setAttribute('id', $namespaceDescription['id']);
foreach ($namespaceDescription['commands'] as $name) {
$namespaceArrayXML->appendChild($commandXML = $dom->createElement('command'));
$commandXML->appendChild($dom->createTextNode($name));
}
}
}
return $dom;
}
protected function describeInputArgument(InputArgument $argument, array $options = array())
{
$this->writeDocument($this->getInputArgumentDocument($argument));
}
protected function describeInputOption(InputOption $option, array $options = array())
{
$this->writeDocument($this->getInputOptionDocument($option));
}
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
{
$this->writeDocument($this->getInputDefinitionDocument($definition));
}
protected function describeCommand(Command $command, array $options = array())
{
$this->writeDocument($this->getCommandDocument($command));
}
protected function describeApplication(Application $application, array $options = array())
{
$this->writeDocument($this->getApplicationDocument($application, isset($options['namespace']) ? $options['namespace'] : null));
}
private function appendDocument(\DOMNode $parentNode, \DOMNode $importedParent)
{
foreach ($importedParent->childNodes as $childNode) {
$parentNode->appendChild($parentNode->ownerDocument->importNode($childNode, true));
}
}
private function writeDocument(\DOMDocument $dom)
{
$dom->formatOutput = true;
$this->write($dom->saveXML());
}
private function getInputArgumentDocument(InputArgument $argument)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($objectXML = $dom->createElement('argument'));
$objectXML->setAttribute('name', $argument->getName());
$objectXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0);
$objectXML->setAttribute('is_array', $argument->isArray() ? 1 : 0);
$objectXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode($argument->getDescription()));
$objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$defaults = is_array($argument->getDefault()) ? $argument->getDefault() : (is_bool($argument->getDefault()) ? array(var_export($argument->getDefault(), true)) : ($argument->getDefault() ? array($argument->getDefault()) : array()));
foreach ($defaults as $default) {
$defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default));
}
return $dom;
}
private function getInputOptionDocument(InputOption $option)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($objectXML = $dom->createElement('option'));
$objectXML->setAttribute('name', '--'.$option->getName());
$pos = strpos($option->getShortcut(), '|');
if (false !== $pos) {
$objectXML->setAttribute('shortcut', '-'.substr($option->getShortcut(), 0, $pos));
$objectXML->setAttribute('shortcuts', '-'.implode('|-', explode('|', $option->getShortcut())));
} else {
$objectXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : '');
}
$objectXML->setAttribute('accept_value', $option->acceptValue() ? 1 : 0);
$objectXML->setAttribute('is_value_required', $option->isValueRequired() ? 1 : 0);
$objectXML->setAttribute('is_multiple', $option->isArray() ? 1 : 0);
$objectXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
if ($option->acceptValue()) {
$defaults = is_array($option->getDefault()) ? $option->getDefault() : (is_bool($option->getDefault()) ? array(var_export($option->getDefault(), true)) : ($option->getDefault() ? array($option->getDefault()) : array()));
$objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
if (!empty($defaults)) {
foreach ($defaults as $default) {
$defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default));
}
}
}
return $dom;
}
}
<?php
namespace Symfony\Component\Console\Event;
class ConsoleCommandEvent extends ConsoleEvent
{
const RETURN_CODE_DISABLED = 113;
private $commandShouldRun = true;
public function disableCommand()
{
return $this->commandShouldRun = false;
}
public function enableCommand()
{
return $this->commandShouldRun = true;
}
public function commandShouldRun()
{
return $this->commandShouldRun;
}
}
<?php
namespace Symfony\Component\Console\Event;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\Event;
class ConsoleEvent extends Event
{
protected $command;
private $input;
private $output;
public function __construct(Command $command, InputInterface $input, OutputInterface $output)
{
$this->command = $command;
$this->input = $input;
$this->output = $output;
}
public function getCommand()
{
return $this->command;
}
public function getInput()
{
return $this->input;
}
public function getOutput()
{
return $this->output;
}
}
<?php
namespace Symfony\Component\Console\Event;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleExceptionEvent extends ConsoleEvent
{
private $exception;
private $exitCode;
public function __construct(Command $command, InputInterface $input, OutputInterface $output, \Exception $exception, $exitCode)
{
parent::__construct($command, $input, $output);
$this->setException($exception);
$this->exitCode = (int) $exitCode;
}
public function getException()
{
return $this->exception;
}
public function setException(\Exception $exception)
{
$this->exception = $exception;
}
public function getExitCode()
{
return $this->exitCode;
}
}
<?php
namespace Symfony\Component\Console\Event;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleTerminateEvent extends ConsoleEvent
{
private $exitCode;
public function __construct(Command $command, InputInterface $input, OutputInterface $output, $exitCode)
{
parent::__construct($command, $input, $output);
$this->setExitCode($exitCode);
}
public function setExitCode($exitCode)
{
$this->exitCode = (int) $exitCode;
}
public function getExitCode()
{
return $this->exitCode;
}
}
<?php
namespace Symfony\Component\Console\Exception;
class CommandNotFoundException extends \InvalidArgumentException implements ExceptionInterface
{
private $alternatives;
public function __construct($message, array $alternatives = array(), $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->alternatives = $alternatives;
}
public function getAlternatives()
{
return $this->alternatives;
}
}
<?php
namespace Symfony\Component\Console\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class InvalidOptionException extends \InvalidArgumentException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class LogicException extends \LogicException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
<?php
namespace Symfony\Component\Console\Formatter;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatter implements OutputFormatterInterface
{
private $decorated;
private $styles = array();
private $styleStack;
public static function escape($text)
{
$text = preg_replace('/([^\\\\]?)</', '$1\\<', $text);
if ('\\' === substr($text, -1)) {
$len = strlen($text);
$text = rtrim($text, '\\');
$text .= str_repeat('<<', $len - strlen($text));
}
return $text;
}
public function __construct($decorated = false, array $styles = array())
{
$this->decorated = (bool) $decorated;
$this->setStyle('error', new OutputFormatterStyle('white', 'red'));
$this->setStyle('info', new OutputFormatterStyle('green'));
$this->setStyle('comment', new OutputFormatterStyle('yellow'));
$this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
foreach ($styles as $name => $style) {
$this->setStyle($name, $style);
}
$this->styleStack = new OutputFormatterStyleStack();
}
public function setDecorated($decorated)
{
$this->decorated = (bool) $decorated;
}
public function isDecorated()
{
return $this->decorated;
}
public function setStyle($name, OutputFormatterStyleInterface $style)
{
$this->styles[strtolower($name)] = $style;
}
public function hasStyle($name)
{
return isset($this->styles[strtolower($name)]);
}
public function getStyle($name)
{
if (!$this->hasStyle($name)) {
throw new InvalidArgumentException(sprintf('Undefined style: %s', $name));
}
return $this->styles[strtolower($name)];
}
public function format($message)
{
$message = (string) $message;
$offset = 0;
$output = '';
$tagRegex = '[a-z][a-z0-9_=;-]*+';
preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $i => $match) {
$pos = $match[1];
$text = $match[0];
if (0 != $pos && '\\' == $message[$pos - 1]) {
continue;
}
$output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset));
$offset = $pos + strlen($text);
if ($open = '/' != $text[1]) {
$tag = $matches[1][$i][0];
} else {
$tag = isset($matches[3][$i][0]) ? $matches[3][$i][0] : '';
}
if (!$open && !$tag) {
$this->styleStack->pop();
} elseif (false === $style = $this->createStyleFromString(strtolower($tag))) {
$output .= $this->applyCurrentStyle($text);
} elseif ($open) {
$this->styleStack->push($style);
} else {
$this->styleStack->pop($style);
}
}
$output .= $this->applyCurrentStyle(substr($message, $offset));
if (false !== strpos($output, '<<')) {
return strtr($output, array('\\<' => '<', '<<' => '\\'));
}
return str_replace('\\<', '<', $output);
}
public function getStyleStack()
{
return $this->styleStack;
}
private function createStyleFromString($string)
{
if (isset($this->styles[$string])) {
return $this->styles[$string];
}
if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', strtolower($string), $matches, PREG_SET_ORDER)) {
return false;
}
$style = new OutputFormatterStyle();
foreach ($matches as $match) {
array_shift($match);
if ('fg' == $match[0]) {
$style->setForeground($match[1]);
} elseif ('bg' == $match[0]) {
$style->setBackground($match[1]);
} else {
try {
$style->setOption($match[1]);
} catch (\InvalidArgumentException $e) {
return false;
}
}
}
return $style;
}
private function applyCurrentStyle($text)
{
return $this->isDecorated() && strlen($text) > 0 ? $this->styleStack->getCurrent()->apply($text) : $text;
}
}
<?php
namespace Symfony\Component\Console\Formatter;
interface OutputFormatterInterface
{
public function setDecorated($decorated);
public function isDecorated();
public function setStyle($name, OutputFormatterStyleInterface $style);
public function hasStyle($name);
public function getStyle($name);
public function format($message);
}
<?php
namespace Symfony\Component\Console\Formatter;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatterStyle implements OutputFormatterStyleInterface
{
private static $availableForegroundColors = array(
'black' => array('set' => 30, 'unset' => 39),
'red' => array('set' => 31, 'unset' => 39),
'green' => array('set' => 32, 'unset' => 39),
'yellow' => array('set' => 33, 'unset' => 39),
'blue' => array('set' => 34, 'unset' => 39),
'magenta' => array('set' => 35, 'unset' => 39),
'cyan' => array('set' => 36, 'unset' => 39),
'white' => array('set' => 37, 'unset' => 39),
'default' => array('set' => 39, 'unset' => 39),
);
private static $availableBackgroundColors = array(
'black' => array('set' => 40, 'unset' => 49),
'red' => array('set' => 41, 'unset' => 49),
'green' => array('set' => 42, 'unset' => 49),
'yellow' => array('set' => 43, 'unset' => 49),
'blue' => array('set' => 44, 'unset' => 49),
'magenta' => array('set' => 45, 'unset' => 49),
'cyan' => array('set' => 46, 'unset' => 49),
'white' => array('set' => 47, 'unset' => 49),
'default' => array('set' => 49, 'unset' => 49),
);
private static $availableOptions = array(
'bold' => array('set' => 1, 'unset' => 22),
'underscore' => array('set' => 4, 'unset' => 24),
'blink' => array('set' => 5, 'unset' => 25),
'reverse' => array('set' => 7, 'unset' => 27),
'conceal' => array('set' => 8, 'unset' => 28),
);
private $foreground;
private $background;
private $options = array();
public function __construct($foreground = null, $background = null, array $options = array())
{
if (null !== $foreground) {
$this->setForeground($foreground);
}
if (null !== $background) {
$this->setBackground($background);
}
if (count($options)) {
$this->setOptions($options);
}
}
public function setForeground($color = null)
{
if (null === $color) {
$this->foreground = null;
return;
}
if (!isset(static::$availableForegroundColors[$color])) {
throw new InvalidArgumentException(sprintf(
'Invalid foreground color specified: "%s". Expected one of (%s)',
$color,
implode(', ', array_keys(static::$availableForegroundColors))
));
}
$this->foreground = static::$availableForegroundColors[$color];
}
public function setBackground($color = null)
{
if (null === $color) {
$this->background = null;
return;
}
if (!isset(static::$availableBackgroundColors[$color])) {
throw new InvalidArgumentException(sprintf(
'Invalid background color specified: "%s". Expected one of (%s)',
$color,
implode(', ', array_keys(static::$availableBackgroundColors))
));
}
$this->background = static::$availableBackgroundColors[$color];
}
public function setOption($option)
{
if (!isset(static::$availableOptions[$option])) {
throw new InvalidArgumentException(sprintf(
'Invalid option specified: "%s". Expected one of (%s)',
$option,
implode(', ', array_keys(static::$availableOptions))
));
}
if (!in_array(static::$availableOptions[$option], $this->options)) {
$this->options[] = static::$availableOptions[$option];
}
}
public function unsetOption($option)
{
if (!isset(static::$availableOptions[$option])) {
throw new InvalidArgumentException(sprintf(
'Invalid option specified: "%s". Expected one of (%s)',
$option,
implode(', ', array_keys(static::$availableOptions))
));
}
$pos = array_search(static::$availableOptions[$option], $this->options);
if (false !== $pos) {
unset($this->options[$pos]);
}
}
public function setOptions(array $options)
{
$this->options = array();
foreach ($options as $option) {
$this->setOption($option);
}
}
public function apply($text)
{
$setCodes = array();
$unsetCodes = array();
if (null !== $this->foreground) {
$setCodes[] = $this->foreground['set'];
$unsetCodes[] = $this->foreground['unset'];
}
if (null !== $this->background) {
$setCodes[] = $this->background['set'];
$unsetCodes[] = $this->background['unset'];
}
if (count($this->options)) {
foreach ($this->options as $option) {
$setCodes[] = $option['set'];
$unsetCodes[] = $option['unset'];
}
}
if (0 === count($setCodes)) {
return $text;
}
return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
}
}
<?php
namespace Symfony\Component\Console\Formatter;
interface OutputFormatterStyleInterface
{
public function setForeground($color = null);
public function setBackground($color = null);
public function setOption($option);
public function unsetOption($option);
public function setOptions(array $options);
public function apply($text);
}
<?php
namespace Symfony\Component\Console\Formatter;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatterStyleStack
{
private $styles;
private $emptyStyle;
public function __construct(OutputFormatterStyleInterface $emptyStyle = null)
{
$this->emptyStyle = $emptyStyle ?: new OutputFormatterStyle();
$this->reset();
}
public function reset()
{
$this->styles = array();
}
public function push(OutputFormatterStyleInterface $style)
{
$this->styles[] = $style;
}
public function pop(OutputFormatterStyleInterface $style = null)
{
if (empty($this->styles)) {
return $this->emptyStyle;
}
if (null === $style) {
return array_pop($this->styles);
}
foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
if ($style->apply('') === $stackedStyle->apply('')) {
$this->styles = array_slice($this->styles, 0, $index);
return $stackedStyle;
}
}
throw new InvalidArgumentException('Incorrectly nested style tag found.');
}
public function getCurrent()
{
if (empty($this->styles)) {
return $this->emptyStyle;
}
return $this->styles[count($this->styles) - 1];
}
public function setEmptyStyle(OutputFormatterStyleInterface $emptyStyle)
{
$this->emptyStyle = $emptyStyle;
return $this;
}
public function getEmptyStyle()
{
return $this->emptyStyle;
}
}
<?php
namespace Symfony\Component\Console\Helper;
class DebugFormatterHelper extends Helper
{
private $colors = array('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default');
private $started = array();
private $count = -1;
public function start($id, $message, $prefix = 'RUN')
{
$this->started[$id] = array('border' => ++$this->count % count($this->colors));
return sprintf("%s<bg=blue;fg=white> %s </> <fg=blue>%s</>\n", $this->getBorder($id), $prefix, $message);
}
public function progress($id, $buffer, $error = false, $prefix = 'OUT', $errorPrefix = 'ERR')
{
$message = '';
if ($error) {
if (isset($this->started[$id]['out'])) {
$message .= "\n";
unset($this->started[$id]['out']);
}
if (!isset($this->started[$id]['err'])) {
$message .= sprintf('%s<bg=red;fg=white> %s </> ', $this->getBorder($id), $errorPrefix);
$this->started[$id]['err'] = true;
}
$message .= str_replace("\n", sprintf("\n%s<bg=red;fg=white> %s </> ", $this->getBorder($id), $errorPrefix), $buffer);
} else {
if (isset($this->started[$id]['err'])) {
$message .= "\n";
unset($this->started[$id]['err']);
}
if (!isset($this->started[$id]['out'])) {
$message .= sprintf('%s<bg=green;fg=white> %s </> ', $this->getBorder($id), $prefix);
$this->started[$id]['out'] = true;
}
$message .= str_replace("\n", sprintf("\n%s<bg=green;fg=white> %s </> ", $this->getBorder($id), $prefix), $buffer);
}
return $message;
}
public function stop($id, $message, $successful, $prefix = 'RES')
{
$trailingEOL = isset($this->started[$id]['out']) || isset($this->started[$id]['err']) ? "\n" : '';
if ($successful) {
return sprintf("%s%s<bg=green;fg=white> %s </> <fg=green>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message);
}
$message = sprintf("%s%s<bg=red;fg=white> %s </> <fg=red>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message);
unset($this->started[$id]['out'], $this->started[$id]['err']);
return $message;
}
private function getBorder($id)
{
return sprintf('<bg=%s> </>', $this->colors[$this->started[$id]['border']]);
}
public function getName()
{
return 'debug_formatter';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Descriptor\DescriptorInterface;
use Symfony\Component\Console\Descriptor\JsonDescriptor;
use Symfony\Component\Console\Descriptor\MarkdownDescriptor;
use Symfony\Component\Console\Descriptor\TextDescriptor;
use Symfony\Component\Console\Descriptor\XmlDescriptor;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class DescriptorHelper extends Helper
{
private $descriptors = array();
public function __construct()
{
$this
->register('txt', new TextDescriptor())
->register('xml', new XmlDescriptor())
->register('json', new JsonDescriptor())
->register('md', new MarkdownDescriptor())
;
}
public function describe(OutputInterface $output, $object, array $options = array())
{
$options = array_merge(array(
'raw_text' => false,
'format' => 'txt',
), $options);
if (!isset($this->descriptors[$options['format']])) {
throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));
}
$descriptor = $this->descriptors[$options['format']];
$descriptor->describe($output, $object, $options);
}
public function register($format, DescriptorInterface $descriptor)
{
$this->descriptors[$format] = $descriptor;
return $this;
}
public function getName()
{
return 'descriptor';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Formatter\OutputFormatter;
class FormatterHelper extends Helper
{
public function formatSection($section, $message, $style = 'info')
{
return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message);
}
public function formatBlock($messages, $style, $large = false)
{
if (!is_array($messages)) {
$messages = array($messages);
}
$len = 0;
$lines = array();
foreach ($messages as $message) {
$message = OutputFormatter::escape($message);
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
$len = max($this->strlen($message) + ($large ? 4 : 2), $len);
}
$messages = $large ? array(str_repeat(' ', $len)) : array();
for ($i = 0; isset($lines[$i]); ++$i) {
$messages[] = $lines[$i].str_repeat(' ', $len - $this->strlen($lines[$i]));
}
if ($large) {
$messages[] = str_repeat(' ', $len);
}
for ($i = 0; isset($messages[$i]); ++$i) {
$messages[$i] = sprintf('<%s>%s</%s>', $style, $messages[$i], $style);
}
return implode("\n", $messages);
}
public function truncate($message, $length, $suffix = '...')
{
$computedLength = $length - $this->strlen($suffix);
if ($computedLength > $this->strlen($message)) {
return $message;
}
if (false === $encoding = mb_detect_encoding($message, null, true)) {
return substr($message, 0, $length).$suffix;
}
return mb_substr($message, 0, $length, $encoding).$suffix;
}
public function getName()
{
return 'formatter';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
abstract class Helper implements HelperInterface
{
protected $helperSet = null;
public function setHelperSet(HelperSet $helperSet = null)
{
$this->helperSet = $helperSet;
}
public function getHelperSet()
{
return $this->helperSet;
}
public static function strlen($string)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return strlen($string);
}
return mb_strwidth($string, $encoding);
}
public static function formatTime($secs)
{
static $timeFormats = array(
array(0, '< 1 sec'),
array(1, '1 sec'),
array(2, 'secs', 1),
array(60, '1 min'),
array(120, 'mins', 60),
array(3600, '1 hr'),
array(7200, 'hrs', 3600),
array(86400, '1 day'),
array(172800, 'days', 86400),
);
foreach ($timeFormats as $index => $format) {
if ($secs >= $format[0]) {
if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0])
|| $index == count($timeFormats) - 1
) {
if (2 == count($format)) {
return $format[1];
}
return floor($secs / $format[2]).' '.$format[1];
}
}
}
}
public static function formatMemory($memory)
{
if ($memory >= 1024 * 1024 * 1024) {
return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024);
}
if ($memory >= 1024 * 1024) {
return sprintf('%.1f MiB', $memory / 1024 / 1024);
}
if ($memory >= 1024) {
return sprintf('%d KiB', $memory / 1024);
}
return sprintf('%d B', $memory);
}
public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, $string)
{
$isDecorated = $formatter->isDecorated();
$formatter->setDecorated(false);
$string = $formatter->format($string);
$string = preg_replace("/\033\[[^m]*m/", '', $string);
$formatter->setDecorated($isDecorated);
return self::strlen($string);
}
}
<?php
namespace Symfony\Component\Console\Helper;
interface HelperInterface
{
public function setHelperSet(HelperSet $helperSet = null);
public function getHelperSet();
public function getName();
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class HelperSet implements \IteratorAggregate
{
private $helpers = array();
private $command;
public function __construct(array $helpers = array())
{
foreach ($helpers as $alias => $helper) {
$this->set($helper, is_int($alias) ? null : $alias);
}
}
public function set(HelperInterface $helper, $alias = null)
{
$this->helpers[$helper->getName()] = $helper;
if (null !== $alias) {
$this->helpers[$alias] = $helper;
}
$helper->setHelperSet($this);
}
public function has($name)
{
return isset($this->helpers[$name]);
}
public function get($name)
{
if (!$this->has($name)) {
throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
}
return $this->helpers[$name];
}
public function setCommand(Command $command = null)
{
$this->command = $command;
}
public function getCommand()
{
return $this->command;
}
public function getIterator()
{
return new \ArrayIterator($this->helpers);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputAwareInterface;
abstract class InputAwareHelper extends Helper implements InputAwareInterface
{
protected $input;
public function setInput(InputInterface $input)
{
$this->input = $input;
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;
class ProcessHelper extends Helper
{
public function run(OutputInterface $output, $cmd, $error = null, callable $callback = null, $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$formatter = $this->getHelperSet()->get('debug_formatter');
if (is_array($cmd)) {
$process = ProcessBuilder::create($cmd)->getProcess();
} elseif ($cmd instanceof Process) {
$process = $cmd;
} else {
$process = new Process($cmd);
}
if ($verbosity <= $output->getVerbosity()) {
$output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine())));
}
if ($output->isDebug()) {
$callback = $this->wrapCallback($output, $process, $callback);
}
$process->run($callback);
if ($verbosity <= $output->getVerbosity()) {
$message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode());
$output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful()));
}
if (!$process->isSuccessful() && null !== $error) {
$output->writeln(sprintf('<error>%s</error>', $this->escapeString($error)));
}
return $process;
}
public function mustRun(OutputInterface $output, $cmd, $error = null, callable $callback = null)
{
$process = $this->run($output, $cmd, $error, $callback);
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return $process;
}
public function wrapCallback(OutputInterface $output, Process $process, callable $callback = null)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$formatter = $this->getHelperSet()->get('debug_formatter');
return function ($type, $buffer) use ($output, $process, $callback, $formatter) {
$output->write($formatter->progress(spl_object_hash($process), $this->escapeString($buffer), Process::ERR === $type));
if (null !== $callback) {
call_user_func($callback, $type, $buffer);
}
};
}
private function escapeString($str)
{
return str_replace('<', '\\<', $str);
}
public function getName()
{
return 'process';
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Exception\LogicException;
class ProgressBar
{
private $barWidth = 28;
private $barChar;
private $emptyBarChar = '-';
private $progressChar = '>';
private $format;
private $internalFormat;
private $redrawFreq = 1;
private $output;
private $step = 0;
private $max;
private $startTime;
private $stepWidth;
private $percent = 0.0;
private $formatLineCount;
private $messages = array();
private $overwrite = true;
private $firstRun = true;
private static $formatters;
private static $formats;
public function __construct(OutputInterface $output, $max = 0)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$this->output = $output;
$this->setMaxSteps($max);
if (!$this->output->isDecorated()) {
$this->overwrite = false;
$this->setRedrawFrequency($max / 10);
}
$this->startTime = time();
}
public static function setPlaceholderFormatterDefinition($name, callable $callable)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
self::$formatters[$name] = $callable;
}
public static function getPlaceholderFormatterDefinition($name)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
}
public static function setFormatDefinition($name, $format)
{
if (!self::$formats) {
self::$formats = self::initFormats();
}
self::$formats[$name] = $format;
}
public static function getFormatDefinition($name)
{
if (!self::$formats) {
self::$formats = self::initFormats();
}
return isset(self::$formats[$name]) ? self::$formats[$name] : null;
}
public function setMessage($message, $name = 'message')
{
$this->messages[$name] = $message;
}
public function getMessage($name = 'message')
{
return $this->messages[$name];
}
public function getStartTime()
{
return $this->startTime;
}
public function getMaxSteps()
{
return $this->max;
}
public function getProgress()
{
return $this->step;
}
private function getStepWidth()
{
return $this->stepWidth;
}
public function getProgressPercent()
{
return $this->percent;
}
public function setBarWidth($size)
{
$this->barWidth = (int) $size;
}
public function getBarWidth()
{
return $this->barWidth;
}
public function setBarCharacter($char)
{
$this->barChar = $char;
}
public function getBarCharacter()
{
if (null === $this->barChar) {
return $this->max ? '=' : $this->emptyBarChar;
}
return $this->barChar;
}
public function setEmptyBarCharacter($char)
{
$this->emptyBarChar = $char;
}
public function getEmptyBarCharacter()
{
return $this->emptyBarChar;
}
public function setProgressCharacter($char)
{
$this->progressChar = $char;
}
public function getProgressCharacter()
{
return $this->progressChar;
}
public function setFormat($format)
{
$this->format = null;
$this->internalFormat = $format;
}
public function setRedrawFrequency($freq)
{
$this->redrawFreq = max((int) $freq, 1);
}
public function start($max = null)
{
$this->startTime = time();
$this->step = 0;
$this->percent = 0.0;
if (null !== $max) {
$this->setMaxSteps($max);
}
$this->display();
}
public function advance($step = 1)
{
$this->setProgress($this->step + $step);
}
public function setOverwrite($overwrite)
{
$this->overwrite = (bool) $overwrite;
}
public function setProgress($step)
{
$step = (int) $step;
if ($step < $this->step) {
throw new LogicException('You can\'t regress the progress bar.');
}
if ($this->max && $step > $this->max) {
$this->max = $step;
}
$prevPeriod = (int) ($this->step / $this->redrawFreq);
$currPeriod = (int) ($step / $this->redrawFreq);
$this->step = $step;
$this->percent = $this->max ? (float) $this->step / $this->max : 0;
if ($prevPeriod !== $currPeriod || $this->max === $step) {
$this->display();
}
}
public function finish()
{
if (!$this->max) {
$this->max = $this->step;
}
if ($this->step === $this->max && !$this->overwrite) {
return;
}
$this->setProgress($this->max);
}
public function display()
{
if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
return;
}
if (null === $this->format) {
$this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
}
$this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) {
if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
$text = call_user_func($formatter, $this, $this->output);
} elseif (isset($this->messages[$matches[1]])) {
$text = $this->messages[$matches[1]];
} else {
return $matches[0];
}
if (isset($matches[2])) {
$text = sprintf('%'.$matches[2], $text);
}
return $text;
}, $this->format));
}
public function clear()
{
if (!$this->overwrite) {
return;
}
if (null === $this->format) {
$this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
}
$this->overwrite('');
}
private function setRealFormat($format)
{
if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
$this->format = self::getFormatDefinition($format.'_nomax');
} elseif (null !== self::getFormatDefinition($format)) {
$this->format = self::getFormatDefinition($format);
} else {
$this->format = $format;
}
$this->formatLineCount = substr_count($this->format, "\n");
}
private function setMaxSteps($max)
{
$this->max = max(0, (int) $max);
$this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
}
private function overwrite($message)
{
if ($this->overwrite) {
if (!$this->firstRun) {
$this->output->write("\x0D");
$this->output->write("\x1B[2K");
if ($this->formatLineCount > 0) {
$this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount));
}
}
} elseif ($this->step > 0) {
$this->output->writeln('');
}
$this->firstRun = false;
$this->output->write($message);
}
private function determineBestFormat()
{
switch ($this->output->getVerbosity()) {
case OutputInterface::VERBOSITY_VERBOSE:
return $this->max ? 'verbose' : 'verbose_nomax';
case OutputInterface::VERBOSITY_VERY_VERBOSE:
return $this->max ? 'very_verbose' : 'very_verbose_nomax';
case OutputInterface::VERBOSITY_DEBUG:
return $this->max ? 'debug' : 'debug_nomax';
default:
return $this->max ? 'normal' : 'normal_nomax';
}
}
private static function initPlaceholderFormatters()
{
return array(
'bar' => function (ProgressBar $bar, OutputInterface $output) {
$completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
$display = str_repeat($bar->getBarCharacter(), $completeBars);
if ($completeBars < $bar->getBarWidth()) {
$emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
$display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
}
return $display;
},
'elapsed' => function (ProgressBar $bar) {
return Helper::formatTime(time() - $bar->getStartTime());
},
'remaining' => function (ProgressBar $bar) {
if (!$bar->getMaxSteps()) {
throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
}
if (!$bar->getProgress()) {
$remaining = 0;
} else {
$remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
}
return Helper::formatTime($remaining);
},
'estimated' => function (ProgressBar $bar) {
if (!$bar->getMaxSteps()) {
throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
}
if (!$bar->getProgress()) {
$estimated = 0;
} else {
$estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
}
return Helper::formatTime($estimated);
},
'memory' => function (ProgressBar $bar) {
return Helper::formatMemory(memory_get_usage(true));
},
'current' => function (ProgressBar $bar) {
return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
},
'max' => function (ProgressBar $bar) {
return $bar->getMaxSteps();
},
'percent' => function (ProgressBar $bar) {
return floor($bar->getProgressPercent() * 100);
},
);
}
private static function initFormats()
{
return array(
'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
'normal_nomax' => ' %current% [%bar%]',
'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Output\OutputInterface;
class ProgressIndicator
{
private $output;
private $startTime;
private $format;
private $message;
private $indicatorValues;
private $indicatorCurrent;
private $indicatorChangeInterval;
private $indicatorUpdateTime;
private $lastMessagesLength;
private $started = false;
private static $formatters;
private static $formats;
public function __construct(OutputInterface $output, $format = null, $indicatorChangeInterval = 100, $indicatorValues = null)
{
$this->output = $output;
if (null === $format) {
$format = $this->determineBestFormat();
}
if (null === $indicatorValues) {
$indicatorValues = array('-', '\\', '|', '/');
}
$indicatorValues = array_values($indicatorValues);
if (2 > count($indicatorValues)) {
throw new InvalidArgumentException('Must have at least 2 indicator value characters.');
}
$this->format = self::getFormatDefinition($format);
$this->indicatorChangeInterval = $indicatorChangeInterval;
$this->indicatorValues = $indicatorValues;
$this->startTime = time();
}
public function setMessage($message)
{
$this->message = $message;
$this->display();
}
public function start($message)
{
if ($this->started) {
throw new LogicException('Progress indicator already started.');
}
$this->message = $message;
$this->started = true;
$this->lastMessagesLength = 0;
$this->startTime = time();
$this->indicatorUpdateTime = $this->getCurrentTimeInMilliseconds() + $this->indicatorChangeInterval;
$this->indicatorCurrent = 0;
$this->display();
}
public function advance()
{
if (!$this->started) {
throw new LogicException('Progress indicator has not yet been started.');
}
if (!$this->output->isDecorated()) {
return;
}
$currentTime = $this->getCurrentTimeInMilliseconds();
if ($currentTime < $this->indicatorUpdateTime) {
return;
}
$this->indicatorUpdateTime = $currentTime + $this->indicatorChangeInterval;
++$this->indicatorCurrent;
$this->display();
}
public function finish($message)
{
if (!$this->started) {
throw new LogicException('Progress indicator has not yet been started.');
}
$this->message = $message;
$this->display();
$this->output->writeln('');
$this->started = false;
}
public static function getFormatDefinition($name)
{
if (!self::$formats) {
self::$formats = self::initFormats();
}
return isset(self::$formats[$name]) ? self::$formats[$name] : null;
}
public static function setPlaceholderFormatterDefinition($name, $callable)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
self::$formatters[$name] = $callable;
}
public static function getPlaceholderFormatterDefinition($name)
{
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
}
return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
}
private function display()
{
if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
return;
}
$self = $this;
$this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) use ($self) {
if ($formatter = $self::getPlaceholderFormatterDefinition($matches[1])) {
return call_user_func($formatter, $self);
}
return $matches[0];
}, $this->format));
}
private function determineBestFormat()
{
switch ($this->output->getVerbosity()) {
case OutputInterface::VERBOSITY_VERBOSE:
return $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi';
case OutputInterface::VERBOSITY_VERY_VERBOSE:
case OutputInterface::VERBOSITY_DEBUG:
return $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi';
default:
return $this->output->isDecorated() ? 'normal' : 'normal_no_ansi';
}
}
private function overwrite($message)
{
if (null !== $this->lastMessagesLength) {
if ($this->lastMessagesLength > Helper::strlenWithoutDecoration($this->output->getFormatter(), $message)) {
$message = str_pad($message, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
}
}
if ($this->output->isDecorated()) {
$this->output->write("\x0D");
$this->output->write($message);
} else {
$this->output->writeln($message);
}
$this->lastMessagesLength = 0;
$len = Helper::strlenWithoutDecoration($this->output->getFormatter(), $message);
if ($len > $this->lastMessagesLength) {
$this->lastMessagesLength = $len;
}
}
private function getCurrentTimeInMilliseconds()
{
return round(microtime(true) * 1000);
}
private static function initPlaceholderFormatters()
{
return array(
'indicator' => function (ProgressIndicator $indicator) {
return $indicator->indicatorValues[$indicator->indicatorCurrent % count($indicator->indicatorValues)];
},
'message' => function (ProgressIndicator $indicator) {
return $indicator->message;
},
'elapsed' => function (ProgressIndicator $indicator) {
return Helper::formatTime(time() - $indicator->startTime);
},
'memory' => function () {
return Helper::formatMemory(memory_get_usage(true));
},
);
}
private static function initFormats()
{
return array(
'normal' => ' %indicator% %message%',
'normal_no_ansi' => ' %message%',
'verbose' => ' %indicator% %message% (%elapsed:6s%)',
'verbose_no_ansi' => ' %message% (%elapsed:6s%)',
'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)',
'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)',
);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Question\ChoiceQuestion;
class QuestionHelper extends Helper
{
private $inputStream;
private static $shell;
private static $stty;
public function ask(InputInterface $input, OutputInterface $output, Question $question)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
if (!$input->isInteractive()) {
return $question->getDefault();
}
if (!$question->getValidator()) {
return $this->doAsk($output, $question);
}
$interviewer = function () use ($output, $question) {
return $this->doAsk($output, $question);
};
return $this->validateAttempts($interviewer, $output, $question);
}
public function setInputStream($stream)
{
if (!is_resource($stream)) {
throw new InvalidArgumentException('Input stream must be a valid resource.');
}
$this->inputStream = $stream;
}
public function getInputStream()
{
return $this->inputStream;
}
public function getName()
{
return 'question';
}
private function doAsk(OutputInterface $output, Question $question)
{
$this->writePrompt($output, $question);
$inputStream = $this->inputStream ?: STDIN;
$autocomplete = $question->getAutocompleterValues();
if (null === $autocomplete || !$this->hasSttyAvailable()) {
$ret = false;
if ($question->isHidden()) {
try {
$ret = trim($this->getHiddenResponse($output, $inputStream));
} catch (\RuntimeException $e) {
if (!$question->isHiddenFallback()) {
throw $e;
}
}
}
if (false === $ret) {
$ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new \RuntimeException('Aborted');
}
$ret = trim($ret);
}
} else {
$ret = trim($this->autocomplete($output, $question, $inputStream));
}
$ret = strlen($ret) > 0 ? $ret : $question->getDefault();
if ($normalizer = $question->getNormalizer()) {
return $normalizer($ret);
}
return $ret;
}
protected function writePrompt(OutputInterface $output, Question $question)
{
$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
$messages = (array) $question->getQuestion();
foreach ($question->getChoices() as $key => $value) {
$width = $maxWidth - $this->strlen($key);
$messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
}
$output->writeln($messages);
$message = $question->getPrompt();
}
$output->write($message);
}
protected function writeError(OutputInterface $output, \Exception $error)
{
if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
$message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
} else {
$message = '<error>'.$error->getMessage().'</error>';
}
$output->writeln($message);
}
private function autocomplete(OutputInterface $output, Question $question, $inputStream)
{
$autocomplete = $question->getAutocompleterValues();
$ret = '';
$i = 0;
$ofs = -1;
$matches = $autocomplete;
$numMatches = count($matches);
$sttyMode = shell_exec('stty -g');
shell_exec('stty -icanon -echo');
$output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
while (!feof($inputStream)) {
$c = fread($inputStream, 1);
if ("\177" === $c) {
if (0 === $numMatches && 0 !== $i) {
--$i;
$output->write("\033[1D");
}
if ($i === 0) {
$ofs = -1;
$matches = $autocomplete;
$numMatches = count($matches);
} else {
$numMatches = 0;
}
$ret = substr($ret, 0, $i);
} elseif ("\033" === $c) {
$c .= fread($inputStream, 2);
if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
if ('A' === $c[2] && -1 === $ofs) {
$ofs = 0;
}
if (0 === $numMatches) {
continue;
}
$ofs += ('A' === $c[2]) ? -1 : 1;
$ofs = ($numMatches + $ofs) % $numMatches;
}
} elseif (ord($c) < 32) {
if ("\t" === $c || "\n" === $c) {
if ($numMatches > 0 && -1 !== $ofs) {
$ret = $matches[$ofs];
$output->write(substr($ret, $i));
$i = strlen($ret);
}
if ("\n" === $c) {
$output->write($c);
break;
}
$numMatches = 0;
}
continue;
} else {
$output->write($c);
$ret .= $c;
++$i;
$numMatches = 0;
$ofs = 0;
foreach ($autocomplete as $value) {
if (0 === strpos($value, $ret) && $i !== strlen($value)) {
$matches[$numMatches++] = $value;
}
}
}
$output->write("\033[K");
if ($numMatches > 0 && -1 !== $ofs) {
$output->write("\0337");
$output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
$output->write("\0338");
}
}
shell_exec(sprintf('stty %s', $sttyMode));
return $ret;
}
private function getHiddenResponse(OutputInterface $output, $inputStream)
{
if ('\\' === DIRECTORY_SEPARATOR) {
$exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
copy($exe, $tmpExe);
$exe = $tmpExe;
}
$value = rtrim(shell_exec($exe));
$output->writeln('');
if (isset($tmpExe)) {
unlink($tmpExe);
}
return $value;
}
if ($this->hasSttyAvailable()) {
$sttyMode = shell_exec('stty -g');
shell_exec('stty -echo');
$value = fgets($inputStream, 4096);
shell_exec(sprintf('stty %s', $sttyMode));
if (false === $value) {
throw new RuntimeException('Aborted');
}
$value = trim($value);
$output->writeln('');
return $value;
}
if (false !== $shell = $this->getShell()) {
$readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
$command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
$value = rtrim(shell_exec($command));
$output->writeln('');
return $value;
}
throw new RuntimeException('Unable to hide the response.');
}
private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
{
$error = null;
$attempts = $question->getMaxAttempts();
while (null === $attempts || $attempts--) {
if (null !== $error) {
$this->writeError($output, $error);
}
try {
return call_user_func($question->getValidator(), $interviewer());
} catch (\Exception $error) {
}
}
throw $error;
}
private function getShell()
{
if (null !== self::$shell) {
return self::$shell;
}
self::$shell = false;
if (file_exists('/usr/bin/env')) {
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
self::$shell = $sh;
break;
}
}
}
return self::$shell;
}
private function hasSttyAvailable()
{
if (null !== self::$stty) {
return self::$stty;
}
exec('stty 2>&1', $output, $exitcode);
return self::$stty = $exitcode === 0;
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
class SymfonyQuestionHelper extends QuestionHelper
{
public function ask(InputInterface $input, OutputInterface $output, Question $question)
{
$validator = $question->getValidator();
$question->setValidator(function ($value) use ($validator) {
if (null !== $validator) {
$value = $validator($value);
}
if (!is_array($value) && !is_bool($value) && 0 === strlen($value)) {
throw new LogicException('A value is required.');
}
return $value;
});
return parent::ask($input, $output, $question);
}
protected function writePrompt(OutputInterface $output, Question $question)
{
$text = $question->getQuestion();
$default = $question->getDefault();
switch (true) {
case null === $default:
$text = sprintf(' <info>%s</info>:', $text);
break;
case $question instanceof ConfirmationQuestion:
$text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
break;
case $question instanceof ChoiceQuestion && $question->isMultiselect():
$choices = $question->getChoices();
$default = explode(',', $default);
foreach ($default as $key => $value) {
$default[$key] = $choices[trim($value)];
}
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, implode(', ', $default));
break;
case $question instanceof ChoiceQuestion:
$choices = $question->getChoices();
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $choices[$default]);
break;
default:
$text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $default);
}
$output->writeln($text);
if ($question instanceof ChoiceQuestion) {
$width = max(array_map('strlen', array_keys($question->getChoices())));
foreach ($question->getChoices() as $key => $value) {
$output->writeln(sprintf(" [<comment>%-${width}s</comment>] %s", $key, $value));
}
}
$output->write(' > ');
}
protected function writeError(OutputInterface $output, \Exception $error)
{
if ($output instanceof SymfonyStyle) {
$output->newLine();
$output->error($error->getMessage());
return;
}
parent::writeError($output, $error);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class Table
{
private $headers = array();
private $rows = array();
private $effectiveColumnWidths = array();
private $numberOfColumns;
private $output;
private $style;
private $columnStyles = array();
private $columnWidths = array();
private static $styles;
public function __construct(OutputInterface $output)
{
$this->output = $output;
if (!self::$styles) {
self::$styles = self::initStyles();
}
$this->setStyle('default');
}
public static function setStyleDefinition($name, TableStyle $style)
{
if (!self::$styles) {
self::$styles = self::initStyles();
}
self::$styles[$name] = $style;
}
public static function getStyleDefinition($name)
{
if (!self::$styles) {
self::$styles = self::initStyles();
}
if (isset(self::$styles[$name])) {
return self::$styles[$name];
}
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
public function setStyle($name)
{
$this->style = $this->resolveStyle($name);
return $this;
}
public function getStyle()
{
return $this->style;
}
public function setColumnStyle($columnIndex, $name)
{
$columnIndex = intval($columnIndex);
$this->columnStyles[$columnIndex] = $this->resolveStyle($name);
return $this;
}
public function getColumnStyle($columnIndex)
{
if (isset($this->columnStyles[$columnIndex])) {
return $this->columnStyles[$columnIndex];
}
return $this->getStyle();
}
public function setColumnWidth($columnIndex, $width)
{
$this->columnWidths[intval($columnIndex)] = intval($width);
return $this;
}
public function setColumnWidths(array $widths)
{
$this->columnWidths = array();
foreach ($widths as $index => $width) {
$this->setColumnWidth($index, $width);
}
return $this;
}
public function setHeaders(array $headers)
{
$headers = array_values($headers);
if (!empty($headers) && !is_array($headers[0])) {
$headers = array($headers);
}
$this->headers = $headers;
return $this;
}
public function setRows(array $rows)
{
$this->rows = array();
return $this->addRows($rows);
}
public function addRows(array $rows)
{
foreach ($rows as $row) {
$this->addRow($row);
}
return $this;
}
public function addRow($row)
{
if ($row instanceof TableSeparator) {
$this->rows[] = $row;
return $this;
}
if (!is_array($row)) {
throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}
$this->rows[] = array_values($row);
return $this;
}
public function setRow($column, array $row)
{
$this->rows[$column] = $row;
return $this;
}
public function render()
{
$this->calculateNumberOfColumns();
$rows = $this->buildTableRows($this->rows);
$headers = $this->buildTableRows($this->headers);
$this->calculateColumnsWidth(array_merge($headers, $rows));
$this->renderRowSeparator();
if (!empty($headers)) {
foreach ($headers as $header) {
$this->renderRow($header, $this->style->getCellHeaderFormat());
$this->renderRowSeparator();
}
}
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
$this->renderRowSeparator();
} else {
$this->renderRow($row, $this->style->getCellRowFormat());
}
}
if (!empty($rows)) {
$this->renderRowSeparator();
}
$this->cleanup();
}
private function renderRowSeparator()
{
if (0 === $count = $this->numberOfColumns) {
return;
}
if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
return;
}
$markup = $this->style->getCrossingChar();
for ($column = 0; $column < $count; ++$column) {
$markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
}
$this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
}
private function renderColumnSeparator()
{
return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
}
private function renderRow(array $row, $cellFormat)
{
if (empty($row)) {
return;
}
$rowContent = $this->renderColumnSeparator();
foreach ($this->getRowColumns($row) as $column) {
$rowContent .= $this->renderCell($row, $column, $cellFormat);
$rowContent .= $this->renderColumnSeparator();
}
$this->output->writeln($rowContent);
}
private function renderCell(array $row, $column, $cellFormat)
{
$cell = isset($row[$column]) ? $row[$column] : '';
$width = $this->effectiveColumnWidths[$column];
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
$width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
}
}
if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
$width += strlen($cell) - mb_strwidth($cell, $encoding);
}
$style = $this->getColumnStyle($column);
if ($cell instanceof TableSeparator) {
return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
}
$width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
$content = sprintf($style->getCellRowContentFormat(), $cell);
return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
}
private function calculateNumberOfColumns()
{
if (null !== $this->numberOfColumns) {
return;
}
$columns = array(0);
foreach (array_merge($this->headers, $this->rows) as $row) {
if ($row instanceof TableSeparator) {
continue;
}
$columns[] = $this->getNumberOfColumns($row);
}
$this->numberOfColumns = max($columns);
}
private function buildTableRows($rows)
{
$unmergedRows = array();
for ($rowKey = 0; $rowKey < count($rows); ++$rowKey) {
$rows = $this->fillNextRows($rows, $rowKey);
foreach ($rows[$rowKey] as $column => $cell) {
if (!strstr($cell, "\n")) {
continue;
}
$lines = explode("\n", $cell);
foreach ($lines as $lineKey => $line) {
if ($cell instanceof TableCell) {
$line = new TableCell($line, array('colspan' => $cell->getColspan()));
}
if (0 === $lineKey) {
$rows[$rowKey][$column] = $line;
} else {
$unmergedRows[$rowKey][$lineKey][$column] = $line;
}
}
}
}
$tableRows = array();
foreach ($rows as $rowKey => $row) {
$tableRows[] = $this->fillCells($row);
if (isset($unmergedRows[$rowKey])) {
$tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
}
}
return $tableRows;
}
private function fillNextRows($rows, $line)
{
$unmergedRows = array();
foreach ($rows[$line] as $column => $cell) {
if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
$nbLines = $cell->getRowspan() - 1;
$lines = array($cell);
if (strstr($cell, "\n")) {
$lines = explode("\n", $cell);
$nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
$rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
unset($lines[0]);
}
$unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
$value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
$unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
}
}
}
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
foreach ($unmergedRow as $cellKey => $cell) {
array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
}
} else {
$row = $this->copyRow($rows, $unmergedRowKey - 1);
foreach ($unmergedRow as $column => $cell) {
if (!empty($cell)) {
$row[$column] = $unmergedRow[$column];
}
}
array_splice($rows, $unmergedRowKey, 0, array($row));
}
}
return $rows;
}
private function fillCells($row)
{
$newRow = array();
foreach ($row as $column => $cell) {
$newRow[] = $cell;
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
$newRow[] = '';
}
}
}
return $newRow ?: $row;
}
private function copyRow($rows, $line)
{
$row = $rows[$line];
foreach ($row as $cellKey => $cellValue) {
$row[$cellKey] = '';
if ($cellValue instanceof TableCell) {
$row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
}
}
return $row;
}
private function getNumberOfColumns(array $row)
{
$columns = count($row);
foreach ($row as $column) {
$columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
}
return $columns;
}
private function getRowColumns($row)
{
$columns = range(0, $this->numberOfColumns - 1);
foreach ($row as $cellKey => $cell) {
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
$columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
}
}
return $columns;
}
private function calculateColumnsWidth($rows)
{
for ($column = 0; $column < $this->numberOfColumns; ++$column) {
$lengths = array();
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
continue;
}
foreach ($row as $i => $cell) {
if ($cell instanceof TableCell) {
$textLength = strlen($cell);
if ($textLength > 0) {
$contentColumns = str_split($cell, ceil($textLength / $cell->getColspan()));
foreach ($contentColumns as $position => $content) {
$row[$i + $position] = $content;
}
}
}
}
$lengths[] = $this->getCellWidth($row, $column);
}
$this->effectiveColumnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
}
}
private function getColumnSeparatorWidth()
{
return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
}
private function getCellWidth(array $row, $column)
{
$cellWidth = 0;
if (isset($row[$column])) {
$cell = $row[$column];
$cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
}
$columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
return max($cellWidth, $columnWidth);
}
private function cleanup()
{
$this->effectiveColumnWidths = array();
$this->numberOfColumns = null;
}
private static function initStyles()
{
$borderless = new TableStyle();
$borderless
->setHorizontalBorderChar('=')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
;
$compact = new TableStyle();
$compact
->setHorizontalBorderChar('')
->setVerticalBorderChar(' ')
->setCrossingChar('')
->setCellRowContentFormat('%s')
;
$styleGuide = new TableStyle();
$styleGuide
->setHorizontalBorderChar('-')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
->setCellHeaderFormat('%s')
;
return array(
'default' => new TableStyle(),
'borderless' => $borderless,
'compact' => $compact,
'symfony-style-guide' => $styleGuide,
);
}
private function resolveStyle($name)
{
if ($name instanceof TableStyle) {
return $name;
}
if (isset(self::$styles[$name])) {
return self::$styles[$name];
}
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class TableCell
{
private $value;
private $options = array(
'rowspan' => 1,
'colspan' => 1,
);
public function __construct($value = '', array $options = array())
{
$this->value = $value;
if ($diff = array_diff(array_keys($options), array_keys($this->options))) {
throw new InvalidArgumentException(sprintf('The TableCell does not support the following options: \'%s\'.', implode('\', \'', $diff)));
}
$this->options = array_merge($this->options, $options);
}
public function __toString()
{
return $this->value;
}
public function getColspan()
{
return (int) $this->options['colspan'];
}
public function getRowspan()
{
return (int) $this->options['rowspan'];
}
}
<?php
namespace Symfony\Component\Console\Helper;
class TableSeparator extends TableCell
{
public function __construct(array $options = array())
{
parent::__construct('', $options);
}
}
<?php
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class TableStyle
{
private $paddingChar = ' ';
private $horizontalBorderChar = '-';
private $verticalBorderChar = '|';
private $crossingChar = '+';
private $cellHeaderFormat = '<info>%s</info>';
private $cellRowFormat = '%s';
private $cellRowContentFormat = ' %s ';
private $borderFormat = '%s';
private $padType = STR_PAD_RIGHT;
public function setPaddingChar($paddingChar)
{
if (!$paddingChar) {
throw new LogicException('The padding char must not be empty');
}
$this->paddingChar = $paddingChar;
return $this;
}
public function getPaddingChar()
{
return $this->paddingChar;
}
public function setHorizontalBorderChar($horizontalBorderChar)
{
$this->horizontalBorderChar = $horizontalBorderChar;
return $this;
}
public function getHorizontalBorderChar()
{
return $this->horizontalBorderChar;
}
public function setVerticalBorderChar($verticalBorderChar)
{
$this->verticalBorderChar = $verticalBorderChar;
return $this;
}
public function getVerticalBorderChar()
{
return $this->verticalBorderChar;
}
public function setCrossingChar($crossingChar)
{
$this->crossingChar = $crossingChar;
return $this;
}
public function getCrossingChar()
{
return $this->crossingChar;
}
public function setCellHeaderFormat($cellHeaderFormat)
{
$this->cellHeaderFormat = $cellHeaderFormat;
return $this;
}
public function getCellHeaderFormat()
{
return $this->cellHeaderFormat;
}
public function setCellRowFormat($cellRowFormat)
{
$this->cellRowFormat = $cellRowFormat;
return $this;
}
public function getCellRowFormat()
{
return $this->cellRowFormat;
}
public function setCellRowContentFormat($cellRowContentFormat)
{
$this->cellRowContentFormat = $cellRowContentFormat;
return $this;
}
public function getCellRowContentFormat()
{
return $this->cellRowContentFormat;
}
public function setBorderFormat($borderFormat)
{
$this->borderFormat = $borderFormat;
return $this;
}
public function getBorderFormat()
{
return $this->borderFormat;
}
public function setPadType($padType)
{
if (!in_array($padType, array(STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH), true)) {
throw new InvalidArgumentException('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).');
}
$this->padType = $padType;
return $this;
}
public function getPadType()
{
return $this->padType;
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\RuntimeException;
class ArgvInput extends Input
{
private $tokens;
private $parsed;
public function __construct(array $argv = null, InputDefinition $definition = null)
{
if (null === $argv) {
$argv = $_SERVER['argv'];
}
array_shift($argv);
$this->tokens = $argv;
parent::__construct($definition);
}
protected function setTokens(array $tokens)
{
$this->tokens = $tokens;
}
protected function parse()
{
$parseOptions = true;
$this->parsed = $this->tokens;
while (null !== $token = array_shift($this->parsed)) {
if ($parseOptions && '' == $token) {
$this->parseArgument($token);
} elseif ($parseOptions && '--' == $token) {
$parseOptions = false;
} elseif ($parseOptions && 0 === strpos($token, '--')) {
$this->parseLongOption($token);
} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
$this->parseShortOption($token);
} else {
$this->parseArgument($token);
}
}
}
private function parseShortOption($token)
{
$name = substr($token, 1);
if (strlen($name) > 1) {
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
$this->addShortOption($name[0], substr($name, 1));
} else {
$this->parseShortOptionSet($name);
}
} else {
$this->addShortOption($name, null);
}
}
private function parseShortOptionSet($name)
{
$len = strlen($name);
for ($i = 0; $i < $len; ++$i) {
if (!$this->definition->hasShortcut($name[$i])) {
throw new RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
}
$option = $this->definition->getOptionForShortcut($name[$i]);
if ($option->acceptValue()) {
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
break;
} else {
$this->addLongOption($option->getName(), null);
}
}
}
private function parseLongOption($token)
{
$name = substr($token, 2);
if (false !== $pos = strpos($name, '=')) {
$this->addLongOption(substr($name, 0, $pos), substr($name, $pos + 1));
} else {
$this->addLongOption($name, null);
}
}
private function parseArgument($token)
{
$c = count($this->arguments);
if ($this->definition->hasArgument($c)) {
$arg = $this->definition->getArgument($c);
$this->arguments[$arg->getName()] = $arg->isArray() ? array($token) : $token;
} elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
$arg = $this->definition->getArgument($c - 1);
$this->arguments[$arg->getName()][] = $token;
} else {
$all = $this->definition->getArguments();
if (count($all)) {
throw new RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
}
throw new RuntimeException(sprintf('No arguments expected, got "%s".', $token));
}
}
private function addShortOption($shortcut, $value)
{
if (!$this->definition->hasShortcut($shortcut)) {
throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
}
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
}
private function addLongOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name));
}
$option = $this->definition->getOption($name);
if (!isset($value[0])) {
$value = null;
}
if (null !== $value && !$option->acceptValue()) {
throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
}
if (null === $value && $option->acceptValue() && count($this->parsed)) {
$next = array_shift($this->parsed);
if (isset($next[0]) && '-' !== $next[0]) {
$value = $next;
} elseif (empty($next)) {
$value = '';
} else {
array_unshift($this->parsed, $next);
}
}
if (null === $value) {
if ($option->isValueRequired()) {
throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
}
if (!$option->isArray()) {
$value = $option->isValueOptional() ? $option->getDefault() : true;
}
}
if ($option->isArray()) {
$this->options[$name][] = $value;
} else {
$this->options[$name] = $value;
}
}
public function getFirstArgument()
{
foreach ($this->tokens as $token) {
if ($token && '-' === $token[0]) {
continue;
}
return $token;
}
}
public function hasParameterOption($values, $onlyParams = false)
{
$values = (array) $values;
foreach ($this->tokens as $token) {
if ($onlyParams && $token === '--') {
return false;
}
foreach ($values as $value) {
if ($token === $value || 0 === strpos($token, $value.'=')) {
return true;
}
}
}
return false;
}
public function getParameterOption($values, $default = false, $onlyParams = false)
{
$values = (array) $values;
$tokens = $this->tokens;
while (0 < count($tokens)) {
$token = array_shift($tokens);
if ($onlyParams && $token === '--') {
return false;
}
foreach ($values as $value) {
if ($token === $value || 0 === strpos($token, $value.'=')) {
if (false !== $pos = strpos($token, '=')) {
return substr($token, $pos + 1);
}
return array_shift($tokens);
}
}
}
return $default;
}
public function __toString()
{
$tokens = array_map(function ($token) {
if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
return $match[1].$this->escapeToken($match[2]);
}
if ($token && $token[0] !== '-') {
return $this->escapeToken($token);
}
return $token;
}, $this->tokens);
return implode(' ', $tokens);
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\InvalidOptionException;
class ArrayInput extends Input
{
private $parameters;
public function __construct(array $parameters, InputDefinition $definition = null)
{
$this->parameters = $parameters;
parent::__construct($definition);
}
public function getFirstArgument()
{
foreach ($this->parameters as $key => $value) {
if ($key && '-' === $key[0]) {
continue;
}
return $value;
}
}
public function hasParameterOption($values, $onlyParams = false)
{
$values = (array) $values;
foreach ($this->parameters as $k => $v) {
if (!is_int($k)) {
$v = $k;
}
if ($onlyParams && $v === '--') {
return false;
}
if (in_array($v, $values)) {
return true;
}
}
return false;
}
public function getParameterOption($values, $default = false, $onlyParams = false)
{
$values = (array) $values;
foreach ($this->parameters as $k => $v) {
if ($onlyParams && ($k === '--' || (is_int($k) && $v === '--'))) {
return false;
}
if (is_int($k)) {
if (in_array($v, $values)) {
return true;
}
} elseif (in_array($k, $values)) {
return $v;
}
}
return $default;
}
public function __toString()
{
$params = array();
foreach ($this->parameters as $param => $val) {
if ($param && '-' === $param[0]) {
$params[] = $param.('' != $val ? '='.$this->escapeToken($val) : '');
} else {
$params[] = $this->escapeToken($val);
}
}
return implode(' ', $params);
}
protected function parse()
{
foreach ($this->parameters as $key => $value) {
if ($key === '--') {
return;
}
if (0 === strpos($key, '--')) {
$this->addLongOption(substr($key, 2), $value);
} elseif ('-' === $key[0]) {
$this->addShortOption(substr($key, 1), $value);
} else {
$this->addArgument($key, $value);
}
}
}
private function addShortOption($shortcut, $value)
{
if (!$this->definition->hasShortcut($shortcut)) {
throw new InvalidOptionException(sprintf('The "-%s" option does not exist.', $shortcut));
}
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
}
private function addLongOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new InvalidOptionException(sprintf('The "--%s" option does not exist.', $name));
}
$option = $this->definition->getOption($name);
if (null === $value) {
if ($option->isValueRequired()) {
throw new InvalidOptionException(sprintf('The "--%s" option requires a value.', $name));
}
$value = $option->isValueOptional() ? $option->getDefault() : true;
}
$this->options[$name] = $value;
}
private function addArgument($name, $value)
{
if (!$this->definition->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
$this->arguments[$name] = $value;
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
abstract class Input implements InputInterface
{
protected $definition;
protected $options = array();
protected $arguments = array();
protected $interactive = true;
public function __construct(InputDefinition $definition = null)
{
if (null === $definition) {
$this->definition = new InputDefinition();
} else {
$this->bind($definition);
$this->validate();
}
}
public function bind(InputDefinition $definition)
{
$this->arguments = array();
$this->options = array();
$this->definition = $definition;
$this->parse();
}
abstract protected function parse();
public function validate()
{
$definition = $this->definition;
$givenArguments = $this->arguments;
$missingArguments = array_filter(array_keys($definition->getArguments()), function ($argument) use ($definition, $givenArguments) {
return !array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired();
});
if (count($missingArguments) > 0) {
throw new RuntimeException(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArguments)));
}
}
public function isInteractive()
{
return $this->interactive;
}
public function setInteractive($interactive)
{
$this->interactive = (bool) $interactive;
}
public function getArguments()
{
return array_merge($this->definition->getArgumentDefaults(), $this->arguments);
}
public function getArgument($name)
{
if (!$this->definition->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
return isset($this->arguments[$name]) ? $this->arguments[$name] : $this->definition->getArgument($name)->getDefault();
}
public function setArgument($name, $value)
{
if (!$this->definition->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
$this->arguments[$name] = $value;
}
public function hasArgument($name)
{
return $this->definition->hasArgument($name);
}
public function getOptions()
{
return array_merge($this->definition->getOptionDefaults(), $this->options);
}
public function getOption($name)
{
if (!$this->definition->hasOption($name)) {
throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
}
return isset($this->options[$name]) ? $this->options[$name] : $this->definition->getOption($name)->getDefault();
}
public function setOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
}
$this->options[$name] = $value;
}
public function hasOption($name)
{
return $this->definition->hasOption($name);
}
public function escapeToken($token)
{
return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token);
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class InputArgument
{
const REQUIRED = 1;
const OPTIONAL = 2;
const IS_ARRAY = 4;
private $name;
private $mode;
private $default;
private $description;
public function __construct($name, $mode = null, $description = '', $default = null)
{
if (null === $mode) {
$mode = self::OPTIONAL;
} elseif (!is_int($mode) || $mode > 7 || $mode < 1) {
throw new InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode));
}
$this->name = $name;
$this->mode = $mode;
$this->description = $description;
$this->setDefault($default);
}
public function getName()
{
return $this->name;
}
public function isRequired()
{
return self::REQUIRED === (self::REQUIRED & $this->mode);
}
public function isArray()
{
return self::IS_ARRAY === (self::IS_ARRAY & $this->mode);
}
public function setDefault($default = null)
{
if (self::REQUIRED === $this->mode && null !== $default) {
throw new LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.');
}
if ($this->isArray()) {
if (null === $default) {
$default = array();
} elseif (!is_array($default)) {
throw new LogicException('A default value for an array argument must be an array.');
}
}
$this->default = $default;
}
public function getDefault()
{
return $this->default;
}
public function getDescription()
{
return $this->description;
}
}
<?php
namespace Symfony\Component\Console\Input;
interface InputAwareInterface
{
public function setInput(InputInterface $input);
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class InputDefinition
{
private $arguments;
private $requiredCount;
private $hasAnArrayArgument = false;
private $hasOptional;
private $options;
private $shortcuts;
public function __construct(array $definition = array())
{
$this->setDefinition($definition);
}
public function setDefinition(array $definition)
{
$arguments = array();
$options = array();
foreach ($definition as $item) {
if ($item instanceof InputOption) {
$options[] = $item;
} else {
$arguments[] = $item;
}
}
$this->setArguments($arguments);
$this->setOptions($options);
}
public function setArguments($arguments = array())
{
$this->arguments = array();
$this->requiredCount = 0;
$this->hasOptional = false;
$this->hasAnArrayArgument = false;
$this->addArguments($arguments);
}
public function addArguments($arguments = array())
{
if (null !== $arguments) {
foreach ($arguments as $argument) {
$this->addArgument($argument);
}
}
}
public function addArgument(InputArgument $argument)
{
if (isset($this->arguments[$argument->getName()])) {
throw new LogicException(sprintf('An argument with name "%s" already exists.', $argument->getName()));
}
if ($this->hasAnArrayArgument) {
throw new LogicException('Cannot add an argument after an array argument.');
}
if ($argument->isRequired() && $this->hasOptional) {
throw new LogicException('Cannot add a required argument after an optional one.');
}
if ($argument->isArray()) {
$this->hasAnArrayArgument = true;
}
if ($argument->isRequired()) {
++$this->requiredCount;
} else {
$this->hasOptional = true;
}
$this->arguments[$argument->getName()] = $argument;
}
public function getArgument($name)
{
if (!$this->hasArgument($name)) {
throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
}
$arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
return $arguments[$name];
}
public function hasArgument($name)
{
$arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
return isset($arguments[$name]);
}
public function getArguments()
{
return $this->arguments;
}
public function getArgumentCount()
{
return $this->hasAnArrayArgument ? PHP_INT_MAX : count($this->arguments);
}
public function getArgumentRequiredCount()
{
return $this->requiredCount;
}
public function getArgumentDefaults()
{
$values = array();
foreach ($this->arguments as $argument) {
$values[$argument->getName()] = $argument->getDefault();
}
return $values;
}
public function setOptions($options = array())
{
$this->options = array();
$this->shortcuts = array();
$this->addOptions($options);
}
public function addOptions($options = array())
{
foreach ($options as $option) {
$this->addOption($option);
}
}
public function addOption(InputOption $option)
{
if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) {
throw new LogicException(sprintf('An option named "%s" already exists.', $option->getName()));
}
if ($option->getShortcut()) {
foreach (explode('|', $option->getShortcut()) as $shortcut) {
if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]])) {
throw new LogicException(sprintf('An option with shortcut "%s" already exists.', $shortcut));
}
}
}
$this->options[$option->getName()] = $option;
if ($option->getShortcut()) {
foreach (explode('|', $option->getShortcut()) as $shortcut) {
$this->shortcuts[$shortcut] = $option->getName();
}
}
}
public function getOption($name)
{
if (!$this->hasOption($name)) {
throw new InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
}
return $this->options[$name];
}
public function hasOption($name)
{
return isset($this->options[$name]);
}
public function getOptions()
{
return $this->options;
}
public function hasShortcut($name)
{
return isset($this->shortcuts[$name]);
}
public function getOptionForShortcut($shortcut)
{
return $this->getOption($this->shortcutToName($shortcut));
}
public function getOptionDefaults()
{
$values = array();
foreach ($this->options as $option) {
$values[$option->getName()] = $option->getDefault();
}
return $values;
}
private function shortcutToName($shortcut)
{
if (!isset($this->shortcuts[$shortcut])) {
throw new InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
}
return $this->shortcuts[$shortcut];
}
public function getSynopsis($short = false)
{
$elements = array();
if ($short && $this->getOptions()) {
$elements[] = '[options]';
} elseif (!$short) {
foreach ($this->getOptions() as $option) {
$value = '';
if ($option->acceptValue()) {
$value = sprintf(
' %s%s%s',
$option->isValueOptional() ? '[' : '',
strtoupper($option->getName()),
$option->isValueOptional() ? ']' : ''
);
}
$shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
$elements[] = sprintf('[%s--%s%s]', $shortcut, $option->getName(), $value);
}
}
if (count($elements) && $this->getArguments()) {
$elements[] = '[--]';
}
foreach ($this->getArguments() as $argument) {
$element = '<'.$argument->getName().'>';
if (!$argument->isRequired()) {
$element = '['.$element.']';
} elseif ($argument->isArray()) {
$element = $element.' ('.$element.')';
}
if ($argument->isArray()) {
$element .= '...';
}
$elements[] = $element;
}
return implode(' ', $elements);
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
interface InputInterface
{
public function getFirstArgument();
public function hasParameterOption($values, $onlyParams = false);
public function getParameterOption($values, $default = false, $onlyParams = false);
public function bind(InputDefinition $definition);
public function validate();
public function getArguments();
public function getArgument($name);
public function setArgument($name, $value);
public function hasArgument($name);
public function getOptions();
public function getOption($name);
public function setOption($name, $value);
public function hasOption($name);
public function isInteractive();
public function setInteractive($interactive);
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class InputOption
{
const VALUE_NONE = 1;
const VALUE_REQUIRED = 2;
const VALUE_OPTIONAL = 4;
const VALUE_IS_ARRAY = 8;
private $name;
private $shortcut;
private $mode;
private $default;
private $description;
public function __construct($name, $shortcut = null, $mode = null, $description = '', $default = null)
{
if (0 === strpos($name, '--')) {
$name = substr($name, 2);
}
if (empty($name)) {
throw new InvalidArgumentException('An option name cannot be empty.');
}
if (empty($shortcut)) {
$shortcut = null;
}
if (null !== $shortcut) {
if (is_array($shortcut)) {
$shortcut = implode('|', $shortcut);
}
$shortcuts = preg_split('{(\|)-?}', ltrim($shortcut, '-'));
$shortcuts = array_filter($shortcuts);
$shortcut = implode('|', $shortcuts);
if (empty($shortcut)) {
throw new InvalidArgumentException('An option shortcut cannot be empty.');
}
}
if (null === $mode) {
$mode = self::VALUE_NONE;
} elseif (!is_int($mode) || $mode > 15 || $mode < 1) {
throw new InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode));
}
$this->name = $name;
$this->shortcut = $shortcut;
$this->mode = $mode;
$this->description = $description;
if ($this->isArray() && !$this->acceptValue()) {
throw new InvalidArgumentException('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.');
}
$this->setDefault($default);
}
public function getShortcut()
{
return $this->shortcut;
}
public function getName()
{
return $this->name;
}
public function acceptValue()
{
return $this->isValueRequired() || $this->isValueOptional();
}
public function isValueRequired()
{
return self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $this->mode);
}
public function isValueOptional()
{
return self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $this->mode);
}
public function isArray()
{
return self::VALUE_IS_ARRAY === (self::VALUE_IS_ARRAY & $this->mode);
}
public function setDefault($default = null)
{
if (self::VALUE_NONE === (self::VALUE_NONE & $this->mode) && null !== $default) {
throw new LogicException('Cannot set a default value when using InputOption::VALUE_NONE mode.');
}
if ($this->isArray()) {
if (null === $default) {
$default = array();
} elseif (!is_array($default)) {
throw new LogicException('A default value for an array option must be an array.');
}
}
$this->default = $this->acceptValue() ? $default : false;
}
public function getDefault()
{
return $this->default;
}
public function getDescription()
{
return $this->description;
}
public function equals(InputOption $option)
{
return $option->getName() === $this->getName()
&& $option->getShortcut() === $this->getShortcut()
&& $option->getDefault() === $this->getDefault()
&& $option->isArray() === $this->isArray()
&& $option->isValueRequired() === $this->isValueRequired()
&& $option->isValueOptional() === $this->isValueOptional()
;
}
}
<?php
namespace Symfony\Component\Console\Input;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class StringInput extends ArgvInput
{
const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
public function __construct($input)
{
parent::__construct(array());
$this->setTokens($this->tokenize($input));
}
private function tokenize($input)
{
$tokens = array();
$length = strlen($input);
$cursor = 0;
while ($cursor < $length) {
if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
} elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
$tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
} elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
$tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
} elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
$tokens[] = stripcslashes($match[1]);
} else {
throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
}
$cursor += strlen($match[0]);
}
return $tokens;
}
}
<?php
namespace Symfony\Component\Console\Logger;
use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
class ConsoleLogger extends AbstractLogger
{
const INFO = 'info';
const ERROR = 'error';
private $output;
private $verbosityLevelMap = array(
LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL,
LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL,
LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE,
LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE,
LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG,
);
private $formatLevelMap = array(
LogLevel::EMERGENCY => self::ERROR,
LogLevel::ALERT => self::ERROR,
LogLevel::CRITICAL => self::ERROR,
LogLevel::ERROR => self::ERROR,
LogLevel::WARNING => self::INFO,
LogLevel::NOTICE => self::INFO,
LogLevel::INFO => self::INFO,
LogLevel::DEBUG => self::INFO,
);
public function __construct(OutputInterface $output, array $verbosityLevelMap = array(), array $formatLevelMap = array())
{
$this->output = $output;
$this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap;
$this->formatLevelMap = $formatLevelMap + $this->formatLevelMap;
}
public function log($level, $message, array $context = array())
{
if (!isset($this->verbosityLevelMap[$level])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
}
if ($this->formatLevelMap[$level] === self::ERROR && $this->output instanceof ConsoleOutputInterface) {
$output = $this->output->getErrorOutput();
} else {
$output = $this->output;
}
if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) {
$output->writeln(sprintf('<%1$s>[%2$s] %3$s</%1$s>', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)));
}
}
private function interpolate($message, array $context)
{
$replace = array();
foreach ($context as $key => $val) {
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace[sprintf('{%s}', $key)] = $val;
}
}
return strtr($message, $replace);
}
}
<?php
namespace Symfony\Component\Console\Output;
class BufferedOutput extends Output
{
private $buffer = '';
public function fetch()
{
$content = $this->buffer;
$this->buffer = '';
return $content;
}
protected function doWrite($message, $newline)
{
$this->buffer .= $message;
if ($newline) {
$this->buffer .= "\n";
}
}
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
{
private $stderr;
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
{
parent::__construct($this->openOutputStream(), $verbosity, $decorated, $formatter);
$actualDecorated = $this->isDecorated();
$this->stderr = new StreamOutput($this->openErrorStream(), $verbosity, $decorated, $this->getFormatter());
if (null === $decorated) {
$this->setDecorated($actualDecorated && $this->stderr->isDecorated());
}
}
public function setDecorated($decorated)
{
parent::setDecorated($decorated);
$this->stderr->setDecorated($decorated);
}
public function setFormatter(OutputFormatterInterface $formatter)
{
parent::setFormatter($formatter);
$this->stderr->setFormatter($formatter);
}
public function setVerbosity($level)
{
parent::setVerbosity($level);
$this->stderr->setVerbosity($level);
}
public function getErrorOutput()
{
return $this->stderr;
}
public function setErrorOutput(OutputInterface $error)
{
$this->stderr = $error;
}
protected function hasStdoutSupport()
{
return false === $this->isRunningOS400();
}
protected function hasStderrSupport()
{
return false === $this->isRunningOS400();
}
private function isRunningOS400()
{
$checks = array(
function_exists('php_uname') ? php_uname('s') : '',
getenv('OSTYPE'),
PHP_OS,
);
return false !== stripos(implode(';', $checks), 'OS400');
}
private function openOutputStream()
{
if (!$this->hasStdoutSupport()) {
return fopen('php://output', 'w');
}
return @fopen('php://stdout', 'w') ?: fopen('php://output', 'w');
}
private function openErrorStream()
{
return fopen($this->hasStderrSupport() ? 'php://stderr' : 'php://output', 'w');
}
}
<?php
namespace Symfony\Component\Console\Output;
interface ConsoleOutputInterface extends OutputInterface
{
public function getErrorOutput();
public function setErrorOutput(OutputInterface $error);
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class NullOutput implements OutputInterface
{
public function setFormatter(OutputFormatterInterface $formatter)
{
}
public function getFormatter()
{
return new OutputFormatter();
}
public function setDecorated($decorated)
{
}
public function isDecorated()
{
return false;
}
public function setVerbosity($level)
{
}
public function getVerbosity()
{
return self::VERBOSITY_QUIET;
}
public function isQuiet()
{
return true;
}
public function isVerbose()
{
return false;
}
public function isVeryVerbose()
{
return false;
}
public function isDebug()
{
return false;
}
public function writeln($messages, $options = self::OUTPUT_NORMAL)
{
}
public function write($messages, $newline = false, $options = self::OUTPUT_NORMAL)
{
}
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Formatter\OutputFormatter;
abstract class Output implements OutputInterface
{
private $verbosity;
private $formatter;
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = false, OutputFormatterInterface $formatter = null)
{
$this->verbosity = null === $verbosity ? self::VERBOSITY_NORMAL : $verbosity;
$this->formatter = $formatter ?: new OutputFormatter();
$this->formatter->setDecorated($decorated);
}
public function setFormatter(OutputFormatterInterface $formatter)
{
$this->formatter = $formatter;
}
public function getFormatter()
{
return $this->formatter;
}
public function setDecorated($decorated)
{
$this->formatter->setDecorated($decorated);
}
public function isDecorated()
{
return $this->formatter->isDecorated();
}
public function setVerbosity($level)
{
$this->verbosity = (int) $level;
}
public function getVerbosity()
{
return $this->verbosity;
}
public function isQuiet()
{
return self::VERBOSITY_QUIET === $this->verbosity;
}
public function isVerbose()
{
return self::VERBOSITY_VERBOSE <= $this->verbosity;
}
public function isVeryVerbose()
{
return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity;
}
public function isDebug()
{
return self::VERBOSITY_DEBUG <= $this->verbosity;
}
public function writeln($messages, $options = self::OUTPUT_NORMAL)
{
$this->write($messages, true, $options);
}
public function write($messages, $newline = false, $options = self::OUTPUT_NORMAL)
{
$messages = (array) $messages;
$types = self::OUTPUT_NORMAL | self::OUTPUT_RAW | self::OUTPUT_PLAIN;
$type = $types & $options ?: self::OUTPUT_NORMAL;
$verbosities = self::VERBOSITY_QUIET | self::VERBOSITY_NORMAL | self::VERBOSITY_VERBOSE | self::VERBOSITY_VERY_VERBOSE | self::VERBOSITY_DEBUG;
$verbosity = $verbosities & $options ?: self::VERBOSITY_NORMAL;
if ($verbosity > $this->getVerbosity()) {
return;
}
foreach ($messages as $message) {
switch ($type) {
case OutputInterface::OUTPUT_NORMAL:
$message = $this->formatter->format($message);
break;
case OutputInterface::OUTPUT_RAW:
break;
case OutputInterface::OUTPUT_PLAIN:
$message = strip_tags($this->formatter->format($message));
break;
}
$this->doWrite($message, $newline);
}
}
abstract protected function doWrite($message, $newline);
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
interface OutputInterface
{
const VERBOSITY_QUIET = 16;
const VERBOSITY_NORMAL = 32;
const VERBOSITY_VERBOSE = 64;
const VERBOSITY_VERY_VERBOSE = 128;
const VERBOSITY_DEBUG = 256;
const OUTPUT_NORMAL = 1;
const OUTPUT_RAW = 2;
const OUTPUT_PLAIN = 4;
public function write($messages, $newline = false, $options = 0);
public function writeln($messages, $options = 0);
public function setVerbosity($level);
public function getVerbosity();
public function isQuiet();
public function isVerbose();
public function isVeryVerbose();
public function isDebug();
public function setDecorated($decorated);
public function isDecorated();
public function setFormatter(OutputFormatterInterface $formatter);
public function getFormatter();
}
<?php
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class StreamOutput extends Output
{
private $stream;
public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
{
if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) {
throw new InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');
}
$this->stream = $stream;
if (null === $decorated) {
$decorated = $this->hasColorSupport();
}
parent::__construct($verbosity, $decorated, $formatter);
}
public function getStream()
{
return $this->stream;
}
protected function doWrite($message, $newline)
{
if (false === @fwrite($this->stream, $message) || ($newline && (false === @fwrite($this->stream, PHP_EOL)))) {
throw new RuntimeException('Unable to write output.');
}
fflush($this->stream);
}
protected function hasColorSupport()
{
if (DIRECTORY_SEPARATOR === '\\') {
return
'10.0.10586' === PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
return function_exists('posix_isatty') && @posix_isatty($this->stream);
}
}
<?php
namespace Symfony\Component\Console\Question;
use Symfony\Component\Console\Exception\InvalidArgumentException;
class ChoiceQuestion extends Question
{
private $choices;
private $multiselect = false;
private $prompt = ' > ';
private $errorMessage = 'Value "%s" is invalid';
public function __construct($question, array $choices, $default = null)
{
parent::__construct($question, $default);
$this->choices = $choices;
$this->setValidator($this->getDefaultValidator());
$this->setAutocompleterValues($choices);
}
public function getChoices()
{
return $this->choices;
}
public function setMultiselect($multiselect)
{
$this->multiselect = $multiselect;
$this->setValidator($this->getDefaultValidator());
return $this;
}
public function isMultiselect()
{
return $this->multiselect;
}
public function getPrompt()
{
return $this->prompt;
}
public function setPrompt($prompt)
{
$this->prompt = $prompt;
return $this;
}
public function setErrorMessage($errorMessage)
{
$this->errorMessage = $errorMessage;
$this->setValidator($this->getDefaultValidator());
return $this;
}
private function getDefaultValidator()
{
$choices = $this->choices;
$errorMessage = $this->errorMessage;
$multiselect = $this->multiselect;
$isAssoc = $this->isAssoc($choices);
return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) {
$selectedChoices = str_replace(' ', '', $selected);
if ($multiselect) {
if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
throw new InvalidArgumentException(sprintf($errorMessage, $selected));
}
$selectedChoices = explode(',', $selectedChoices);
} else {
$selectedChoices = array($selected);
}
$multiselectChoices = array();
foreach ($selectedChoices as $value) {
$results = array();
foreach ($choices as $key => $choice) {
if ($choice === $value) {
$results[] = $key;
}
}
if (count($results) > 1) {
throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of %s.', implode(' or ', $results)));
}
$result = array_search($value, $choices);
if (!$isAssoc) {
if (false !== $result) {
$result = $choices[$result];
} elseif (isset($choices[$value])) {
$result = $choices[$value];
}
} elseif (false === $result && isset($choices[$value])) {
$result = $value;
}
if (false === $result) {
throw new InvalidArgumentException(sprintf($errorMessage, $value));
}
$multiselectChoices[] = (string) $result;
}
if ($multiselect) {
return $multiselectChoices;
}
return current($multiselectChoices);
};
}
}
<?php
namespace Symfony\Component\Console\Question;
class ConfirmationQuestion extends Question
{
private $trueAnswerRegex;
public function __construct($question, $default = true, $trueAnswerRegex = '/^y/i')
{
parent::__construct($question, (bool) $default);
$this->trueAnswerRegex = $trueAnswerRegex;
$this->setNormalizer($this->getDefaultNormalizer());
}
private function getDefaultNormalizer()
{
$default = $this->getDefault();
$regex = $this->trueAnswerRegex;
return function ($answer) use ($default, $regex) {
if (is_bool($answer)) {
return $answer;
}
$answerIsTrue = (bool) preg_match($regex, $answer);
if (false === $default) {
return $answer && $answerIsTrue;
}
return !$answer || $answerIsTrue;
};
}
}
<?php
namespace Symfony\Component\Console\Question;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;
class Question
{
private $question;
private $attempts;
private $hidden = false;
private $hiddenFallback = true;
private $autocompleterValues;
private $validator;
private $default;
private $normalizer;
public function __construct($question, $default = null)
{
$this->question = $question;
$this->default = $default;
}
public function getQuestion()
{
return $this->question;
}
public function getDefault()
{
return $this->default;
}
public function isHidden()
{
return $this->hidden;
}
public function setHidden($hidden)
{
if ($this->autocompleterValues) {
throw new LogicException('A hidden question cannot use the autocompleter.');
}
$this->hidden = (bool) $hidden;
return $this;
}
public function isHiddenFallback()
{
return $this->hiddenFallback;
}
public function setHiddenFallback($fallback)
{
$this->hiddenFallback = (bool) $fallback;
return $this;
}
public function getAutocompleterValues()
{
return $this->autocompleterValues;
}
public function setAutocompleterValues($values)
{
if (is_array($values)) {
$values = $this->isAssoc($values) ? array_merge(array_keys($values), array_values($values)) : array_values($values);
}
if (null !== $values && !is_array($values)) {
if (!$values instanceof \Traversable || !$values instanceof \Countable) {
throw new InvalidArgumentException('Autocompleter values can be either an array, `null` or an object implementing both `Countable` and `Traversable` interfaces.');
}
}
if ($this->hidden) {
throw new LogicException('A hidden question cannot use the autocompleter.');
}
$this->autocompleterValues = $values;
return $this;
}
public function setValidator(callable $validator = null)
{
$this->validator = $validator;
return $this;
}
public function getValidator()
{
return $this->validator;
}
public function setMaxAttempts($attempts)
{
if (null !== $attempts && $attempts < 1) {
throw new InvalidArgumentException('Maximum number of attempts must be a positive value.');
}
$this->attempts = $attempts;
return $this;
}
public function getMaxAttempts()
{
return $this->attempts;
}
public function setNormalizer(callable $normalizer)
{
$this->normalizer = $normalizer;
return $this;
}
public function getNormalizer()
{
return $this->normalizer;
}
protected function isAssoc($array)
{
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
}
<?php
namespace Symfony\Component\Console\Style;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
abstract class OutputStyle implements OutputInterface, StyleInterface
{
private $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
public function newLine($count = 1)
{
$this->output->write(str_repeat(PHP_EOL, $count));
}
public function createProgressBar($max = 0)
{
return new ProgressBar($this->output, $max);
}
public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
$this->output->write($messages, $newline, $type);
}
public function writeln($messages, $type = self::OUTPUT_NORMAL)
{
$this->output->writeln($messages, $type);
}
public function setVerbosity($level)
{
$this->output->setVerbosity($level);
}
public function getVerbosity()
{
return $this->output->getVerbosity();
}
public function setDecorated($decorated)
{
$this->output->setDecorated($decorated);
}
public function isDecorated()
{
return $this->output->isDecorated();
}
public function setFormatter(OutputFormatterInterface $formatter)
{
$this->output->setFormatter($formatter);
}
public function getFormatter()
{
return $this->output->getFormatter();
}
public function isQuiet()
{
return $this->output->isQuiet();
}
public function isVerbose()
{
return $this->output->isVerbose();
}
public function isVeryVerbose()
{
return $this->output->isVeryVerbose();
}
public function isDebug()
{
return $this->output->isDebug();
}
}
<?php
namespace Symfony\Component\Console\Style;
interface StyleInterface
{
public function title($message);
public function section($message);
public function listing(array $elements);
public function text($message);
public function success($message);
public function error($message);
public function warning($message);
public function note($message);
public function caution($message);
public function table(array $headers, array $rows);
public function ask($question, $default = null, $validator = null);
public function askHidden($question, $validator = null);
public function confirm($question, $default = true);
public function choice($question, array $choices, $default = null);
public function newLine($count = 1);
public function progressStart($max = 0);
public function progressAdvance($step = 1);
public function progressFinish();
}
<?php
namespace Symfony\Component\Console\Style;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
class SymfonyStyle extends OutputStyle
{
const MAX_LINE_LENGTH = 120;
private $input;
private $questionHelper;
private $progressBar;
private $lineLength;
private $bufferedOutput;
public function __construct(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->bufferedOutput = new BufferedOutput($output->getVerbosity(), false, clone $output->getFormatter());
$this->lineLength = min($this->getTerminalWidth() - (int) (DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
parent::__construct($output);
}
public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false)
{
$messages = is_array($messages) ? array_values($messages) : array($messages);
$this->autoPrependBlock();
$this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, true));
$this->newLine();
}
public function title($message)
{
$this->autoPrependBlock();
$this->writeln(array(
sprintf('<comment>%s</>', $message),
sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
));
$this->newLine();
}
public function section($message)
{
$this->autoPrependBlock();
$this->writeln(array(
sprintf('<comment>%s</>', $message),
sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
));
$this->newLine();
}
public function listing(array $elements)
{
$this->autoPrependText();
$elements = array_map(function ($element) {
return sprintf(' * %s', $element);
}, $elements);
$this->writeln($elements);
$this->newLine();
}
public function text($message)
{
$this->autoPrependText();
$messages = is_array($message) ? array_values($message) : array($message);
foreach ($messages as $message) {
$this->writeln(sprintf(' %s', $message));
}
}
public function comment($message)
{
$messages = is_array($message) ? array_values($message) : array($message);
$this->autoPrependBlock();
$this->writeln($this->createBlock($messages, null, null, '<fg=default;bg=default> // </>'));
$this->newLine();
}
public function success($message)
{
$this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
}
public function error($message)
{
$this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
}
public function warning($message)
{
$this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
}
public function note($message)
{
$this->block($message, 'NOTE', 'fg=yellow', ' ! ');
}
public function caution($message)
{
$this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
}
public function table(array $headers, array $rows)
{
$style = clone Table::getStyleDefinition('symfony-style-guide');
$style->setCellHeaderFormat('<info>%s</info>');
$table = new Table($this);
$table->setHeaders($headers);
$table->setRows($rows);
$table->setStyle($style);
$table->render();
$this->newLine();
}
public function ask($question, $default = null, $validator = null)
{
$question = new Question($question, $default);
$question->setValidator($validator);
return $this->askQuestion($question);
}
public function askHidden($question, $validator = null)
{
$question = new Question($question);
$question->setHidden(true);
$question->setValidator($validator);
return $this->askQuestion($question);
}
public function confirm($question, $default = true)
{
return $this->askQuestion(new ConfirmationQuestion($question, $default));
}
public function choice($question, array $choices, $default = null)
{
if (null !== $default) {
$values = array_flip($choices);
$default = $values[$default];
}
return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
}
public function progressStart($max = 0)
{
$this->progressBar = $this->createProgressBar($max);
$this->progressBar->start();
}
public function progressAdvance($step = 1)
{
$this->getProgressBar()->advance($step);
}
public function progressFinish()
{
$this->getProgressBar()->finish();
$this->newLine(2);
$this->progressBar = null;
}
public function createProgressBar($max = 0)
{
$progressBar = parent::createProgressBar($max);
if ('\\' !== DIRECTORY_SEPARATOR) {
$progressBar->setEmptyBarCharacter('â–‘');
$progressBar->setProgressCharacter('');
$progressBar->setBarCharacter('â–“');
}
return $progressBar;
}
public function askQuestion(Question $question)
{
if ($this->input->isInteractive()) {
$this->autoPrependBlock();
}
if (!$this->questionHelper) {
$this->questionHelper = new SymfonyQuestionHelper();
}
$answer = $this->questionHelper->ask($this->input, $this, $question);
if ($this->input->isInteractive()) {
$this->newLine();
$this->bufferedOutput->write("\n");
}
return $answer;
}
public function writeln($messages, $type = self::OUTPUT_NORMAL)
{
parent::writeln($messages, $type);
$this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
}
public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
parent::write($messages, $newline, $type);
$this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
}
public function newLine($count = 1)
{
parent::newLine($count);
$this->bufferedOutput->write(str_repeat("\n", $count));
}
private function getProgressBar()
{
if (!$this->progressBar) {
throw new RuntimeException('The ProgressBar is not started.');
}
return $this->progressBar;
}
private function getTerminalWidth()
{
$application = new Application();
$dimensions = $application->getTerminalDimensions();
return $dimensions[0] ?: self::MAX_LINE_LENGTH;
}
private function autoPrependBlock()
{
$chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
if (!isset($chars[0])) {
return $this->newLine();
}
$this->newLine(2 - substr_count($chars, "\n"));
}
private function autoPrependText()
{
$fetched = $this->bufferedOutput->fetch();
if ("\n" !== substr($fetched, -1)) {
$this->newLine();
}
}
private function reduceBuffer($messages)
{
return array_map(function ($value) {
return substr($value, -4);
}, array_merge(array($this->bufferedOutput->fetch()), (array) $messages));
}
private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
{
$indentLength = 0;
$prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
$lines = array();
if (null !== $type) {
$type = sprintf('[%s] ', $type);
$indentLength = strlen($type);
$lineIndentation = str_repeat(' ', $indentLength);
}
foreach ($messages as $key => $message) {
if ($escape) {
$message = OutputFormatter::escape($message);
}
$lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true)));
if (count($messages) > 1 && $key < count($messages) - 1) {
$lines[] = '';
}
}
$firstLineIndex = 0;
if ($padding && $this->isDecorated()) {
$firstLineIndex = 1;
array_unshift($lines, '');
$lines[] = '';
}
foreach ($lines as $i => &$line) {
if (null !== $type) {
$line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
}
$line = $prefix.$line;
$line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
if ($style) {
$line = sprintf('<%s>%s</>', $style, $line);
}
}
return $lines;
}
}
<?php
namespace Symfony\Component\Console\Tester;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
class ApplicationTester
{
private $application;
private $input;
private $statusCode;
private $output;
private $captureStreamsIndependently = false;
public function __construct(Application $application)
{
$this->application = $application;
}
public function run(array $input, $options = array())
{
$this->input = new ArrayInput($input);
if (isset($options['interactive'])) {
$this->input->setInteractive($options['interactive']);
}
$this->captureStreamsIndependently = array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately'];
if (!$this->captureStreamsIndependently) {
$this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) {
$this->output->setDecorated($options['decorated']);
}
if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
} else {
$this->output = new ConsoleOutput(
isset($options['verbosity']) ? $options['verbosity'] : ConsoleOutput::VERBOSITY_NORMAL,
isset($options['decorated']) ? $options['decorated'] : null
);
$errorOutput = new StreamOutput(fopen('php://memory', 'w', false));
$errorOutput->setFormatter($this->output->getFormatter());
$errorOutput->setVerbosity($this->output->getVerbosity());
$errorOutput->setDecorated($this->output->isDecorated());
$reflectedOutput = new \ReflectionObject($this->output);
$strErrProperty = $reflectedOutput->getProperty('stderr');
$strErrProperty->setAccessible(true);
$strErrProperty->setValue($this->output, $errorOutput);
$reflectedParent = $reflectedOutput->getParentClass();
$streamProperty = $reflectedParent->getProperty('stream');
$streamProperty->setAccessible(true);
$streamProperty->setValue($this->output, fopen('php://memory', 'w', false));
}
return $this->statusCode = $this->application->run($this->input, $this->output);
}
public function getDisplay($normalize = false)
{
rewind($this->output->getStream());
$display = stream_get_contents($this->output->getStream());
if ($normalize) {
$display = str_replace(PHP_EOL, "\n", $display);
}
return $display;
}
public function getErrorOutput($normalize = false)
{
if (!$this->captureStreamsIndependently) {
throw new \LogicException('The error output is not available when the tester is run without "capture_stderr_separately" option set.');
}
rewind($this->output->getErrorOutput()->getStream());
$display = stream_get_contents($this->output->getErrorOutput()->getStream());
if ($normalize) {
$display = str_replace(PHP_EOL, "\n", $display);
}
return $display;
}
public function getInput()
{
return $this->input;
}
public function getOutput()
{
return $this->output;
}
public function getStatusCode()
{
return $this->statusCode;
}
}
<?php
namespace Symfony\Component\Console\Tester;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CommandTester
{
private $command;
private $input;
private $output;
private $statusCode;
public function __construct(Command $command)
{
$this->command = $command;
}
public function execute(array $input, array $options = array())
{
if (!isset($input['command'])
&& (null !== $application = $this->command->getApplication())
&& $application->getDefinition()->hasArgument('command')
) {
$input = array_merge(array('command' => $this->command->getName()), $input);
}
$this->input = new ArrayInput($input);
if (isset($options['interactive'])) {
$this->input->setInteractive($options['interactive']);
}
$this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) {
$this->output->setDecorated($options['decorated']);
}
if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
return $this->statusCode = $this->command->run($this->input, $this->output);
}
public function getDisplay($normalize = false)
{
rewind($this->output->getStream());
$display = stream_get_contents($this->output->getStream());
if ($normalize) {
$display = str_replace(PHP_EOL, "\n", $display);
}
return $display;
}
public function getInput()
{
return $this->input;
}
public function getOutput()
{
return $this->output;
}
public function getStatusCode()
{
return $this->statusCode;
}
}
<?php
namespace Symfony\Component\Filesystem\Exception;
interface ExceptionInterface
{
}
<?php
namespace Symfony\Component\Filesystem\Exception;
class FileNotFoundException extends IOException
{
public function __construct($message = null, $code = 0, \Exception $previous = null, $path = null)
{
if (null === $message) {
if (null === $path) {
$message = 'File could not be found.';
} else {
$message = sprintf('File "%s" could not be found.', $path);
}
}
parent::__construct($message, $code, $previous, $path);
}
}
<?php
namespace Symfony\Component\Filesystem\Exception;
class IOException extends \RuntimeException implements IOExceptionInterface
{
private $path;
public function __construct($message, $code = 0, \Exception $previous = null, $path = null)
{
$this->path = $path;
parent::__construct($message, $code, $previous);
}
public function getPath()
{
return $this->path;
}
}
<?php
namespace Symfony\Component\Filesystem\Exception;
interface IOExceptionInterface extends ExceptionInterface
{
public function getPath();
}
<?php
namespace Symfony\Component\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
class Filesystem
{
public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
{
if (stream_is_local($originFile) && !is_file($originFile)) {
throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
}
$this->mkdir(dirname($targetFile));
$doCopy = true;
if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
$doCopy = filemtime($originFile) > filemtime($targetFile);
}
if ($doCopy) {
if (false === $source = @fopen($originFile, 'r')) {
throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
}
if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
}
$bytesCopied = stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
unset($source, $target);
if (!is_file($targetFile)) {
throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
}
@chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
if (stream_is_local($originFile) && $bytesCopied !== ($bytesOrigin = filesize($originFile))) {
throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile);
}
}
}
public function mkdir($dirs, $mode = 0777)
{
foreach ($this->toIterator($dirs) as $dir) {
if (is_dir($dir)) {
continue;
}
if (true !== @mkdir($dir, $mode, true)) {
$error = error_get_last();
if (!is_dir($dir)) {
if ($error) {
throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
}
throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
}
}
}
}
public function exists($files)
{
foreach ($this->toIterator($files) as $file) {
if ('\\' === DIRECTORY_SEPARATOR && strlen($file) > 258) {
throw new IOException('Could not check if file exist because path length exceeds 258 characters.', 0, null, $file);
}
if (!file_exists($file)) {
return false;
}
}
return true;
}
public function touch($files, $time = null, $atime = null)
{
foreach ($this->toIterator($files) as $file) {
$touch = $time ? @touch($file, $time, $atime) : @touch($file);
if (true !== $touch) {
throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
}
}
}
public function remove($files)
{
if ($files instanceof \Traversable) {
$files = iterator_to_array($files, false);
} elseif (!is_array($files)) {
$files = array($files);
}
$files = array_reverse($files);
foreach ($files as $file) {
if (is_link($file)) {
if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {
$error = error_get_last();
throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
}
} elseif (is_dir($file)) {
$this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
if (!@rmdir($file) && file_exists($file)) {
$error = error_get_last();
throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message']));
}
} elseif (!@unlink($file) && file_exists($file)) {
$error = error_get_last();
throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, $error['message']));
}
}
}
public function chmod($files, $mode, $umask = 0000, $recursive = false)
{
foreach ($this->toIterator($files) as $file) {
if (true !== @chmod($file, $mode & ~$umask)) {
throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
}
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
}
}
}
public function chown($files, $user, $recursive = false)
{
foreach ($this->toIterator($files) as $file) {
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chown(new \FilesystemIterator($file), $user, true);
}
if (is_link($file) && function_exists('lchown')) {
if (true !== @lchown($file, $user)) {
throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
}
} else {
if (true !== @chown($file, $user)) {
throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
}
}
}
}
public function chgrp($files, $group, $recursive = false)
{
foreach ($this->toIterator($files) as $file) {
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chgrp(new \FilesystemIterator($file), $group, true);
}
if (is_link($file) && function_exists('lchgrp')) {
if (true !== @lchgrp($file, $group) || (defined('HHVM_VERSION') && !posix_getgrnam($group))) {
throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
}
} else {
if (true !== @chgrp($file, $group)) {
throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
}
}
}
}
public function rename($origin, $target, $overwrite = false)
{
if (!$overwrite && $this->isReadable($target)) {
throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
}
if (true !== @rename($origin, $target)) {
throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
}
}
private function isReadable($filename)
{
if ('\\' === DIRECTORY_SEPARATOR && strlen($filename) > 258) {
throw new IOException('Could not check if file is readable because path length exceeds 258 characters.', 0, null, $filename);
}
return is_readable($filename);
}
public function symlink($originDir, $targetDir, $copyOnWindows = false)
{
if ('\\' === DIRECTORY_SEPARATOR) {
$originDir = strtr($originDir, '/', '\\');
$targetDir = strtr($targetDir, '/', '\\');
if ($copyOnWindows) {
$this->mirror($originDir, $targetDir);
return;
}
}
$this->mkdir(dirname($targetDir));
$ok = false;
if (is_link($targetDir)) {
if (readlink($targetDir) != $originDir) {
$this->remove($targetDir);
} else {
$ok = true;
}
}
if (!$ok && true !== @symlink($originDir, $targetDir)) {
$report = error_get_last();
if (is_array($report)) {
if ('\\' === DIRECTORY_SEPARATOR && false !== strpos($report['message'], 'error code(1314)')) {
throw new IOException('Unable to create symlink due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', 0, null, $targetDir);
}
}
throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
}
}
public function makePathRelative($endPath, $startPath)
{
if ('\\' === DIRECTORY_SEPARATOR) {
$endPath = str_replace('\\', '/', $endPath);
$startPath = str_replace('\\', '/', $startPath);
}
$startPathArr = explode('/', trim($startPath, '/'));
$endPathArr = explode('/', trim($endPath, '/'));
$index = 0;
while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
++$index;
}
$depth = count($startPathArr) - $index;
if ('/' === $startPath[0] && 0 === $index && 1 === $depth) {
$traverser = '';
} else {
$traverser = str_repeat('../', $depth);
}
$endPathRemainder = implode('/', array_slice($endPathArr, $index));
$relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
return '' === $relativePath ? './' : $relativePath;
}
public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
{
$targetDir = rtrim($targetDir, '/\\');
$originDir = rtrim($originDir, '/\\');
if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
$deleteIterator = $iterator;
if (null === $deleteIterator) {
$flags = \FilesystemIterator::SKIP_DOTS;
$deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
}
foreach ($deleteIterator as $file) {
$origin = str_replace($targetDir, $originDir, $file->getPathname());
if (!$this->exists($origin)) {
$this->remove($file);
}
}
}
$copyOnWindows = false;
if (isset($options['copy_on_windows'])) {
$copyOnWindows = $options['copy_on_windows'];
}
if (null === $iterator) {
$flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
}
if ($this->exists($originDir)) {
$this->mkdir($targetDir);
}
foreach ($iterator as $file) {
$target = str_replace($originDir, $targetDir, $file->getPathname());
if ($copyOnWindows) {
if (is_file($file)) {
$this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
} elseif (is_dir($file)) {
$this->mkdir($target);
} else {
throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
}
} else {
if (is_link($file)) {
$this->symlink($file->getLinkTarget(), $target);
} elseif (is_dir($file)) {
$this->mkdir($target);
} elseif (is_file($file)) {
$this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
} else {
throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
}
}
}
}
public function isAbsolutePath($file)
{
return strspn($file, '/\\', 0, 1)
|| (strlen($file) > 3 && ctype_alpha($file[0])
&& substr($file, 1, 1) === ':'
&& strspn($file, '/\\', 2, 1)
)
|| null !== parse_url($file, PHP_URL_SCHEME)
;
}
public function tempnam($dir, $prefix)
{
list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
$tmpFile = @tempnam($hierarchy, $prefix);
if (false !== $tmpFile) {
if (null !== $scheme && 'gs' !== $scheme) {
return $scheme.'://'.$tmpFile;
}
return $tmpFile;
}
throw new IOException('A temporary file could not be created.');
}
for ($i = 0; $i < 10; ++$i) {
$tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
$handle = @fopen($tmpFile, 'x+');
if (false === $handle) {
continue;
}
@fclose($handle);
return $tmpFile;
}
throw new IOException('A temporary file could not be created.');
}
public function dumpFile($filename, $content)
{
$dir = dirname($filename);
if (!is_dir($dir)) {
$this->mkdir($dir);
} elseif (!is_writable($dir)) {
throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
}
$tmpFile = $this->tempnam($dir, basename($filename));
if (false === @file_put_contents($tmpFile, $content)) {
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
}
@chmod($tmpFile, 0666);
$this->rename($tmpFile, $filename, true);
}
private function toIterator($files)
{
if (!$files instanceof \Traversable) {
$files = new \ArrayObject(is_array($files) ? $files : array($files));
}
return $files;
}
private function getSchemeAndHierarchy($filename)
{
$components = explode('://', $filename, 2);
return 2 === count($components) ? array($components[0], $components[1]) : array(null, $components[0]);
}
}
<?php
namespace Symfony\Component\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
class LockHandler
{
private $file;
private $handle;
public function __construct($name, $lockPath = null)
{
$lockPath = $lockPath ?: sys_get_temp_dir();
if (!is_dir($lockPath)) {
$fs = new Filesystem();
$fs->mkdir($lockPath);
}
if (!is_writable($lockPath)) {
throw new IOException(sprintf('The directory "%s" is not writable.', $lockPath), 0, null, $lockPath);
}
$this->file = sprintf('%s/sf.%s.%s.lock', $lockPath, preg_replace('/[^a-z0-9\._-]+/i', '-', $name), hash('sha256', $name));
}
public function lock($blocking = false)
{
if ($this->handle) {
return true;
}
set_error_handler(function () {});
if (!$this->handle = fopen($this->file, 'r')) {
if ($this->handle = fopen($this->file, 'x')) {
chmod($this->file, 0444);
} elseif (!$this->handle = fopen($this->file, 'r')) {
usleep(100);
$this->handle = fopen($this->file, 'r');
}
}
restore_error_handler();
if (!$this->handle) {
$error = error_get_last();
throw new IOException($error['message'], 0, null, $this->file);
}
if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) {
fclose($this->handle);
$this->handle = null;
return false;
}
return true;
}
public function release()
{
if ($this->handle) {
flock($this->handle, LOCK_UN | LOCK_NB);
fclose($this->handle);
$this->handle = null;
}
}
}
<?php
namespace Symfony\Component\Config;
use Symfony\Component\Config\Resource\SelfCheckingResourceChecker;
class ConfigCache extends ResourceCheckerConfigCache
{
private $debug;
public function __construct($file, $debug)
{
parent::__construct($file, array(
new SelfCheckingResourceChecker(),
));
$this->debug = (bool) $debug;
}
public function isFresh()
{
if (!$this->debug && is_file($this->getPath())) {
return true;
}
return parent::isFresh();
}
}
<?php
namespace Symfony\Component\Config;
class ConfigCacheFactory implements ConfigCacheFactoryInterface
{
private $debug;
public function __construct($debug)
{
$this->debug = $debug;
}
public function cache($file, $callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException(sprintf('Invalid type for callback argument. Expected callable, but got "%s".', gettype($callback)));
}
$cache = new ConfigCache($file, $this->debug);
if (!$cache->isFresh()) {
call_user_func($callback, $cache);
}
return $cache;
}
}
<?php
namespace Symfony\Component\Config;
interface ConfigCacheFactoryInterface
{
public function cache($file, $callable);
}
<?php
namespace Symfony\Component\Config;
use Symfony\Component\Config\Resource\ResourceInterface;
interface ConfigCacheInterface
{
public function getPath();
public function isFresh();
public function write($content, array $metadata = null);
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
use Symfony\Component\Config\Definition\Exception\UnsetKeyException;
class ArrayNode extends BaseNode implements PrototypeNodeInterface
{
protected $xmlRemappings = array();
protected $children = array();
protected $allowFalse = false;
protected $allowNewKeys = true;
protected $addIfNotSet = false;
protected $performDeepMerging = true;
protected $ignoreExtraKeys = false;
protected $removeExtraKeys = true;
protected $normalizeKeys = true;
public function setNormalizeKeys($normalizeKeys)
{
$this->normalizeKeys = (bool) $normalizeKeys;
}
protected function preNormalize($value)
{
if (!$this->normalizeKeys || !is_array($value)) {
return $value;
}
$normalized = array();
foreach ($value as $k => $v) {
if (false !== strpos($k, '-') && false === strpos($k, '_') && !array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) {
$normalized[$normalizedKey] = $v;
} else {
$normalized[$k] = $v;
}
}
return $normalized;
}
public function getChildren()
{
return $this->children;
}
public function setXmlRemappings(array $remappings)
{
$this->xmlRemappings = $remappings;
}
public function getXmlRemappings()
{
return $this->xmlRemappings;
}
public function setAddIfNotSet($boolean)
{
$this->addIfNotSet = (bool) $boolean;
}
public function setAllowFalse($allow)
{
$this->allowFalse = (bool) $allow;
}
public function setAllowNewKeys($allow)
{
$this->allowNewKeys = (bool) $allow;
}
public function setPerformDeepMerging($boolean)
{
$this->performDeepMerging = (bool) $boolean;
}
public function setIgnoreExtraKeys($boolean, $remove = true)
{
$this->ignoreExtraKeys = (bool) $boolean;
$this->removeExtraKeys = $this->ignoreExtraKeys && $remove;
}
public function setName($name)
{
$this->name = $name;
}
public function hasDefaultValue()
{
return $this->addIfNotSet;
}
public function getDefaultValue()
{
if (!$this->hasDefaultValue()) {
throw new \RuntimeException(sprintf('The node at path "%s" has no default value.', $this->getPath()));
}
$defaults = array();
foreach ($this->children as $name => $child) {
if ($child->hasDefaultValue()) {
$defaults[$name] = $child->getDefaultValue();
}
}
return $defaults;
}
public function addChild(NodeInterface $node)
{
$name = $node->getName();
if (!strlen($name)) {
throw new \InvalidArgumentException('Child nodes must be named.');
}
if (isset($this->children[$name])) {
throw new \InvalidArgumentException(sprintf('A child node named "%s" already exists.', $name));
}
$this->children[$name] = $node;
}
protected function finalizeValue($value)
{
if (false === $value) {
$msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value));
throw new UnsetKeyException($msg);
}
foreach ($this->children as $name => $child) {
if (!array_key_exists($name, $value)) {
if ($child->isRequired()) {
$msg = sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath());
$ex = new InvalidConfigurationException($msg);
$ex->setPath($this->getPath());
throw $ex;
}
if ($child->hasDefaultValue()) {
$value[$name] = $child->getDefaultValue();
}
continue;
}
try {
$value[$name] = $child->finalize($value[$name]);
} catch (UnsetKeyException $e) {
unset($value[$name]);
}
}
return $value;
}
protected function validateType($value)
{
if (!is_array($value) && (!$this->allowFalse || false !== $value)) {
$ex = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected array, but got %s',
$this->getPath(),
gettype($value)
));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
$ex->setPath($this->getPath());
throw $ex;
}
}
protected function normalizeValue($value)
{
if (false === $value) {
return $value;
}
$value = $this->remapXml($value);
$normalized = array();
foreach ($value as $name => $val) {
if (isset($this->children[$name])) {
$normalized[$name] = $this->children[$name]->normalize($val);
unset($value[$name]);
} elseif (!$this->removeExtraKeys) {
$normalized[$name] = $val;
}
}
if (count($value) && !$this->ignoreExtraKeys) {
$msg = sprintf('Unrecognized option%s "%s" under "%s"', 1 === count($value) ? '' : 's', implode(', ', array_keys($value)), $this->getPath());
$ex = new InvalidConfigurationException($msg);
$ex->setPath($this->getPath());
throw $ex;
}
return $normalized;
}
protected function remapXml($value)
{
foreach ($this->xmlRemappings as list($singular, $plural)) {
if (!isset($value[$singular])) {
continue;
}
$value[$plural] = Processor::normalizeConfig($value, $singular, $plural);
unset($value[$singular]);
}
return $value;
}
protected function mergeValues($leftSide, $rightSide)
{
if (false === $rightSide) {
return false;
}
if (false === $leftSide || !$this->performDeepMerging) {
return $rightSide;
}
foreach ($rightSide as $k => $v) {
if (!array_key_exists($k, $leftSide)) {
if (!$this->allowNewKeys) {
$ex = new InvalidConfigurationException(sprintf(
'You are not allowed to define new elements for path "%s". '
.'Please define all elements for this path in one config file. '
.'If you are trying to overwrite an element, make sure you redefine it '
.'with the same name.',
$this->getPath()
));
$ex->setPath($this->getPath());
throw $ex;
}
$leftSide[$k] = $v;
continue;
}
if (!isset($this->children[$k])) {
throw new \RuntimeException('merge() expects a normalized config array.');
}
$leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v);
}
return $leftSide;
}
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
abstract class BaseNode implements NodeInterface
{
protected $name;
protected $parent;
protected $normalizationClosures = array();
protected $finalValidationClosures = array();
protected $allowOverwrite = true;
protected $required = false;
protected $equivalentValues = array();
protected $attributes = array();
public function __construct($name, NodeInterface $parent = null)
{
if (false !== strpos($name, '.')) {
throw new \InvalidArgumentException('The name must not contain ".".');
}
$this->name = $name;
$this->parent = $parent;
}
public function setAttribute($key, $value)
{
$this->attributes[$key] = $value;
}
public function getAttribute($key, $default = null)
{
return isset($this->attributes[$key]) ? $this->attributes[$key] : $default;
}
public function hasAttribute($key)
{
return isset($this->attributes[$key]);
}
public function getAttributes()
{
return $this->attributes;
}
public function setAttributes(array $attributes)
{
$this->attributes = $attributes;
}
public function removeAttribute($key)
{
unset($this->attributes[$key]);
}
public function setInfo($info)
{
$this->setAttribute('info', $info);
}
public function getInfo()
{
return $this->getAttribute('info');
}
public function setExample($example)
{
$this->setAttribute('example', $example);
}
public function getExample()
{
return $this->getAttribute('example');
}
public function addEquivalentValue($originalValue, $equivalentValue)
{
$this->equivalentValues[] = array($originalValue, $equivalentValue);
}
public function setRequired($boolean)
{
$this->required = (bool) $boolean;
}
public function setAllowOverwrite($allow)
{
$this->allowOverwrite = (bool) $allow;
}
public function setNormalizationClosures(array $closures)
{
$this->normalizationClosures = $closures;
}
public function setFinalValidationClosures(array $closures)
{
$this->finalValidationClosures = $closures;
}
public function isRequired()
{
return $this->required;
}
public function getName()
{
return $this->name;
}
public function getPath()
{
$path = $this->name;
if (null !== $this->parent) {
$path = $this->parent->getPath().'.'.$path;
}
return $path;
}
final public function merge($leftSide, $rightSide)
{
if (!$this->allowOverwrite) {
throw new ForbiddenOverwriteException(sprintf(
'Configuration path "%s" cannot be overwritten. You have to '
.'define all options for this path, and any of its sub-paths in '
.'one configuration section.',
$this->getPath()
));
}
$this->validateType($leftSide);
$this->validateType($rightSide);
return $this->mergeValues($leftSide, $rightSide);
}
final public function normalize($value)
{
$value = $this->preNormalize($value);
foreach ($this->normalizationClosures as $closure) {
$value = $closure($value);
}
foreach ($this->equivalentValues as $data) {
if ($data[0] === $value) {
$value = $data[1];
}
}
$this->validateType($value);
return $this->normalizeValue($value);
}
protected function preNormalize($value)
{
return $value;
}
public function getParent()
{
return $this->parent;
}
final public function finalize($value)
{
$this->validateType($value);
$value = $this->finalizeValue($value);
foreach ($this->finalValidationClosures as $closure) {
try {
$value = $closure($value);
} catch (Exception $e) {
throw $e;
} catch (\Exception $e) {
throw new InvalidConfigurationException(sprintf('Invalid configuration for path "%s": %s', $this->getPath(), $e->getMessage()), $e->getCode(), $e);
}
}
return $value;
}
abstract protected function validateType($value);
abstract protected function normalizeValue($value);
abstract protected function mergeValues($leftSide, $rightSide);
abstract protected function finalizeValue($value);
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
class BooleanNode extends ScalarNode
{
protected function validateType($value)
{
if (!is_bool($value)) {
$ex = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected boolean, but got %s.',
$this->getPath(),
gettype($value)
));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
$ex->setPath($this->getPath());
throw $ex;
}
}
protected function isValueEmpty($value)
{
return false;
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\PrototypedArrayNode;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinitionInterface
{
protected $performDeepMerging = true;
protected $ignoreExtraKeys = false;
protected $removeExtraKeys = true;
protected $children = array();
protected $prototype;
protected $atLeastOne = false;
protected $allowNewKeys = true;
protected $key;
protected $removeKeyItem;
protected $addDefaults = false;
protected $addDefaultChildren = false;
protected $nodeBuilder;
protected $normalizeKeys = true;
public function __construct($name, NodeParentInterface $parent = null)
{
parent::__construct($name, $parent);
$this->nullEquivalent = array();
$this->trueEquivalent = array();
}
public function setBuilder(NodeBuilder $builder)
{
$this->nodeBuilder = $builder;
}
public function children()
{
return $this->getNodeBuilder();
}
public function prototype($type)
{
return $this->prototype = $this->getNodeBuilder()->node(null, $type)->setParent($this);
}
public function addDefaultsIfNotSet()
{
$this->addDefaults = true;
return $this;
}
public function addDefaultChildrenIfNoneSet($children = null)
{
$this->addDefaultChildren = $children;
return $this;
}
public function requiresAtLeastOneElement()
{
$this->atLeastOne = true;
return $this;
}
public function disallowNewKeysInSubsequentConfigs()
{
$this->allowNewKeys = false;
return $this;
}
public function fixXmlConfig($singular, $plural = null)
{
$this->normalization()->remap($singular, $plural);
return $this;
}
public function useAttributeAsKey($name, $removeKeyItem = true)
{
$this->key = $name;
$this->removeKeyItem = $removeKeyItem;
return $this;
}
public function canBeUnset($allow = true)
{
$this->merge()->allowUnset($allow);
return $this;
}
public function canBeEnabled()
{
$this
->addDefaultsIfNotSet()
->treatFalseLike(array('enabled' => false))
->treatTrueLike(array('enabled' => true))
->treatNullLike(array('enabled' => true))
->beforeNormalization()
->ifArray()
->then(function ($v) {
$v['enabled'] = isset($v['enabled']) ? $v['enabled'] : true;
return $v;
})
->end()
->children()
->booleanNode('enabled')
->defaultFalse()
;
return $this;
}
public function canBeDisabled()
{
$this
->addDefaultsIfNotSet()
->treatFalseLike(array('enabled' => false))
->treatTrueLike(array('enabled' => true))
->treatNullLike(array('enabled' => true))
->children()
->booleanNode('enabled')
->defaultTrue()
;
return $this;
}
public function performNoDeepMerging()
{
$this->performDeepMerging = false;
return $this;
}
public function ignoreExtraKeys($remove = true)
{
$this->ignoreExtraKeys = true;
$this->removeExtraKeys = $remove;
return $this;
}
public function normalizeKeys($bool)
{
$this->normalizeKeys = (bool) $bool;
return $this;
}
public function append(NodeDefinition $node)
{
$this->children[$node->name] = $node->setParent($this);
return $this;
}
protected function getNodeBuilder()
{
if (null === $this->nodeBuilder) {
$this->nodeBuilder = new NodeBuilder();
}
return $this->nodeBuilder->setParent($this);
}
protected function createNode()
{
if (null === $this->prototype) {
$node = new ArrayNode($this->name, $this->parent);
$this->validateConcreteNode($node);
$node->setAddIfNotSet($this->addDefaults);
foreach ($this->children as $child) {
$child->parent = $node;
$node->addChild($child->getNode());
}
} else {
$node = new PrototypedArrayNode($this->name, $this->parent);
$this->validatePrototypeNode($node);
if (null !== $this->key) {
$node->setKeyAttribute($this->key, $this->removeKeyItem);
}
if (true === $this->atLeastOne) {
$node->setMinNumberOfElements(1);
}
if ($this->default) {
$node->setDefaultValue($this->defaultValue);
}
if (false !== $this->addDefaultChildren) {
$node->setAddChildrenIfNoneSet($this->addDefaultChildren);
if ($this->prototype instanceof static && null === $this->prototype->prototype) {
$this->prototype->addDefaultsIfNotSet();
}
}
$this->prototype->parent = $node;
$node->setPrototype($this->prototype->getNode());
}
$node->setAllowNewKeys($this->allowNewKeys);
$node->addEquivalentValue(null, $this->nullEquivalent);
$node->addEquivalentValue(true, $this->trueEquivalent);
$node->addEquivalentValue(false, $this->falseEquivalent);
$node->setPerformDeepMerging($this->performDeepMerging);
$node->setRequired($this->required);
$node->setIgnoreExtraKeys($this->ignoreExtraKeys, $this->removeExtraKeys);
$node->setNormalizeKeys($this->normalizeKeys);
if (null !== $this->normalization) {
$node->setNormalizationClosures($this->normalization->before);
$node->setXmlRemappings($this->normalization->remappings);
}
if (null !== $this->merge) {
$node->setAllowOverwrite($this->merge->allowOverwrite);
$node->setAllowFalse($this->merge->allowFalse);
}
if (null !== $this->validation) {
$node->setFinalValidationClosures($this->validation->rules);
}
return $node;
}
protected function validateConcreteNode(ArrayNode $node)
{
$path = $node->getPath();
if (null !== $this->key) {
throw new InvalidDefinitionException(
sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path)
);
}
if (true === $this->atLeastOne) {
throw new InvalidDefinitionException(
sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path)
);
}
if ($this->default) {
throw new InvalidDefinitionException(
sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path)
);
}
if (false !== $this->addDefaultChildren) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path)
);
}
}
protected function validatePrototypeNode(PrototypedArrayNode $node)
{
$path = $node->getPath();
if ($this->addDefaults) {
throw new InvalidDefinitionException(
sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path)
);
}
if (false !== $this->addDefaultChildren) {
if ($this->default) {
throw new InvalidDefinitionException(
sprintf('A default value and default children might not be used together at path "%s"', $path)
);
}
if (null !== $this->key && (null === $this->addDefaultChildren || is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path)
);
}
if (null === $this->key && (is_string($this->addDefaultChildren) || is_array($this->addDefaultChildren))) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path)
);
}
}
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\BooleanNode;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
class BooleanNodeDefinition extends ScalarNodeDefinition
{
public function __construct($name, NodeParentInterface $parent = null)
{
parent::__construct($name, $parent);
$this->nullEquivalent = true;
}
protected function instantiateNode()
{
return new BooleanNode($this->name, $this->parent);
}
public function cannotBeEmpty()
{
throw new InvalidDefinitionException('->cannotBeEmpty() is not applicable to BooleanNodeDefinition.');
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\EnumNode;
class EnumNodeDefinition extends ScalarNodeDefinition
{
private $values;
public function values(array $values)
{
$values = array_unique($values);
if (empty($values)) {
throw new \InvalidArgumentException('->values() must be called with at least one value.');
}
$this->values = $values;
return $this;
}
protected function instantiateNode()
{
if (null === $this->values) {
throw new \RuntimeException('You must call ->values() on enum nodes.');
}
return new EnumNode($this->name, $this->parent, $this->values);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\Exception\UnsetKeyException;
class ExprBuilder
{
protected $node;
public $ifPart;
public $thenPart;
public function __construct(NodeDefinition $node)
{
$this->node = $node;
}
public function always(\Closure $then = null)
{
$this->ifPart = function ($v) { return true; };
if (null !== $then) {
$this->thenPart = $then;
}
return $this;
}
public function ifTrue(\Closure $closure = null)
{
if (null === $closure) {
$closure = function ($v) { return true === $v; };
}
$this->ifPart = $closure;
return $this;
}
public function ifString()
{
$this->ifPart = function ($v) { return is_string($v); };
return $this;
}
public function ifNull()
{
$this->ifPart = function ($v) { return null === $v; };
return $this;
}
public function ifArray()
{
$this->ifPart = function ($v) { return is_array($v); };
return $this;
}
public function ifInArray(array $array)
{
$this->ifPart = function ($v) use ($array) { return in_array($v, $array, true); };
return $this;
}
public function ifNotInArray(array $array)
{
$this->ifPart = function ($v) use ($array) { return !in_array($v, $array, true); };
return $this;
}
public function then(\Closure $closure)
{
$this->thenPart = $closure;
return $this;
}
public function thenEmptyArray()
{
$this->thenPart = function ($v) { return array(); };
return $this;
}
public function thenInvalid($message)
{
$this->thenPart = function ($v) use ($message) {throw new \InvalidArgumentException(sprintf($message, json_encode($v))); };
return $this;
}
public function thenUnset()
{
$this->thenPart = function ($v) { throw new UnsetKeyException('Unsetting key'); };
return $this;
}
public function end()
{
if (null === $this->ifPart) {
throw new \RuntimeException('You must specify an if part.');
}
if (null === $this->thenPart) {
throw new \RuntimeException('You must specify a then part.');
}
return $this->node;
}
public static function buildExpressions(array $expressions)
{
foreach ($expressions as $k => $expr) {
if ($expr instanceof self) {
$if = $expr->ifPart;
$then = $expr->thenPart;
$expressions[$k] = function ($v) use ($if, $then) {
return $if($v) ? $then($v) : $v;
};
}
}
return $expressions;
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\FloatNode;
class FloatNodeDefinition extends NumericNodeDefinition
{
protected function instantiateNode()
{
return new FloatNode($this->name, $this->parent, $this->min, $this->max);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\IntegerNode;
class IntegerNodeDefinition extends NumericNodeDefinition
{
protected function instantiateNode()
{
return new IntegerNode($this->name, $this->parent, $this->min, $this->max);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
class MergeBuilder
{
protected $node;
public $allowFalse = false;
public $allowOverwrite = true;
public function __construct(NodeDefinition $node)
{
$this->node = $node;
}
public function allowUnset($allow = true)
{
$this->allowFalse = $allow;
return $this;
}
public function denyOverwrite($deny = true)
{
$this->allowOverwrite = !$deny;
return $this;
}
public function end()
{
return $this->node;
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
class NodeBuilder implements NodeParentInterface
{
protected $parent;
protected $nodeMapping;
public function __construct()
{
$this->nodeMapping = array(
'variable' => __NAMESPACE__.'\\VariableNodeDefinition',
'scalar' => __NAMESPACE__.'\\ScalarNodeDefinition',
'boolean' => __NAMESPACE__.'\\BooleanNodeDefinition',
'integer' => __NAMESPACE__.'\\IntegerNodeDefinition',
'float' => __NAMESPACE__.'\\FloatNodeDefinition',
'array' => __NAMESPACE__.'\\ArrayNodeDefinition',
'enum' => __NAMESPACE__.'\\EnumNodeDefinition',
);
}
public function setParent(ParentNodeDefinitionInterface $parent = null)
{
$this->parent = $parent;
return $this;
}
public function arrayNode($name)
{
return $this->node($name, 'array');
}
public function scalarNode($name)
{
return $this->node($name, 'scalar');
}
public function booleanNode($name)
{
return $this->node($name, 'boolean');
}
public function integerNode($name)
{
return $this->node($name, 'integer');
}
public function floatNode($name)
{
return $this->node($name, 'float');
}
public function enumNode($name)
{
return $this->node($name, 'enum');
}
public function variableNode($name)
{
return $this->node($name, 'variable');
}
public function end()
{
return $this->parent;
}
public function node($name, $type)
{
$class = $this->getNodeClass($type);
$node = new $class($name);
$this->append($node);
return $node;
}
public function append(NodeDefinition $node)
{
if ($node instanceof ParentNodeDefinitionInterface) {
$builder = clone $this;
$builder->setParent(null);
$node->setBuilder($builder);
}
if (null !== $this->parent) {
$this->parent->append($node);
$node->setParent($this);
}
return $this;
}
public function setNodeClass($type, $class)
{
$this->nodeMapping[strtolower($type)] = $class;
return $this;
}
protected function getNodeClass($type)
{
$type = strtolower($type);
if (!isset($this->nodeMapping[$type])) {
throw new \RuntimeException(sprintf('The node type "%s" is not registered.', $type));
}
$class = $this->nodeMapping[$type];
if (!class_exists($class)) {
throw new \RuntimeException(sprintf('The node class "%s" does not exist.', $class));
}
return $class;
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
abstract class NodeDefinition implements NodeParentInterface
{
protected $name;
protected $normalization;
protected $validation;
protected $defaultValue;
protected $default = false;
protected $required = false;
protected $merge;
protected $allowEmptyValue = true;
protected $nullEquivalent;
protected $trueEquivalent = true;
protected $falseEquivalent = false;
protected $parent;
protected $attributes = array();
public function __construct($name, NodeParentInterface $parent = null)
{
$this->parent = $parent;
$this->name = $name;
}
public function setParent(NodeParentInterface $parent)
{
$this->parent = $parent;
return $this;
}
public function info($info)
{
return $this->attribute('info', $info);
}
public function example($example)
{
return $this->attribute('example', $example);
}
public function attribute($key, $value)
{
$this->attributes[$key] = $value;
return $this;
}
public function end()
{
return $this->parent;
}
public function getNode($forceRootNode = false)
{
if ($forceRootNode) {
$this->parent = null;
}
if (null !== $this->normalization) {
$this->normalization->before = ExprBuilder::buildExpressions($this->normalization->before);
}
if (null !== $this->validation) {
$this->validation->rules = ExprBuilder::buildExpressions($this->validation->rules);
}
$node = $this->createNode();
$node->setAttributes($this->attributes);
return $node;
}
public function defaultValue($value)
{
$this->default = true;
$this->defaultValue = $value;
return $this;
}
public function isRequired()
{
$this->required = true;
return $this;
}
public function treatNullLike($value)
{
$this->nullEquivalent = $value;
return $this;
}
public function treatTrueLike($value)
{
$this->trueEquivalent = $value;
return $this;
}
public function treatFalseLike($value)
{
$this->falseEquivalent = $value;
return $this;
}
public function defaultNull()
{
return $this->defaultValue(null);
}
public function defaultTrue()
{
return $this->defaultValue(true);
}
public function defaultFalse()
{
return $this->defaultValue(false);
}
public function beforeNormalization()
{
return $this->normalization()->before();
}
public function cannotBeEmpty()
{
$this->allowEmptyValue = false;
return $this;
}
public function validate()
{
return $this->validation()->rule();
}
public function cannotBeOverwritten($deny = true)
{
$this->merge()->denyOverwrite($deny);
return $this;
}
protected function validation()
{
if (null === $this->validation) {
$this->validation = new ValidationBuilder($this);
}
return $this->validation;
}
protected function merge()
{
if (null === $this->merge) {
$this->merge = new MergeBuilder($this);
}
return $this->merge;
}
protected function normalization()
{
if (null === $this->normalization) {
$this->normalization = new NormalizationBuilder($this);
}
return $this->normalization;
}
abstract protected function createNode();
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
interface NodeParentInterface
{
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
class NormalizationBuilder
{
protected $node;
public $before = array();
public $remappings = array();
public function __construct(NodeDefinition $node)
{
$this->node = $node;
}
public function remap($key, $plural = null)
{
$this->remappings[] = array($key, null === $plural ? $key.'s' : $plural);
return $this;
}
public function before(\Closure $closure = null)
{
if (null !== $closure) {
$this->before[] = $closure;
return $this;
}
return $this->before[] = new ExprBuilder($this->node);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
abstract class NumericNodeDefinition extends ScalarNodeDefinition
{
protected $min;
protected $max;
public function max($max)
{
if (isset($this->min) && $this->min > $max) {
throw new \InvalidArgumentException(sprintf('You cannot define a max(%s) as you already have a min(%s)', $max, $this->min));
}
$this->max = $max;
return $this;
}
public function min($min)
{
if (isset($this->max) && $this->max < $min) {
throw new \InvalidArgumentException(sprintf('You cannot define a min(%s) as you already have a max(%s)', $min, $this->max));
}
$this->min = $min;
return $this;
}
public function cannotBeEmpty()
{
throw new InvalidDefinitionException('->cannotBeEmpty() is not applicable to NumericNodeDefinition.');
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
interface ParentNodeDefinitionInterface
{
public function children();
public function append(NodeDefinition $node);
public function setBuilder(NodeBuilder $builder);
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\ScalarNode;
class ScalarNodeDefinition extends VariableNodeDefinition
{
protected function instantiateNode()
{
return new ScalarNode($this->name, $this->parent);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\NodeInterface;
class TreeBuilder implements NodeParentInterface
{
protected $tree;
protected $root;
protected $builder;
public function root($name, $type = 'array', NodeBuilder $builder = null)
{
$builder = $builder ?: new NodeBuilder();
return $this->root = $builder->node($name, $type)->setParent($this);
}
public function buildTree()
{
if (null === $this->root) {
throw new \RuntimeException('The configuration tree has no root node.');
}
if (null !== $this->tree) {
return $this->tree;
}
return $this->tree = $this->root->getNode(true);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
class ValidationBuilder
{
protected $node;
public $rules = array();
public function __construct(NodeDefinition $node)
{
$this->node = $node;
}
public function rule(\Closure $closure = null)
{
if (null !== $closure) {
$this->rules[] = $closure;
return $this;
}
return $this->rules[] = new ExprBuilder($this->node);
}
}
<?php
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\VariableNode;
class VariableNodeDefinition extends NodeDefinition
{
protected function instantiateNode()
{
return new VariableNode($this->name, $this->parent);
}
protected function createNode()
{
$node = $this->instantiateNode();
if (null !== $this->normalization) {
$node->setNormalizationClosures($this->normalization->before);
}
if (null !== $this->merge) {
$node->setAllowOverwrite($this->merge->allowOverwrite);
}
if (true === $this->default) {
$node->setDefaultValue($this->defaultValue);
}
$node->setAllowEmptyValue($this->allowEmptyValue);
$node->addEquivalentValue(null, $this->nullEquivalent);
$node->addEquivalentValue(true, $this->trueEquivalent);
$node->addEquivalentValue(false, $this->falseEquivalent);
$node->setRequired($this->required);
if (null !== $this->validation) {
$node->setFinalValidationClosures($this->validation->rules);
}
return $node;
}
}
<?php
namespace Symfony\Component\Config\Definition;
interface ConfigurationInterface
{
public function getConfigTreeBuilder();
}
<?php
namespace Symfony\Component\Config\Definition\Dumper;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\EnumNode;
use Symfony\Component\Config\Definition\PrototypedArrayNode;
class XmlReferenceDumper
{
private $reference;
public function dump(ConfigurationInterface $configuration, $namespace = null)
{
return $this->dumpNode($configuration->getConfigTreeBuilder()->buildTree(), $namespace);
}
public function dumpNode(NodeInterface $node, $namespace = null)
{
$this->reference = '';
$this->writeNode($node, 0, true, $namespace);
$ref = $this->reference;
$this->reference = null;
return $ref;
}
private function writeNode(NodeInterface $node, $depth = 0, $root = false, $namespace = null)
{
$rootName = ($root ? 'config' : $node->getName());
$rootNamespace = ($namespace ?: ($root ? 'http://example.org/schema/dic/'.$node->getName() : null));
if ($node->getParent()) {
$remapping = array_filter($node->getParent()->getXmlRemappings(), function ($mapping) use ($rootName) {
return $rootName === $mapping[1];
});
if (count($remapping)) {
list($singular) = current($remapping);
$rootName = $singular;
}
}
$rootName = str_replace('_', '-', $rootName);
$rootAttributes = array();
$rootAttributeComments = array();
$rootChildren = array();
$rootComments = array();
if ($node instanceof ArrayNode) {
$children = $node->getChildren();
if ($rootInfo = $node->getInfo()) {
$rootComments[] = $rootInfo;
}
if ($rootNamespace) {
$rootComments[] = 'Namespace: '.$rootNamespace;
}
if ($node instanceof PrototypedArrayNode) {
$prototype = $node->getPrototype();
$info = 'prototype';
if (null !== $prototype->getInfo()) {
$info .= ': '.$prototype->getInfo();
}
array_unshift($rootComments, $info);
if ($key = $node->getKeyAttribute()) {
$rootAttributes[$key] = str_replace('-', ' ', $rootName).' '.$key;
}
if ($prototype instanceof ArrayNode) {
$children = $prototype->getChildren();
} else {
if ($prototype->hasDefaultValue()) {
$prototypeValue = $prototype->getDefaultValue();
} else {
switch (get_class($prototype)) {
case 'Symfony\Component\Config\Definition\ScalarNode':
$prototypeValue = 'scalar value';
break;
case 'Symfony\Component\Config\Definition\FloatNode':
case 'Symfony\Component\Config\Definition\IntegerNode':
$prototypeValue = 'numeric value';
break;
case 'Symfony\Component\Config\Definition\BooleanNode':
$prototypeValue = 'true|false';
break;
case 'Symfony\Component\Config\Definition\EnumNode':
$prototypeValue = implode('|', array_map('json_encode', $prototype->getValues()));
break;
default:
$prototypeValue = 'value';
}
}
}
}
foreach ($children as $child) {
if (!$child instanceof ArrayNode) {
$name = str_replace('_', '-', $child->getName());
$value = '%%%%not_defined%%%%';
$comments = array();
if ($info = $child->getInfo()) {
$comments[] = $info;
}
if ($example = $child->getExample()) {
$comments[] = 'Example: '.$example;
}
if ($child->isRequired()) {
$comments[] = 'Required';
}
if ($child instanceof EnumNode) {
$comments[] = 'One of '.implode('; ', array_map('json_encode', $child->getValues()));
}
if (count($comments)) {
$rootAttributeComments[$name] = implode(";\n", $comments);
}
if ($child->hasDefaultValue()) {
$value = $child->getDefaultValue();
}
$rootAttributes[$name] = $value;
} else {
$rootChildren[] = $child;
}
}
}
if (count($rootComments)) {
foreach ($rootComments as $comment) {
$this->writeLine('<!-- '.$comment.' -->', $depth);
}
}
if (count($rootAttributeComments)) {
foreach ($rootAttributeComments as $attrName => $comment) {
$commentDepth = $depth + 4 + strlen($attrName) + 2;
$commentLines = explode("\n", $comment);
$multiline = (count($commentLines) > 1);
$comment = implode(PHP_EOL.str_repeat(' ', $commentDepth), $commentLines);
if ($multiline) {
$this->writeLine('<!--', $depth);
$this->writeLine($attrName.': '.$comment, $depth + 4);
$this->writeLine('-->', $depth);
} else {
$this->writeLine('<!-- '.$attrName.': '.$comment.' -->', $depth);
}
}
}
$rootIsVariablePrototype = isset($prototypeValue);
$rootIsEmptyTag = (0 === count($rootChildren) && !$rootIsVariablePrototype);
$rootOpenTag = '<'.$rootName;
if (1 >= ($attributesCount = count($rootAttributes))) {
if (1 === $attributesCount) {
$rootOpenTag .= sprintf(' %s="%s"', current(array_keys($rootAttributes)), $this->writeValue(current($rootAttributes)));
}
$rootOpenTag .= $rootIsEmptyTag ? ' />' : '>';
if ($rootIsVariablePrototype) {
$rootOpenTag .= $prototypeValue.'</'.$rootName.'>';
}
$this->writeLine($rootOpenTag, $depth);
} else {
$this->writeLine($rootOpenTag, $depth);
$i = 1;
foreach ($rootAttributes as $attrName => $attrValue) {
$attr = sprintf('%s="%s"', $attrName, $this->writeValue($attrValue));
$this->writeLine($attr, $depth + 4);
if ($attributesCount === $i++) {
$this->writeLine($rootIsEmptyTag ? '/>' : '>', $depth);
if ($rootIsVariablePrototype) {
$rootOpenTag .= $prototypeValue.'</'.$rootName.'>';
}
}
}
}
foreach ($rootChildren as $child) {
$this->writeLine('');
$this->writeNode($child, $depth + 4);
}
if (!$rootIsEmptyTag && !$rootIsVariablePrototype) {
$this->writeLine('');
$rootEndTag = '</'.$rootName.'>';
$this->writeLine($rootEndTag, $depth);
}
}
private function writeLine($text, $indent = 0)
{
$indent = strlen($text) + $indent;
$format = '%'.$indent.'s';
$this->reference .= sprintf($format, $text).PHP_EOL;
}
private function writeValue($value)
{
if ('%%%%not_defined%%%%' === $value) {
return '';
}
if (is_string($value) || is_numeric($value)) {
return $value;
}
if (false === $value) {
return 'false';
}
if (true === $value) {
return 'true';
}
if (null === $value) {
return 'null';
}
if (empty($value)) {
return '';
}
if (is_array($value)) {
return implode(',', $value);
}
}
}
<?php
namespace Symfony\Component\Config\Definition\Dumper;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\EnumNode;
use Symfony\Component\Config\Definition\PrototypedArrayNode;
use Symfony\Component\Yaml\Inline;
class YamlReferenceDumper
{
private $reference;
public function dump(ConfigurationInterface $configuration)
{
return $this->dumpNode($configuration->getConfigTreeBuilder()->buildTree());
}
public function dumpNode(NodeInterface $node)
{
$this->reference = '';
$this->writeNode($node);
$ref = $this->reference;
$this->reference = null;
return $ref;
}
private function writeNode(NodeInterface $node, $depth = 0)
{
$comments = array();
$default = '';
$defaultArray = null;
$children = null;
$example = $node->getExample();
if ($node instanceof ArrayNode) {
$children = $node->getChildren();
if ($node instanceof PrototypedArrayNode) {
$prototype = $node->getPrototype();
if ($prototype instanceof ArrayNode) {
$children = $prototype->getChildren();
}
if ($key = $node->getKeyAttribute()) {
$keyNodeClass = 'Symfony\Component\Config\Definition\\'.($prototype instanceof ArrayNode ? 'ArrayNode' : 'ScalarNode');
$keyNode = new $keyNodeClass($key, $node);
$info = 'Prototype';
if (null !== $prototype->getInfo()) {
$info .= ': '.$prototype->getInfo();
}
$keyNode->setInfo($info);
foreach ($children as $childNode) {
$keyNode->addChild($childNode);
}
$children = array($key => $keyNode);
}
}
if (!$children) {
if ($node->hasDefaultValue() && count($defaultArray = $node->getDefaultValue())) {
$default = '';
} elseif (!is_array($example)) {
$default = '[]';
}
}
} elseif ($node instanceof EnumNode) {
$comments[] = 'One of '.implode('; ', array_map('json_encode', $node->getValues()));
$default = $node->hasDefaultValue() ? Inline::dump($node->getDefaultValue()) : '~';
} else {
$default = '~';
if ($node->hasDefaultValue()) {
$default = $node->getDefaultValue();
if (is_array($default)) {
if (count($defaultArray = $node->getDefaultValue())) {
$default = '';
} elseif (!is_array($example)) {
$default = '[]';
}
} else {
$default = Inline::dump($default);
}
}
}
if ($node->isRequired()) {
$comments[] = 'Required';
}
if ($example && !is_array($example)) {
$comments[] = 'Example: '.$example;
}
$default = (string) $default != '' ? ' '.$default : '';
$comments = count($comments) ? '# '.implode(', ', $comments) : '';
$text = rtrim(sprintf('%-20s %s %s', $node->getName().':', $default, $comments), ' ');
if ($info = $node->getInfo()) {
$this->writeLine('');
$info = str_replace("\n", sprintf("\n%".($depth * 4).'s# ', ' '), $info);
$this->writeLine('# '.$info, $depth * 4);
}
$this->writeLine($text, $depth * 4);
if ($defaultArray) {
$this->writeLine('');
$message = count($defaultArray) > 1 ? 'Defaults' : 'Default';
$this->writeLine('# '.$message.':', $depth * 4 + 4);
$this->writeArray($defaultArray, $depth + 1);
}
if (is_array($example)) {
$this->writeLine('');
$message = count($example) > 1 ? 'Examples' : 'Example';
$this->writeLine('# '.$message.':', $depth * 4 + 4);
$this->writeArray($example, $depth + 1);
}
if ($children) {
foreach ($children as $childNode) {
$this->writeNode($childNode, $depth + 1);
}
}
}
private function writeLine($text, $indent = 0)
{
$indent = strlen($text) + $indent;
$format = '%'.$indent.'s';
$this->reference .= sprintf($format, $text)."\n";
}
private function writeArray(array $array, $depth)
{
$isIndexed = array_values($array) === $array;
foreach ($array as $key => $value) {
if (is_array($value)) {
$val = '';
} else {
$val = $value;
}
if ($isIndexed) {
$this->writeLine('- '.$val, $depth * 4);
} else {
$this->writeLine(sprintf('%-20s %s', $key.':', $val), $depth * 4);
}
if (is_array($value)) {
$this->writeArray($value, $depth + 1);
}
}
}
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
class EnumNode extends ScalarNode
{
private $values;
public function __construct($name, NodeInterface $parent = null, array $values = array())
{
$values = array_unique($values);
if (empty($values)) {
throw new \InvalidArgumentException('$values must contain at least one element.');
}
parent::__construct($name, $parent);
$this->values = $values;
}
public function getValues()
{
return $this->values;
}
protected function finalizeValue($value)
{
$value = parent::finalizeValue($value);
if (!in_array($value, $this->values, true)) {
$ex = new InvalidConfigurationException(sprintf(
'The value %s is not allowed for path "%s". Permissible values: %s',
json_encode($value),
$this->getPath(),
implode(', ', array_map('json_encode', $this->values))));
$ex->setPath($this->getPath());
throw $ex;
}
return $value;
}
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class DuplicateKeyException extends InvalidConfigurationException
{
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class Exception extends \RuntimeException
{
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class ForbiddenOverwriteException extends InvalidConfigurationException
{
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class InvalidConfigurationException extends Exception
{
private $path;
private $containsHints = false;
public function setPath($path)
{
$this->path = $path;
}
public function getPath()
{
return $this->path;
}
public function addHint($hint)
{
if (!$this->containsHints) {
$this->message .= "\nHint: ".$hint;
$this->containsHints = true;
} else {
$this->message .= ', '.$hint;
}
}
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class InvalidDefinitionException extends Exception
{
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class InvalidTypeException extends InvalidConfigurationException
{
}
<?php
namespace Symfony\Component\Config\Definition\Exception;
class UnsetKeyException extends Exception
{
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
class FloatNode extends NumericNode
{
protected function validateType($value)
{
if (is_int($value)) {
$value = (float) $value;
}
if (!is_float($value)) {
$ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected float, but got %s.', $this->getPath(), gettype($value)));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
$ex->setPath($this->getPath());
throw $ex;
}
}
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
class IntegerNode extends NumericNode
{
protected function validateType($value)
{
if (!is_int($value)) {
$ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected int, but got %s.', $this->getPath(), gettype($value)));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
$ex->setPath($this->getPath());
throw $ex;
}
}
}
<?php
namespace Symfony\Component\Config\Definition;
interface NodeInterface
{
public function getName();
public function getPath();
public function isRequired();
public function hasDefaultValue();
public function getDefaultValue();
public function normalize($value);
public function merge($leftSide, $rightSide);
public function finalize($value);
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
class NumericNode extends ScalarNode
{
protected $min;
protected $max;
public function __construct($name, NodeInterface $parent = null, $min = null, $max = null)
{
parent::__construct($name, $parent);
$this->min = $min;
$this->max = $max;
}
protected function finalizeValue($value)
{
$value = parent::finalizeValue($value);
$errorMsg = null;
if (isset($this->min) && $value < $this->min) {
$errorMsg = sprintf('The value %s is too small for path "%s". Should be greater than or equal to %s', $value, $this->getPath(), $this->min);
}
if (isset($this->max) && $value > $this->max) {
$errorMsg = sprintf('The value %s is too big for path "%s". Should be less than or equal to %s', $value, $this->getPath(), $this->max);
}
if (isset($errorMsg)) {
$ex = new InvalidConfigurationException($errorMsg);
$ex->setPath($this->getPath());
throw $ex;
}
return $value;
}
protected function isValueEmpty($value)
{
return false;
}
}
<?php
namespace Symfony\Component\Config\Definition;
class Processor
{
public function process(NodeInterface $configTree, array $configs)
{
$currentConfig = array();
foreach ($configs as $config) {
$config = $configTree->normalize($config);
$currentConfig = $configTree->merge($currentConfig, $config);
}
return $configTree->finalize($currentConfig);
}
public function processConfiguration(ConfigurationInterface $configuration, array $configs)
{
return $this->process($configuration->getConfigTreeBuilder()->buildTree(), $configs);
}
public static function normalizeConfig($config, $key, $plural = null)
{
if (null === $plural) {
$plural = $key.'s';
}
if (isset($config[$plural])) {
return $config[$plural];
}
if (isset($config[$key])) {
if (is_string($config[$key]) || !is_int(key($config[$key]))) {
return array($config[$key]);
}
return $config[$key];
}
return array();
}
}
<?php
namespace Symfony\Component\Config\Definition;
interface PrototypeNodeInterface extends NodeInterface
{
public function setName($name);
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Exception\DuplicateKeyException;
use Symfony\Component\Config\Definition\Exception\UnsetKeyException;
use Symfony\Component\Config\Definition\Exception\Exception;
class PrototypedArrayNode extends ArrayNode
{
protected $prototype;
protected $keyAttribute;
protected $removeKeyAttribute = false;
protected $minNumberOfElements = 0;
protected $defaultValue = array();
protected $defaultChildren;
public function setMinNumberOfElements($number)
{
$this->minNumberOfElements = $number;
}
public function setKeyAttribute($attribute, $remove = true)
{
$this->keyAttribute = $attribute;
$this->removeKeyAttribute = $remove;
}
public function getKeyAttribute()
{
return $this->keyAttribute;
}
public function setDefaultValue($value)
{
if (!is_array($value)) {
throw new \InvalidArgumentException($this->getPath().': the default value of an array node has to be an array.');
}
$this->defaultValue = $value;
}
public function hasDefaultValue()
{
return true;
}
public function setAddChildrenIfNoneSet($children = array('defaults'))
{
if (null === $children) {
$this->defaultChildren = array('defaults');
} else {
$this->defaultChildren = is_int($children) && $children > 0 ? range(1, $children) : (array) $children;
}
}
public function getDefaultValue()
{
if (null !== $this->defaultChildren) {
$default = $this->prototype->hasDefaultValue() ? $this->prototype->getDefaultValue() : array();
$defaults = array();
foreach (array_values($this->defaultChildren) as $i => $name) {
$defaults[null === $this->keyAttribute ? $i : $name] = $default;
}
return $defaults;
}
return $this->defaultValue;
}
public function setPrototype(PrototypeNodeInterface $node)
{
$this->prototype = $node;
}
public function getPrototype()
{
return $this->prototype;
}
public function addChild(NodeInterface $node)
{
throw new Exception('A prototyped array node can not have concrete children.');
}
protected function finalizeValue($value)
{
if (false === $value) {
$msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value));
throw new UnsetKeyException($msg);
}
foreach ($value as $k => $v) {
$this->prototype->setName($k);
try {
$value[$k] = $this->prototype->finalize($v);
} catch (UnsetKeyException $e) {
unset($value[$k]);
}
}
if (count($value) < $this->minNumberOfElements) {
$msg = sprintf('The path "%s" should have at least %d element(s) defined.', $this->getPath(), $this->minNumberOfElements);
$ex = new InvalidConfigurationException($msg);
$ex->setPath($this->getPath());
throw $ex;
}
return $value;
}
protected function normalizeValue($value)
{
if (false === $value) {
return $value;
}
$value = $this->remapXml($value);
$isAssoc = array_keys($value) !== range(0, count($value) - 1);
$normalized = array();
foreach ($value as $k => $v) {
if (null !== $this->keyAttribute && is_array($v)) {
if (!isset($v[$this->keyAttribute]) && is_int($k) && !$isAssoc) {
$msg = sprintf('The attribute "%s" must be set for path "%s".', $this->keyAttribute, $this->getPath());
$ex = new InvalidConfigurationException($msg);
$ex->setPath($this->getPath());
throw $ex;
} elseif (isset($v[$this->keyAttribute])) {
$k = $v[$this->keyAttribute];
if ($this->removeKeyAttribute) {
unset($v[$this->keyAttribute]);
}
if (1 == count($v) && isset($v['value'])) {
$v = $v['value'];
}
}
if (array_key_exists($k, $normalized)) {
$msg = sprintf('Duplicate key "%s" for path "%s".', $k, $this->getPath());
$ex = new DuplicateKeyException($msg);
$ex->setPath($this->getPath());
throw $ex;
}
}
$this->prototype->setName($k);
if (null !== $this->keyAttribute || $isAssoc) {
$normalized[$k] = $this->prototype->normalize($v);
} else {
$normalized[] = $this->prototype->normalize($v);
}
}
return $normalized;
}
protected function mergeValues($leftSide, $rightSide)
{
if (false === $rightSide) {
return false;
}
if (false === $leftSide || !$this->performDeepMerging) {
return $rightSide;
}
foreach ($rightSide as $k => $v) {
if (null === $this->keyAttribute) {
$leftSide[] = $v;
continue;
}
if (!array_key_exists($k, $leftSide)) {
if (!$this->allowNewKeys) {
$ex = new InvalidConfigurationException(sprintf(
'You are not allowed to define new elements for path "%s". '.
'Please define all elements for this path in one config file.',
$this->getPath()
));
$ex->setPath($this->getPath());
throw $ex;
}
$leftSide[$k] = $v;
continue;
}
$this->prototype->setName($k);
$leftSide[$k] = $this->prototype->merge($leftSide[$k], $v);
}
return $leftSide;
}
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
class ScalarNode extends VariableNode
{
protected function validateType($value)
{
if (!is_scalar($value) && null !== $value) {
$ex = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected scalar, but got %s.',
$this->getPath(),
gettype($value)
));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
$ex->setPath($this->getPath());
throw $ex;
}
}
protected function isValueEmpty($value)
{
return null === $value || '' === $value;
}
}
<?php
namespace Symfony\Component\Config\Definition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
class VariableNode extends BaseNode implements PrototypeNodeInterface
{
protected $defaultValueSet = false;
protected $defaultValue;
protected $allowEmptyValue = true;
public function setDefaultValue($value)
{
$this->defaultValueSet = true;
$this->defaultValue = $value;
}
public function hasDefaultValue()
{
return $this->defaultValueSet;
}
public function getDefaultValue()
{
$v = $this->defaultValue;
return $v instanceof \Closure ? $v() : $v;
}
public function setAllowEmptyValue($boolean)
{
$this->allowEmptyValue = (bool) $boolean;
}
public function setName($name)
{
$this->name = $name;
}
protected function validateType($value)
{
}
protected function finalizeValue($value)
{
if (!$this->allowEmptyValue && $this->isValueEmpty($value)) {
$ex = new InvalidConfigurationException(sprintf(
'The path "%s" cannot contain an empty value, but got %s.',
$this->getPath(),
json_encode($value)
));
if ($hint = $this->getInfo()) {
$ex->addHint($hint);
}
$ex->setPath($this->getPath());
throw $ex;
}
return $value;
}
protected function normalizeValue($value)
{
return $value;
}
protected function mergeValues($leftSide, $rightSide)
{
return $rightSide;
}
protected function isValueEmpty($value)
{
return empty($value);
}
}
<?php
namespace Symfony\Component\Config\Exception;
class FileLoaderImportCircularReferenceException extends FileLoaderLoadException
{
public function __construct(array $resources, $code = null, $previous = null)
{
$message = sprintf('Circular reference detected in "%s" ("%s" > "%s").', $this->varToString($resources[0]), implode('" > "', $resources), $resources[0]);
\Exception::__construct($message, $code, $previous);
}
}
<?php
namespace Symfony\Component\Config\Exception;
class FileLoaderLoadException extends \Exception
{
public function __construct($resource, $sourceResource = null, $code = null, $previous = null)
{
$message = '';
if ($previous) {
if ('.' === substr($previous->getMessage(), -1)) {
$trimmedMessage = substr($previous->getMessage(), 0, -1);
$message .= sprintf('%s', $trimmedMessage).' in ';
} else {
$message .= sprintf('%s', $previous->getMessage()).' in ';
}
$message .= $resource.' ';
if (null === $sourceResource) {
$message .= sprintf('(which is loaded in resource "%s")', $this->varToString($resource));
} else {
$message .= sprintf('(which is being imported from "%s")', $this->varToString($sourceResource));
}
$message .= '.';
} elseif (null === $sourceResource) {
$message .= sprintf('Cannot load resource "%s".', $this->varToString($resource));
} else {
$message .= sprintf('Cannot import resource "%s" from "%s".', $this->varToString($resource), $this->varToString($sourceResource));
}
if ('@' === $resource[0]) {
$parts = explode(DIRECTORY_SEPARATOR, $resource);
$bundle = substr($parts[0], 1);
$message .= sprintf(' Make sure the "%s" bundle is correctly registered and loaded in the application kernel class.', $bundle);
$message .= sprintf(' If the bundle is registered, make sure the bundle path "%s" is not empty.', $resource);
}
parent::__construct($message, $code, $previous);
}
protected function varToString($var)
{
if (is_object($var)) {
return sprintf('Object(%s)', get_class($var));
}
if (is_array($var)) {
$a = array();
foreach ($var as $k => $v) {
$a[] = sprintf('%s => %s', $k, $this->varToString($v));
}
return sprintf('Array(%s)', implode(', ', $a));
}
if (is_resource($var)) {
return sprintf('Resource(%s)', get_resource_type($var));
}
if (null === $var) {
return 'null';
}
if (false === $var) {
return 'false';
}
if (true === $var) {
return 'true';
}
return (string) $var;
}
}
<?php
namespace Symfony\Component\Config;
class FileLocator implements FileLocatorInterface
{
protected $paths;
public function __construct($paths = array())
{
$this->paths = (array) $paths;
}
public function locate($name, $currentPath = null, $first = true)
{
if ('' == $name) {
throw new \InvalidArgumentException('An empty file name is not valid to be located.');
}
if ($this->isAbsolutePath($name)) {
if (!file_exists($name)) {
throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $name));
}
return $name;
}
$paths = $this->paths;
if (null !== $currentPath) {
array_unshift($paths, $currentPath);
}
$paths = array_unique($paths);
$filepaths = array();
foreach ($paths as $path) {
if (file_exists($file = $path.DIRECTORY_SEPARATOR.$name)) {
if (true === $first) {
return $file;
}
$filepaths[] = $file;
}
}
if (!$filepaths) {
throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $name, implode(', ', $paths)));
}
return $filepaths;
}
private function isAbsolutePath($file)
{
if ($file[0] === '/' || $file[0] === '\\'
|| (strlen($file) > 3 && ctype_alpha($file[0])
&& $file[1] === ':'
&& ($file[2] === '\\' || $file[2] === '/')
)
|| null !== parse_url($file, PHP_URL_SCHEME)
) {
return true;
}
return false;
}
}
<?php
namespace Symfony\Component\Config;
interface FileLocatorInterface
{
public function locate($name, $currentPath = null, $first = true);
}
<?php
namespace Symfony\Component\Config\Loader;
use Symfony\Component\Config\Exception\FileLoaderLoadException;
class DelegatingLoader extends Loader
{
public function __construct(LoaderResolverInterface $resolver)
{
$this->resolver = $resolver;
}
public function load($resource, $type = null)
{
if (false === $loader = $this->resolver->resolve($resource, $type)) {
throw new FileLoaderLoadException($resource);
}
return $loader->load($resource, $type);
}
public function supports($resource, $type = null)
{
return false !== $this->resolver->resolve($resource, $type);
}
}
<?php
namespace Symfony\Component\Config\Loader;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Exception\FileLoaderLoadException;
use Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException;
abstract class FileLoader extends Loader
{
protected static $loading = array();
protected $locator;
private $currentDir;
public function __construct(FileLocatorInterface $locator)
{
$this->locator = $locator;
}
public function setCurrentDir($dir)
{
$this->currentDir = $dir;
}
public function getLocator()
{
return $this->locator;
}
public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null)
{
try {
$loader = $this->resolve($resource, $type);
if ($loader instanceof self && null !== $this->currentDir) {
$resource = $loader->getLocator()->locate($resource, $this->currentDir, false);
}
$resources = is_array($resource) ? $resource : array($resource);
for ($i = 0; $i < $resourcesCount = count($resources); ++$i) {
if (isset(self::$loading[$resources[$i]])) {
if ($i == $resourcesCount - 1) {
throw new FileLoaderImportCircularReferenceException(array_keys(self::$loading));
}
} else {
$resource = $resources[$i];
break;
}
}
self::$loading[$resource] = true;
try {
$ret = $loader->load($resource, $type);
} finally {
unset(self::$loading[$resource]);
}
return $ret;
} catch (FileLoaderImportCircularReferenceException $e) {
throw $e;
} catch (\Exception $e) {
if (!$ignoreErrors) {
if ($e instanceof FileLoaderLoadException) {
throw $e;
}
throw new FileLoaderLoadException($resource, $sourceResource, null, $e);
}
}
}
}
<?php
namespace Symfony\Component\Config\Loader;
use Symfony\Component\Config\Exception\FileLoaderLoadException;
abstract class Loader implements LoaderInterface
{
protected $resolver;
public function getResolver()
{
return $this->resolver;
}
public function setResolver(LoaderResolverInterface $resolver)
{
$this->resolver = $resolver;
}
public function import($resource, $type = null)
{
return $this->resolve($resource, $type)->load($resource, $type);
}
public function resolve($resource, $type = null)
{
if ($this->supports($resource, $type)) {
return $this;
}
$loader = null === $this->resolver ? false : $this->resolver->resolve($resource, $type);
if (false === $loader) {
throw new FileLoaderLoadException($resource);
}
return $loader;
}
}
<?php
namespace Symfony\Component\Config\Loader;
interface LoaderInterface
{
public function load($resource, $type = null);
public function supports($resource, $type = null);
public function getResolver();
public function setResolver(LoaderResolverInterface $resolver);
}
<?php
namespace Symfony\Component\Config\Loader;
class LoaderResolver implements LoaderResolverInterface
{
private $loaders = array();
public function __construct(array $loaders = array())
{
foreach ($loaders as $loader) {
$this->addLoader($loader);
}
}
public function resolve($resource, $type = null)
{
foreach ($this->loaders as $loader) {
if ($loader->supports($resource, $type)) {
return $loader;
}
}
return false;
}
public function addLoader(LoaderInterface $loader)
{
$this->loaders[] = $loader;
$loader->setResolver($this);
}
public function getLoaders()
{
return $this->loaders;
}
}
<?php
namespace Symfony\Component\Config\Loader;
interface LoaderResolverInterface
{
public function resolve($resource, $type = null);
}
<?php
namespace Symfony\Component\Config\Resource;
class DirectoryResource implements SelfCheckingResourceInterface, \Serializable
{
private $resource;
private $pattern;
public function __construct($resource, $pattern = null)
{
$this->resource = realpath($resource);
$this->pattern = $pattern;
if (false === $this->resource || !is_dir($this->resource)) {
throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist.', $resource));
}
}
public function __toString()
{
return md5(serialize(array($this->resource, $this->pattern)));
}
public function getResource()
{
return $this->resource;
}
public function getPattern()
{
return $this->pattern;
}
public function isFresh($timestamp)
{
if (!is_dir($this->resource)) {
return false;
}
$newestMTime = filemtime($this->resource);
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->resource), \RecursiveIteratorIterator::SELF_FIRST) as $file) {
if ($this->pattern && $file->isFile() && !preg_match($this->pattern, $file->getBasename())) {
continue;
}
if ($file->isDir() && '/..' === substr($file, -3)) {
continue;
}
$newestMTime = max($file->getMTime(), $newestMTime);
}
return $newestMTime < $timestamp;
}
public function serialize()
{
return serialize(array($this->resource, $this->pattern));
}
public function unserialize($serialized)
{
list($this->resource, $this->pattern) = unserialize($serialized);
}
}
<?php
namespace Symfony\Component\Config\Resource;
class FileExistenceResource implements SelfCheckingResourceInterface, \Serializable
{
private $resource;
private $exists;
public function __construct($resource)
{
$this->resource = (string) $resource;
$this->exists = file_exists($resource);
}
public function __toString()
{
return $this->resource;
}
public function getResource()
{
return $this->resource;
}
public function isFresh($timestamp)
{
return file_exists($this->resource) === $this->exists;
}
public function serialize()
{
return serialize(array($this->resource, $this->exists));
}
public function unserialize($serialized)
{
list($this->resource, $this->exists) = unserialize($serialized);
}
}
<?php
namespace Symfony\Component\Config\Resource;
class FileResource implements SelfCheckingResourceInterface, \Serializable
{
private $resource;
public function __construct($resource)
{
$this->resource = realpath($resource);
if (false === $this->resource && file_exists($resource)) {
$this->resource = $resource;
}
if (false === $this->resource) {
throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $resource));
}
}
public function __toString()
{
return $this->resource;
}
public function getResource()
{
return $this->resource;
}
public function isFresh($timestamp)
{
return file_exists($this->resource) && @filemtime($this->resource) <= $timestamp;
}
public function serialize()
{
return serialize($this->resource);
}
public function unserialize($serialized)
{
$this->resource = unserialize($serialized);
}
}
<?php
namespace Symfony\Component\Config\Resource;
interface ResourceInterface
{
public function __toString();
}
<?php
namespace Symfony\Component\Config\Resource;
use Symfony\Component\Config\ResourceCheckerInterface;
class SelfCheckingResourceChecker implements ResourceCheckerInterface
{
public function supports(ResourceInterface $metadata)
{
return $metadata instanceof SelfCheckingResourceInterface;
}
public function isFresh(ResourceInterface $resource, $timestamp)
{
return $resource->isFresh($timestamp);
}
}
<?php
namespace Symfony\Component\Config\Resource;
interface SelfCheckingResourceInterface extends ResourceInterface
{
public function isFresh($timestamp);
}
<?php
namespace Symfony\Component\Config;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
class ResourceCheckerConfigCache implements ConfigCacheInterface
{
private $file;
private $resourceCheckers;
public function __construct($file, array $resourceCheckers = array())
{
$this->file = $file;
$this->resourceCheckers = $resourceCheckers;
}
public function getPath()
{
return $this->file;
}
public function isFresh()
{
if (!is_file($this->file)) {
return false;
}
if (!$this->resourceCheckers) {
return true;
}
$metadata = $this->getMetaFile();
if (!is_file($metadata)) {
return true;
}
$time = filemtime($this->file);
$meta = unserialize(file_get_contents($metadata));
foreach ($meta as $resource) {
foreach ($this->resourceCheckers as $checker) {
if (!$checker->supports($resource)) {
continue;
}
if ($checker->isFresh($resource, $time)) {
break;
}
return false;
}
}
return true;
}
public function write($content, array $metadata = null)
{
$mode = 0666;
$umask = umask();
$filesystem = new Filesystem();
$filesystem->dumpFile($this->file, $content, null);
try {
$filesystem->chmod($this->file, $mode, $umask);
} catch (IOException $e) {
}
if (null !== $metadata) {
$filesystem->dumpFile($this->getMetaFile(), serialize($metadata), null);
try {
$filesystem->chmod($this->getMetaFile(), $mode, $umask);
} catch (IOException $e) {
}
}
}
private function getMetaFile()
{
return $this->file.'.meta';
}
}
<?php
namespace Symfony\Component\Config;
class ResourceCheckerConfigCacheFactory implements ConfigCacheFactoryInterface
{
private $resourceCheckers = array();
public function __construct(array $resourceCheckers = array())
{
$this->resourceCheckers = $resourceCheckers;
}
public function cache($file, $callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException(sprintf('Invalid type for callback argument. Expected callable, but got "%s".', gettype($callback)));
}
$cache = new ResourceCheckerConfigCache($file, $this->resourceCheckers);
if (!$cache->isFresh()) {
call_user_func($callback, $cache);
}
return $cache;
}
}
<?php
namespace Symfony\Component\Config;
use Symfony\Component\Config\Resource\ResourceInterface;
interface ResourceCheckerInterface
{
public function supports(ResourceInterface $metadata);
public function isFresh(ResourceInterface $resource, $timestamp);
}
<?php
namespace Symfony\Component\Config\Util;
class XmlUtils
{
private function __construct()
{
}
public static function loadFile($file, $schemaOrCallable = null)
{
$content = @file_get_contents($file);
if ('' === trim($content)) {
throw new \InvalidArgumentException(sprintf('File %s does not contain valid XML, it is empty.', $file));
}
$internalErrors = libxml_use_internal_errors(true);
$disableEntities = libxml_disable_entity_loader(true);
libxml_clear_errors();
$dom = new \DOMDocument();
$dom->validateOnParse = true;
if (!$dom->loadXML($content, LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
libxml_disable_entity_loader($disableEntities);
throw new \InvalidArgumentException(implode("\n", static::getXmlErrors($internalErrors)));
}
$dom->normalizeDocument();
libxml_use_internal_errors($internalErrors);
libxml_disable_entity_loader($disableEntities);
foreach ($dom->childNodes as $child) {
if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
throw new \InvalidArgumentException('Document types are not allowed.');
}
}
if (null !== $schemaOrCallable) {
$internalErrors = libxml_use_internal_errors(true);
libxml_clear_errors();
$e = null;
if (is_callable($schemaOrCallable)) {
try {
$valid = call_user_func($schemaOrCallable, $dom, $internalErrors);
} catch (\Exception $e) {
$valid = false;
}
} elseif (!is_array($schemaOrCallable) && is_file((string) $schemaOrCallable)) {
$schemaSource = file_get_contents((string) $schemaOrCallable);
$valid = @$dom->schemaValidateSource($schemaSource);
} else {
libxml_use_internal_errors($internalErrors);
throw new \InvalidArgumentException('The schemaOrCallable argument has to be a valid path to XSD file or callable.');
}
if (!$valid) {
$messages = static::getXmlErrors($internalErrors);
if (empty($messages)) {
$messages = array(sprintf('The XML file "%s" is not valid.', $file));
}
throw new \InvalidArgumentException(implode("\n", $messages), 0, $e);
}
}
libxml_clear_errors();
libxml_use_internal_errors($internalErrors);
return $dom;
}
public static function convertDomElementToArray(\DOMElement $element, $checkPrefix = true)
{
$prefix = (string) $element->prefix;
$empty = true;
$config = array();
foreach ($element->attributes as $name => $node) {
if ($checkPrefix && !in_array((string) $node->prefix, array('', $prefix), true)) {
continue;
}
$config[$name] = static::phpize($node->value);
$empty = false;
}
$nodeValue = false;
foreach ($element->childNodes as $node) {
if ($node instanceof \DOMText) {
if ('' !== trim($node->nodeValue)) {
$nodeValue = trim($node->nodeValue);
$empty = false;
}
} elseif ($checkPrefix && $prefix != (string) $node->prefix) {
continue;
} elseif (!$node instanceof \DOMComment) {
$value = static::convertDomElementToArray($node, $checkPrefix);
$key = $node->localName;
if (isset($config[$key])) {
if (!is_array($config[$key]) || !is_int(key($config[$key]))) {
$config[$key] = array($config[$key]);
}
$config[$key][] = $value;
} else {
$config[$key] = $value;
}
$empty = false;
}
}
if (false !== $nodeValue) {
$value = static::phpize($nodeValue);
if (count($config)) {
$config['value'] = $value;
} else {
$config = $value;
}
}
return !$empty ? $config : null;
}
public static function phpize($value)
{
$value = (string) $value;
$lowercaseValue = strtolower($value);
switch (true) {
case 'null' === $lowercaseValue:
return;
case ctype_digit($value):
$raw = $value;
$cast = (int) $value;
return '0' == $value[0] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
case isset($value[1]) && '-' === $value[0] && ctype_digit(substr($value, 1)):
$raw = $value;
$cast = (int) $value;
return '0' == $value[1] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
case 'true' === $lowercaseValue:
return true;
case 'false' === $lowercaseValue:
return false;
case isset($value[1]) && '0b' == $value[0].$value[1]:
return bindec($value);
case is_numeric($value):
return '0x' === $value[0].$value[1] ? hexdec($value) : (float) $value;
case preg_match('/^0x[0-9a-f]++$/i', $value):
return hexdec($value);
case preg_match('/^(-|\+)?[0-9]+(\.[0-9]+)?$/', $value):
return (float) $value;
default:
return $value;
}
}
protected static function getXmlErrors($internalErrors)
{
$errors = array();
foreach (libxml_get_errors() as $error) {
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code,
trim($error->message),
$error->file ?: 'n/a',
$error->line,
$error->column
);
}
libxml_clear_errors();
libxml_use_internal_errors($internalErrors);
return $errors;
}
}
<?php
namespace Symfony\Component\EventDispatcher;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContainerAwareEventDispatcher extends EventDispatcher
{
private $container;
private $listenerIds = array();
private $listeners = array();
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
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 => list($serviceId, $method, $priority)) {
$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);
}
public function hasListeners($eventName = null)
{
if (null === $eventName) {
return (bool) count($this->listenerIds) || (bool) count($this->listeners);
}
if (isset($this->listenerIds[$eventName])) {
return true;
}
return parent::hasListeners($eventName);
}
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);
}
public function getListenerPriority($eventName, $listener)
{
$this->lazyLoad($eventName);
return parent::getListenerPriority($eventName, $listener);
}
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;
}
protected function lazyLoad($eventName)
{
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as list($serviceId, $method, $priority)) {
$listener = $this->container->get($serviceId);
$key = $serviceId.'.'.$method;
if (!isset($this->listeners[$eventName][$key])) {
$this->addListener($eventName, array($listener, $method), $priority);
} elseif ($listener !== $this->listeners[$eventName][$key]) {
parent::removeListener($eventName, array($this->listeners[$eventName][$key], $method));
$this->addListener($eventName, array($listener, $method), $priority);
}
$this->listeners[$eventName][$key] = $listener;
}
}
}
}
<?php
namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Stopwatch\Stopwatch;
use Psr\Log\LoggerInterface;
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();
}
public function addListener($eventName, $listener, $priority = 0)
{
$this->dispatcher->addListener($eventName, $listener, $priority);
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->dispatcher->addSubscriber($subscriber);
}
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);
}
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
return $this->dispatcher->removeSubscriber($subscriber);
}
public function getListeners($eventName = null)
{
return $this->dispatcher->getListeners($eventName);
}
public function getListenerPriority($eventName, $listener)
{
return $this->dispatcher->getListenerPriority($eventName, $listener);
}
public function hasListeners($eventName = null)
{
return $this->dispatcher->hasListeners($eventName);
}
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;
}
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;
}
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));
}
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;
}
public function __call($method, $arguments)
{
return call_user_func_array(array($this->dispatcher, $method), $arguments);
}
protected function preDispatch($eventName, Event $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) {
continue;
}
$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('Notified event "{event}" to listener "{listener}".', array('event' => $eventName, 'listener' => $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('Listener "{listener}" was not called for event "{event}".', array('listener' => $info['pretty'], 'event' => $eventName));
}
if ($listener->stoppedPropagation()) {
if (null !== $this->logger) {
$this->logger->debug('Listener "{listener}" stopped propagation of the event "{event}".', array('listener' => $info['pretty'], 'event' => $eventName));
}
$skipped = true;
}
}
}
private function getListenerInfo($listener, $eventName)
{
$info = array(
'event' => $eventName,
'priority' => $this->getListenerPriority($eventName, $listener),
);
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
namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
interface TraceableEventDispatcherInterface extends EventDispatcherInterface
{
public function getCalledListeners();
public function getNotCalledListeners();
}
<?php
namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
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
namespace Symfony\Component\EventDispatcher\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class RegisterListenersPass implements CompilerPassInterface
{
protected $dispatcherService;
protected $listenerTag;
protected $subscriberTag;
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));
}
$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));
}
}
}
<?php
namespace Symfony\Component\EventDispatcher;
class Event
{
private $propagationStopped = false;
public function isPropagationStopped()
{
return $this->propagationStopped;
}
public function stopPropagation()
{
$this->propagationStopped = true;
}
}
<?php
namespace Symfony\Component\EventDispatcher;
class EventDispatcher implements EventDispatcherInterface
{
private $listeners = array();
private $sorted = array();
public function dispatch($eventName, Event $event = null)
{
if (null === $event) {
$event = new Event();
}
if ($listeners = $this->getListeners($eventName)) {
$this->doDispatch($listeners, $eventName, $event);
}
return $event;
}
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);
}
public function getListenerPriority($eventName, $listener)
{
if (!isset($this->listeners[$eventName])) {
return;
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
if (false !== ($key = array_search($listener, $listeners, true))) {
return $priority;
}
}
}
public function hasListeners($eventName = null)
{
return (bool) count($this->getListeners($eventName));
}
public function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[$eventName][$priority][] = $listener;
unset($this->sorted[$eventName]);
}
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]);
}
}
}
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);
}
}
}
}
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]));
}
}
}
protected function doDispatch($listeners, $eventName, Event $event)
{
foreach ($listeners as $listener) {
if ($event->isPropagationStopped()) {
break;
}
call_user_func($listener, $event, $eventName, $this);
}
}
private function sortListeners($eventName)
{
krsort($this->listeners[$eventName]);
$this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]);
}
}
<?php
namespace Symfony\Component\EventDispatcher;
interface EventDispatcherInterface
{
public function dispatch($eventName, Event $event = null);
public function addListener($eventName, $listener, $priority = 0);
public function addSubscriber(EventSubscriberInterface $subscriber);
public function removeListener($eventName, $listener);
public function removeSubscriber(EventSubscriberInterface $subscriber);
public function getListeners($eventName = null);
public function getListenerPriority($eventName, $listener);
public function hasListeners($eventName = null);
}
<?php
namespace Symfony\Component\EventDispatcher;
interface EventSubscriberInterface
{
public static function getSubscribedEvents();
}
<?php
namespace Symfony\Component\EventDispatcher;
class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
{
protected $subject;
protected $arguments;
public function __construct($subject = null, array $arguments = array())
{
$this->subject = $subject;
$this->arguments = $arguments;
}
public function getSubject()
{
return $this->subject;
}
public function getArgument($key)
{
if ($this->hasArgument($key)) {
return $this->arguments[$key];
}
throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key));
}
public function setArgument($key, $value)
{
$this->arguments[$key] = $value;
return $this;
}
public function getArguments()
{
return $this->arguments;
}
public function setArguments(array $args = array())
{
$this->arguments = $args;
return $this;
}
public function hasArgument($key)
{
return array_key_exists($key, $this->arguments);
}
public function offsetGet($key)
{
return $this->getArgument($key);
}
public function offsetSet($key, $value)
{
$this->setArgument($key, $value);
}
public function offsetUnset($key)
{
if ($this->hasArgument($key)) {
unset($this->arguments[$key]);
}
}
public function offsetExists($key)
{
return $this->hasArgument($key);
}
public function getIterator()
{
return new \ArrayIterator($this->arguments);
}
}
<?php
namespace Symfony\Component\EventDispatcher;
class ImmutableEventDispatcher implements EventDispatcherInterface
{
private $dispatcher;
public function __construct(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function dispatch($eventName, Event $event = null)
{
return $this->dispatcher->dispatch($eventName, $event);
}
public function addListener($eventName, $listener, $priority = 0)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function removeListener($eventName, $listener)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
}
public function getListeners($eventName = null)
{
return $this->dispatcher->getListeners($eventName);
}
public function getListenerPriority($eventName, $listener)
{
return $this->dispatcher->getListenerPriority($eventName, $listener);
}
public function hasListeners($eventName = null)
{
return $this->dispatcher->hasListeners($eventName);
}
}
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src'),
'Guzzle\\Tests' => array($vendorDir . '/guzzle/guzzle/tests'),
'Guzzle' => array($vendorDir . '/guzzle/guzzle/src'),
);
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/type-resolver/src', $vendorDir . '/phpdocumentor/reflection-docblock/src'),
'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'),
'Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Symfony\\Component\\Config\\' => array($vendorDir . '/symfony/config'),
'Symfony\\CS\\' => array($baseDir . '/Symfony/CS'),
'Satooshi\\' => array($vendorDir . '/satooshi/php-coveralls/src/Satooshi'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
);
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'DeepCopy\\DeepCopy' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/DeepCopy.php',
'DeepCopy\\Exception\\CloneException' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineCollectionFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineCollectionFilter.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineEmptyCollectionFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php',
'DeepCopy\\Filter\\Filter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php',
'DeepCopy\\Filter\\KeepFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/KeepFilter.php',
'DeepCopy\\Filter\\ReplaceFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/ReplaceFilter.php',
'DeepCopy\\Filter\\SetNullFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.php',
'DeepCopy\\Matcher\\Matcher' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Matcher/Matcher.php',
'DeepCopy\\Matcher\\PropertyMatcher' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyMatcher.php',
'DeepCopy\\Matcher\\PropertyNameMatcher' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php',
'DeepCopy\\Matcher\\PropertyTypeMatcher' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.php',
'DeepCopy\\Reflection\\ReflectionHelper' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.php',
'DeepCopy\\TypeFilter\\ReplaceFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php',
'DeepCopy\\TypeFilter\\ShallowCopyFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php',
'DeepCopy\\TypeFilter\\TypeFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.php',
'DeepCopy\\TypeMatcher\\TypeMatcher' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/TypeMatcher/TypeMatcher.php',
'Doctrine\\Instantiator\\Exception\\ExceptionInterface' => $vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator/Exception/ExceptionInterface.php',
'Doctrine\\Instantiator\\Exception\\InvalidArgumentException' => $vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator/Exception/InvalidArgumentException.php',
'Doctrine\\Instantiator\\Exception\\UnexpectedValueException' => $vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator/Exception/UnexpectedValueException.php',
'Doctrine\\Instantiator\\Instantiator' => $vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator/Instantiator.php',
'Doctrine\\Instantiator\\InstantiatorInterface' => $vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator/InstantiatorInterface.php',
'File_Iterator' => $vendorDir . '/phpunit/php-file-iterator/src/Iterator.php',
'File_Iterator_Facade' => $vendorDir . '/phpunit/php-file-iterator/src/Facade.php',
'File_Iterator_Factory' => $vendorDir . '/phpunit/php-file-iterator/src/Factory.php',
'Guzzle\\Batch\\AbstractBatchDecorator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php',
'Guzzle\\Batch\\Batch' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/Batch.php',
'Guzzle\\Batch\\BatchBuilder' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.php',
'Guzzle\\Batch\\BatchClosureDivisor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php',
'Guzzle\\Batch\\BatchClosureTransfer' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php',
'Guzzle\\Batch\\BatchCommandTransfer' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php',
'Guzzle\\Batch\\BatchDivisorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php',
'Guzzle\\Batch\\BatchInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchInterface.php',
'Guzzle\\Batch\\BatchRequestTransfer' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchRequestTransfer.php',
'Guzzle\\Batch\\BatchSizeDivisor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php',
'Guzzle\\Batch\\BatchTransferInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.php',
'Guzzle\\Batch\\ExceptionBufferingBatch' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php',
'Guzzle\\Batch\\Exception\\BatchTransferException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/Exception/BatchTransferException.php',
'Guzzle\\Batch\\FlushingBatch' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php',
'Guzzle\\Batch\\HistoryBatch' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.php',
'Guzzle\\Batch\\NotifyingBatch' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php',
'Guzzle\\Cache\\AbstractCacheAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php',
'Guzzle\\Cache\\CacheAdapterFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php',
'Guzzle\\Cache\\CacheAdapterInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.php',
'Guzzle\\Cache\\ClosureCacheAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/ClosureCacheAdapter.php',
'Guzzle\\Cache\\DoctrineCacheAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.php',
'Guzzle\\Cache\\NullCacheAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php',
'Guzzle\\Cache\\Zf1CacheAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/Zf1CacheAdapter.php',
'Guzzle\\Cache\\Zf2CacheAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.php',
'Guzzle\\Common\\AbstractHasDispatcher' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php',
'Guzzle\\Common\\Collection' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Collection.php',
'Guzzle\\Common\\Event' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Event.php',
'Guzzle\\Common\\Exception\\BadMethodCallException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php',
'Guzzle\\Common\\Exception\\ExceptionCollection' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Exception/ExceptionCollection.php',
'Guzzle\\Common\\Exception\\GuzzleException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.php',
'Guzzle\\Common\\Exception\\InvalidArgumentException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Exception/InvalidArgumentException.php',
'Guzzle\\Common\\Exception\\RuntimeException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Exception/RuntimeException.php',
'Guzzle\\Common\\Exception\\UnexpectedValueException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Exception/UnexpectedValueException.php',
'Guzzle\\Common\\FromConfigInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/FromConfigInterface.php',
'Guzzle\\Common\\HasDispatcherInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/HasDispatcherInterface.php',
'Guzzle\\Common\\ToArrayInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/ToArrayInterface.php',
'Guzzle\\Common\\Version' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Common/Version.php',
'Guzzle\\Http\\AbstractEntityBodyDecorator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.php',
'Guzzle\\Http\\CachingEntityBody' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.php',
'Guzzle\\Http\\Client' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Client.php',
'Guzzle\\Http\\ClientInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php',
'Guzzle\\Http\\Curl\\CurlHandle' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlHandle.php',
'Guzzle\\Http\\Curl\\CurlMulti' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php',
'Guzzle\\Http\\Curl\\CurlMultiInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php',
'Guzzle\\Http\\Curl\\CurlMultiProxy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiProxy.php',
'Guzzle\\Http\\Curl\\CurlVersion' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php',
'Guzzle\\Http\\Curl\\RequestMediator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php',
'Guzzle\\Http\\EntityBody' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/EntityBody.php',
'Guzzle\\Http\\EntityBodyInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php',
'Guzzle\\Http\\Exception\\BadResponseException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/BadResponseException.php',
'Guzzle\\Http\\Exception\\ClientErrorResponseException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.php',
'Guzzle\\Http\\Exception\\CouldNotRewindStreamException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/CouldNotRewindStreamException.php',
'Guzzle\\Http\\Exception\\CurlException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/CurlException.php',
'Guzzle\\Http\\Exception\\HttpException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php',
'Guzzle\\Http\\Exception\\MultiTransferException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/MultiTransferException.php',
'Guzzle\\Http\\Exception\\RequestException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php',
'Guzzle\\Http\\Exception\\ServerErrorResponseException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.php',
'Guzzle\\Http\\Exception\\TooManyRedirectsException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Exception/TooManyRedirectsException.php',
'Guzzle\\Http\\IoEmittingEntityBody' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/IoEmittingEntityBody.php',
'Guzzle\\Http\\Message\\AbstractMessage' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php',
'Guzzle\\Http\\Message\\EntityEnclosingRequest' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php',
'Guzzle\\Http\\Message\\EntityEnclosingRequestInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php',
'Guzzle\\Http\\Message\\Header' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header.php',
'Guzzle\\Http\\Message\\Header\\CacheControl' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.php',
'Guzzle\\Http\\Message\\Header\\HeaderCollection' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php',
'Guzzle\\Http\\Message\\Header\\HeaderFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php',
'Guzzle\\Http\\Message\\Header\\HeaderFactoryInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php',
'Guzzle\\Http\\Message\\Header\\HeaderInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderInterface.php',
'Guzzle\\Http\\Message\\Header\\Link' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/Link.php',
'Guzzle\\Http\\Message\\MessageInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php',
'Guzzle\\Http\\Message\\PostFile' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/PostFile.php',
'Guzzle\\Http\\Message\\PostFileInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.php',
'Guzzle\\Http\\Message\\Request' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Request.php',
'Guzzle\\Http\\Message\\RequestFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php',
'Guzzle\\Http\\Message\\RequestFactoryInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php',
'Guzzle\\Http\\Message\\RequestInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/RequestInterface.php',
'Guzzle\\Http\\Message\\Response' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Message/Response.php',
'Guzzle\\Http\\Mimetypes' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Mimetypes.php',
'Guzzle\\Http\\QueryAggregator\\CommaAggregator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.php',
'Guzzle\\Http\\QueryAggregator\\DuplicateAggregator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.php',
'Guzzle\\Http\\QueryAggregator\\PhpAggregator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php',
'Guzzle\\Http\\QueryAggregator\\QueryAggregatorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php',
'Guzzle\\Http\\QueryString' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/QueryString.php',
'Guzzle\\Http\\ReadLimitEntityBody' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php',
'Guzzle\\Http\\RedirectPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php',
'Guzzle\\Http\\StaticClient' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/StaticClient.php',
'Guzzle\\Http\\Url' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Http/Url.php',
'Guzzle\\Inflection\\Inflector' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Inflection/Inflector.php',
'Guzzle\\Inflection\\InflectorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Inflection/InflectorInterface.php',
'Guzzle\\Inflection\\MemoizingInflector' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Inflection/MemoizingInflector.php',
'Guzzle\\Inflection\\PreComputedInflector' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.php',
'Guzzle\\Iterator\\AppendIterator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.php',
'Guzzle\\Iterator\\ChunkedIterator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php',
'Guzzle\\Iterator\\FilterIterator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.php',
'Guzzle\\Iterator\\MapIterator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.php',
'Guzzle\\Iterator\\MethodProxyIterator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php',
'Guzzle\\Log\\AbstractLogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php',
'Guzzle\\Log\\ArrayLogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php',
'Guzzle\\Log\\ClosureLogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php',
'Guzzle\\Log\\LogAdapterInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php',
'Guzzle\\Log\\MessageFormatter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/MessageFormatter.php',
'Guzzle\\Log\\MonologLogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php',
'Guzzle\\Log\\PsrLogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.php',
'Guzzle\\Log\\Zf1LogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.php',
'Guzzle\\Log\\Zf2LogAdapter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php',
'Guzzle\\Parser\\Cookie\\CookieParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php',
'Guzzle\\Parser\\Cookie\\CookieParserInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php',
'Guzzle\\Parser\\Message\\AbstractMessageParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Message/AbstractMessageParser.php',
'Guzzle\\Parser\\Message\\MessageParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php',
'Guzzle\\Parser\\Message\\MessageParserInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php',
'Guzzle\\Parser\\Message\\PeclHttpMessageParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Message/PeclHttpMessageParser.php',
'Guzzle\\Parser\\ParserRegistry' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php',
'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php',
'Guzzle\\Parser\\UriTemplate\\UriTemplate' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplate.php',
'Guzzle\\Parser\\UriTemplate\\UriTemplateInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php',
'Guzzle\\Parser\\Url\\UrlParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParser.php',
'Guzzle\\Parser\\Url\\UrlParserInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.php',
'Guzzle\\Plugin\\Async\\AsyncPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php',
'Guzzle\\Plugin\\Backoff\\AbstractBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\AbstractErrorCodeBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\BackoffLogger' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.php',
'Guzzle\\Plugin\\Backoff\\BackoffPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php',
'Guzzle\\Plugin\\Backoff\\BackoffStrategyInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php',
'Guzzle\\Plugin\\Backoff\\CallbackBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\ConstantBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\CurlBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\ExponentialBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\HttpBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\LinearBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\ReasonPhraseBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\TruncatedBackoffStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php',
'Guzzle\\Plugin\\Cache\\CacheKeyProviderInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php',
'Guzzle\\Plugin\\Cache\\CachePlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CachePlugin.php',
'Guzzle\\Plugin\\Cache\\CacheStorageInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php',
'Guzzle\\Plugin\\Cache\\CallbackCanCacheStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.php',
'Guzzle\\Plugin\\Cache\\CanCacheStrategyInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php',
'Guzzle\\Plugin\\Cache\\DefaultCacheKeyProvider' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.php',
'Guzzle\\Plugin\\Cache\\DefaultCacheStorage' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php',
'Guzzle\\Plugin\\Cache\\DefaultCanCacheStrategy' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php',
'Guzzle\\Plugin\\Cache\\DefaultRevalidation' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php',
'Guzzle\\Plugin\\Cache\\DenyRevalidation' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php',
'Guzzle\\Plugin\\Cache\\RevalidationInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/RevalidationInterface.php',
'Guzzle\\Plugin\\Cache\\SkipRevalidation' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/SkipRevalidation.php',
'Guzzle\\Plugin\\Cookie\\Cookie' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php',
'Guzzle\\Plugin\\Cookie\\CookieJar\\ArrayCookieJar' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php',
'Guzzle\\Plugin\\Cookie\\CookieJar\\CookieJarInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php',
'Guzzle\\Plugin\\Cookie\\CookieJar\\FileCookieJar' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php',
'Guzzle\\Plugin\\Cookie\\CookiePlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.php',
'Guzzle\\Plugin\\Cookie\\Exception\\InvalidCookieException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php',
'Guzzle\\Plugin\\CurlAuth\\CurlAuthPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.php',
'Guzzle\\Plugin\\ErrorResponse\\ErrorResponseExceptionInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php',
'Guzzle\\Plugin\\ErrorResponse\\ErrorResponsePlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.php',
'Guzzle\\Plugin\\ErrorResponse\\Exception\\ErrorResponseException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php',
'Guzzle\\Plugin\\History\\HistoryPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.php',
'Guzzle\\Plugin\\Log\\LogPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.php',
'Guzzle\\Plugin\\Md5\\CommandContentMd5Plugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php',
'Guzzle\\Plugin\\Md5\\Md5ValidatorPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php',
'Guzzle\\Plugin\\Mock\\MockPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.php',
'Guzzle\\Plugin\\Oauth\\OauthPlugin' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php',
'Guzzle\\Service\\AbstractConfigLoader' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php',
'Guzzle\\Service\\Builder\\ServiceBuilder' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.php',
'Guzzle\\Service\\Builder\\ServiceBuilderInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.php',
'Guzzle\\Service\\Builder\\ServiceBuilderLoader' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderLoader.php',
'Guzzle\\Service\\CachingConfigLoader' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php',
'Guzzle\\Service\\Client' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Client.php',
'Guzzle\\Service\\ClientInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php',
'Guzzle\\Service\\Command\\AbstractCommand' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/AbstractCommand.php',
'Guzzle\\Service\\Command\\ClosureCommand' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php',
'Guzzle\\Service\\Command\\CommandInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.php',
'Guzzle\\Service\\Command\\CreateResponseClassEvent' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/CreateResponseClassEvent.php',
'Guzzle\\Service\\Command\\DefaultRequestSerializer' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.php',
'Guzzle\\Service\\Command\\DefaultResponseParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.php',
'Guzzle\\Service\\Command\\Factory\\AliasFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.php',
'Guzzle\\Service\\Command\\Factory\\CompositeFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.php',
'Guzzle\\Service\\Command\\Factory\\ConcreteClassFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php',
'Guzzle\\Service\\Command\\Factory\\FactoryInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.php',
'Guzzle\\Service\\Command\\Factory\\MapFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/MapFactory.php',
'Guzzle\\Service\\Command\\Factory\\ServiceDescriptionFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\AbstractRequestVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\BodyVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\HeaderVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\JsonVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\PostFieldVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\PostFileVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\QueryVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\RequestVisitorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\ResponseBodyVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\XmlVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\AbstractResponseVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\BodyVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\HeaderVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\JsonVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\ReasonPhraseVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\ResponseVisitorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\StatusCodeVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\XmlVisitor' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\VisitorFlyweight' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php',
'Guzzle\\Service\\Command\\OperationCommand' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php',
'Guzzle\\Service\\Command\\OperationResponseParser' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php',
'Guzzle\\Service\\Command\\RequestSerializerInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.php',
'Guzzle\\Service\\Command\\ResponseClassInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/ResponseClassInterface.php',
'Guzzle\\Service\\Command\\ResponseParserInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Command/ResponseParserInterface.php',
'Guzzle\\Service\\ConfigLoaderInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/ConfigLoaderInterface.php',
'Guzzle\\Service\\Description\\Operation' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/Operation.php',
'Guzzle\\Service\\Description\\OperationInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php',
'Guzzle\\Service\\Description\\Parameter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/Parameter.php',
'Guzzle\\Service\\Description\\SchemaFormatter' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.php',
'Guzzle\\Service\\Description\\SchemaValidator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php',
'Guzzle\\Service\\Description\\ServiceDescription' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php',
'Guzzle\\Service\\Description\\ServiceDescriptionInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.php',
'Guzzle\\Service\\Description\\ServiceDescriptionLoader' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionLoader.php',
'Guzzle\\Service\\Description\\ValidatorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php',
'Guzzle\\Service\\Exception\\CommandException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/CommandException.php',
'Guzzle\\Service\\Exception\\CommandTransferException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/CommandTransferException.php',
'Guzzle\\Service\\Exception\\DescriptionBuilderException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php',
'Guzzle\\Service\\Exception\\InconsistentClientTransferException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/InconsistentClientTransferException.php',
'Guzzle\\Service\\Exception\\ResponseClassException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php',
'Guzzle\\Service\\Exception\\ServiceBuilderException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceBuilderException.php',
'Guzzle\\Service\\Exception\\ServiceNotFoundException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceNotFoundException.php',
'Guzzle\\Service\\Exception\\ValidationException' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Exception/ValidationException.php',
'Guzzle\\Service\\Resource\\AbstractResourceIteratorFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php',
'Guzzle\\Service\\Resource\\CompositeResourceIteratorFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php',
'Guzzle\\Service\\Resource\\MapResourceIteratorFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.php',
'Guzzle\\Service\\Resource\\Model' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php',
'Guzzle\\Service\\Resource\\ResourceIterator' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php',
'Guzzle\\Service\\Resource\\ResourceIteratorApplyBatched' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php',
'Guzzle\\Service\\Resource\\ResourceIteratorClassFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php',
'Guzzle\\Service\\Resource\\ResourceIteratorFactoryInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php',
'Guzzle\\Service\\Resource\\ResourceIteratorInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorInterface.php',
'Guzzle\\Stream\\PhpStreamRequestFactory' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php',
'Guzzle\\Stream\\Stream' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Stream/Stream.php',
'Guzzle\\Stream\\StreamInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php',
'Guzzle\\Stream\\StreamRequestFactoryInterface' => $vendorDir . '/guzzle/guzzle/src/Guzzle/Stream/StreamRequestFactoryInterface.php',
'Guzzle\\Tests\\Batch\\AbstractBatchDecoratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/AbstractBatchDecoratorTest.php',
'Guzzle\\Tests\\Batch\\BatchBuilderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchBuilderTest.php',
'Guzzle\\Tests\\Batch\\BatchClosureDivisorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureDivisorTest.php',
'Guzzle\\Tests\\Batch\\BatchClosureTransferTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureTransferTest.php',
'Guzzle\\Tests\\Batch\\BatchCommandTransferTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchCommandTransferTest.php',
'Guzzle\\Tests\\Batch\\BatchRequestTransferTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchRequestTransferTest.php',
'Guzzle\\Tests\\Batch\\BatchSizeDivisorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchSizeDivisorTest.php',
'Guzzle\\Tests\\Batch\\BatchTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchTest.php',
'Guzzle\\Tests\\Batch\\ExceptionBufferingBatchTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/ExceptionBufferingBatchTest.php',
'Guzzle\\Tests\\Batch\\FlushingBatchTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/FlushingBatchTest.php',
'Guzzle\\Tests\\Batch\\HistoryBatchTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/HistoryBatchTest.php',
'Guzzle\\Tests\\Batch\\NotifyingBatchTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/NotifyingBatchTest.php',
'Guzzle\\Tests\\Cache\\CacheAdapterFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterFactoryTest.php',
'Guzzle\\Tests\\Cache\\CacheAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterTest.php',
'Guzzle\\Tests\\Cache\\ClosureCacheAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/ClosureCacheAdapterTest.php',
'Guzzle\\Tests\\Cache\\Zf2CacheAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/Zf2CacheAdapterTest.php',
'Guzzle\\Tests\\Common\\AbstractHasAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Common/AbstractHasDispatcherTest.php',
'Guzzle\\Tests\\Common\\Cache\\NullCacheAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/NullCacheAdapterTest.php',
'Guzzle\\Tests\\Common\\CollectionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Common/CollectionTest.php',
'Guzzle\\Tests\\Common\\EventTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Common/EventTest.php',
'Guzzle\\Tests\\Common\\Exception\\BatchTransferExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/BatchTransferExceptionTest.php',
'Guzzle\\Tests\\Common\\Exception\\ExceptionCollectionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php',
'Guzzle\\Tests\\Common\\VersionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Common/VersionTest.php',
'Guzzle\\Tests\\GuzzleTestCase' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/GuzzleTestCase.php',
'Guzzle\\Tests\\Http\\AbstractEntityBodyDecoratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/AbstractEntityBodyDecoratorTest.php',
'Guzzle\\Tests\\Http\\CachingEntityBodyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/CachingEntityBodyTest.php',
'Guzzle\\Tests\\Http\\ClientTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/ClientTest.php',
'Guzzle\\Tests\\Http\\CommaAggregatorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/CommaAggregatorTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlHandleTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlHandleTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlMultiProxyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiProxyTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlMultiTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlVersionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlVersionTest.php',
'Guzzle\\Tests\\Http\\Curl\\RequestMediatorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/RequestMediatorTest.php',
'Guzzle\\Tests\\Http\\DuplicateAggregatorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/DuplicateAggregatorTest.php',
'Guzzle\\Tests\\Http\\EntityBodyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/EntityBodyTest.php',
'Guzzle\\Tests\\Http\\Exception\\CurlExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/CurlExceptionTest.php',
'Guzzle\\Tests\\Http\\Exception\\ExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/ExceptionTest.php',
'Guzzle\\Tests\\Http\\Exception\\MultiTransferExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/MultiTransferExceptionTest.php',
'Guzzle\\Tests\\Http\\IoEmittingEntityBodyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/IoEmittingEntityBodyTest.php',
'Guzzle\\Tests\\Http\\Message\\AbstractMessageTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/AbstractMessageTest.php',
'Guzzle\\Tests\\Http\\Message\\EntityEnclosingRequestTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/EntityEnclosingRequestTest.php',
'Guzzle\\Tests\\Http\\Message\\HeaderComparison' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php',
'Guzzle\\Tests\\Http\\Message\\HeaderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderTest.php',
'Guzzle\\Tests\\Http\\Message\\Header\\HeaderFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/HeaderFactoryTest.php',
'Guzzle\\Tests\\Http\\Message\\Header\\LinkTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/LinkTest.php',
'Guzzle\\Tests\\Http\\Message\\HttpRequestFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestFactoryTest.php',
'Guzzle\\Tests\\Http\\Message\\PostFileTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/PostFileTest.php',
'Guzzle\\Tests\\Http\\Message\\RequestTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestTest.php',
'Guzzle\\Tests\\Http\\MimetypesTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/MimetypesTest.php',
'Guzzle\\Tests\\Http\\PhpAggregatorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/PhpAggregatorTest.php',
'Guzzle\\Tests\\Http\\QueryStringTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryStringTest.php',
'Guzzle\\Tests\\Http\\ReadLimitEntityBodyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/ReadLimitEntityBodyTest.php',
'Guzzle\\Tests\\Http\\Server' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.php',
'Guzzle\\Tests\\Http\\UrlTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php',
'Guzzle\\Tests\\Inflection\\InflectorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Inflection/InflectorTest.php',
'Guzzle\\Tests\\Inflection\\MemoizingInflectorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Inflection/MemoizingInflectorTest.php',
'Guzzle\\Tests\\Inflection\\PreComputedInflectorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Inflection/PreComputedInflectorTest.php',
'Guzzle\\Tests\\Iterator\\AppendIteratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/AppendIteratorTest.php',
'Guzzle\\Tests\\Iterator\\ChunkedIteratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/ChunkedIteratorTest.php',
'Guzzle\\Tests\\Iterator\\FilterIteratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/FilterIteratorTest.php',
'Guzzle\\Tests\\Iterator\\MapIteratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MapIteratorTest.php',
'Guzzle\\Tests\\Iterator\\MethodProxyIteratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MethodProxyIteratorTest.php',
'Guzzle\\Tests\\Log\\ArrayLogAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Log/ArrayLogAdapterTest.php',
'Guzzle\\Tests\\Log\\ClosureLogAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Log/ClosureLogAdapterTest.php',
'Guzzle\\Tests\\Log\\MessageFormatterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Log/MessageFormatterTest.php',
'Guzzle\\Tests\\Log\\PsrLogAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Log/PsrLogAdapterTest.php',
'Guzzle\\Tests\\Log\\Zf2LogAdapterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Log/Zf2LogAdapterTest.php',
'Guzzle\\Tests\\Message\\HeaderComparisonTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparisonTest.php',
'Guzzle\\Tests\\Message\\ResponseTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/ResponseTest.php',
'Guzzle\\Tests\\Mock\\CustomResponseModel' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/CustomResponseModel.php',
'Guzzle\\Tests\\Mock\\ErrorResponseMock' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/ErrorResponseMock.php',
'Guzzle\\Tests\\Mock\\ExceptionMock' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/ExceptionMock.php',
'Guzzle\\Tests\\Mock\\MockMulti' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockMulti.php',
'Guzzle\\Tests\\Mock\\MockObserver' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockObserver.php',
'Guzzle\\Tests\\Mock\\MockSubject' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockSubject.php',
'Guzzle\\Tests\\Parser\\Cookie\\CookieParserProvider' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserProvider.php',
'Guzzle\\Tests\\Parser\\Cookie\\CookieParserTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserTest.php',
'Guzzle\\Tests\\Parser\\Message\\MessageParserProvider' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.php',
'Guzzle\\Tests\\Parser\\Message\\MessageParserTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserTest.php',
'Guzzle\\Tests\\Parser\\Message\\PeclHttpMessageParserTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/PeclHttpMessageParserTest.php',
'Guzzle\\Tests\\Parser\\ParserRegistryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/ParserRegistryTest.php',
'Guzzle\\Tests\\Parsers\\UriTemplate\\AbstractUriTemplateTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/AbstractUriTemplateTest.php',
'Guzzle\\Tests\\Parsers\\UriTemplate\\PeclUriTemplateTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/PeclUriTemplateTest.php',
'Guzzle\\Tests\\Parsers\\UriTemplate\\UriTemplateTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/UriTemplateTest.php',
'Guzzle\\Tests\\Plugin\\Async\\AsyncPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Async/AsyncPluginTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\AbstractBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/AbstractBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\BackoffLoggerTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffLoggerTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\BackoffPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffPluginTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\CallbackBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CallbackBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\ConstantBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ConstantBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\CurlBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CurlBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\ExponentialBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ExponentialBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\HttpBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/HttpBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\LinearBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/LinearBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\ReasonPhraseBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ReasonPhraseBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\TruncatedBackoffStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/TruncatedBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\CachePluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CachePluginTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\CallbackCanCacheStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CallbackCanCacheStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DefaultCacheStorageTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCacheStorageTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DefaultCanCacheStrategyTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCanCacheStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DefaultRevalidationTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultRevalidationTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DenyRevalidationTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DenyRevalidationTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\SkipRevalidationTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/SkipRevalidationTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookieJar\\ArrayCookieJarTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/ArrayCookieJarTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookieJar\\FileCookieJarTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/FileCookieJarTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookiePluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookiePluginTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookieTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieTest.php',
'Guzzle\\Tests\\Plugin\\CurlAuth\\CurlAuthPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/CurlAuth/CurlAuthPluginTest.php',
'Guzzle\\Tests\\Plugin\\ErrorResponse\\ErrorResponsePluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/ErrorResponse/ErrorResponsePluginTest.php',
'Guzzle\\Tests\\Plugin\\History\\HistoryPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/History/HistoryPluginTest.php',
'Guzzle\\Tests\\Plugin\\Log\\LogPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Log/LogPluginTest.php',
'Guzzle\\Tests\\Plugin\\Md5\\CommandContentMd5PluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/CommandContentMd5PluginTest.php',
'Guzzle\\Tests\\Plugin\\Md5\\Md5ValidatorPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/Md5ValidatorPluginTest.php',
'Guzzle\\Tests\\Plugin\\Mock\\MockPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Mock/MockPluginTest.php',
'Guzzle\\Tests\\Plugin\\Oauth\\OauthPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Oauth/OauthPluginTest.php',
'Guzzle\\Tests\\Plugin\\Redirect\\RedirectPluginTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/RedirectPluginTest.php',
'Guzzle\\Tests\\Plugin\\Redirect\\StaticClientTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/StaticClientTest.php',
'Guzzle\\Tests\\Service\\AbstractConfigLoaderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/AbstractConfigLoaderTest.php',
'Guzzle\\Tests\\Service\\Builder\\ServiceBuilderLoaderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderLoaderTest.php',
'Guzzle\\Tests\\Service\\CachingConfigLoaderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/CachingConfigLoaderTest.php',
'Guzzle\\Tests\\Service\\ClientTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/ClientTest.php',
'Guzzle\\Tests\\Service\\Command\\AbstractCommandTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/AbstractCommandTest.php',
'Guzzle\\Tests\\Service\\Command\\AliasFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/AliasFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\ClosureCommandTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/ClosureCommandTest.php',
'Guzzle\\Tests\\Service\\Command\\CommandTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/CommandTest.php',
'Guzzle\\Tests\\Service\\Command\\CompositeFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/CompositeFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\ConcreteClassFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ConcreteClassFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\DefaultRequestSerializerTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultRequestSerializerTest.php',
'Guzzle\\Tests\\Service\\Command\\DefaultResponseParserTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultResponseParserTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\AbstractVisitorTestCase' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\BodyVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/BodyVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\HeaderVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/HeaderVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\JsonVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/JsonVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\PostFieldVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFieldVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\PostFileVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFileVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\QueryVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/QueryVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\ResponseBodyVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/ResponseBodyVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\XmlVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/XmlVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\AbstractResponseVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/AbstractResponseVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\BodyVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/BodyVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\HeaderVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/HeaderVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\JsonVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/JsonVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\ReasonPhraseVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/ReasonPhraseVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\StatusCodeVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/StatusCodeVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\XmlVisitorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/XmlVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\MapFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/MapFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\OperationCommandTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationCommandTest.php',
'Guzzle\\Tests\\Service\\Command\\OperationResponseParserTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationResponseParserTest.php',
'Guzzle\\Tests\\Service\\Command\\ServiceDescriptionFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ServiceDescriptionFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\VisitorFlyweightTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/VisitorFlyweightTest.php',
'Guzzle\\Tests\\Service\\Description\\OperationTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/OperationTest.php',
'Guzzle\\Tests\\Service\\Description\\ParameterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ParameterTest.php',
'Guzzle\\Tests\\Service\\Description\\SchemaFormatterTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaFormatterTest.php',
'Guzzle\\Tests\\Service\\Description\\SchemaValidatorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaValidatorTest.php',
'Guzzle\\Tests\\Service\\Description\\ServiceDescriptionLoaderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionLoaderTest.php',
'Guzzle\\Tests\\Service\\Description\\ServiceDescriptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionTest.php',
'Guzzle\\Tests\\Service\\Exception\\CommandTransferExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/CommandTransferExceptionTest.php',
'Guzzle\\Tests\\Service\\Exception\\InconsistentClientTransferExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/InconsistentClientTransferExceptionTest.php',
'Guzzle\\Tests\\Service\\Exception\\ValidationExceptionTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/ValidationExceptionTest.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\IterableCommand' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/IterableCommand.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/MockCommand.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\OtherCommand' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/OtherCommand.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\Sub\\Sub' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/Sub/Sub.php',
'Guzzle\\Tests\\Service\\Mock\\MockClient' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/MockClient.php',
'Guzzle\\Tests\\Service\\Mock\\Model\\MockCommandIterator' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Model/MockCommandIterator.php',
'Guzzle\\Tests\\Service\\Resource\\CompositeResourceIteratorFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/CompositeResourceIteratorFactoryTest.php',
'Guzzle\\Tests\\Service\\Resource\\MapResourceIteratorFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/MapResourceIteratorFactoryTest.php',
'Guzzle\\Tests\\Service\\Resource\\ModelTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ModelTest.php',
'Guzzle\\Tests\\Service\\Resource\\ResourceIteratorClassFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorClassFactoryTest.php',
'Guzzle\\Tests\\Service\\Resource\\ResourceIteratorTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorTest.php',
'Guzzle\\Tests\\Service\\ServiceBuilderTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderTest.php',
'Guzzle\\Tests\\Stream\\PhpStreamRequestFactoryTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Stream/PhpStreamRequestFactoryTest.php',
'Guzzle\\Tests\\Stream\\StreamTest' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Stream/StreamTest.php',
'PHPUnit\\Framework\\TestCase' => $vendorDir . '/phpunit/phpunit/src/ForwardCompatibility/TestCase.php',
'PHPUnit_Exception' => $vendorDir . '/phpunit/phpunit/src/Exception.php',
'PHPUnit_Extensions_GroupTestSuite' => $vendorDir . '/phpunit/phpunit/src/Extensions/GroupTestSuite.php',
'PHPUnit_Extensions_PhptTestCase' => $vendorDir . '/phpunit/phpunit/src/Extensions/PhptTestCase.php',
'PHPUnit_Extensions_PhptTestSuite' => $vendorDir . '/phpunit/phpunit/src/Extensions/PhptTestSuite.php',
'PHPUnit_Extensions_RepeatedTest' => $vendorDir . '/phpunit/phpunit/src/Extensions/RepeatedTest.php',
'PHPUnit_Extensions_TestDecorator' => $vendorDir . '/phpunit/phpunit/src/Extensions/TestDecorator.php',
'PHPUnit_Extensions_TicketListener' => $vendorDir . '/phpunit/phpunit/src/Extensions/TicketListener.php',
'PHPUnit_Framework_Assert' => $vendorDir . '/phpunit/phpunit/src/Framework/Assert.php',
'PHPUnit_Framework_AssertionFailedError' => $vendorDir . '/phpunit/phpunit/src/Framework/AssertionFailedError.php',
'PHPUnit_Framework_BaseTestListener' => $vendorDir . '/phpunit/phpunit/src/Framework/BaseTestListener.php',
'PHPUnit_Framework_CodeCoverageException' => $vendorDir . '/phpunit/phpunit/src/Framework/CodeCoverageException.php',
'PHPUnit_Framework_Constraint' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint.php',
'PHPUnit_Framework_Constraint_And' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/And.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_Count' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Count.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_ExceptionMessageRegExp' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegExp.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_IsTrue' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsTrue.php',
'PHPUnit_Framework_Constraint_IsType' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsType.php',
'PHPUnit_Framework_Constraint_JsonMatches' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php',
'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches/ErrorMessageProvider.php',
'PHPUnit_Framework_Constraint_LessThan' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LessThan.php',
'PHPUnit_Framework_Constraint_Not' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Not.php',
'PHPUnit_Framework_Constraint_ObjectHasAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php',
'PHPUnit_Framework_Constraint_Or' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Or.php',
'PHPUnit_Framework_Constraint_PCREMatch' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/PCREMatch.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_StringMatches' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringMatches.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_TraversableContainsOnly' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php',
'PHPUnit_Framework_Constraint_Xor' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Xor.php',
'PHPUnit_Framework_CoveredCodeNotExecutedException' => $vendorDir . '/phpunit/phpunit/src/Framework/PHPUnit_Framework_CoveredCodeNotExecutedException.php',
'PHPUnit_Framework_Error' => $vendorDir . '/phpunit/phpunit/src/Framework/Error.php',
'PHPUnit_Framework_Error_Deprecated' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Deprecated.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.php',
'PHPUnit_Framework_ExceptionWrapper' => $vendorDir . '/phpunit/phpunit/src/Framework/ExceptionWrapper.php',
'PHPUnit_Framework_ExpectationFailedException' => $vendorDir . '/phpunit/phpunit/src/Framework/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/IncompleteTestError.php',
'PHPUnit_Framework_InvalidCoversTargetException' => $vendorDir . '/phpunit/phpunit/src/Framework/InvalidCoversTargetException.php',
'PHPUnit_Framework_MissingCoversAnnotationException' => $vendorDir . '/phpunit/phpunit/src/Framework/PHPUnit_Framework_MissingCoversAnnotationException.php',
'PHPUnit_Framework_MockObject_BadMethodCallException' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/BadMethodCallException.php',
'PHPUnit_Framework_MockObject_Builder_Identity' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Identity.php',
'PHPUnit_Framework_MockObject_Builder_InvocationMocker' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/InvocationMocker.php',
'PHPUnit_Framework_MockObject_Builder_Match' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Match.php',
'PHPUnit_Framework_MockObject_Builder_MethodNameMatch' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/MethodNameMatch.php',
'PHPUnit_Framework_MockObject_Builder_Namespace' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Namespace.php',
'PHPUnit_Framework_MockObject_Builder_ParametersMatch' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/ParametersMatch.php',
'PHPUnit_Framework_MockObject_Builder_Stub' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Stub.php',
'PHPUnit_Framework_MockObject_Exception' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/Exception.php',
'PHPUnit_Framework_MockObject_Generator' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php',
'PHPUnit_Framework_MockObject_Invocation' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation.php',
'PHPUnit_Framework_MockObject_InvocationMocker' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/InvocationMocker.php',
'PHPUnit_Framework_MockObject_Invocation_Object' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Object.php',
'PHPUnit_Framework_MockObject_Invocation_Static' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Static.php',
'PHPUnit_Framework_MockObject_Invokable' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invokable.php',
'PHPUnit_Framework_MockObject_Matcher' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher.php',
'PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyInvokedCount.php',
'PHPUnit_Framework_MockObject_Matcher_AnyParameters' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyParameters.php',
'PHPUnit_Framework_MockObject_Matcher_ConsecutiveParameters' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/ConsecutiveParameters.php',
'PHPUnit_Framework_MockObject_Matcher_Invocation' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Invocation.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtIndex.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastCount.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastOnce.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtMostCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtMostCount.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedCount.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedRecorder' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedRecorder.php',
'PHPUnit_Framework_MockObject_Matcher_MethodName' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/MethodName.php',
'PHPUnit_Framework_MockObject_Matcher_Parameters' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Parameters.php',
'PHPUnit_Framework_MockObject_Matcher_StatelessInvocation' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/StatelessInvocation.php',
'PHPUnit_Framework_MockObject_MockBuilder' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockBuilder.php',
'PHPUnit_Framework_MockObject_MockObject' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockObject.php',
'PHPUnit_Framework_MockObject_RuntimeException' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/RuntimeException.php',
'PHPUnit_Framework_MockObject_Stub' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub.php',
'PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ConsecutiveCalls.php',
'PHPUnit_Framework_MockObject_Stub_Exception' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Exception.php',
'PHPUnit_Framework_MockObject_Stub_MatcherCollection' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/MatcherCollection.php',
'PHPUnit_Framework_MockObject_Stub_Return' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Return.php',
'PHPUnit_Framework_MockObject_Stub_ReturnArgument' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnArgument.php',
'PHPUnit_Framework_MockObject_Stub_ReturnCallback' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnCallback.php',
'PHPUnit_Framework_MockObject_Stub_ReturnReference' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnReference.php',
'PHPUnit_Framework_MockObject_Stub_ReturnSelf' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnSelf.php',
'PHPUnit_Framework_MockObject_Stub_ReturnValueMap' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnValueMap.php',
'PHPUnit_Framework_MockObject_Verifiable' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Verifiable.php',
'PHPUnit_Framework_OutputError' => $vendorDir . '/phpunit/phpunit/src/Framework/OutputError.php',
'PHPUnit_Framework_RiskyTest' => $vendorDir . '/phpunit/phpunit/src/Framework/RiskyTest.php',
'PHPUnit_Framework_RiskyTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/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/SkippedTestError.php',
'PHPUnit_Framework_SkippedTestSuiteError' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTestSuiteError.php',
'PHPUnit_Framework_SyntheticError' => $vendorDir . '/phpunit/phpunit/src/Framework/SyntheticError.php',
'PHPUnit_Framework_Test' => $vendorDir . '/phpunit/phpunit/src/Framework/Test.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_TestResult' => $vendorDir . '/phpunit/phpunit/src/Framework/TestResult.php',
'PHPUnit_Framework_TestSuite' => $vendorDir . '/phpunit/phpunit/src/Framework/TestSuite.php',
'PHPUnit_Framework_TestSuite_DataProvider' => $vendorDir . '/phpunit/phpunit/src/Framework/TestSuite/DataProvider.php',
'PHPUnit_Framework_UnintentionallyCoveredCodeError' => $vendorDir . '/phpunit/phpunit/src/Framework/UnintentionallyCoveredCodeError.php',
'PHPUnit_Framework_Warning' => $vendorDir . '/phpunit/phpunit/src/Framework/Warning.php',
'PHPUnit_Framework_WarningTestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/WarningTestCase.php',
'PHPUnit_Runner_BaseTestRunner' => $vendorDir . '/phpunit/phpunit/src/Runner/BaseTestRunner.php',
'PHPUnit_Runner_Exception' => $vendorDir . '/phpunit/phpunit/src/Runner/Exception.php',
'PHPUnit_Runner_Filter_Factory' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Factory.php',
'PHPUnit_Runner_Filter_GroupFilterIterator' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Group.php',
'PHPUnit_Runner_Filter_Group_Exclude' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Group/Exclude.php',
'PHPUnit_Runner_Filter_Group_Include' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Group/Include.php',
'PHPUnit_Runner_Filter_Test' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Test.php',
'PHPUnit_Runner_StandardTestSuiteLoader' => $vendorDir . '/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php',
'PHPUnit_Runner_TestSuiteLoader' => $vendorDir . '/phpunit/phpunit/src/Runner/TestSuiteLoader.php',
'PHPUnit_Runner_Version' => $vendorDir . '/phpunit/phpunit/src/Runner/Version.php',
'PHPUnit_TextUI_Command' => $vendorDir . '/phpunit/phpunit/src/TextUI/Command.php',
'PHPUnit_TextUI_ResultPrinter' => $vendorDir . '/phpunit/phpunit/src/TextUI/ResultPrinter.php',
'PHPUnit_TextUI_TestRunner' => $vendorDir . '/phpunit/phpunit/src/TextUI/TestRunner.php',
'PHPUnit_Util_Blacklist' => $vendorDir . '/phpunit/phpunit/src/Util/Blacklist.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_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_InvalidArgumentHelper' => $vendorDir . '/phpunit/phpunit/src/Util/InvalidArgumentHelper.php',
'PHPUnit_Util_Log_JSON' => $vendorDir . '/phpunit/phpunit/src/Util/Log/JSON.php',
'PHPUnit_Util_Log_JUnit' => $vendorDir . '/phpunit/phpunit/src/Util/Log/JUnit.php',
'PHPUnit_Util_Log_TAP' => $vendorDir . '/phpunit/phpunit/src/Util/Log/TAP.php',
'PHPUnit_Util_Log_TeamCity' => $vendorDir . '/phpunit/phpunit/src/Util/Log/TeamCity.php',
'PHPUnit_Util_PHP' => $vendorDir . '/phpunit/phpunit/src/Util/PHP.php',
'PHPUnit_Util_PHP_Default' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/Default.php',
'PHPUnit_Util_PHP_Windows' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/Windows.php',
'PHPUnit_Util_Printer' => $vendorDir . '/phpunit/phpunit/src/Util/Printer.php',
'PHPUnit_Util_Regex' => $vendorDir . '/phpunit/phpunit/src/Util/Regex.php',
'PHPUnit_Util_String' => $vendorDir . '/phpunit/phpunit/src/Util/String.php',
'PHPUnit_Util_Test' => $vendorDir . '/phpunit/phpunit/src/Util/Test.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_ResultPrinter_HTML' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/HTML.php',
'PHPUnit_Util_TestDox_ResultPrinter_Text' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/Text.php',
'PHPUnit_Util_TestDox_ResultPrinter_XML' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/XML.php',
'PHPUnit_Util_TestSuiteIterator' => $vendorDir . '/phpunit/phpunit/src/Util/TestSuiteIterator.php',
'PHPUnit_Util_Type' => $vendorDir . '/phpunit/phpunit/src/Util/Type.php',
'PHPUnit_Util_XML' => $vendorDir . '/phpunit/phpunit/src/Util/XML.php',
'PHP_Timer' => $vendorDir . '/phpunit/php-timer/src/Timer.php',
'PHP_Token' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_TokenWithScope' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_TokenWithScopeAndVisibility' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ABSTRACT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AMPERSAND' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AND_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ARRAY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ARRAY_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ASYNC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AWAIT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BACKTICK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BAD_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOLEAN_AND' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOLEAN_OR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOL_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BREAK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CALLABLE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CARET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CASE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CATCH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS_NAME_CONSTANT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLONE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_BRACKET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_CURLY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_SQUARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_TAG' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COALESCE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COLON' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMMA' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMMENT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMPILER_HALT_OFFSET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONCAT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONSTANT_ENCAPSED_STRING' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONTINUE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CURLY_OPEN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DEC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DECLARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DEFAULT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIV' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIV_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DNUMBER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOC_COMMENT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOLLAR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_ARROW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_COLON' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_QUOTES' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ECHO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELLIPSIS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELSE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELSEIF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EMPTY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENCAPSED_AND_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDDECLARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDFOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDFOREACH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDIF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDSWITCH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDWHILE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_END_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENUM' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EQUALS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EVAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXCLAMATION_MARK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXIT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXTENDS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FILE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FINAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FINALLY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FOREACH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FUNCTION' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FUNC_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GLOBAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GOTO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_HALT_COMPILER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IMPLEMENTS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INCLUDE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INCLUDE_ONCE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INLINE_HTML' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INSTANCEOF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INSTEADOF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INTERFACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INT_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ISSET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_GREATER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_NOT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_NOT_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_SMALLER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_Includes' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_JOIN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_ARROW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_CP' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_OP' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LINE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LIST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LNUMBER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_AND' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_OR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_XOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_METHOD_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MINUS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MINUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MOD_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MULT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MUL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NAMESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NEW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NS_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NS_SEPARATOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NUM_STRING' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OBJECT_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OBJECT_OPERATOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ONUMBER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_BRACKET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_CURLY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_SQUARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_TAG' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_TAG_WITH_ECHO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PERCENT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PIPE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PLUS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PLUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_POW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_POW_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PRINT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PRIVATE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PROTECTED' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PUBLIC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_QUESTION_MARK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_REQUIRE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_REQUIRE_ONCE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_RETURN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SEMICOLON' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SHAPE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SPACESHIP' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_START_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STATIC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING_VARNAME' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SWITCH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_Stream' => $vendorDir . '/phpunit/php-token-stream/src/Token/Stream.php',
'PHP_Token_Stream_CachingFactory' => $vendorDir . '/phpunit/php-token-stream/src/Token/Stream/CachingFactory.php',
'PHP_Token_THROW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TILDE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRAIT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRAIT_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPELIST_GT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPELIST_LT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_UNSET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_UNSET_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_USE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_VAR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_VARIABLE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHERE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHILE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_ATTRIBUTE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CATEGORY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CATEGORY_LABEL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CHILDREN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_LABEL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_REQUIRED' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TAG_GT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TAG_LT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TEXT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XOR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_YIELD' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_YIELD_FROM' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
'Prophecy\\Argument' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument.php',
'Prophecy\\Argument\\ArgumentsWildcard' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/ArgumentsWildcard.php',
'Prophecy\\Argument\\Token\\AnyValueToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/AnyValueToken.php',
'Prophecy\\Argument\\Token\\AnyValuesToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/AnyValuesToken.php',
'Prophecy\\Argument\\Token\\ApproximateValueToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/ApproximateValueToken.php',
'Prophecy\\Argument\\Token\\ArrayCountToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayCountToken.php',
'Prophecy\\Argument\\Token\\ArrayEntryToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayEntryToken.php',
'Prophecy\\Argument\\Token\\ArrayEveryEntryToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayEveryEntryToken.php',
'Prophecy\\Argument\\Token\\CallbackToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/CallbackToken.php',
'Prophecy\\Argument\\Token\\ExactValueToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/ExactValueToken.php',
'Prophecy\\Argument\\Token\\IdenticalValueToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/IdenticalValueToken.php',
'Prophecy\\Argument\\Token\\LogicalAndToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/LogicalAndToken.php',
'Prophecy\\Argument\\Token\\LogicalNotToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/LogicalNotToken.php',
'Prophecy\\Argument\\Token\\ObjectStateToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/ObjectStateToken.php',
'Prophecy\\Argument\\Token\\StringContainsToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/StringContainsToken.php',
'Prophecy\\Argument\\Token\\TokenInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/TokenInterface.php',
'Prophecy\\Argument\\Token\\TypeToken' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Argument/Token/TypeToken.php',
'Prophecy\\Call\\Call' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Call/Call.php',
'Prophecy\\Call\\CallCenter' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Call/CallCenter.php',
'Prophecy\\Comparator\\ClosureComparator' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Comparator/ClosureComparator.php',
'Prophecy\\Comparator\\Factory' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Comparator/Factory.php',
'Prophecy\\Comparator\\ProphecyComparator' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Comparator/ProphecyComparator.php',
'Prophecy\\Doubler\\CachedDoubler' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/CachedDoubler.php',
'Prophecy\\Doubler\\ClassPatch\\ClassPatchInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ClassPatchInterface.php',
'Prophecy\\Doubler\\ClassPatch\\DisableConstructorPatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/DisableConstructorPatch.php',
'Prophecy\\Doubler\\ClassPatch\\HhvmExceptionPatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/HhvmExceptionPatch.php',
'Prophecy\\Doubler\\ClassPatch\\KeywordPatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/KeywordPatch.php',
'Prophecy\\Doubler\\ClassPatch\\MagicCallPatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/MagicCallPatch.php',
'Prophecy\\Doubler\\ClassPatch\\ProphecySubjectPatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ProphecySubjectPatch.php',
'Prophecy\\Doubler\\ClassPatch\\ReflectionClassNewInstancePatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ReflectionClassNewInstancePatch.php',
'Prophecy\\Doubler\\ClassPatch\\SplFileInfoPatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/SplFileInfoPatch.php',
'Prophecy\\Doubler\\ClassPatch\\TraversablePatch' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/TraversablePatch.php',
'Prophecy\\Doubler\\DoubleInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/DoubleInterface.php',
'Prophecy\\Doubler\\Doubler' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Doubler.php',
'Prophecy\\Doubler\\Generator\\ClassCodeGenerator' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCodeGenerator.php',
'Prophecy\\Doubler\\Generator\\ClassCreator' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCreator.php',
'Prophecy\\Doubler\\Generator\\ClassMirror' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassMirror.php',
'Prophecy\\Doubler\\Generator\\Node\\ArgumentNode' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/ArgumentNode.php',
'Prophecy\\Doubler\\Generator\\Node\\ClassNode' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/ClassNode.php',
'Prophecy\\Doubler\\Generator\\Node\\MethodNode' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/MethodNode.php',
'Prophecy\\Doubler\\Generator\\ReflectionInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ReflectionInterface.php',
'Prophecy\\Doubler\\LazyDouble' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/LazyDouble.php',
'Prophecy\\Doubler\\NameGenerator' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Doubler/NameGenerator.php',
'Prophecy\\Exception\\Call\\UnexpectedCallException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Call/UnexpectedCallException.php',
'Prophecy\\Exception\\Doubler\\ClassCreatorException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassCreatorException.php',
'Prophecy\\Exception\\Doubler\\ClassMirrorException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassMirrorException.php',
'Prophecy\\Exception\\Doubler\\ClassNotFoundException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassNotFoundException.php',
'Prophecy\\Exception\\Doubler\\DoubleException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/DoubleException.php',
'Prophecy\\Exception\\Doubler\\DoublerException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/DoublerException.php',
'Prophecy\\Exception\\Doubler\\InterfaceNotFoundException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/InterfaceNotFoundException.php',
'Prophecy\\Exception\\Doubler\\MethodNotExtendableException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/MethodNotExtendableException.php',
'Prophecy\\Exception\\Doubler\\MethodNotFoundException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/MethodNotFoundException.php',
'Prophecy\\Exception\\Doubler\\ReturnByReferenceException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ReturnByReferenceException.php',
'Prophecy\\Exception\\Exception' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Exception.php',
'Prophecy\\Exception\\InvalidArgumentException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/InvalidArgumentException.php',
'Prophecy\\Exception\\Prediction\\AggregateException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/AggregateException.php',
'Prophecy\\Exception\\Prediction\\FailedPredictionException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/FailedPredictionException.php',
'Prophecy\\Exception\\Prediction\\NoCallsException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/NoCallsException.php',
'Prophecy\\Exception\\Prediction\\PredictionException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/PredictionException.php',
'Prophecy\\Exception\\Prediction\\UnexpectedCallsCountException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/UnexpectedCallsCountException.php',
'Prophecy\\Exception\\Prediction\\UnexpectedCallsException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/UnexpectedCallsException.php',
'Prophecy\\Exception\\Prophecy\\MethodProphecyException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prophecy/MethodProphecyException.php',
'Prophecy\\Exception\\Prophecy\\ObjectProphecyException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prophecy/ObjectProphecyException.php',
'Prophecy\\Exception\\Prophecy\\ProphecyException' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Exception/Prophecy/ProphecyException.php',
'Prophecy\\PhpDocumentor\\ClassAndInterfaceTagRetriever' => $vendorDir . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/ClassAndInterfaceTagRetriever.php',
'Prophecy\\PhpDocumentor\\ClassTagRetriever' => $vendorDir . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/ClassTagRetriever.php',
'Prophecy\\PhpDocumentor\\LegacyClassTagRetriever' => $vendorDir . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/LegacyClassTagRetriever.php',
'Prophecy\\PhpDocumentor\\MethodTagRetrieverInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/MethodTagRetrieverInterface.php',
'Prophecy\\Prediction\\CallPrediction' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prediction/CallPrediction.php',
'Prophecy\\Prediction\\CallTimesPrediction' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prediction/CallTimesPrediction.php',
'Prophecy\\Prediction\\CallbackPrediction' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prediction/CallbackPrediction.php',
'Prophecy\\Prediction\\NoCallsPrediction' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prediction/NoCallsPrediction.php',
'Prophecy\\Prediction\\PredictionInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prediction/PredictionInterface.php',
'Prophecy\\Promise\\CallbackPromise' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Promise/CallbackPromise.php',
'Prophecy\\Promise\\PromiseInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Promise/PromiseInterface.php',
'Prophecy\\Promise\\ReturnArgumentPromise' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Promise/ReturnArgumentPromise.php',
'Prophecy\\Promise\\ReturnPromise' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Promise/ReturnPromise.php',
'Prophecy\\Promise\\ThrowPromise' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Promise/ThrowPromise.php',
'Prophecy\\Prophecy\\MethodProphecy' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophecy/MethodProphecy.php',
'Prophecy\\Prophecy\\ObjectProphecy' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophecy/ObjectProphecy.php',
'Prophecy\\Prophecy\\ProphecyInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophecy/ProphecyInterface.php',
'Prophecy\\Prophecy\\ProphecySubjectInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophecy/ProphecySubjectInterface.php',
'Prophecy\\Prophecy\\Revealer' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophecy/Revealer.php',
'Prophecy\\Prophecy\\RevealerInterface' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophecy/RevealerInterface.php',
'Prophecy\\Prophet' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Prophet.php',
'Prophecy\\Util\\ExportUtil' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Util/ExportUtil.php',
'Prophecy\\Util\\StringUtil' => $vendorDir . '/phpspec/prophecy/src/Prophecy/Util/StringUtil.php',
'Psr\\Log\\AbstractLogger' => $vendorDir . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => $vendorDir . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => $vendorDir . '/psr/log/Psr/Log/LogLevel.php',
'Psr\\Log\\LoggerAwareInterface' => $vendorDir . '/psr/log/Psr/Log/LoggerAwareInterface.php',
'Psr\\Log\\LoggerAwareTrait' => $vendorDir . '/psr/log/Psr/Log/LoggerAwareTrait.php',
'Psr\\Log\\LoggerInterface' => $vendorDir . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => $vendorDir . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => $vendorDir . '/psr/log/Psr/Log/NullLogger.php',
'Psr\\Log\\Test\\DummyTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Satooshi\\Bundle\\CoverallsBundle\\Console\\Application' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Console/Application.php',
'Satooshi\\Bundle\\CoverallsBundle\\CoverallsBundle' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/CoverallsBundle.php',
'Satooshi\\Bundle\\CoverallsBundle\\Entity\\ArrayConvertable' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Entity/ArrayConvertable.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Api\\CoverallsApi' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/CoverallsApi.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Api\\Jobs' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/Jobs.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Collector\\CiEnvVarsCollector' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CiEnvVarsCollector.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Collector\\CloverXmlCoverageCollector' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CloverXmlCoverageCollector.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Collector\\GitInfoCollector' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/GitInfoCollector.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Command\\CoverallsV1JobsCommand' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Command/CoverallsV1JobsCommand.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Config\\Configuration' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configuration.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Config\\Configurator' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configurator.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Config\\CoverallsConfiguration' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/CoverallsConfiguration.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\CoverallsV1Bundle' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/CoverallsV1Bundle.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Coveralls' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Coveralls.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Exception\\RequirementsNotSatisfiedException' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Exception/RequirementsNotSatisfiedException.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Git\\Commit' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Commit.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Git\\Git' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Git.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Git\\Remote' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Remote.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\JsonFile' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/JsonFile.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Metrics' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Metrics.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\SourceFile' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/SourceFile.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Repository\\JobsRepository' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Repository/JobsRepository.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Version' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Version.php',
'Satooshi\\Component\\File\\Path' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Component/File/Path.php',
'Satooshi\\Component\\Log\\ConsoleLogger' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Component/Log/ConsoleLogger.php',
'Satooshi\\Component\\System\\Git\\GitCommand' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Component/System/Git/GitCommand.php',
'Satooshi\\Component\\System\\SystemCommand' => $vendorDir . '/satooshi/php-coveralls/src/Satooshi/Component/System/SystemCommand.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\\HHVM' => $vendorDir . '/phpunit/php-code-coverage/src/Driver/HHVM.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\\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\\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\\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\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php',
'SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php',
'SebastianBergmann\\Diff\\LCS\\LongestCommonSubsequence' => $vendorDir . '/sebastian/diff/src/LCS/LongestCommonSubsequence.php',
'SebastianBergmann\\Diff\\LCS\\MemoryEfficientImplementation' => $vendorDir . '/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php',
'SebastianBergmann\\Diff\\LCS\\TimeEfficientImplementation' => $vendorDir . '/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php',
'SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php',
'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php',
'SebastianBergmann\\Environment\\Console' => $vendorDir . '/sebastian/environment/src/Console.php',
'SebastianBergmann\\Environment\\Runtime' => $vendorDir . '/sebastian/environment/src/Runtime.php',
'SebastianBergmann\\Exporter\\Exporter' => $vendorDir . '/sebastian/exporter/src/Exporter.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/Exception.php',
'SebastianBergmann\\GlobalState\\Restorer' => $vendorDir . '/sebastian/global-state/src/Restorer.php',
'SebastianBergmann\\GlobalState\\RuntimeException' => $vendorDir . '/sebastian/global-state/src/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\\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\\Version' => $vendorDir . '/sebastian/version/src/Version.php',
'Symfony\\CS\\AbstractAlignFixer' => $baseDir . '/Symfony/CS/AbstractAlignFixer.php',
'Symfony\\CS\\AbstractAnnotationRemovalFixer' => $baseDir . '/Symfony/CS/AbstractAnnotationRemovalFixer.php',
'Symfony\\CS\\AbstractFixer' => $baseDir . '/Symfony/CS/AbstractFixer.php',
'Symfony\\CS\\AbstractLinesBeforeNamespaceFixer' => $baseDir . '/Symfony/CS/AbstractLinesBeforeNamespaceFixer.php',
'Symfony\\CS\\AbstractPhpdocTypesFixer' => $baseDir . '/Symfony/CS/AbstractPhpdocTypesFixer.php',
'Symfony\\CS\\Config' => $baseDir . '/Symfony/CS/Config.php',
'Symfony\\CS\\ConfigAwareInterface' => $baseDir . '/Symfony/CS/ConfigAwareInterface.php',
'Symfony\\CS\\ConfigInterface' => $baseDir . '/Symfony/CS/ConfigInterface.php',
'Symfony\\CS\\Config\\Config' => $baseDir . '/Symfony/CS/Config/Config.php',
'Symfony\\CS\\Config\\MagentoConfig' => $baseDir . '/Symfony/CS/Config/MagentoConfig.php',
'Symfony\\CS\\Config\\Symfony23Config' => $baseDir . '/Symfony/CS/Config/Symfony23Config.php',
'Symfony\\CS\\ConfigurationException\\InvalidConfigurationException' => $baseDir . '/Symfony/CS/ConfigurationException/InvalidConfigurationException.php',
'Symfony\\CS\\ConfigurationException\\InvalidFixerConfigurationException' => $baseDir . '/Symfony/CS/ConfigurationException/InvalidFixerConfigurationException.php',
'Symfony\\CS\\ConfigurationResolver' => $baseDir . '/Symfony/CS/ConfigurationResolver.php',
'Symfony\\CS\\Console\\Application' => $baseDir . '/Symfony/CS/Console/Application.php',
'Symfony\\CS\\Console\\Command\\FixCommand' => $baseDir . '/Symfony/CS/Console/Command/FixCommand.php',
'Symfony\\CS\\Console\\Command\\ReadmeCommand' => $baseDir . '/Symfony/CS/Console/Command/ReadmeCommand.php',
'Symfony\\CS\\Console\\Command\\SelfUpdateCommand' => $baseDir . '/Symfony/CS/Console/Command/SelfUpdateCommand.php',
'Symfony\\CS\\DocBlock\\Annotation' => $baseDir . '/Symfony/CS/DocBlock/Annotation.php',
'Symfony\\CS\\DocBlock\\DocBlock' => $baseDir . '/Symfony/CS/DocBlock/DocBlock.php',
'Symfony\\CS\\DocBlock\\Line' => $baseDir . '/Symfony/CS/DocBlock/Line.php',
'Symfony\\CS\\DocBlock\\Tag' => $baseDir . '/Symfony/CS/DocBlock/Tag.php',
'Symfony\\CS\\DocBlock\\TagComparator' => $baseDir . '/Symfony/CS/DocBlock/TagComparator.php',
'Symfony\\CS\\ErrorsManager' => $baseDir . '/Symfony/CS/ErrorsManager.php',
'Symfony\\CS\\FileCacheManager' => $baseDir . '/Symfony/CS/FileCacheManager.php',
'Symfony\\CS\\FileRemoval' => $baseDir . '/Symfony/CS/FileRemoval.php',
'Symfony\\CS\\Finder' => $baseDir . '/Symfony/CS/Finder.php',
'Symfony\\CS\\FinderInterface' => $baseDir . '/Symfony/CS/FinderInterface.php',
'Symfony\\CS\\Finder\\DefaultFinder' => $baseDir . '/Symfony/CS/Finder/DefaultFinder.php',
'Symfony\\CS\\Finder\\MagentoFinder' => $baseDir . '/Symfony/CS/Finder/MagentoFinder.php',
'Symfony\\CS\\Finder\\Symfony23Finder' => $baseDir . '/Symfony/CS/Finder/Symfony23Finder.php',
'Symfony\\CS\\Fixer' => $baseDir . '/Symfony/CS/Fixer.php',
'Symfony\\CS\\FixerFileProcessedEvent' => $baseDir . '/Symfony/CS/FixerFileProcessedEvent.php',
'Symfony\\CS\\FixerInterface' => $baseDir . '/Symfony/CS/FixerInterface.php',
'Symfony\\CS\\Fixer\\Contrib\\AlignDoubleArrowFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/AlignDoubleArrowFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\AlignEqualsFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/AlignEqualsFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ClassKeywordRemoveFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/ClassKeywordRemoveFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\CombineConsecutiveUnsetsFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/CombineConsecutiveUnsetsFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ConcatWithSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/ConcatWithSpacesFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\EchoToPrintFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/EchoToPrintFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\EmptyReturnFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/EmptyReturnFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\EregToPregFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/EregToPregFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\HeaderCommentFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/HeaderCommentFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\LogicalNotOperatorsWithSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\LogicalNotOperatorsWithSuccessorSpaceFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\LongArraySyntaxFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/LongArraySyntaxFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\MbStrFunctionsFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/MbStrFunctionsFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\MultilineSpacesBeforeSemicolonFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NewlineAfterOpenTagFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/NewlineAfterOpenTagFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NoBlankLinesBeforeNamespaceFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NoUselessElseFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/NoUselessElseFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NoUselessReturnFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/NoUselessReturnFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\OrderedUseFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/OrderedUseFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\Php4ConstructorFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/Php4ConstructorFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpUnitConstructFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/PhpUnitConstructFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpUnitDedicateAssertFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/PhpUnitDedicateAssertFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpUnitStrictFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/PhpUnitStrictFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpdocOrderFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/PhpdocOrderFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpdocVarToTypeFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/PhpdocVarToTypeFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ShortArraySyntaxFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/ShortArraySyntaxFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ShortEchoTagFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/ShortEchoTagFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\SilencedDeprecationErrorFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/SilencedDeprecationErrorFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\StrictFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/StrictFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\StrictParamFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/StrictParamFixer.php',
'Symfony\\CS\\Fixer\\PSR0\\Psr0Fixer' => $baseDir . '/Symfony/CS/Fixer/PSR0/Psr0Fixer.php',
'Symfony\\CS\\Fixer\\PSR1\\EncodingFixer' => $baseDir . '/Symfony/CS/Fixer/PSR1/EncodingFixer.php',
'Symfony\\CS\\Fixer\\PSR1\\ShortTagFixer' => $baseDir . '/Symfony/CS/Fixer/PSR1/ShortTagFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\BracesFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/BracesFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\ClassDefinitionFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/ClassDefinitionFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\ElseifFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/ElseifFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\EofEndingFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/EofEndingFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\FunctionCallSpaceFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/FunctionCallSpaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\FunctionDeclarationFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/FunctionDeclarationFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\IndentationFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/IndentationFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LineAfterNamespaceFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/LineAfterNamespaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LinefeedFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/LinefeedFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LowercaseConstantsFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/LowercaseConstantsFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LowercaseKeywordsFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/LowercaseKeywordsFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\MethodArgumentSpaceFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/MethodArgumentSpaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\MultipleUseFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/MultipleUseFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\NoTrailingWhitespaceInCommentFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/NoTrailingWhitespaceInCommentFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\ParenthesisFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/ParenthesisFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\PhpClosingTagFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/PhpClosingTagFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\SingleLineAfterImportsFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/SingleLineAfterImportsFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\SwitchCaseSemicolonToColonFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/SwitchCaseSemicolonToColonFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\SwitchCaseSpaceFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/SwitchCaseSpaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\TrailingSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/TrailingSpacesFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\VisibilityFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/VisibilityFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ArrayElementNoSpaceBeforeCommaFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ArrayElementWhiteSpaceAfterCommaFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\BlanklineAfterOpenTagFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/BlanklineAfterOpenTagFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ConcatWithoutSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ConcatWithoutSpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DeclareEqualNormalizeFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/DeclareEqualNormalizeFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DoubleArrowMultilineWhitespacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DuplicateSemicolonFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/DuplicateSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ExtraEmptyLinesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ExtraEmptyLinesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\FunctionTypehintSpaceFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/FunctionTypehintSpaceFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\HashToSlashCommentFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/HashToSlashCommentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\HeredocToNowdocFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/HeredocToNowdocFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\IncludeFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/IncludeFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\JoinFunctionFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/JoinFunctionFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ListCommasFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ListCommasFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\LowercaseCastFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/LowercaseCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\MethodArgumentDefaultValueFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/MethodArgumentDefaultValueFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\MultilineArrayTrailingCommaFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/MultilineArrayTrailingCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NamespaceNoLeadingWhitespaceFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NativeFunctionCasingFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NativeFunctionCasingFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NewWithBracesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NewWithBracesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoBlankLinesAfterClassOpeningFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyCommentFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NoEmptyCommentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyLinesAfterPhpdocsFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyPhpdocFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NoEmptyPhpdocFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyStatementFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NoEmptyStatementFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ObjectOperatorFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ObjectOperatorFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\OperatorsSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/OperatorsSpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocAnnotationWithoutDotFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocAnnotationWithoutDotFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocIndentFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocIndentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocInlineTagFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocInlineTagFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocNoAccessFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocNoAccessFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocNoEmptyReturnFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocNoEmptyReturnFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocNoPackageFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocNoPackageFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocParamsFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocParamsFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocScalarFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocScalarFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocSeparationFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocSeparationFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocShortDescriptionFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocShortDescriptionFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocSingleLineVarSpacingFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocSingleLineVarSpacingFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocToCommentFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocToCommentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocTrimFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocTrimFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocTypeToVarFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocTypeToVarFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocTypesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocTypesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocVarWithoutNameFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocVarWithoutNameFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PreIncrementFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PreIncrementFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PrintToEchoFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PrintToEchoFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\RemoveLeadingSlashUseFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/RemoveLeadingSlashUseFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\RemoveLinesBetweenUsesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/RemoveLinesBetweenUsesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ReturnFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ReturnFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SelfAccessorFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SelfAccessorFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ShortBoolCastFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ShortBoolCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ShortScalarCastFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ShortScalarCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SingleArrayNoTrailingCommaFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SingleArrayNoTrailingCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SingleBlankLineBeforeNamespaceFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SingleQuoteFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SingleQuoteFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SpacesAfterSemicolonFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SpacesAfterSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SpacesBeforeSemicolonFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SpacesBeforeSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SpacesCastFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/SpacesCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\StandardizeNotEqualFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/StandardizeNotEqualFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\TernarySpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/TernarySpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\TrimArraySpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/TrimArraySpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnalignDoubleArrowFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/UnalignDoubleArrowFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnalignEqualsFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/UnalignEqualsFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnaryOperatorsSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/UnaryOperatorsSpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnneededControlParenthesesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/UnneededControlParenthesesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnusedUseFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/UnusedUseFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\WhitespacyLinesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/WhitespacyLinesFixer.php',
'Symfony\\CS\\LintManager' => $baseDir . '/Symfony/CS/LintManager.php',
'Symfony\\CS\\StdinFileInfo' => $baseDir . '/Symfony/CS/StdinFileInfo.php',
'Symfony\\CS\\Test\\IntegrationCase' => $baseDir . '/Symfony/CS/Test/IntegrationCase.php',
'Symfony\\CS\\Test\\IntegrationCaseFactory' => $baseDir . '/Symfony/CS/Test/IntegrationCaseFactory.php',
'Symfony\\CS\\Tests\\AbstractFixerTest' => $baseDir . '/Symfony/CS/Tests/AbstractFixerTest.php',
'Symfony\\CS\\Tests\\AbstractIntegrationTest' => $baseDir . '/Symfony/CS/Tests/AbstractIntegrationTest.php',
'Symfony\\CS\\Tests\\Config\\ConfigTest' => $baseDir . '/Symfony/CS/Tests/Config/ConfigTest.php',
'Symfony\\CS\\Tests\\ConfigurationResolverTest' => $baseDir . '/Symfony/CS/Tests/ConfigurationResolverTest.php',
'Symfony\\CS\\Tests\\Console\\ApplicationTest' => $baseDir . '/Symfony/CS/Tests/Console/ApplicationTest.php',
'Symfony\\CS\\Tests\\Console\\TextDiffTest' => $baseDir . '/Symfony/CS/Tests/Console/TextDiffTest.php',
'Symfony\\CS\\Tests\\DocBlock\\AnnotationTest' => $baseDir . '/Symfony/CS/Tests/DocBlock/AnnotationTest.php',
'Symfony\\CS\\Tests\\DocBlock\\DocBlockTest' => $baseDir . '/Symfony/CS/Tests/DocBlock/DocBlockTest.php',
'Symfony\\CS\\Tests\\DocBlock\\LineTest' => $baseDir . '/Symfony/CS/Tests/DocBlock/LineTest.php',
'Symfony\\CS\\Tests\\DocBlock\\TagComparatorTest' => $baseDir . '/Symfony/CS/Tests/DocBlock/TagComparatorTest.php',
'Symfony\\CS\\Tests\\DocBlock\\TagTest' => $baseDir . '/Symfony/CS/Tests/DocBlock/TagTest.php',
'Symfony\\CS\\Tests\\Finder\\DefaultFinderTest' => $baseDir . '/Symfony/CS/Tests/Finder/DefaultFinderTest.php',
'Symfony\\CS\\Tests\\FixerTest' => $baseDir . '/Symfony/CS/Tests/FixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\AbstractFixerTestBase' => $baseDir . '/Symfony/CS/Tests/Fixer/AbstractFixerTestBase.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\AlignDoubleArrowFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/AlignDoubleArrowFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\AlignEqualsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/AlignEqualsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ClassKeywordRemoveFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/ClassKeywordRemoveFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\CombineConsecutiveUnsetsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/CombineConsecutiveUnsetsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ConcatWithSpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/ConcatWithSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\EchoToPrintFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/EchoToPrintFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\EmptyReturnFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/EmptyReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\EregToPregFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/EregToPregFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\HeaderCommentFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/HeaderCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\LogicalNotOperatorsWithSpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\LogicalNotOperatorsWithSuccessorSpaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\LongArraySyntaxFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/LongArraySyntaxFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\MbStrFunctionsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/MbStrFunctionsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\MultilineSpacesBeforeSemicolonFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NewlineAfterOpenTagFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/NewlineAfterOpenTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NoBlankLinesBeforeNamespaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NoUselessElseFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/NoUselessElseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NoUselessReturnFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/NoUselessReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\OrderedUseFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/OrderedUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\Php4ConstructorFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/Php4ConstructorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpUnitConstructFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/PhpUnitConstructFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpUnitDedicateAssertFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/PhpUnitDedicateAssertFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpUnitStrictFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/PhpUnitStrictFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpdocOrderFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/PhpdocOrderFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpdocVarToTypeFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/PhpdocVarToTypeFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ShortArraySyntaxFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/ShortArraySyntaxFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ShortEchoTagFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/ShortEchoTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\SilencedDeprecationErrorFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/SilencedDeprecationErrorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\StrictFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/StrictFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\StrictParamFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Contrib/StrictParamFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR0\\Psr0FixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR0/Psr0FixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR1\\EncodingFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR1/EncodingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR1\\ShortTagFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR1/ShortTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\BracesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/BracesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\ClassDefinitionFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/ClassDefinitionFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\ElseifFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/ElseifFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\EofEndingFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/EofEndingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\FunctionCallSpaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/FunctionCallSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\FunctionDeclarationFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/FunctionDeclarationFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\IndentationFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/IndentationFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LineAfterNamespaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/LineAfterNamespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LinefeedFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/LinefeedFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LowercaseConstantsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/LowercaseConstantsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LowercaseKeywordsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/LowercaseKeywordsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\MethodArgumentSpaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/MethodArgumentSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\MultipleUseFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/MultipleUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\NoTrailingWhitespaceInCommentFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/NoTrailingWhitespaceInCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\ParenthesisFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/ParenthesisFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\PhpClosingTagFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/PhpClosingTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\SingleLineAfterImportsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/SingleLineAfterImportsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\SwitchCaseSemicolonToColonFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/SwitchCaseSemicolonToColonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\SwitchCaseSpaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/SwitchCaseSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\TrailingSpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/TrailingSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\VisibilityFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/PSR2/VisibilityFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ArrayElementNoSpaceBeforeCommaFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ArrayElementWhiteSpaceAfterCommaFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\BlanklineAfterOpenTagFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/BlanklineAfterOpenTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ConcatWithoutSpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ConcatWithoutSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\DeclareEqualNormalizeFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/DeclareEqualNormalizeFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\DoubleArrowMultilineWhitespacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\DuplicateSemicolonFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/DuplicateSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ExtraEmptyLinesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ExtraEmptyLinesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\FunctionTypehintSpaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/FunctionTypehintSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\HashToSlashCommentFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/HashToSlashCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\HeredocToNowdocFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/HeredocToNowdocFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\IncludeFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/IncludeFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\JoinFunctionFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/JoinFunctionFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ListCommasFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ListCommasFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\LowercaseCastFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/LowercaseCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\MethodArgumentDefaultValueFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/MethodArgumentDefaultValueFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\MultilineArrayTrailingCommaFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/MultilineArrayTrailingCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NamespaceNoLeadingWhitespaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NativeFunctionCasingFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NativeFunctionCasingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NewWithBracesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NewWithBracesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoBlankLinesAfterClassOpeningFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyCommentFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyLinesAfterPhpdocsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyPhpdocFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyPhpdocFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyStatementFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyStatementFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ObjectOperatorFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ObjectOperatorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\OperatorsSpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/OperatorsSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocAnnotationWithoutDotFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocAnnotationWithoutDotFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocIndentFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocIndentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocInlineTagFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocInlineTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocNoAccessFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoAccessFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocNoEmptyReturnFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoEmptyReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocNoPackageFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoPackageFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocParamsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocParamsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocScalarFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocScalarFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocSeparationFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocSeparationFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocShortDescriptionFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocShortDescriptionFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocSingleLineVarSpacingFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocSingleLineVarSpacingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocToCommentFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocToCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocTrimFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocTrimFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocTypeToVarFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocTypeToVarFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocTypesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocTypesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocVarWithoutNameFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocVarWithoutNameFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PreIncrementFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PreIncrementFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PrintToEchoFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/PrintToEchoFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\RemoveLeadingSlashUseFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/RemoveLeadingSlashUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\RemoveLinesBetweenUsesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/RemoveLinesBetweenUsesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ReturnFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SelfAccessorFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SelfAccessorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ShortBoolCastFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ShortBoolCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ShortScalarCastFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/ShortScalarCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SingleArrayNoTrailingCommaFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SingleArrayNoTrailingCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SingleBlankLineBeforeNamespaceFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SingleQuoteFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SingleQuoteFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SpacesAfterSemicolonFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SpacesAfterSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SpacesBeforeSemicolonFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SpacesBeforeSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SpacesCastFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/SpacesCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\StandardizeNotEqualFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/StandardizeNotEqualFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\TernarySpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/TernarySpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\TrimArraySpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/TrimArraySpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnalignDoubleArrowFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/UnalignDoubleArrowFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnalignEqualsFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/UnalignEqualsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnaryOperatorsSpacesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/UnaryOperatorsSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnneededControlParenthesesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/UnneededControlParenthesesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnusedUseFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/UnusedUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\WhitespacyLinesFixerTest' => $baseDir . '/Symfony/CS/Tests/Fixer/Symfony/WhitespacyLinesFixerTest.php',
'Symfony\\CS\\Tests\\IntegrationTest' => $baseDir . '/Symfony/CS/Tests/IntegrationTest.php',
'Symfony\\CS\\Tests\\ReadmeTest' => $baseDir . '/Symfony/CS/Tests/ReadmeTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\AbstractTransformerTestBase' => $baseDir . '/Symfony/CS/Tests/Tokenizer/AbstractTransformerTestBase.php',
'Symfony\\CS\\Tests\\Tokenizer\\TokenTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/TokenTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\TokensTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/TokensTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\ArrayTypehintTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/Transformer/ArrayTypehintTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\ClassConstantTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/Transformer/ClassConstantTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\CurlyCloseTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/Transformer/CurlyCloseTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\DollarCloseCurlyBracesTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/Transformer/DollarCloseCurlyBracesTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\DynamicPropBraceTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/Transformer/DynamicPropBraceTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\DynamicVarBraceTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/Transformer/DynamicVarBraceTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\TransformersTest' => $baseDir . '/Symfony/CS/Tests/Tokenizer/TransformersTest.php',
'Symfony\\CS\\Tests\\ToolInfoTest' => $baseDir . '/Symfony/CS/Tests/ToolInfoTest.php',
'Symfony\\CS\\Tests\\UtilsTest' => $baseDir . '/Symfony/CS/Tests/UtilsTest.php',
'Symfony\\CS\\Tokenizer\\AbstractTransformer' => $baseDir . '/Symfony/CS/Tokenizer/AbstractTransformer.php',
'Symfony\\CS\\Tokenizer\\Token' => $baseDir . '/Symfony/CS/Tokenizer/Token.php',
'Symfony\\CS\\Tokenizer\\Tokens' => $baseDir . '/Symfony/CS/Tokenizer/Tokens.php',
'Symfony\\CS\\Tokenizer\\TransformerInterface' => $baseDir . '/Symfony/CS/Tokenizer/TransformerInterface.php',
'Symfony\\CS\\Tokenizer\\Transformer\\ArrayTypehint' => $baseDir . '/Symfony/CS/Tokenizer/Transformer/ArrayTypehint.php',
'Symfony\\CS\\Tokenizer\\Transformer\\ClassConstant' => $baseDir . '/Symfony/CS/Tokenizer/Transformer/ClassConstant.php',
'Symfony\\CS\\Tokenizer\\Transformer\\CurlyClose' => $baseDir . '/Symfony/CS/Tokenizer/Transformer/CurlyClose.php',
'Symfony\\CS\\Tokenizer\\Transformer\\DollarCloseCurlyBraces' => $baseDir . '/Symfony/CS/Tokenizer/Transformer/DollarCloseCurlyBraces.php',
'Symfony\\CS\\Tokenizer\\Transformer\\DynamicPropBrace' => $baseDir . '/Symfony/CS/Tokenizer/Transformer/DynamicPropBrace.php',
'Symfony\\CS\\Tokenizer\\Transformer\\DynamicVarBrace' => $baseDir . '/Symfony/CS/Tokenizer/Transformer/DynamicVarBrace.php',
'Symfony\\CS\\Tokenizer\\Transformers' => $baseDir . '/Symfony/CS/Tokenizer/Transformers.php',
'Symfony\\CS\\ToolInfo' => $baseDir . '/Symfony/CS/ToolInfo.php',
'Symfony\\CS\\UniqueFileIterator' => $baseDir . '/Symfony/CS/UniqueFileIterator.php',
'Symfony\\CS\\Utils' => $baseDir . '/Symfony/CS/Utils.php',
'Symfony\\Component\\Config\\ConfigCache' => $vendorDir . '/symfony/config/ConfigCache.php',
'Symfony\\Component\\Config\\ConfigCacheFactory' => $vendorDir . '/symfony/config/ConfigCacheFactory.php',
'Symfony\\Component\\Config\\ConfigCacheFactoryInterface' => $vendorDir . '/symfony/config/ConfigCacheFactoryInterface.php',
'Symfony\\Component\\Config\\ConfigCacheInterface' => $vendorDir . '/symfony/config/ConfigCacheInterface.php',
'Symfony\\Component\\Config\\Definition\\ArrayNode' => $vendorDir . '/symfony/config/Definition/ArrayNode.php',
'Symfony\\Component\\Config\\Definition\\BaseNode' => $vendorDir . '/symfony/config/Definition/BaseNode.php',
'Symfony\\Component\\Config\\Definition\\BooleanNode' => $vendorDir . '/symfony/config/Definition/BooleanNode.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ArrayNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/ArrayNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\BooleanNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/BooleanNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\EnumNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/EnumNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ExprBuilder' => $vendorDir . '/symfony/config/Definition/Builder/ExprBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\FloatNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/FloatNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\IntegerNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/IntegerNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\MergeBuilder' => $vendorDir . '/symfony/config/Definition/Builder/MergeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeBuilder' => $vendorDir . '/symfony/config/Definition/Builder/NodeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/NodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeParentInterface' => $vendorDir . '/symfony/config/Definition/Builder/NodeParentInterface.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NormalizationBuilder' => $vendorDir . '/symfony/config/Definition/Builder/NormalizationBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NumericNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/NumericNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ParentNodeDefinitionInterface' => $vendorDir . '/symfony/config/Definition/Builder/ParentNodeDefinitionInterface.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ScalarNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/ScalarNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\TreeBuilder' => $vendorDir . '/symfony/config/Definition/Builder/TreeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ValidationBuilder' => $vendorDir . '/symfony/config/Definition/Builder/ValidationBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\VariableNodeDefinition' => $vendorDir . '/symfony/config/Definition/Builder/VariableNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\ConfigurationInterface' => $vendorDir . '/symfony/config/Definition/ConfigurationInterface.php',
'Symfony\\Component\\Config\\Definition\\Dumper\\XmlReferenceDumper' => $vendorDir . '/symfony/config/Definition/Dumper/XmlReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\Dumper\\YamlReferenceDumper' => $vendorDir . '/symfony/config/Definition/Dumper/YamlReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\EnumNode' => $vendorDir . '/symfony/config/Definition/EnumNode.php',
'Symfony\\Component\\Config\\Definition\\Exception\\DuplicateKeyException' => $vendorDir . '/symfony/config/Definition/Exception/DuplicateKeyException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\Exception' => $vendorDir . '/symfony/config/Definition/Exception/Exception.php',
'Symfony\\Component\\Config\\Definition\\Exception\\ForbiddenOverwriteException' => $vendorDir . '/symfony/config/Definition/Exception/ForbiddenOverwriteException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidConfigurationException' => $vendorDir . '/symfony/config/Definition/Exception/InvalidConfigurationException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidDefinitionException' => $vendorDir . '/symfony/config/Definition/Exception/InvalidDefinitionException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidTypeException' => $vendorDir . '/symfony/config/Definition/Exception/InvalidTypeException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\UnsetKeyException' => $vendorDir . '/symfony/config/Definition/Exception/UnsetKeyException.php',
'Symfony\\Component\\Config\\Definition\\FloatNode' => $vendorDir . '/symfony/config/Definition/FloatNode.php',
'Symfony\\Component\\Config\\Definition\\IntegerNode' => $vendorDir . '/symfony/config/Definition/IntegerNode.php',
'Symfony\\Component\\Config\\Definition\\NodeInterface' => $vendorDir . '/symfony/config/Definition/NodeInterface.php',
'Symfony\\Component\\Config\\Definition\\NumericNode' => $vendorDir . '/symfony/config/Definition/NumericNode.php',
'Symfony\\Component\\Config\\Definition\\Processor' => $vendorDir . '/symfony/config/Definition/Processor.php',
'Symfony\\Component\\Config\\Definition\\PrototypeNodeInterface' => $vendorDir . '/symfony/config/Definition/PrototypeNodeInterface.php',
'Symfony\\Component\\Config\\Definition\\PrototypedArrayNode' => $vendorDir . '/symfony/config/Definition/PrototypedArrayNode.php',
'Symfony\\Component\\Config\\Definition\\ScalarNode' => $vendorDir . '/symfony/config/Definition/ScalarNode.php',
'Symfony\\Component\\Config\\Definition\\VariableNode' => $vendorDir . '/symfony/config/Definition/VariableNode.php',
'Symfony\\Component\\Config\\Exception\\FileLoaderImportCircularReferenceException' => $vendorDir . '/symfony/config/Exception/FileLoaderImportCircularReferenceException.php',
'Symfony\\Component\\Config\\Exception\\FileLoaderLoadException' => $vendorDir . '/symfony/config/Exception/FileLoaderLoadException.php',
'Symfony\\Component\\Config\\FileLocator' => $vendorDir . '/symfony/config/FileLocator.php',
'Symfony\\Component\\Config\\FileLocatorInterface' => $vendorDir . '/symfony/config/FileLocatorInterface.php',
'Symfony\\Component\\Config\\Loader\\DelegatingLoader' => $vendorDir . '/symfony/config/Loader/DelegatingLoader.php',
'Symfony\\Component\\Config\\Loader\\FileLoader' => $vendorDir . '/symfony/config/Loader/FileLoader.php',
'Symfony\\Component\\Config\\Loader\\Loader' => $vendorDir . '/symfony/config/Loader/Loader.php',
'Symfony\\Component\\Config\\Loader\\LoaderInterface' => $vendorDir . '/symfony/config/Loader/LoaderInterface.php',
'Symfony\\Component\\Config\\Loader\\LoaderResolver' => $vendorDir . '/symfony/config/Loader/LoaderResolver.php',
'Symfony\\Component\\Config\\Loader\\LoaderResolverInterface' => $vendorDir . '/symfony/config/Loader/LoaderResolverInterface.php',
'Symfony\\Component\\Config\\ResourceCheckerConfigCache' => $vendorDir . '/symfony/config/ResourceCheckerConfigCache.php',
'Symfony\\Component\\Config\\ResourceCheckerConfigCacheFactory' => $vendorDir . '/symfony/config/ResourceCheckerConfigCacheFactory.php',
'Symfony\\Component\\Config\\ResourceCheckerInterface' => $vendorDir . '/symfony/config/ResourceCheckerInterface.php',
'Symfony\\Component\\Config\\Resource\\DirectoryResource' => $vendorDir . '/symfony/config/Resource/DirectoryResource.php',
'Symfony\\Component\\Config\\Resource\\FileExistenceResource' => $vendorDir . '/symfony/config/Resource/FileExistenceResource.php',
'Symfony\\Component\\Config\\Resource\\FileResource' => $vendorDir . '/symfony/config/Resource/FileResource.php',
'Symfony\\Component\\Config\\Resource\\ResourceInterface' => $vendorDir . '/symfony/config/Resource/ResourceInterface.php',
'Symfony\\Component\\Config\\Resource\\SelfCheckingResourceChecker' => $vendorDir . '/symfony/config/Resource/SelfCheckingResourceChecker.php',
'Symfony\\Component\\Config\\Resource\\SelfCheckingResourceInterface' => $vendorDir . '/symfony/config/Resource/SelfCheckingResourceInterface.php',
'Symfony\\Component\\Config\\Util\\XmlUtils' => $vendorDir . '/symfony/config/Util/XmlUtils.php',
'Symfony\\Component\\Console\\Application' => $vendorDir . '/symfony/console/Application.php',
'Symfony\\Component\\Console\\Command\\Command' => $vendorDir . '/symfony/console/Command/Command.php',
'Symfony\\Component\\Console\\Command\\HelpCommand' => $vendorDir . '/symfony/console/Command/HelpCommand.php',
'Symfony\\Component\\Console\\Command\\ListCommand' => $vendorDir . '/symfony/console/Command/ListCommand.php',
'Symfony\\Component\\Console\\ConsoleEvents' => $vendorDir . '/symfony/console/ConsoleEvents.php',
'Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => $vendorDir . '/symfony/console/Descriptor/ApplicationDescription.php',
'Symfony\\Component\\Console\\Descriptor\\Descriptor' => $vendorDir . '/symfony/console/Descriptor/Descriptor.php',
'Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => $vendorDir . '/symfony/console/Descriptor/DescriptorInterface.php',
'Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => $vendorDir . '/symfony/console/Descriptor/JsonDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => $vendorDir . '/symfony/console/Descriptor/MarkdownDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => $vendorDir . '/symfony/console/Descriptor/TextDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => $vendorDir . '/symfony/console/Descriptor/XmlDescriptor.php',
'Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => $vendorDir . '/symfony/console/Event/ConsoleCommandEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleEvent' => $vendorDir . '/symfony/console/Event/ConsoleEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleExceptionEvent' => $vendorDir . '/symfony/console/Event/ConsoleExceptionEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => $vendorDir . '/symfony/console/Event/ConsoleTerminateEvent.php',
'Symfony\\Component\\Console\\Exception\\CommandNotFoundException' => $vendorDir . '/symfony/console/Exception/CommandNotFoundException.php',
'Symfony\\Component\\Console\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/console/Exception/ExceptionInterface.php',
'Symfony\\Component\\Console\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/console/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Console\\Exception\\InvalidOptionException' => $vendorDir . '/symfony/console/Exception/InvalidOptionException.php',
'Symfony\\Component\\Console\\Exception\\LogicException' => $vendorDir . '/symfony/console/Exception/LogicException.php',
'Symfony\\Component\\Console\\Exception\\RuntimeException' => $vendorDir . '/symfony/console/Exception/RuntimeException.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatter' => $vendorDir . '/symfony/console/Formatter/OutputFormatter.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => $vendorDir . '/symfony/console/Formatter/OutputFormatterInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyle.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyleInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyleStack.php',
'Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => $vendorDir . '/symfony/console/Helper/DebugFormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\DescriptorHelper' => $vendorDir . '/symfony/console/Helper/DescriptorHelper.php',
'Symfony\\Component\\Console\\Helper\\FormatterHelper' => $vendorDir . '/symfony/console/Helper/FormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\Helper' => $vendorDir . '/symfony/console/Helper/Helper.php',
'Symfony\\Component\\Console\\Helper\\HelperInterface' => $vendorDir . '/symfony/console/Helper/HelperInterface.php',
'Symfony\\Component\\Console\\Helper\\HelperSet' => $vendorDir . '/symfony/console/Helper/HelperSet.php',
'Symfony\\Component\\Console\\Helper\\InputAwareHelper' => $vendorDir . '/symfony/console/Helper/InputAwareHelper.php',
'Symfony\\Component\\Console\\Helper\\ProcessHelper' => $vendorDir . '/symfony/console/Helper/ProcessHelper.php',
'Symfony\\Component\\Console\\Helper\\ProgressBar' => $vendorDir . '/symfony/console/Helper/ProgressBar.php',
'Symfony\\Component\\Console\\Helper\\ProgressIndicator' => $vendorDir . '/symfony/console/Helper/ProgressIndicator.php',
'Symfony\\Component\\Console\\Helper\\QuestionHelper' => $vendorDir . '/symfony/console/Helper/QuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\SymfonyQuestionHelper' => $vendorDir . '/symfony/console/Helper/SymfonyQuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\Table' => $vendorDir . '/symfony/console/Helper/Table.php',
'Symfony\\Component\\Console\\Helper\\TableCell' => $vendorDir . '/symfony/console/Helper/TableCell.php',
'Symfony\\Component\\Console\\Helper\\TableSeparator' => $vendorDir . '/symfony/console/Helper/TableSeparator.php',
'Symfony\\Component\\Console\\Helper\\TableStyle' => $vendorDir . '/symfony/console/Helper/TableStyle.php',
'Symfony\\Component\\Console\\Input\\ArgvInput' => $vendorDir . '/symfony/console/Input/ArgvInput.php',
'Symfony\\Component\\Console\\Input\\ArrayInput' => $vendorDir . '/symfony/console/Input/ArrayInput.php',
'Symfony\\Component\\Console\\Input\\Input' => $vendorDir . '/symfony/console/Input/Input.php',
'Symfony\\Component\\Console\\Input\\InputArgument' => $vendorDir . '/symfony/console/Input/InputArgument.php',
'Symfony\\Component\\Console\\Input\\InputAwareInterface' => $vendorDir . '/symfony/console/Input/InputAwareInterface.php',
'Symfony\\Component\\Console\\Input\\InputDefinition' => $vendorDir . '/symfony/console/Input/InputDefinition.php',
'Symfony\\Component\\Console\\Input\\InputInterface' => $vendorDir . '/symfony/console/Input/InputInterface.php',
'Symfony\\Component\\Console\\Input\\InputOption' => $vendorDir . '/symfony/console/Input/InputOption.php',
'Symfony\\Component\\Console\\Input\\StringInput' => $vendorDir . '/symfony/console/Input/StringInput.php',
'Symfony\\Component\\Console\\Logger\\ConsoleLogger' => $vendorDir . '/symfony/console/Logger/ConsoleLogger.php',
'Symfony\\Component\\Console\\Output\\BufferedOutput' => $vendorDir . '/symfony/console/Output/BufferedOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutput' => $vendorDir . '/symfony/console/Output/ConsoleOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => $vendorDir . '/symfony/console/Output/ConsoleOutputInterface.php',
'Symfony\\Component\\Console\\Output\\NullOutput' => $vendorDir . '/symfony/console/Output/NullOutput.php',
'Symfony\\Component\\Console\\Output\\Output' => $vendorDir . '/symfony/console/Output/Output.php',
'Symfony\\Component\\Console\\Output\\OutputInterface' => $vendorDir . '/symfony/console/Output/OutputInterface.php',
'Symfony\\Component\\Console\\Output\\StreamOutput' => $vendorDir . '/symfony/console/Output/StreamOutput.php',
'Symfony\\Component\\Console\\Question\\ChoiceQuestion' => $vendorDir . '/symfony/console/Question/ChoiceQuestion.php',
'Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => $vendorDir . '/symfony/console/Question/ConfirmationQuestion.php',
'Symfony\\Component\\Console\\Question\\Question' => $vendorDir . '/symfony/console/Question/Question.php',
'Symfony\\Component\\Console\\Style\\OutputStyle' => $vendorDir . '/symfony/console/Style/OutputStyle.php',
'Symfony\\Component\\Console\\Style\\StyleInterface' => $vendorDir . '/symfony/console/Style/StyleInterface.php',
'Symfony\\Component\\Console\\Style\\SymfonyStyle' => $vendorDir . '/symfony/console/Style/SymfonyStyle.php',
'Symfony\\Component\\Console\\Tester\\ApplicationTester' => $vendorDir . '/symfony/console/Tester/ApplicationTester.php',
'Symfony\\Component\\Console\\Tester\\CommandTester' => $vendorDir . '/symfony/console/Tester/CommandTester.php',
'Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/ContainerAwareEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface' => $vendorDir . '/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener' => $vendorDir . '/symfony/event-dispatcher/Debug/WrappedListener.php',
'Symfony\\Component\\EventDispatcher\\DependencyInjection\\RegisterListenersPass' => $vendorDir . '/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php',
'Symfony\\Component\\EventDispatcher\\Event' => $vendorDir . '/symfony/event-dispatcher/Event.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcher' => $vendorDir . '/symfony/event-dispatcher/EventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcherInterface' => $vendorDir . '/symfony/event-dispatcher/EventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface' => $vendorDir . '/symfony/event-dispatcher/EventSubscriberInterface.php',
'Symfony\\Component\\EventDispatcher\\GenericEvent' => $vendorDir . '/symfony/event-dispatcher/GenericEvent.php',
'Symfony\\Component\\EventDispatcher\\ImmutableEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/ImmutableEventDispatcher.php',
'Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/filesystem/Exception/ExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => $vendorDir . '/symfony/filesystem/Exception/FileNotFoundException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOException' => $vendorDir . '/symfony/filesystem/Exception/IOException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => $vendorDir . '/symfony/filesystem/Exception/IOExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Filesystem' => $vendorDir . '/symfony/filesystem/Filesystem.php',
'Symfony\\Component\\Filesystem\\LockHandler' => $vendorDir . '/symfony/filesystem/LockHandler.php',
'Symfony\\Component\\Finder\\Comparator\\Comparator' => $vendorDir . '/symfony/finder/Comparator/Comparator.php',
'Symfony\\Component\\Finder\\Comparator\\DateComparator' => $vendorDir . '/symfony/finder/Comparator/DateComparator.php',
'Symfony\\Component\\Finder\\Comparator\\NumberComparator' => $vendorDir . '/symfony/finder/Comparator/NumberComparator.php',
'Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => $vendorDir . '/symfony/finder/Exception/AccessDeniedException.php',
'Symfony\\Component\\Finder\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/finder/Exception/ExceptionInterface.php',
'Symfony\\Component\\Finder\\Finder' => $vendorDir . '/symfony/finder/Finder.php',
'Symfony\\Component\\Finder\\Glob' => $vendorDir . '/symfony/finder/Glob.php',
'Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => $vendorDir . '/symfony/finder/Iterator/CustomFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DateRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DepthRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => $vendorDir . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FileTypeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilecontentFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilenameFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => $vendorDir . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => $vendorDir . '/symfony/finder/Iterator/PathFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => $vendorDir . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/SizeRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SortableIterator' => $vendorDir . '/symfony/finder/Iterator/SortableIterator.php',
'Symfony\\Component\\Finder\\SplFileInfo' => $vendorDir . '/symfony/finder/SplFileInfo.php',
'Symfony\\Component\\Process\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/process/Exception/ExceptionInterface.php',
'Symfony\\Component\\Process\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/process/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Process\\Exception\\LogicException' => $vendorDir . '/symfony/process/Exception/LogicException.php',
'Symfony\\Component\\Process\\Exception\\ProcessFailedException' => $vendorDir . '/symfony/process/Exception/ProcessFailedException.php',
'Symfony\\Component\\Process\\Exception\\ProcessTimedOutException' => $vendorDir . '/symfony/process/Exception/ProcessTimedOutException.php',
'Symfony\\Component\\Process\\Exception\\RuntimeException' => $vendorDir . '/symfony/process/Exception/RuntimeException.php',
'Symfony\\Component\\Process\\ExecutableFinder' => $vendorDir . '/symfony/process/ExecutableFinder.php',
'Symfony\\Component\\Process\\InputStream' => $vendorDir . '/symfony/process/InputStream.php',
'Symfony\\Component\\Process\\PhpExecutableFinder' => $vendorDir . '/symfony/process/PhpExecutableFinder.php',
'Symfony\\Component\\Process\\PhpProcess' => $vendorDir . '/symfony/process/PhpProcess.php',
'Symfony\\Component\\Process\\Pipes\\AbstractPipes' => $vendorDir . '/symfony/process/Pipes/AbstractPipes.php',
'Symfony\\Component\\Process\\Pipes\\PipesInterface' => $vendorDir . '/symfony/process/Pipes/PipesInterface.php',
'Symfony\\Component\\Process\\Pipes\\UnixPipes' => $vendorDir . '/symfony/process/Pipes/UnixPipes.php',
'Symfony\\Component\\Process\\Pipes\\WindowsPipes' => $vendorDir . '/symfony/process/Pipes/WindowsPipes.php',
'Symfony\\Component\\Process\\Process' => $vendorDir . '/symfony/process/Process.php',
'Symfony\\Component\\Process\\ProcessBuilder' => $vendorDir . '/symfony/process/ProcessBuilder.php',
'Symfony\\Component\\Process\\ProcessUtils' => $vendorDir . '/symfony/process/ProcessUtils.php',
'Symfony\\Component\\Stopwatch\\Section' => $vendorDir . '/symfony/stopwatch/Section.php',
'Symfony\\Component\\Stopwatch\\Stopwatch' => $vendorDir . '/symfony/stopwatch/Stopwatch.php',
'Symfony\\Component\\Stopwatch\\StopwatchEvent' => $vendorDir . '/symfony/stopwatch/StopwatchEvent.php',
'Symfony\\Component\\Stopwatch\\StopwatchPeriod' => $vendorDir . '/symfony/stopwatch/StopwatchPeriod.php',
'Symfony\\Component\\Yaml\\Dumper' => $vendorDir . '/symfony/yaml/Dumper.php',
'Symfony\\Component\\Yaml\\Escaper' => $vendorDir . '/symfony/yaml/Escaper.php',
'Symfony\\Component\\Yaml\\Exception\\DumpException' => $vendorDir . '/symfony/yaml/Exception/DumpException.php',
'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/yaml/Exception/ExceptionInterface.php',
'Symfony\\Component\\Yaml\\Exception\\ParseException' => $vendorDir . '/symfony/yaml/Exception/ParseException.php',
'Symfony\\Component\\Yaml\\Exception\\RuntimeException' => $vendorDir . '/symfony/yaml/Exception/RuntimeException.php',
'Symfony\\Component\\Yaml\\Inline' => $vendorDir . '/symfony/yaml/Inline.php',
'Symfony\\Component\\Yaml\\Parser' => $vendorDir . '/symfony/yaml/Parser.php',
'Symfony\\Component\\Yaml\\Unescaper' => $vendorDir . '/symfony/yaml/Unescaper.php',
'Symfony\\Component\\Yaml\\Yaml' => $vendorDir . '/symfony/yaml/Yaml.php',
'Symfony\\Polyfill\\Mbstring\\Mbstring' => $vendorDir . '/symfony/polyfill-mbstring/Mbstring.php',
'Text_Template' => $vendorDir . '/phpunit/php-text-template/src/Template.php',
'Webmozart\\Assert\\Assert' => $vendorDir . '/webmozart/assert/src/Assert.php',
'phpDocumentor\\Reflection\\DocBlock' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock.php',
'phpDocumentor\\Reflection\\DocBlockFactory' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlockFactory.php',
'phpDocumentor\\Reflection\\DocBlockFactoryInterface' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlockFactoryInterface.php',
'phpDocumentor\\Reflection\\DocBlock\\Description' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Description.php',
'phpDocumentor\\Reflection\\DocBlock\\DescriptionFactory' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/DescriptionFactory.php',
'phpDocumentor\\Reflection\\DocBlock\\Serializer' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Serializer.php',
'phpDocumentor\\Reflection\\DocBlock\\StandardTagFactory' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/StandardTagFactory.php',
'phpDocumentor\\Reflection\\DocBlock\\Tag' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tag.php',
'phpDocumentor\\Reflection\\DocBlock\\TagFactory' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/TagFactory.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Author' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Author.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\BaseTag' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/BaseTag.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Covers' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Covers.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Deprecated' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Deprecated.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Example' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Example.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Factory\\StaticMethod' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Factory/StaticMethod.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Factory\\Strategy' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Factory/Strategy.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Formatter' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Formatter.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Formatter\\PassthroughFormatter' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Formatter/PassthroughFormatter.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Generic' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Generic.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Link' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Link.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Method' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Method.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Param' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Param.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Property' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Property.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\PropertyRead' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/PropertyRead.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\PropertyWrite' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/PropertyWrite.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Return_' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Return_.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\See' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/See.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Since' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Since.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Source' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Source.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Throws' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Throws.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Uses' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Uses.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Var_' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Var_.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Version' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Version.php',
'phpDocumentor\\Reflection\\Element' => $vendorDir . '/phpdocumentor/reflection-common/src/Element.php',
'phpDocumentor\\Reflection\\ExampleFinder' => $vendorDir . '/phpdocumentor/reflection-docblock/src/DocBlock/ExampleFinder.php',
'phpDocumentor\\Reflection\\File' => $vendorDir . '/phpdocumentor/reflection-common/src/File.php',
'phpDocumentor\\Reflection\\Fqsen' => $vendorDir . '/phpdocumentor/reflection-common/src/Fqsen.php',
'phpDocumentor\\Reflection\\FqsenResolver' => $vendorDir . '/phpdocumentor/type-resolver/src/FqsenResolver.php',
'phpDocumentor\\Reflection\\Location' => $vendorDir . '/phpdocumentor/reflection-common/src/Location.php',
'phpDocumentor\\Reflection\\Project' => $vendorDir . '/phpdocumentor/reflection-common/src/Project.php',
'phpDocumentor\\Reflection\\ProjectFactory' => $vendorDir . '/phpdocumentor/reflection-common/src/ProjectFactory.php',
'phpDocumentor\\Reflection\\Type' => $vendorDir . '/phpdocumentor/type-resolver/src/Type.php',
'phpDocumentor\\Reflection\\TypeResolver' => $vendorDir . '/phpdocumentor/type-resolver/src/TypeResolver.php',
'phpDocumentor\\Reflection\\Types\\Array_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Array_.php',
'phpDocumentor\\Reflection\\Types\\Boolean' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Boolean.php',
'phpDocumentor\\Reflection\\Types\\Callable_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Callable_.php',
'phpDocumentor\\Reflection\\Types\\Compound' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Compound.php',
'phpDocumentor\\Reflection\\Types\\Context' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Context.php',
'phpDocumentor\\Reflection\\Types\\ContextFactory' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/ContextFactory.php',
'phpDocumentor\\Reflection\\Types\\Float_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Float_.php',
'phpDocumentor\\Reflection\\Types\\Integer' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Integer.php',
'phpDocumentor\\Reflection\\Types\\Mixed' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Mixed.php',
'phpDocumentor\\Reflection\\Types\\Null_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Null_.php',
'phpDocumentor\\Reflection\\Types\\Object_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Object_.php',
'phpDocumentor\\Reflection\\Types\\Resource' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Resource.php',
'phpDocumentor\\Reflection\\Types\\Scalar' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Scalar.php',
'phpDocumentor\\Reflection\\Types\\Self_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Self_.php',
'phpDocumentor\\Reflection\\Types\\Static_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Static_.php',
'phpDocumentor\\Reflection\\Types\\String_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/String_.php',
'phpDocumentor\\Reflection\\Types\\This' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/This.php',
'phpDocumentor\\Reflection\\Types\\Void_' => $vendorDir . '/phpdocumentor/type-resolver/src/Types/Void_.php',
);
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
);
<?php
namespace Composer\Autoload;
class ComposerStaticInit9d67f5014a965adc352c6ef25d43195e
{
public static $files = array (
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
);
public static $prefixLengthsPsr4 = array (
'p' =>
array (
'phpDocumentor\\Reflection\\' => 25,
),
'W' =>
array (
'Webmozart\\Assert\\' => 17,
),
'S' =>
array (
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Component\\Yaml\\' => 23,
'Symfony\\Component\\Stopwatch\\' => 28,
'Symfony\\Component\\Process\\' => 26,
'Symfony\\Component\\Finder\\' => 25,
'Symfony\\Component\\Filesystem\\' => 29,
'Symfony\\Component\\EventDispatcher\\' => 34,
'Symfony\\Component\\Console\\' => 26,
'Symfony\\Component\\Config\\' => 25,
'Symfony\\CS\\' => 11,
'Satooshi\\' => 9,
),
'P' =>
array (
'Psr\\Log\\' => 8,
),
'D' =>
array (
'Doctrine\\Instantiator\\' => 22,
'DeepCopy\\' => 9,
),
);
public static $prefixDirsPsr4 = array (
'phpDocumentor\\Reflection\\' =>
array (
0 => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src',
1 => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src',
2 => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src',
),
'Webmozart\\Assert\\' =>
array (
0 => __DIR__ . '/..' . '/webmozart/assert/src',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Component\\Yaml\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/yaml',
),
'Symfony\\Component\\Stopwatch\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/stopwatch',
),
'Symfony\\Component\\Process\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/process',
),
'Symfony\\Component\\Finder\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/finder',
),
'Symfony\\Component\\Filesystem\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/filesystem',
),
'Symfony\\Component\\EventDispatcher\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/event-dispatcher',
),
'Symfony\\Component\\Console\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
'Symfony\\Component\\Config\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/config',
),
'Symfony\\CS\\' =>
array (
0 => __DIR__ . '/../..' . '/Symfony/CS',
),
'Satooshi\\' =>
array (
0 => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'Doctrine\\Instantiator\\' =>
array (
0 => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator',
),
'DeepCopy\\' =>
array (
0 => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy',
),
);
public static $prefixesPsr0 = array (
'P' =>
array (
'Prophecy\\' =>
array (
0 => __DIR__ . '/..' . '/phpspec/prophecy/src',
),
),
'G' =>
array (
'Guzzle\\Tests' =>
array (
0 => __DIR__ . '/..' . '/guzzle/guzzle/tests',
),
'Guzzle' =>
array (
0 => __DIR__ . '/..' . '/guzzle/guzzle/src',
),
),
);
public static $classMap = array (
'DeepCopy\\DeepCopy' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/DeepCopy.php',
'DeepCopy\\Exception\\CloneException' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineCollectionFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineCollectionFilter.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineEmptyCollectionFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php',
'DeepCopy\\Filter\\Filter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php',
'DeepCopy\\Filter\\KeepFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Filter/KeepFilter.php',
'DeepCopy\\Filter\\ReplaceFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Filter/ReplaceFilter.php',
'DeepCopy\\Filter\\SetNullFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.php',
'DeepCopy\\Matcher\\Matcher' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Matcher/Matcher.php',
'DeepCopy\\Matcher\\PropertyMatcher' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyMatcher.php',
'DeepCopy\\Matcher\\PropertyNameMatcher' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php',
'DeepCopy\\Matcher\\PropertyTypeMatcher' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.php',
'DeepCopy\\Reflection\\ReflectionHelper' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.php',
'DeepCopy\\TypeFilter\\ReplaceFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php',
'DeepCopy\\TypeFilter\\ShallowCopyFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php',
'DeepCopy\\TypeFilter\\TypeFilter' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.php',
'DeepCopy\\TypeMatcher\\TypeMatcher' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/TypeMatcher/TypeMatcher.php',
'Doctrine\\Instantiator\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator/Exception/ExceptionInterface.php',
'Doctrine\\Instantiator\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator/Exception/InvalidArgumentException.php',
'Doctrine\\Instantiator\\Exception\\UnexpectedValueException' => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator/Exception/UnexpectedValueException.php',
'Doctrine\\Instantiator\\Instantiator' => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator/Instantiator.php',
'Doctrine\\Instantiator\\InstantiatorInterface' => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator/InstantiatorInterface.php',
'File_Iterator' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Iterator.php',
'File_Iterator_Facade' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Facade.php',
'File_Iterator_Factory' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Factory.php',
'Guzzle\\Batch\\AbstractBatchDecorator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php',
'Guzzle\\Batch\\Batch' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/Batch.php',
'Guzzle\\Batch\\BatchBuilder' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.php',
'Guzzle\\Batch\\BatchClosureDivisor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php',
'Guzzle\\Batch\\BatchClosureTransfer' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php',
'Guzzle\\Batch\\BatchCommandTransfer' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php',
'Guzzle\\Batch\\BatchDivisorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php',
'Guzzle\\Batch\\BatchInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchInterface.php',
'Guzzle\\Batch\\BatchRequestTransfer' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchRequestTransfer.php',
'Guzzle\\Batch\\BatchSizeDivisor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php',
'Guzzle\\Batch\\BatchTransferInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.php',
'Guzzle\\Batch\\ExceptionBufferingBatch' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php',
'Guzzle\\Batch\\Exception\\BatchTransferException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/Exception/BatchTransferException.php',
'Guzzle\\Batch\\FlushingBatch' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php',
'Guzzle\\Batch\\HistoryBatch' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.php',
'Guzzle\\Batch\\NotifyingBatch' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php',
'Guzzle\\Cache\\AbstractCacheAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php',
'Guzzle\\Cache\\CacheAdapterFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php',
'Guzzle\\Cache\\CacheAdapterInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.php',
'Guzzle\\Cache\\ClosureCacheAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/ClosureCacheAdapter.php',
'Guzzle\\Cache\\DoctrineCacheAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.php',
'Guzzle\\Cache\\NullCacheAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php',
'Guzzle\\Cache\\Zf1CacheAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/Zf1CacheAdapter.php',
'Guzzle\\Cache\\Zf2CacheAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.php',
'Guzzle\\Common\\AbstractHasDispatcher' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php',
'Guzzle\\Common\\Collection' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Collection.php',
'Guzzle\\Common\\Event' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Event.php',
'Guzzle\\Common\\Exception\\BadMethodCallException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php',
'Guzzle\\Common\\Exception\\ExceptionCollection' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Exception/ExceptionCollection.php',
'Guzzle\\Common\\Exception\\GuzzleException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.php',
'Guzzle\\Common\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Exception/InvalidArgumentException.php',
'Guzzle\\Common\\Exception\\RuntimeException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Exception/RuntimeException.php',
'Guzzle\\Common\\Exception\\UnexpectedValueException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Exception/UnexpectedValueException.php',
'Guzzle\\Common\\FromConfigInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/FromConfigInterface.php',
'Guzzle\\Common\\HasDispatcherInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/HasDispatcherInterface.php',
'Guzzle\\Common\\ToArrayInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/ToArrayInterface.php',
'Guzzle\\Common\\Version' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Common/Version.php',
'Guzzle\\Http\\AbstractEntityBodyDecorator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.php',
'Guzzle\\Http\\CachingEntityBody' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.php',
'Guzzle\\Http\\Client' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Client.php',
'Guzzle\\Http\\ClientInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php',
'Guzzle\\Http\\Curl\\CurlHandle' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlHandle.php',
'Guzzle\\Http\\Curl\\CurlMulti' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php',
'Guzzle\\Http\\Curl\\CurlMultiInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php',
'Guzzle\\Http\\Curl\\CurlMultiProxy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiProxy.php',
'Guzzle\\Http\\Curl\\CurlVersion' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php',
'Guzzle\\Http\\Curl\\RequestMediator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php',
'Guzzle\\Http\\EntityBody' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/EntityBody.php',
'Guzzle\\Http\\EntityBodyInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php',
'Guzzle\\Http\\Exception\\BadResponseException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/BadResponseException.php',
'Guzzle\\Http\\Exception\\ClientErrorResponseException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.php',
'Guzzle\\Http\\Exception\\CouldNotRewindStreamException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/CouldNotRewindStreamException.php',
'Guzzle\\Http\\Exception\\CurlException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/CurlException.php',
'Guzzle\\Http\\Exception\\HttpException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php',
'Guzzle\\Http\\Exception\\MultiTransferException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/MultiTransferException.php',
'Guzzle\\Http\\Exception\\RequestException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php',
'Guzzle\\Http\\Exception\\ServerErrorResponseException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.php',
'Guzzle\\Http\\Exception\\TooManyRedirectsException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Exception/TooManyRedirectsException.php',
'Guzzle\\Http\\IoEmittingEntityBody' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/IoEmittingEntityBody.php',
'Guzzle\\Http\\Message\\AbstractMessage' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php',
'Guzzle\\Http\\Message\\EntityEnclosingRequest' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php',
'Guzzle\\Http\\Message\\EntityEnclosingRequestInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php',
'Guzzle\\Http\\Message\\Header' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header.php',
'Guzzle\\Http\\Message\\Header\\CacheControl' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.php',
'Guzzle\\Http\\Message\\Header\\HeaderCollection' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php',
'Guzzle\\Http\\Message\\Header\\HeaderFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php',
'Guzzle\\Http\\Message\\Header\\HeaderFactoryInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php',
'Guzzle\\Http\\Message\\Header\\HeaderInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderInterface.php',
'Guzzle\\Http\\Message\\Header\\Link' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Header/Link.php',
'Guzzle\\Http\\Message\\MessageInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php',
'Guzzle\\Http\\Message\\PostFile' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/PostFile.php',
'Guzzle\\Http\\Message\\PostFileInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.php',
'Guzzle\\Http\\Message\\Request' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Request.php',
'Guzzle\\Http\\Message\\RequestFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php',
'Guzzle\\Http\\Message\\RequestFactoryInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php',
'Guzzle\\Http\\Message\\RequestInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/RequestInterface.php',
'Guzzle\\Http\\Message\\Response' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Message/Response.php',
'Guzzle\\Http\\Mimetypes' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Mimetypes.php',
'Guzzle\\Http\\QueryAggregator\\CommaAggregator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.php',
'Guzzle\\Http\\QueryAggregator\\DuplicateAggregator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.php',
'Guzzle\\Http\\QueryAggregator\\PhpAggregator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php',
'Guzzle\\Http\\QueryAggregator\\QueryAggregatorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php',
'Guzzle\\Http\\QueryString' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/QueryString.php',
'Guzzle\\Http\\ReadLimitEntityBody' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php',
'Guzzle\\Http\\RedirectPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php',
'Guzzle\\Http\\StaticClient' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/StaticClient.php',
'Guzzle\\Http\\Url' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Http/Url.php',
'Guzzle\\Inflection\\Inflector' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Inflection/Inflector.php',
'Guzzle\\Inflection\\InflectorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Inflection/InflectorInterface.php',
'Guzzle\\Inflection\\MemoizingInflector' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Inflection/MemoizingInflector.php',
'Guzzle\\Inflection\\PreComputedInflector' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.php',
'Guzzle\\Iterator\\AppendIterator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.php',
'Guzzle\\Iterator\\ChunkedIterator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php',
'Guzzle\\Iterator\\FilterIterator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.php',
'Guzzle\\Iterator\\MapIterator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.php',
'Guzzle\\Iterator\\MethodProxyIterator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php',
'Guzzle\\Log\\AbstractLogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php',
'Guzzle\\Log\\ArrayLogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php',
'Guzzle\\Log\\ClosureLogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php',
'Guzzle\\Log\\LogAdapterInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php',
'Guzzle\\Log\\MessageFormatter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/MessageFormatter.php',
'Guzzle\\Log\\MonologLogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php',
'Guzzle\\Log\\PsrLogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.php',
'Guzzle\\Log\\Zf1LogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.php',
'Guzzle\\Log\\Zf2LogAdapter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php',
'Guzzle\\Parser\\Cookie\\CookieParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php',
'Guzzle\\Parser\\Cookie\\CookieParserInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php',
'Guzzle\\Parser\\Message\\AbstractMessageParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Message/AbstractMessageParser.php',
'Guzzle\\Parser\\Message\\MessageParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php',
'Guzzle\\Parser\\Message\\MessageParserInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php',
'Guzzle\\Parser\\Message\\PeclHttpMessageParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Message/PeclHttpMessageParser.php',
'Guzzle\\Parser\\ParserRegistry' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php',
'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php',
'Guzzle\\Parser\\UriTemplate\\UriTemplate' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplate.php',
'Guzzle\\Parser\\UriTemplate\\UriTemplateInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php',
'Guzzle\\Parser\\Url\\UrlParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParser.php',
'Guzzle\\Parser\\Url\\UrlParserInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.php',
'Guzzle\\Plugin\\Async\\AsyncPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php',
'Guzzle\\Plugin\\Backoff\\AbstractBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\AbstractErrorCodeBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\BackoffLogger' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.php',
'Guzzle\\Plugin\\Backoff\\BackoffPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php',
'Guzzle\\Plugin\\Backoff\\BackoffStrategyInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php',
'Guzzle\\Plugin\\Backoff\\CallbackBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\ConstantBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\CurlBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\ExponentialBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\HttpBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\LinearBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\ReasonPhraseBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php',
'Guzzle\\Plugin\\Backoff\\TruncatedBackoffStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php',
'Guzzle\\Plugin\\Cache\\CacheKeyProviderInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php',
'Guzzle\\Plugin\\Cache\\CachePlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CachePlugin.php',
'Guzzle\\Plugin\\Cache\\CacheStorageInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php',
'Guzzle\\Plugin\\Cache\\CallbackCanCacheStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.php',
'Guzzle\\Plugin\\Cache\\CanCacheStrategyInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php',
'Guzzle\\Plugin\\Cache\\DefaultCacheKeyProvider' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.php',
'Guzzle\\Plugin\\Cache\\DefaultCacheStorage' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php',
'Guzzle\\Plugin\\Cache\\DefaultCanCacheStrategy' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php',
'Guzzle\\Plugin\\Cache\\DefaultRevalidation' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php',
'Guzzle\\Plugin\\Cache\\DenyRevalidation' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php',
'Guzzle\\Plugin\\Cache\\RevalidationInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/RevalidationInterface.php',
'Guzzle\\Plugin\\Cache\\SkipRevalidation' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cache/SkipRevalidation.php',
'Guzzle\\Plugin\\Cookie\\Cookie' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php',
'Guzzle\\Plugin\\Cookie\\CookieJar\\ArrayCookieJar' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php',
'Guzzle\\Plugin\\Cookie\\CookieJar\\CookieJarInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php',
'Guzzle\\Plugin\\Cookie\\CookieJar\\FileCookieJar' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php',
'Guzzle\\Plugin\\Cookie\\CookiePlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.php',
'Guzzle\\Plugin\\Cookie\\Exception\\InvalidCookieException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php',
'Guzzle\\Plugin\\CurlAuth\\CurlAuthPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.php',
'Guzzle\\Plugin\\ErrorResponse\\ErrorResponseExceptionInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php',
'Guzzle\\Plugin\\ErrorResponse\\ErrorResponsePlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.php',
'Guzzle\\Plugin\\ErrorResponse\\Exception\\ErrorResponseException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php',
'Guzzle\\Plugin\\History\\HistoryPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.php',
'Guzzle\\Plugin\\Log\\LogPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.php',
'Guzzle\\Plugin\\Md5\\CommandContentMd5Plugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php',
'Guzzle\\Plugin\\Md5\\Md5ValidatorPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php',
'Guzzle\\Plugin\\Mock\\MockPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.php',
'Guzzle\\Plugin\\Oauth\\OauthPlugin' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php',
'Guzzle\\Service\\AbstractConfigLoader' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php',
'Guzzle\\Service\\Builder\\ServiceBuilder' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.php',
'Guzzle\\Service\\Builder\\ServiceBuilderInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.php',
'Guzzle\\Service\\Builder\\ServiceBuilderLoader' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderLoader.php',
'Guzzle\\Service\\CachingConfigLoader' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php',
'Guzzle\\Service\\Client' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Client.php',
'Guzzle\\Service\\ClientInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php',
'Guzzle\\Service\\Command\\AbstractCommand' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/AbstractCommand.php',
'Guzzle\\Service\\Command\\ClosureCommand' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php',
'Guzzle\\Service\\Command\\CommandInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.php',
'Guzzle\\Service\\Command\\CreateResponseClassEvent' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/CreateResponseClassEvent.php',
'Guzzle\\Service\\Command\\DefaultRequestSerializer' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.php',
'Guzzle\\Service\\Command\\DefaultResponseParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.php',
'Guzzle\\Service\\Command\\Factory\\AliasFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.php',
'Guzzle\\Service\\Command\\Factory\\CompositeFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.php',
'Guzzle\\Service\\Command\\Factory\\ConcreteClassFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php',
'Guzzle\\Service\\Command\\Factory\\FactoryInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.php',
'Guzzle\\Service\\Command\\Factory\\MapFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/MapFactory.php',
'Guzzle\\Service\\Command\\Factory\\ServiceDescriptionFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\AbstractRequestVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\BodyVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\HeaderVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\JsonVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\PostFieldVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\PostFileVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\QueryVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\RequestVisitorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\ResponseBodyVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Request\\XmlVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\AbstractResponseVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\BodyVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\HeaderVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\JsonVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\ReasonPhraseVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\ResponseVisitorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\StatusCodeVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\Response\\XmlVisitor' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php',
'Guzzle\\Service\\Command\\LocationVisitor\\VisitorFlyweight' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php',
'Guzzle\\Service\\Command\\OperationCommand' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php',
'Guzzle\\Service\\Command\\OperationResponseParser' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php',
'Guzzle\\Service\\Command\\RequestSerializerInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.php',
'Guzzle\\Service\\Command\\ResponseClassInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/ResponseClassInterface.php',
'Guzzle\\Service\\Command\\ResponseParserInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Command/ResponseParserInterface.php',
'Guzzle\\Service\\ConfigLoaderInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/ConfigLoaderInterface.php',
'Guzzle\\Service\\Description\\Operation' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/Operation.php',
'Guzzle\\Service\\Description\\OperationInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php',
'Guzzle\\Service\\Description\\Parameter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/Parameter.php',
'Guzzle\\Service\\Description\\SchemaFormatter' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.php',
'Guzzle\\Service\\Description\\SchemaValidator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php',
'Guzzle\\Service\\Description\\ServiceDescription' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php',
'Guzzle\\Service\\Description\\ServiceDescriptionInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.php',
'Guzzle\\Service\\Description\\ServiceDescriptionLoader' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionLoader.php',
'Guzzle\\Service\\Description\\ValidatorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php',
'Guzzle\\Service\\Exception\\CommandException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/CommandException.php',
'Guzzle\\Service\\Exception\\CommandTransferException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/CommandTransferException.php',
'Guzzle\\Service\\Exception\\DescriptionBuilderException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php',
'Guzzle\\Service\\Exception\\InconsistentClientTransferException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/InconsistentClientTransferException.php',
'Guzzle\\Service\\Exception\\ResponseClassException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php',
'Guzzle\\Service\\Exception\\ServiceBuilderException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceBuilderException.php',
'Guzzle\\Service\\Exception\\ServiceNotFoundException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceNotFoundException.php',
'Guzzle\\Service\\Exception\\ValidationException' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Exception/ValidationException.php',
'Guzzle\\Service\\Resource\\AbstractResourceIteratorFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php',
'Guzzle\\Service\\Resource\\CompositeResourceIteratorFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php',
'Guzzle\\Service\\Resource\\MapResourceIteratorFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.php',
'Guzzle\\Service\\Resource\\Model' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php',
'Guzzle\\Service\\Resource\\ResourceIterator' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php',
'Guzzle\\Service\\Resource\\ResourceIteratorApplyBatched' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php',
'Guzzle\\Service\\Resource\\ResourceIteratorClassFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php',
'Guzzle\\Service\\Resource\\ResourceIteratorFactoryInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php',
'Guzzle\\Service\\Resource\\ResourceIteratorInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorInterface.php',
'Guzzle\\Stream\\PhpStreamRequestFactory' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php',
'Guzzle\\Stream\\Stream' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Stream/Stream.php',
'Guzzle\\Stream\\StreamInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php',
'Guzzle\\Stream\\StreamRequestFactoryInterface' => __DIR__ . '/..' . '/guzzle/guzzle/src/Guzzle/Stream/StreamRequestFactoryInterface.php',
'Guzzle\\Tests\\Batch\\AbstractBatchDecoratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/AbstractBatchDecoratorTest.php',
'Guzzle\\Tests\\Batch\\BatchBuilderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchBuilderTest.php',
'Guzzle\\Tests\\Batch\\BatchClosureDivisorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureDivisorTest.php',
'Guzzle\\Tests\\Batch\\BatchClosureTransferTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureTransferTest.php',
'Guzzle\\Tests\\Batch\\BatchCommandTransferTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchCommandTransferTest.php',
'Guzzle\\Tests\\Batch\\BatchRequestTransferTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchRequestTransferTest.php',
'Guzzle\\Tests\\Batch\\BatchSizeDivisorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchSizeDivisorTest.php',
'Guzzle\\Tests\\Batch\\BatchTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchTest.php',
'Guzzle\\Tests\\Batch\\ExceptionBufferingBatchTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/ExceptionBufferingBatchTest.php',
'Guzzle\\Tests\\Batch\\FlushingBatchTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/FlushingBatchTest.php',
'Guzzle\\Tests\\Batch\\HistoryBatchTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/HistoryBatchTest.php',
'Guzzle\\Tests\\Batch\\NotifyingBatchTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Batch/NotifyingBatchTest.php',
'Guzzle\\Tests\\Cache\\CacheAdapterFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterFactoryTest.php',
'Guzzle\\Tests\\Cache\\CacheAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterTest.php',
'Guzzle\\Tests\\Cache\\ClosureCacheAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/ClosureCacheAdapterTest.php',
'Guzzle\\Tests\\Cache\\Zf2CacheAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/Zf2CacheAdapterTest.php',
'Guzzle\\Tests\\Common\\AbstractHasAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Common/AbstractHasDispatcherTest.php',
'Guzzle\\Tests\\Common\\Cache\\NullCacheAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Cache/NullCacheAdapterTest.php',
'Guzzle\\Tests\\Common\\CollectionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Common/CollectionTest.php',
'Guzzle\\Tests\\Common\\EventTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Common/EventTest.php',
'Guzzle\\Tests\\Common\\Exception\\BatchTransferExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/BatchTransferExceptionTest.php',
'Guzzle\\Tests\\Common\\Exception\\ExceptionCollectionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php',
'Guzzle\\Tests\\Common\\VersionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Common/VersionTest.php',
'Guzzle\\Tests\\GuzzleTestCase' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/GuzzleTestCase.php',
'Guzzle\\Tests\\Http\\AbstractEntityBodyDecoratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/AbstractEntityBodyDecoratorTest.php',
'Guzzle\\Tests\\Http\\CachingEntityBodyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/CachingEntityBodyTest.php',
'Guzzle\\Tests\\Http\\ClientTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/ClientTest.php',
'Guzzle\\Tests\\Http\\CommaAggregatorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/CommaAggregatorTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlHandleTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlHandleTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlMultiProxyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiProxyTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlMultiTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiTest.php',
'Guzzle\\Tests\\Http\\Curl\\CurlVersionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlVersionTest.php',
'Guzzle\\Tests\\Http\\Curl\\RequestMediatorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/RequestMediatorTest.php',
'Guzzle\\Tests\\Http\\DuplicateAggregatorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/DuplicateAggregatorTest.php',
'Guzzle\\Tests\\Http\\EntityBodyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/EntityBodyTest.php',
'Guzzle\\Tests\\Http\\Exception\\CurlExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/CurlExceptionTest.php',
'Guzzle\\Tests\\Http\\Exception\\ExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/ExceptionTest.php',
'Guzzle\\Tests\\Http\\Exception\\MultiTransferExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/MultiTransferExceptionTest.php',
'Guzzle\\Tests\\Http\\IoEmittingEntityBodyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/IoEmittingEntityBodyTest.php',
'Guzzle\\Tests\\Http\\Message\\AbstractMessageTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/AbstractMessageTest.php',
'Guzzle\\Tests\\Http\\Message\\EntityEnclosingRequestTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/EntityEnclosingRequestTest.php',
'Guzzle\\Tests\\Http\\Message\\HeaderComparison' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php',
'Guzzle\\Tests\\Http\\Message\\HeaderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderTest.php',
'Guzzle\\Tests\\Http\\Message\\Header\\HeaderFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/HeaderFactoryTest.php',
'Guzzle\\Tests\\Http\\Message\\Header\\LinkTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/LinkTest.php',
'Guzzle\\Tests\\Http\\Message\\HttpRequestFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestFactoryTest.php',
'Guzzle\\Tests\\Http\\Message\\PostFileTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/PostFileTest.php',
'Guzzle\\Tests\\Http\\Message\\RequestTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestTest.php',
'Guzzle\\Tests\\Http\\MimetypesTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/MimetypesTest.php',
'Guzzle\\Tests\\Http\\PhpAggregatorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/PhpAggregatorTest.php',
'Guzzle\\Tests\\Http\\QueryStringTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryStringTest.php',
'Guzzle\\Tests\\Http\\ReadLimitEntityBodyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/ReadLimitEntityBodyTest.php',
'Guzzle\\Tests\\Http\\Server' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.php',
'Guzzle\\Tests\\Http\\UrlTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php',
'Guzzle\\Tests\\Inflection\\InflectorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Inflection/InflectorTest.php',
'Guzzle\\Tests\\Inflection\\MemoizingInflectorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Inflection/MemoizingInflectorTest.php',
'Guzzle\\Tests\\Inflection\\PreComputedInflectorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Inflection/PreComputedInflectorTest.php',
'Guzzle\\Tests\\Iterator\\AppendIteratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/AppendIteratorTest.php',
'Guzzle\\Tests\\Iterator\\ChunkedIteratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/ChunkedIteratorTest.php',
'Guzzle\\Tests\\Iterator\\FilterIteratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/FilterIteratorTest.php',
'Guzzle\\Tests\\Iterator\\MapIteratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MapIteratorTest.php',
'Guzzle\\Tests\\Iterator\\MethodProxyIteratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MethodProxyIteratorTest.php',
'Guzzle\\Tests\\Log\\ArrayLogAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Log/ArrayLogAdapterTest.php',
'Guzzle\\Tests\\Log\\ClosureLogAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Log/ClosureLogAdapterTest.php',
'Guzzle\\Tests\\Log\\MessageFormatterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Log/MessageFormatterTest.php',
'Guzzle\\Tests\\Log\\PsrLogAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Log/PsrLogAdapterTest.php',
'Guzzle\\Tests\\Log\\Zf2LogAdapterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Log/Zf2LogAdapterTest.php',
'Guzzle\\Tests\\Message\\HeaderComparisonTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparisonTest.php',
'Guzzle\\Tests\\Message\\ResponseTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/ResponseTest.php',
'Guzzle\\Tests\\Mock\\CustomResponseModel' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/CustomResponseModel.php',
'Guzzle\\Tests\\Mock\\ErrorResponseMock' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/ErrorResponseMock.php',
'Guzzle\\Tests\\Mock\\ExceptionMock' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/ExceptionMock.php',
'Guzzle\\Tests\\Mock\\MockMulti' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockMulti.php',
'Guzzle\\Tests\\Mock\\MockObserver' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockObserver.php',
'Guzzle\\Tests\\Mock\\MockSubject' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockSubject.php',
'Guzzle\\Tests\\Parser\\Cookie\\CookieParserProvider' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserProvider.php',
'Guzzle\\Tests\\Parser\\Cookie\\CookieParserTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserTest.php',
'Guzzle\\Tests\\Parser\\Message\\MessageParserProvider' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.php',
'Guzzle\\Tests\\Parser\\Message\\MessageParserTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserTest.php',
'Guzzle\\Tests\\Parser\\Message\\PeclHttpMessageParserTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/PeclHttpMessageParserTest.php',
'Guzzle\\Tests\\Parser\\ParserRegistryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/ParserRegistryTest.php',
'Guzzle\\Tests\\Parsers\\UriTemplate\\AbstractUriTemplateTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/AbstractUriTemplateTest.php',
'Guzzle\\Tests\\Parsers\\UriTemplate\\PeclUriTemplateTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/PeclUriTemplateTest.php',
'Guzzle\\Tests\\Parsers\\UriTemplate\\UriTemplateTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/UriTemplateTest.php',
'Guzzle\\Tests\\Plugin\\Async\\AsyncPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Async/AsyncPluginTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\AbstractBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/AbstractBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\BackoffLoggerTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffLoggerTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\BackoffPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffPluginTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\CallbackBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CallbackBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\ConstantBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ConstantBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\CurlBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CurlBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\ExponentialBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ExponentialBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\HttpBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/HttpBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\LinearBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/LinearBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\ReasonPhraseBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ReasonPhraseBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Backoff\\TruncatedBackoffStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/TruncatedBackoffStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\CachePluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CachePluginTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\CallbackCanCacheStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CallbackCanCacheStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DefaultCacheStorageTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCacheStorageTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DefaultCanCacheStrategyTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCanCacheStrategyTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DefaultRevalidationTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultRevalidationTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\DenyRevalidationTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DenyRevalidationTest.php',
'Guzzle\\Tests\\Plugin\\Cache\\SkipRevalidationTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/SkipRevalidationTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookieJar\\ArrayCookieJarTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/ArrayCookieJarTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookieJar\\FileCookieJarTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/FileCookieJarTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookiePluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookiePluginTest.php',
'Guzzle\\Tests\\Plugin\\Cookie\\CookieTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieTest.php',
'Guzzle\\Tests\\Plugin\\CurlAuth\\CurlAuthPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/CurlAuth/CurlAuthPluginTest.php',
'Guzzle\\Tests\\Plugin\\ErrorResponse\\ErrorResponsePluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/ErrorResponse/ErrorResponsePluginTest.php',
'Guzzle\\Tests\\Plugin\\History\\HistoryPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/History/HistoryPluginTest.php',
'Guzzle\\Tests\\Plugin\\Log\\LogPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Log/LogPluginTest.php',
'Guzzle\\Tests\\Plugin\\Md5\\CommandContentMd5PluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/CommandContentMd5PluginTest.php',
'Guzzle\\Tests\\Plugin\\Md5\\Md5ValidatorPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/Md5ValidatorPluginTest.php',
'Guzzle\\Tests\\Plugin\\Mock\\MockPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Mock/MockPluginTest.php',
'Guzzle\\Tests\\Plugin\\Oauth\\OauthPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Oauth/OauthPluginTest.php',
'Guzzle\\Tests\\Plugin\\Redirect\\RedirectPluginTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/RedirectPluginTest.php',
'Guzzle\\Tests\\Plugin\\Redirect\\StaticClientTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Http/StaticClientTest.php',
'Guzzle\\Tests\\Service\\AbstractConfigLoaderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/AbstractConfigLoaderTest.php',
'Guzzle\\Tests\\Service\\Builder\\ServiceBuilderLoaderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderLoaderTest.php',
'Guzzle\\Tests\\Service\\CachingConfigLoaderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/CachingConfigLoaderTest.php',
'Guzzle\\Tests\\Service\\ClientTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/ClientTest.php',
'Guzzle\\Tests\\Service\\Command\\AbstractCommandTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/AbstractCommandTest.php',
'Guzzle\\Tests\\Service\\Command\\AliasFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/AliasFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\ClosureCommandTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/ClosureCommandTest.php',
'Guzzle\\Tests\\Service\\Command\\CommandTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/CommandTest.php',
'Guzzle\\Tests\\Service\\Command\\CompositeFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/CompositeFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\ConcreteClassFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ConcreteClassFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\DefaultRequestSerializerTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultRequestSerializerTest.php',
'Guzzle\\Tests\\Service\\Command\\DefaultResponseParserTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultResponseParserTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\AbstractVisitorTestCase' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\BodyVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/BodyVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\HeaderVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/HeaderVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\JsonVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/JsonVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\PostFieldVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFieldVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\PostFileVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFileVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\QueryVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/QueryVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\ResponseBodyVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/ResponseBodyVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\XmlVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/XmlVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\AbstractResponseVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/AbstractResponseVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\BodyVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/BodyVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\HeaderVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/HeaderVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\JsonVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/JsonVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\ReasonPhraseVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/ReasonPhraseVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\StatusCodeVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/StatusCodeVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Response\\XmlVisitorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/XmlVisitorTest.php',
'Guzzle\\Tests\\Service\\Command\\MapFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/MapFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\OperationCommandTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationCommandTest.php',
'Guzzle\\Tests\\Service\\Command\\OperationResponseParserTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationResponseParserTest.php',
'Guzzle\\Tests\\Service\\Command\\ServiceDescriptionFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ServiceDescriptionFactoryTest.php',
'Guzzle\\Tests\\Service\\Command\\VisitorFlyweightTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/VisitorFlyweightTest.php',
'Guzzle\\Tests\\Service\\Description\\OperationTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/OperationTest.php',
'Guzzle\\Tests\\Service\\Description\\ParameterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ParameterTest.php',
'Guzzle\\Tests\\Service\\Description\\SchemaFormatterTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaFormatterTest.php',
'Guzzle\\Tests\\Service\\Description\\SchemaValidatorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaValidatorTest.php',
'Guzzle\\Tests\\Service\\Description\\ServiceDescriptionLoaderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionLoaderTest.php',
'Guzzle\\Tests\\Service\\Description\\ServiceDescriptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionTest.php',
'Guzzle\\Tests\\Service\\Exception\\CommandTransferExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/CommandTransferExceptionTest.php',
'Guzzle\\Tests\\Service\\Exception\\InconsistentClientTransferExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/InconsistentClientTransferExceptionTest.php',
'Guzzle\\Tests\\Service\\Exception\\ValidationExceptionTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/ValidationExceptionTest.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\IterableCommand' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/IterableCommand.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/MockCommand.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\OtherCommand' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/OtherCommand.php',
'Guzzle\\Tests\\Service\\Mock\\Command\\Sub\\Sub' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/Sub/Sub.php',
'Guzzle\\Tests\\Service\\Mock\\MockClient' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/MockClient.php',
'Guzzle\\Tests\\Service\\Mock\\Model\\MockCommandIterator' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Model/MockCommandIterator.php',
'Guzzle\\Tests\\Service\\Resource\\CompositeResourceIteratorFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/CompositeResourceIteratorFactoryTest.php',
'Guzzle\\Tests\\Service\\Resource\\MapResourceIteratorFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/MapResourceIteratorFactoryTest.php',
'Guzzle\\Tests\\Service\\Resource\\ModelTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ModelTest.php',
'Guzzle\\Tests\\Service\\Resource\\ResourceIteratorClassFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorClassFactoryTest.php',
'Guzzle\\Tests\\Service\\Resource\\ResourceIteratorTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorTest.php',
'Guzzle\\Tests\\Service\\ServiceBuilderTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderTest.php',
'Guzzle\\Tests\\Stream\\PhpStreamRequestFactoryTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Stream/PhpStreamRequestFactoryTest.php',
'Guzzle\\Tests\\Stream\\StreamTest' => __DIR__ . '/..' . '/guzzle/guzzle/tests/Guzzle/Tests/Stream/StreamTest.php',
'PHPUnit\\Framework\\TestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/ForwardCompatibility/TestCase.php',
'PHPUnit_Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Exception.php',
'PHPUnit_Extensions_GroupTestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Extensions/GroupTestSuite.php',
'PHPUnit_Extensions_PhptTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Extensions/PhptTestCase.php',
'PHPUnit_Extensions_PhptTestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Extensions/PhptTestSuite.php',
'PHPUnit_Extensions_RepeatedTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Extensions/RepeatedTest.php',
'PHPUnit_Extensions_TestDecorator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Extensions/TestDecorator.php',
'PHPUnit_Extensions_TicketListener' => __DIR__ . '/..' . '/phpunit/phpunit/src/Extensions/TicketListener.php',
'PHPUnit_Framework_Assert' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Assert.php',
'PHPUnit_Framework_AssertionFailedError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/AssertionFailedError.php',
'PHPUnit_Framework_BaseTestListener' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/BaseTestListener.php',
'PHPUnit_Framework_CodeCoverageException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/CodeCoverageException.php',
'PHPUnit_Framework_Constraint' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint.php',
'PHPUnit_Framework_Constraint_And' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/And.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_Count' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Count.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_ExceptionMessageRegExp' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegExp.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_IsTrue' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsTrue.php',
'PHPUnit_Framework_Constraint_IsType' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsType.php',
'PHPUnit_Framework_Constraint_JsonMatches' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php',
'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches/ErrorMessageProvider.php',
'PHPUnit_Framework_Constraint_LessThan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LessThan.php',
'PHPUnit_Framework_Constraint_Not' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Not.php',
'PHPUnit_Framework_Constraint_ObjectHasAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php',
'PHPUnit_Framework_Constraint_Or' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Or.php',
'PHPUnit_Framework_Constraint_PCREMatch' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/PCREMatch.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_StringMatches' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringMatches.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_TraversableContainsOnly' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php',
'PHPUnit_Framework_Constraint_Xor' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Xor.php',
'PHPUnit_Framework_CoveredCodeNotExecutedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/PHPUnit_Framework_CoveredCodeNotExecutedException.php',
'PHPUnit_Framework_Error' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error.php',
'PHPUnit_Framework_Error_Deprecated' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Deprecated.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.php',
'PHPUnit_Framework_ExceptionWrapper' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/ExceptionWrapper.php',
'PHPUnit_Framework_ExpectationFailedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/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/IncompleteTestError.php',
'PHPUnit_Framework_InvalidCoversTargetException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/InvalidCoversTargetException.php',
'PHPUnit_Framework_MissingCoversAnnotationException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/PHPUnit_Framework_MissingCoversAnnotationException.php',
'PHPUnit_Framework_MockObject_BadMethodCallException' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/BadMethodCallException.php',
'PHPUnit_Framework_MockObject_Builder_Identity' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Identity.php',
'PHPUnit_Framework_MockObject_Builder_InvocationMocker' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/InvocationMocker.php',
'PHPUnit_Framework_MockObject_Builder_Match' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Match.php',
'PHPUnit_Framework_MockObject_Builder_MethodNameMatch' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/MethodNameMatch.php',
'PHPUnit_Framework_MockObject_Builder_Namespace' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Namespace.php',
'PHPUnit_Framework_MockObject_Builder_ParametersMatch' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/ParametersMatch.php',
'PHPUnit_Framework_MockObject_Builder_Stub' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Stub.php',
'PHPUnit_Framework_MockObject_Exception' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/Exception.php',
'PHPUnit_Framework_MockObject_Generator' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php',
'PHPUnit_Framework_MockObject_Invocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation.php',
'PHPUnit_Framework_MockObject_InvocationMocker' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/InvocationMocker.php',
'PHPUnit_Framework_MockObject_Invocation_Object' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Object.php',
'PHPUnit_Framework_MockObject_Invocation_Static' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Static.php',
'PHPUnit_Framework_MockObject_Invokable' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invokable.php',
'PHPUnit_Framework_MockObject_Matcher' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher.php',
'PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyInvokedCount.php',
'PHPUnit_Framework_MockObject_Matcher_AnyParameters' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyParameters.php',
'PHPUnit_Framework_MockObject_Matcher_ConsecutiveParameters' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/ConsecutiveParameters.php',
'PHPUnit_Framework_MockObject_Matcher_Invocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Invocation.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtIndex.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastCount.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastOnce.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedAtMostCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtMostCount.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedCount.php',
'PHPUnit_Framework_MockObject_Matcher_InvokedRecorder' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedRecorder.php',
'PHPUnit_Framework_MockObject_Matcher_MethodName' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/MethodName.php',
'PHPUnit_Framework_MockObject_Matcher_Parameters' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Parameters.php',
'PHPUnit_Framework_MockObject_Matcher_StatelessInvocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/StatelessInvocation.php',
'PHPUnit_Framework_MockObject_MockBuilder' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockBuilder.php',
'PHPUnit_Framework_MockObject_MockObject' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockObject.php',
'PHPUnit_Framework_MockObject_RuntimeException' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/RuntimeException.php',
'PHPUnit_Framework_MockObject_Stub' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub.php',
'PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ConsecutiveCalls.php',
'PHPUnit_Framework_MockObject_Stub_Exception' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Exception.php',
'PHPUnit_Framework_MockObject_Stub_MatcherCollection' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/MatcherCollection.php',
'PHPUnit_Framework_MockObject_Stub_Return' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Return.php',
'PHPUnit_Framework_MockObject_Stub_ReturnArgument' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnArgument.php',
'PHPUnit_Framework_MockObject_Stub_ReturnCallback' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnCallback.php',
'PHPUnit_Framework_MockObject_Stub_ReturnReference' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnReference.php',
'PHPUnit_Framework_MockObject_Stub_ReturnSelf' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnSelf.php',
'PHPUnit_Framework_MockObject_Stub_ReturnValueMap' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnValueMap.php',
'PHPUnit_Framework_MockObject_Verifiable' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Verifiable.php',
'PHPUnit_Framework_OutputError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/OutputError.php',
'PHPUnit_Framework_RiskyTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/RiskyTest.php',
'PHPUnit_Framework_RiskyTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/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/SkippedTestError.php',
'PHPUnit_Framework_SkippedTestSuiteError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTestSuiteError.php',
'PHPUnit_Framework_SyntheticError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SyntheticError.php',
'PHPUnit_Framework_Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Test.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_TestResult' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestResult.php',
'PHPUnit_Framework_TestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestSuite.php',
'PHPUnit_Framework_TestSuite_DataProvider' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestSuite/DataProvider.php',
'PHPUnit_Framework_UnintentionallyCoveredCodeError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/UnintentionallyCoveredCodeError.php',
'PHPUnit_Framework_Warning' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Warning.php',
'PHPUnit_Framework_WarningTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/WarningTestCase.php',
'PHPUnit_Runner_BaseTestRunner' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/BaseTestRunner.php',
'PHPUnit_Runner_Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Exception.php',
'PHPUnit_Runner_Filter_Factory' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Factory.php',
'PHPUnit_Runner_Filter_GroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Group.php',
'PHPUnit_Runner_Filter_Group_Exclude' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Group/Exclude.php',
'PHPUnit_Runner_Filter_Group_Include' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Group/Include.php',
'PHPUnit_Runner_Filter_Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Test.php',
'PHPUnit_Runner_StandardTestSuiteLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php',
'PHPUnit_Runner_TestSuiteLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/TestSuiteLoader.php',
'PHPUnit_Runner_Version' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Version.php',
'PHPUnit_TextUI_Command' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/Command.php',
'PHPUnit_TextUI_ResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/ResultPrinter.php',
'PHPUnit_TextUI_TestRunner' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/TestRunner.php',
'PHPUnit_Util_Blacklist' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Blacklist.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_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_InvalidArgumentHelper' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/InvalidArgumentHelper.php',
'PHPUnit_Util_Log_JSON' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/JSON.php',
'PHPUnit_Util_Log_JUnit' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/JUnit.php',
'PHPUnit_Util_Log_TAP' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/TAP.php',
'PHPUnit_Util_Log_TeamCity' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/TeamCity.php',
'PHPUnit_Util_PHP' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP.php',
'PHPUnit_Util_PHP_Default' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/Default.php',
'PHPUnit_Util_PHP_Windows' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/Windows.php',
'PHPUnit_Util_Printer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Printer.php',
'PHPUnit_Util_Regex' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Regex.php',
'PHPUnit_Util_String' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/String.php',
'PHPUnit_Util_Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Test.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_ResultPrinter_HTML' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/HTML.php',
'PHPUnit_Util_TestDox_ResultPrinter_Text' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/Text.php',
'PHPUnit_Util_TestDox_ResultPrinter_XML' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/XML.php',
'PHPUnit_Util_TestSuiteIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestSuiteIterator.php',
'PHPUnit_Util_Type' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Type.php',
'PHPUnit_Util_XML' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/XML.php',
'PHP_Timer' => __DIR__ . '/..' . '/phpunit/php-timer/src/Timer.php',
'PHP_Token' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_TokenWithScope' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_TokenWithScopeAndVisibility' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ABSTRACT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AMPERSAND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AND_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ARRAY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ARRAY_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ASYNC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AWAIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BACKTICK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BAD_CHARACTER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOLEAN_AND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOLEAN_OR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOL_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BREAK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CALLABLE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CARET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CASE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CATCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CHARACTER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS_NAME_CONSTANT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLONE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_BRACKET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_CURLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_SQUARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_TAG' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COALESCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMMA' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMMENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMPILER_HALT_OFFSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONCAT_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONSTANT_ENCAPSED_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONTINUE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CURLY_OPEN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DEC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DECLARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DEFAULT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIV' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIV_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DNUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOC_COMMENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOLLAR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_ARROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_COLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_QUOTES' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ECHO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELLIPSIS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELSE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELSEIF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EMPTY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENCAPSED_AND_WHITESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDDECLARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDFOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDFOREACH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDIF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDSWITCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDWHILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_END_HEREDOC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENUM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EQUALS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EVAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXCLAMATION_MARK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXTENDS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FINAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FINALLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FOREACH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FUNCTION' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FUNC_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GLOBAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GOTO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_HALT_COMPILER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IMPLEMENTS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INCLUDE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INCLUDE_ONCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INLINE_HTML' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INSTANCEOF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INSTEADOF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INTERFACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INT_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ISSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_GREATER_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_IDENTICAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_NOT_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_NOT_IDENTICAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_SMALLER_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_Includes' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_JOIN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_ARROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_CP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_OP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LINE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LIST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LNUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_AND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_OR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_XOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_METHOD_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MINUS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MINUS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MOD_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MULT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MUL_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NAMESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NEW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NS_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NS_SEPARATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NUM_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OBJECT_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OBJECT_OPERATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ONUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_BRACKET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_CURLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_SQUARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_TAG' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_TAG_WITH_ECHO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PERCENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PIPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PLUS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PLUS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_POW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_POW_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PRINT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PRIVATE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PROTECTED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PUBLIC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_QUESTION_MARK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_REQUIRE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_REQUIRE_ONCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_RETURN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SEMICOLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SHAPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SL_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SPACESHIP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_START_HEREDOC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STATIC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING_VARNAME' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SWITCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_Stream' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token/Stream.php',
'PHP_Token_Stream_CachingFactory' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token/Stream/CachingFactory.php',
'PHP_Token_THROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TILDE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRAIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRAIT_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPELIST_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPELIST_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_UNSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_UNSET_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_USE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_VAR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_VARIABLE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHERE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHITESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_ATTRIBUTE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CATEGORY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CATEGORY_LABEL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CHILDREN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_LABEL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_REQUIRED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TAG_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TAG_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TEXT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XOR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_YIELD' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_YIELD_FROM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'Prophecy\\Argument' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument.php',
'Prophecy\\Argument\\ArgumentsWildcard' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/ArgumentsWildcard.php',
'Prophecy\\Argument\\Token\\AnyValueToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/AnyValueToken.php',
'Prophecy\\Argument\\Token\\AnyValuesToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/AnyValuesToken.php',
'Prophecy\\Argument\\Token\\ApproximateValueToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/ApproximateValueToken.php',
'Prophecy\\Argument\\Token\\ArrayCountToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayCountToken.php',
'Prophecy\\Argument\\Token\\ArrayEntryToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayEntryToken.php',
'Prophecy\\Argument\\Token\\ArrayEveryEntryToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/ArrayEveryEntryToken.php',
'Prophecy\\Argument\\Token\\CallbackToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/CallbackToken.php',
'Prophecy\\Argument\\Token\\ExactValueToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/ExactValueToken.php',
'Prophecy\\Argument\\Token\\IdenticalValueToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/IdenticalValueToken.php',
'Prophecy\\Argument\\Token\\LogicalAndToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/LogicalAndToken.php',
'Prophecy\\Argument\\Token\\LogicalNotToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/LogicalNotToken.php',
'Prophecy\\Argument\\Token\\ObjectStateToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/ObjectStateToken.php',
'Prophecy\\Argument\\Token\\StringContainsToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/StringContainsToken.php',
'Prophecy\\Argument\\Token\\TokenInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/TokenInterface.php',
'Prophecy\\Argument\\Token\\TypeToken' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Argument/Token/TypeToken.php',
'Prophecy\\Call\\Call' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Call/Call.php',
'Prophecy\\Call\\CallCenter' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Call/CallCenter.php',
'Prophecy\\Comparator\\ClosureComparator' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Comparator/ClosureComparator.php',
'Prophecy\\Comparator\\Factory' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Comparator/Factory.php',
'Prophecy\\Comparator\\ProphecyComparator' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Comparator/ProphecyComparator.php',
'Prophecy\\Doubler\\CachedDoubler' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/CachedDoubler.php',
'Prophecy\\Doubler\\ClassPatch\\ClassPatchInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ClassPatchInterface.php',
'Prophecy\\Doubler\\ClassPatch\\DisableConstructorPatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/DisableConstructorPatch.php',
'Prophecy\\Doubler\\ClassPatch\\HhvmExceptionPatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/HhvmExceptionPatch.php',
'Prophecy\\Doubler\\ClassPatch\\KeywordPatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/KeywordPatch.php',
'Prophecy\\Doubler\\ClassPatch\\MagicCallPatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/MagicCallPatch.php',
'Prophecy\\Doubler\\ClassPatch\\ProphecySubjectPatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ProphecySubjectPatch.php',
'Prophecy\\Doubler\\ClassPatch\\ReflectionClassNewInstancePatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/ReflectionClassNewInstancePatch.php',
'Prophecy\\Doubler\\ClassPatch\\SplFileInfoPatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/SplFileInfoPatch.php',
'Prophecy\\Doubler\\ClassPatch\\TraversablePatch' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/ClassPatch/TraversablePatch.php',
'Prophecy\\Doubler\\DoubleInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/DoubleInterface.php',
'Prophecy\\Doubler\\Doubler' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Doubler.php',
'Prophecy\\Doubler\\Generator\\ClassCodeGenerator' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCodeGenerator.php',
'Prophecy\\Doubler\\Generator\\ClassCreator' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassCreator.php',
'Prophecy\\Doubler\\Generator\\ClassMirror' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ClassMirror.php',
'Prophecy\\Doubler\\Generator\\Node\\ArgumentNode' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/ArgumentNode.php',
'Prophecy\\Doubler\\Generator\\Node\\ClassNode' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/ClassNode.php',
'Prophecy\\Doubler\\Generator\\Node\\MethodNode' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/Node/MethodNode.php',
'Prophecy\\Doubler\\Generator\\ReflectionInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/Generator/ReflectionInterface.php',
'Prophecy\\Doubler\\LazyDouble' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/LazyDouble.php',
'Prophecy\\Doubler\\NameGenerator' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Doubler/NameGenerator.php',
'Prophecy\\Exception\\Call\\UnexpectedCallException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Call/UnexpectedCallException.php',
'Prophecy\\Exception\\Doubler\\ClassCreatorException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassCreatorException.php',
'Prophecy\\Exception\\Doubler\\ClassMirrorException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassMirrorException.php',
'Prophecy\\Exception\\Doubler\\ClassNotFoundException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ClassNotFoundException.php',
'Prophecy\\Exception\\Doubler\\DoubleException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/DoubleException.php',
'Prophecy\\Exception\\Doubler\\DoublerException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/DoublerException.php',
'Prophecy\\Exception\\Doubler\\InterfaceNotFoundException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/InterfaceNotFoundException.php',
'Prophecy\\Exception\\Doubler\\MethodNotExtendableException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/MethodNotExtendableException.php',
'Prophecy\\Exception\\Doubler\\MethodNotFoundException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/MethodNotFoundException.php',
'Prophecy\\Exception\\Doubler\\ReturnByReferenceException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Doubler/ReturnByReferenceException.php',
'Prophecy\\Exception\\Exception' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Exception.php',
'Prophecy\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/InvalidArgumentException.php',
'Prophecy\\Exception\\Prediction\\AggregateException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/AggregateException.php',
'Prophecy\\Exception\\Prediction\\FailedPredictionException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/FailedPredictionException.php',
'Prophecy\\Exception\\Prediction\\NoCallsException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/NoCallsException.php',
'Prophecy\\Exception\\Prediction\\PredictionException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/PredictionException.php',
'Prophecy\\Exception\\Prediction\\UnexpectedCallsCountException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/UnexpectedCallsCountException.php',
'Prophecy\\Exception\\Prediction\\UnexpectedCallsException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prediction/UnexpectedCallsException.php',
'Prophecy\\Exception\\Prophecy\\MethodProphecyException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prophecy/MethodProphecyException.php',
'Prophecy\\Exception\\Prophecy\\ObjectProphecyException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prophecy/ObjectProphecyException.php',
'Prophecy\\Exception\\Prophecy\\ProphecyException' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Exception/Prophecy/ProphecyException.php',
'Prophecy\\PhpDocumentor\\ClassAndInterfaceTagRetriever' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/ClassAndInterfaceTagRetriever.php',
'Prophecy\\PhpDocumentor\\ClassTagRetriever' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/ClassTagRetriever.php',
'Prophecy\\PhpDocumentor\\LegacyClassTagRetriever' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/LegacyClassTagRetriever.php',
'Prophecy\\PhpDocumentor\\MethodTagRetrieverInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/PhpDocumentor/MethodTagRetrieverInterface.php',
'Prophecy\\Prediction\\CallPrediction' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prediction/CallPrediction.php',
'Prophecy\\Prediction\\CallTimesPrediction' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prediction/CallTimesPrediction.php',
'Prophecy\\Prediction\\CallbackPrediction' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prediction/CallbackPrediction.php',
'Prophecy\\Prediction\\NoCallsPrediction' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prediction/NoCallsPrediction.php',
'Prophecy\\Prediction\\PredictionInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prediction/PredictionInterface.php',
'Prophecy\\Promise\\CallbackPromise' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Promise/CallbackPromise.php',
'Prophecy\\Promise\\PromiseInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Promise/PromiseInterface.php',
'Prophecy\\Promise\\ReturnArgumentPromise' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Promise/ReturnArgumentPromise.php',
'Prophecy\\Promise\\ReturnPromise' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Promise/ReturnPromise.php',
'Prophecy\\Promise\\ThrowPromise' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Promise/ThrowPromise.php',
'Prophecy\\Prophecy\\MethodProphecy' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophecy/MethodProphecy.php',
'Prophecy\\Prophecy\\ObjectProphecy' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophecy/ObjectProphecy.php',
'Prophecy\\Prophecy\\ProphecyInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophecy/ProphecyInterface.php',
'Prophecy\\Prophecy\\ProphecySubjectInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophecy/ProphecySubjectInterface.php',
'Prophecy\\Prophecy\\Revealer' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophecy/Revealer.php',
'Prophecy\\Prophecy\\RevealerInterface' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophecy/RevealerInterface.php',
'Prophecy\\Prophet' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Prophet.php',
'Prophecy\\Util\\ExportUtil' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Util/ExportUtil.php',
'Prophecy\\Util\\StringUtil' => __DIR__ . '/..' . '/phpspec/prophecy/src/Prophecy/Util/StringUtil.php',
'Psr\\Log\\AbstractLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => __DIR__ . '/..' . '/psr/log/Psr/Log/LogLevel.php',
'Psr\\Log\\LoggerAwareInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerAwareInterface.php',
'Psr\\Log\\LoggerAwareTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerAwareTrait.php',
'Psr\\Log\\LoggerInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/NullLogger.php',
'Psr\\Log\\Test\\DummyTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Satooshi\\Bundle\\CoverallsBundle\\Console\\Application' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Console/Application.php',
'Satooshi\\Bundle\\CoverallsBundle\\CoverallsBundle' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/CoverallsBundle.php',
'Satooshi\\Bundle\\CoverallsBundle\\Entity\\ArrayConvertable' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Entity/ArrayConvertable.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Api\\CoverallsApi' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/CoverallsApi.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Api\\Jobs' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/Jobs.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Collector\\CiEnvVarsCollector' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CiEnvVarsCollector.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Collector\\CloverXmlCoverageCollector' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CloverXmlCoverageCollector.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Collector\\GitInfoCollector' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/GitInfoCollector.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Command\\CoverallsV1JobsCommand' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Command/CoverallsV1JobsCommand.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Config\\Configuration' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configuration.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Config\\Configurator' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configurator.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Config\\CoverallsConfiguration' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/CoverallsConfiguration.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\CoverallsV1Bundle' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/CoverallsV1Bundle.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Coveralls' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Coveralls.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Exception\\RequirementsNotSatisfiedException' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Exception/RequirementsNotSatisfiedException.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Git\\Commit' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Commit.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Git\\Git' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Git.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Git\\Remote' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Remote.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\JsonFile' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/JsonFile.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\Metrics' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Metrics.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Entity\\SourceFile' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/SourceFile.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Repository\\JobsRepository' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Repository/JobsRepository.php',
'Satooshi\\Bundle\\CoverallsV1Bundle\\Version' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Version.php',
'Satooshi\\Component\\File\\Path' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Component/File/Path.php',
'Satooshi\\Component\\Log\\ConsoleLogger' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Component/Log/ConsoleLogger.php',
'Satooshi\\Component\\System\\Git\\GitCommand' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Component/System/Git/GitCommand.php',
'Satooshi\\Component\\System\\SystemCommand' => __DIR__ . '/..' . '/satooshi/php-coveralls/src/Satooshi/Component/System/SystemCommand.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\\HHVM' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/HHVM.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\\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\\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\\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\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php',
'SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php',
'SebastianBergmann\\Diff\\LCS\\LongestCommonSubsequence' => __DIR__ . '/..' . '/sebastian/diff/src/LCS/LongestCommonSubsequence.php',
'SebastianBergmann\\Diff\\LCS\\MemoryEfficientImplementation' => __DIR__ . '/..' . '/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php',
'SebastianBergmann\\Diff\\LCS\\TimeEfficientImplementation' => __DIR__ . '/..' . '/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php',
'SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php',
'SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php',
'SebastianBergmann\\Environment\\Console' => __DIR__ . '/..' . '/sebastian/environment/src/Console.php',
'SebastianBergmann\\Environment\\Runtime' => __DIR__ . '/..' . '/sebastian/environment/src/Runtime.php',
'SebastianBergmann\\Exporter\\Exporter' => __DIR__ . '/..' . '/sebastian/exporter/src/Exporter.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/Exception.php',
'SebastianBergmann\\GlobalState\\Restorer' => __DIR__ . '/..' . '/sebastian/global-state/src/Restorer.php',
'SebastianBergmann\\GlobalState\\RuntimeException' => __DIR__ . '/..' . '/sebastian/global-state/src/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\\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\\Version' => __DIR__ . '/..' . '/sebastian/version/src/Version.php',
'Symfony\\CS\\AbstractAlignFixer' => __DIR__ . '/../..' . '/Symfony/CS/AbstractAlignFixer.php',
'Symfony\\CS\\AbstractAnnotationRemovalFixer' => __DIR__ . '/../..' . '/Symfony/CS/AbstractAnnotationRemovalFixer.php',
'Symfony\\CS\\AbstractFixer' => __DIR__ . '/../..' . '/Symfony/CS/AbstractFixer.php',
'Symfony\\CS\\AbstractLinesBeforeNamespaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/AbstractLinesBeforeNamespaceFixer.php',
'Symfony\\CS\\AbstractPhpdocTypesFixer' => __DIR__ . '/../..' . '/Symfony/CS/AbstractPhpdocTypesFixer.php',
'Symfony\\CS\\Config' => __DIR__ . '/../..' . '/Symfony/CS/Config.php',
'Symfony\\CS\\ConfigAwareInterface' => __DIR__ . '/../..' . '/Symfony/CS/ConfigAwareInterface.php',
'Symfony\\CS\\ConfigInterface' => __DIR__ . '/../..' . '/Symfony/CS/ConfigInterface.php',
'Symfony\\CS\\Config\\Config' => __DIR__ . '/../..' . '/Symfony/CS/Config/Config.php',
'Symfony\\CS\\Config\\MagentoConfig' => __DIR__ . '/../..' . '/Symfony/CS/Config/MagentoConfig.php',
'Symfony\\CS\\Config\\Symfony23Config' => __DIR__ . '/../..' . '/Symfony/CS/Config/Symfony23Config.php',
'Symfony\\CS\\ConfigurationException\\InvalidConfigurationException' => __DIR__ . '/../..' . '/Symfony/CS/ConfigurationException/InvalidConfigurationException.php',
'Symfony\\CS\\ConfigurationException\\InvalidFixerConfigurationException' => __DIR__ . '/../..' . '/Symfony/CS/ConfigurationException/InvalidFixerConfigurationException.php',
'Symfony\\CS\\ConfigurationResolver' => __DIR__ . '/../..' . '/Symfony/CS/ConfigurationResolver.php',
'Symfony\\CS\\Console\\Application' => __DIR__ . '/../..' . '/Symfony/CS/Console/Application.php',
'Symfony\\CS\\Console\\Command\\FixCommand' => __DIR__ . '/../..' . '/Symfony/CS/Console/Command/FixCommand.php',
'Symfony\\CS\\Console\\Command\\ReadmeCommand' => __DIR__ . '/../..' . '/Symfony/CS/Console/Command/ReadmeCommand.php',
'Symfony\\CS\\Console\\Command\\SelfUpdateCommand' => __DIR__ . '/../..' . '/Symfony/CS/Console/Command/SelfUpdateCommand.php',
'Symfony\\CS\\DocBlock\\Annotation' => __DIR__ . '/../..' . '/Symfony/CS/DocBlock/Annotation.php',
'Symfony\\CS\\DocBlock\\DocBlock' => __DIR__ . '/../..' . '/Symfony/CS/DocBlock/DocBlock.php',
'Symfony\\CS\\DocBlock\\Line' => __DIR__ . '/../..' . '/Symfony/CS/DocBlock/Line.php',
'Symfony\\CS\\DocBlock\\Tag' => __DIR__ . '/../..' . '/Symfony/CS/DocBlock/Tag.php',
'Symfony\\CS\\DocBlock\\TagComparator' => __DIR__ . '/../..' . '/Symfony/CS/DocBlock/TagComparator.php',
'Symfony\\CS\\ErrorsManager' => __DIR__ . '/../..' . '/Symfony/CS/ErrorsManager.php',
'Symfony\\CS\\FileCacheManager' => __DIR__ . '/../..' . '/Symfony/CS/FileCacheManager.php',
'Symfony\\CS\\FileRemoval' => __DIR__ . '/../..' . '/Symfony/CS/FileRemoval.php',
'Symfony\\CS\\Finder' => __DIR__ . '/../..' . '/Symfony/CS/Finder.php',
'Symfony\\CS\\FinderInterface' => __DIR__ . '/../..' . '/Symfony/CS/FinderInterface.php',
'Symfony\\CS\\Finder\\DefaultFinder' => __DIR__ . '/../..' . '/Symfony/CS/Finder/DefaultFinder.php',
'Symfony\\CS\\Finder\\MagentoFinder' => __DIR__ . '/../..' . '/Symfony/CS/Finder/MagentoFinder.php',
'Symfony\\CS\\Finder\\Symfony23Finder' => __DIR__ . '/../..' . '/Symfony/CS/Finder/Symfony23Finder.php',
'Symfony\\CS\\Fixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer.php',
'Symfony\\CS\\FixerFileProcessedEvent' => __DIR__ . '/../..' . '/Symfony/CS/FixerFileProcessedEvent.php',
'Symfony\\CS\\FixerInterface' => __DIR__ . '/../..' . '/Symfony/CS/FixerInterface.php',
'Symfony\\CS\\Fixer\\Contrib\\AlignDoubleArrowFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/AlignDoubleArrowFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\AlignEqualsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/AlignEqualsFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ClassKeywordRemoveFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/ClassKeywordRemoveFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\CombineConsecutiveUnsetsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/CombineConsecutiveUnsetsFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ConcatWithSpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/ConcatWithSpacesFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\EchoToPrintFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/EchoToPrintFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\EmptyReturnFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/EmptyReturnFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\EregToPregFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/EregToPregFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\HeaderCommentFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/HeaderCommentFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\LogicalNotOperatorsWithSpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\LogicalNotOperatorsWithSuccessorSpaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\LongArraySyntaxFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/LongArraySyntaxFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\MbStrFunctionsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/MbStrFunctionsFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\MultilineSpacesBeforeSemicolonFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NewlineAfterOpenTagFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/NewlineAfterOpenTagFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NoBlankLinesBeforeNamespaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NoUselessElseFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/NoUselessElseFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\NoUselessReturnFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/NoUselessReturnFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\OrderedUseFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/OrderedUseFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\Php4ConstructorFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/Php4ConstructorFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpUnitConstructFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/PhpUnitConstructFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpUnitDedicateAssertFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/PhpUnitDedicateAssertFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpUnitStrictFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/PhpUnitStrictFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpdocOrderFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/PhpdocOrderFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\PhpdocVarToTypeFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/PhpdocVarToTypeFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ShortArraySyntaxFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/ShortArraySyntaxFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\ShortEchoTagFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/ShortEchoTagFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\SilencedDeprecationErrorFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/SilencedDeprecationErrorFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\StrictFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/StrictFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\StrictParamFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Contrib/StrictParamFixer.php',
'Symfony\\CS\\Fixer\\PSR0\\Psr0Fixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR0/Psr0Fixer.php',
'Symfony\\CS\\Fixer\\PSR1\\EncodingFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR1/EncodingFixer.php',
'Symfony\\CS\\Fixer\\PSR1\\ShortTagFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR1/ShortTagFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\BracesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/BracesFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\ClassDefinitionFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/ClassDefinitionFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\ElseifFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/ElseifFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\EofEndingFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/EofEndingFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\FunctionCallSpaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/FunctionCallSpaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\FunctionDeclarationFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/FunctionDeclarationFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\IndentationFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/IndentationFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LineAfterNamespaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/LineAfterNamespaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LinefeedFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/LinefeedFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LowercaseConstantsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/LowercaseConstantsFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\LowercaseKeywordsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/LowercaseKeywordsFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\MethodArgumentSpaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/MethodArgumentSpaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\MultipleUseFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/MultipleUseFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\NoTrailingWhitespaceInCommentFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/NoTrailingWhitespaceInCommentFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\ParenthesisFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/ParenthesisFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\PhpClosingTagFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/PhpClosingTagFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\SingleLineAfterImportsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/SingleLineAfterImportsFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\SwitchCaseSemicolonToColonFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/SwitchCaseSemicolonToColonFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\SwitchCaseSpaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/SwitchCaseSpaceFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\TrailingSpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/TrailingSpacesFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\VisibilityFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/PSR2/VisibilityFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ArrayElementNoSpaceBeforeCommaFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ArrayElementWhiteSpaceAfterCommaFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\BlanklineAfterOpenTagFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/BlanklineAfterOpenTagFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ConcatWithoutSpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ConcatWithoutSpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DeclareEqualNormalizeFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/DeclareEqualNormalizeFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DoubleArrowMultilineWhitespacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DuplicateSemicolonFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/DuplicateSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ExtraEmptyLinesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ExtraEmptyLinesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\FunctionTypehintSpaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/FunctionTypehintSpaceFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\HashToSlashCommentFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/HashToSlashCommentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\HeredocToNowdocFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/HeredocToNowdocFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\IncludeFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/IncludeFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\JoinFunctionFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/JoinFunctionFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ListCommasFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ListCommasFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\LowercaseCastFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/LowercaseCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\MethodArgumentDefaultValueFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/MethodArgumentDefaultValueFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\MultilineArrayTrailingCommaFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/MultilineArrayTrailingCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NamespaceNoLeadingWhitespaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NativeFunctionCasingFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NativeFunctionCasingFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NewWithBracesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NewWithBracesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoBlankLinesAfterClassOpeningFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyCommentFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NoEmptyCommentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyLinesAfterPhpdocsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyPhpdocFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NoEmptyPhpdocFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NoEmptyStatementFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/NoEmptyStatementFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ObjectOperatorFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ObjectOperatorFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\OperatorsSpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/OperatorsSpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocAnnotationWithoutDotFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocAnnotationWithoutDotFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocIndentFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocIndentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocInlineTagFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocInlineTagFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocNoAccessFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocNoAccessFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocNoEmptyReturnFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocNoEmptyReturnFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocNoPackageFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocNoPackageFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocParamsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocParamsFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocScalarFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocScalarFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocSeparationFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocSeparationFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocShortDescriptionFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocShortDescriptionFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocSingleLineVarSpacingFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocSingleLineVarSpacingFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocToCommentFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocToCommentFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocTrimFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocTrimFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocTypeToVarFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocTypeToVarFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocTypesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocTypesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PhpdocVarWithoutNameFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PhpdocVarWithoutNameFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PreIncrementFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PreIncrementFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\PrintToEchoFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/PrintToEchoFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\RemoveLeadingSlashUseFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/RemoveLeadingSlashUseFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\RemoveLinesBetweenUsesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/RemoveLinesBetweenUsesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ReturnFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ReturnFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SelfAccessorFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SelfAccessorFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ShortBoolCastFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ShortBoolCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ShortScalarCastFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/ShortScalarCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SingleArrayNoTrailingCommaFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SingleArrayNoTrailingCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SingleBlankLineBeforeNamespaceFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SingleQuoteFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SingleQuoteFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SpacesAfterSemicolonFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SpacesAfterSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SpacesBeforeSemicolonFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SpacesBeforeSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\SpacesCastFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/SpacesCastFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\StandardizeNotEqualFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/StandardizeNotEqualFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\TernarySpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/TernarySpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\TrimArraySpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/TrimArraySpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnalignDoubleArrowFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/UnalignDoubleArrowFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnalignEqualsFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/UnalignEqualsFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnaryOperatorsSpacesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/UnaryOperatorsSpacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnneededControlParenthesesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/UnneededControlParenthesesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\UnusedUseFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/UnusedUseFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\WhitespacyLinesFixer' => __DIR__ . '/../..' . '/Symfony/CS/Fixer/Symfony/WhitespacyLinesFixer.php',
'Symfony\\CS\\LintManager' => __DIR__ . '/../..' . '/Symfony/CS/LintManager.php',
'Symfony\\CS\\StdinFileInfo' => __DIR__ . '/../..' . '/Symfony/CS/StdinFileInfo.php',
'Symfony\\CS\\Test\\IntegrationCase' => __DIR__ . '/../..' . '/Symfony/CS/Test/IntegrationCase.php',
'Symfony\\CS\\Test\\IntegrationCaseFactory' => __DIR__ . '/../..' . '/Symfony/CS/Test/IntegrationCaseFactory.php',
'Symfony\\CS\\Tests\\AbstractFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/AbstractFixerTest.php',
'Symfony\\CS\\Tests\\AbstractIntegrationTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/AbstractIntegrationTest.php',
'Symfony\\CS\\Tests\\Config\\ConfigTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Config/ConfigTest.php',
'Symfony\\CS\\Tests\\ConfigurationResolverTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/ConfigurationResolverTest.php',
'Symfony\\CS\\Tests\\Console\\ApplicationTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Console/ApplicationTest.php',
'Symfony\\CS\\Tests\\Console\\TextDiffTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Console/TextDiffTest.php',
'Symfony\\CS\\Tests\\DocBlock\\AnnotationTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/DocBlock/AnnotationTest.php',
'Symfony\\CS\\Tests\\DocBlock\\DocBlockTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/DocBlock/DocBlockTest.php',
'Symfony\\CS\\Tests\\DocBlock\\LineTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/DocBlock/LineTest.php',
'Symfony\\CS\\Tests\\DocBlock\\TagComparatorTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/DocBlock/TagComparatorTest.php',
'Symfony\\CS\\Tests\\DocBlock\\TagTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/DocBlock/TagTest.php',
'Symfony\\CS\\Tests\\Finder\\DefaultFinderTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Finder/DefaultFinderTest.php',
'Symfony\\CS\\Tests\\FixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/FixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\AbstractFixerTestBase' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/AbstractFixerTestBase.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\AlignDoubleArrowFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/AlignDoubleArrowFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\AlignEqualsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/AlignEqualsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ClassKeywordRemoveFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/ClassKeywordRemoveFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\CombineConsecutiveUnsetsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/CombineConsecutiveUnsetsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ConcatWithSpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/ConcatWithSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\EchoToPrintFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/EchoToPrintFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\EmptyReturnFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/EmptyReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\EregToPregFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/EregToPregFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\HeaderCommentFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/HeaderCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\LogicalNotOperatorsWithSpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\LogicalNotOperatorsWithSuccessorSpaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\LongArraySyntaxFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/LongArraySyntaxFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\MbStrFunctionsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/MbStrFunctionsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\MultilineSpacesBeforeSemicolonFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NewlineAfterOpenTagFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/NewlineAfterOpenTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NoBlankLinesBeforeNamespaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NoUselessElseFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/NoUselessElseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\NoUselessReturnFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/NoUselessReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\OrderedUseFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/OrderedUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\Php4ConstructorFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/Php4ConstructorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpUnitConstructFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/PhpUnitConstructFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpUnitDedicateAssertFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/PhpUnitDedicateAssertFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpUnitStrictFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/PhpUnitStrictFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpdocOrderFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/PhpdocOrderFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\PhpdocVarToTypeFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/PhpdocVarToTypeFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ShortArraySyntaxFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/ShortArraySyntaxFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\ShortEchoTagFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/ShortEchoTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\SilencedDeprecationErrorFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/SilencedDeprecationErrorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\StrictFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/StrictFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Contrib\\StrictParamFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Contrib/StrictParamFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR0\\Psr0FixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR0/Psr0FixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR1\\EncodingFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR1/EncodingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR1\\ShortTagFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR1/ShortTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\BracesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/BracesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\ClassDefinitionFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/ClassDefinitionFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\ElseifFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/ElseifFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\EofEndingFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/EofEndingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\FunctionCallSpaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/FunctionCallSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\FunctionDeclarationFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/FunctionDeclarationFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\IndentationFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/IndentationFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LineAfterNamespaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/LineAfterNamespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LinefeedFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/LinefeedFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LowercaseConstantsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/LowercaseConstantsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\LowercaseKeywordsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/LowercaseKeywordsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\MethodArgumentSpaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/MethodArgumentSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\MultipleUseFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/MultipleUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\NoTrailingWhitespaceInCommentFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/NoTrailingWhitespaceInCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\ParenthesisFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/ParenthesisFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\PhpClosingTagFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/PhpClosingTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\SingleLineAfterImportsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/SingleLineAfterImportsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\SwitchCaseSemicolonToColonFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/SwitchCaseSemicolonToColonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\SwitchCaseSpaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/SwitchCaseSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\TrailingSpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/TrailingSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\PSR2\\VisibilityFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/PSR2/VisibilityFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ArrayElementNoSpaceBeforeCommaFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ArrayElementWhiteSpaceAfterCommaFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\BlanklineAfterOpenTagFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/BlanklineAfterOpenTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ConcatWithoutSpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ConcatWithoutSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\DeclareEqualNormalizeFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/DeclareEqualNormalizeFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\DoubleArrowMultilineWhitespacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\DuplicateSemicolonFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/DuplicateSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ExtraEmptyLinesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ExtraEmptyLinesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\FunctionTypehintSpaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/FunctionTypehintSpaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\HashToSlashCommentFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/HashToSlashCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\HeredocToNowdocFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/HeredocToNowdocFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\IncludeFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/IncludeFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\JoinFunctionFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/JoinFunctionFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ListCommasFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ListCommasFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\LowercaseCastFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/LowercaseCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\MethodArgumentDefaultValueFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/MethodArgumentDefaultValueFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\MultilineArrayTrailingCommaFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/MultilineArrayTrailingCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NamespaceNoLeadingWhitespaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NativeFunctionCasingFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NativeFunctionCasingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NewWithBracesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NewWithBracesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoBlankLinesAfterClassOpeningFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyCommentFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyLinesAfterPhpdocsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyPhpdocFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyPhpdocFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\NoEmptyStatementFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/NoEmptyStatementFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ObjectOperatorFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ObjectOperatorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\OperatorsSpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/OperatorsSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocAnnotationWithoutDotFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocAnnotationWithoutDotFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocIndentFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocIndentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocInlineTagFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocInlineTagFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocNoAccessFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoAccessFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocNoEmptyReturnFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoEmptyReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocNoPackageFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoPackageFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocParamsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocParamsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocScalarFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocScalarFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocSeparationFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocSeparationFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocShortDescriptionFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocShortDescriptionFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocSingleLineVarSpacingFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocSingleLineVarSpacingFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocToCommentFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocToCommentFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocTrimFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocTrimFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocTypeToVarFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocTypeToVarFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocTypesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocTypesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PhpdocVarWithoutNameFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PhpdocVarWithoutNameFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PreIncrementFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PreIncrementFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\PrintToEchoFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/PrintToEchoFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\RemoveLeadingSlashUseFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/RemoveLeadingSlashUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\RemoveLinesBetweenUsesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/RemoveLinesBetweenUsesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ReturnFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ReturnFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SelfAccessorFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SelfAccessorFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ShortBoolCastFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ShortBoolCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\ShortScalarCastFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/ShortScalarCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SingleArrayNoTrailingCommaFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SingleArrayNoTrailingCommaFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SingleBlankLineBeforeNamespaceFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SingleQuoteFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SingleQuoteFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SpacesAfterSemicolonFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SpacesAfterSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SpacesBeforeSemicolonFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SpacesBeforeSemicolonFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\SpacesCastFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/SpacesCastFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\StandardizeNotEqualFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/StandardizeNotEqualFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\TernarySpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/TernarySpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\TrimArraySpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/TrimArraySpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnalignDoubleArrowFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/UnalignDoubleArrowFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnalignEqualsFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/UnalignEqualsFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnaryOperatorsSpacesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/UnaryOperatorsSpacesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnneededControlParenthesesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/UnneededControlParenthesesFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\UnusedUseFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/UnusedUseFixerTest.php',
'Symfony\\CS\\Tests\\Fixer\\Symfony\\WhitespacyLinesFixerTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Fixer/Symfony/WhitespacyLinesFixerTest.php',
'Symfony\\CS\\Tests\\IntegrationTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/IntegrationTest.php',
'Symfony\\CS\\Tests\\ReadmeTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/ReadmeTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\AbstractTransformerTestBase' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/AbstractTransformerTestBase.php',
'Symfony\\CS\\Tests\\Tokenizer\\TokenTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/TokenTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\TokensTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/TokensTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\ArrayTypehintTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/Transformer/ArrayTypehintTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\ClassConstantTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/Transformer/ClassConstantTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\CurlyCloseTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/Transformer/CurlyCloseTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\DollarCloseCurlyBracesTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/Transformer/DollarCloseCurlyBracesTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\DynamicPropBraceTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/Transformer/DynamicPropBraceTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\Transformer\\DynamicVarBraceTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/Transformer/DynamicVarBraceTest.php',
'Symfony\\CS\\Tests\\Tokenizer\\TransformersTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/Tokenizer/TransformersTest.php',
'Symfony\\CS\\Tests\\ToolInfoTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/ToolInfoTest.php',
'Symfony\\CS\\Tests\\UtilsTest' => __DIR__ . '/../..' . '/Symfony/CS/Tests/UtilsTest.php',
'Symfony\\CS\\Tokenizer\\AbstractTransformer' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/AbstractTransformer.php',
'Symfony\\CS\\Tokenizer\\Token' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Token.php',
'Symfony\\CS\\Tokenizer\\Tokens' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Tokens.php',
'Symfony\\CS\\Tokenizer\\TransformerInterface' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/TransformerInterface.php',
'Symfony\\CS\\Tokenizer\\Transformer\\ArrayTypehint' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformer/ArrayTypehint.php',
'Symfony\\CS\\Tokenizer\\Transformer\\ClassConstant' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformer/ClassConstant.php',
'Symfony\\CS\\Tokenizer\\Transformer\\CurlyClose' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformer/CurlyClose.php',
'Symfony\\CS\\Tokenizer\\Transformer\\DollarCloseCurlyBraces' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformer/DollarCloseCurlyBraces.php',
'Symfony\\CS\\Tokenizer\\Transformer\\DynamicPropBrace' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformer/DynamicPropBrace.php',
'Symfony\\CS\\Tokenizer\\Transformer\\DynamicVarBrace' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformer/DynamicVarBrace.php',
'Symfony\\CS\\Tokenizer\\Transformers' => __DIR__ . '/../..' . '/Symfony/CS/Tokenizer/Transformers.php',
'Symfony\\CS\\ToolInfo' => __DIR__ . '/../..' . '/Symfony/CS/ToolInfo.php',
'Symfony\\CS\\UniqueFileIterator' => __DIR__ . '/../..' . '/Symfony/CS/UniqueFileIterator.php',
'Symfony\\CS\\Utils' => __DIR__ . '/../..' . '/Symfony/CS/Utils.php',
'Symfony\\Component\\Config\\ConfigCache' => __DIR__ . '/..' . '/symfony/config/ConfigCache.php',
'Symfony\\Component\\Config\\ConfigCacheFactory' => __DIR__ . '/..' . '/symfony/config/ConfigCacheFactory.php',
'Symfony\\Component\\Config\\ConfigCacheFactoryInterface' => __DIR__ . '/..' . '/symfony/config/ConfigCacheFactoryInterface.php',
'Symfony\\Component\\Config\\ConfigCacheInterface' => __DIR__ . '/..' . '/symfony/config/ConfigCacheInterface.php',
'Symfony\\Component\\Config\\Definition\\ArrayNode' => __DIR__ . '/..' . '/symfony/config/Definition/ArrayNode.php',
'Symfony\\Component\\Config\\Definition\\BaseNode' => __DIR__ . '/..' . '/symfony/config/Definition/BaseNode.php',
'Symfony\\Component\\Config\\Definition\\BooleanNode' => __DIR__ . '/..' . '/symfony/config/Definition/BooleanNode.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ArrayNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/ArrayNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\BooleanNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/BooleanNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\EnumNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/EnumNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ExprBuilder' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/ExprBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\FloatNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/FloatNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\IntegerNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/IntegerNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\MergeBuilder' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/MergeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeBuilder' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/NodeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/NodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeParentInterface' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/NodeParentInterface.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NormalizationBuilder' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/NormalizationBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NumericNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/NumericNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ParentNodeDefinitionInterface' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/ParentNodeDefinitionInterface.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ScalarNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/ScalarNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\TreeBuilder' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/TreeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ValidationBuilder' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/ValidationBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\VariableNodeDefinition' => __DIR__ . '/..' . '/symfony/config/Definition/Builder/VariableNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\ConfigurationInterface' => __DIR__ . '/..' . '/symfony/config/Definition/ConfigurationInterface.php',
'Symfony\\Component\\Config\\Definition\\Dumper\\XmlReferenceDumper' => __DIR__ . '/..' . '/symfony/config/Definition/Dumper/XmlReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\Dumper\\YamlReferenceDumper' => __DIR__ . '/..' . '/symfony/config/Definition/Dumper/YamlReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\EnumNode' => __DIR__ . '/..' . '/symfony/config/Definition/EnumNode.php',
'Symfony\\Component\\Config\\Definition\\Exception\\DuplicateKeyException' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/DuplicateKeyException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\Exception' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/Exception.php',
'Symfony\\Component\\Config\\Definition\\Exception\\ForbiddenOverwriteException' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/ForbiddenOverwriteException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidConfigurationException' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/InvalidConfigurationException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidDefinitionException' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/InvalidDefinitionException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidTypeException' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/InvalidTypeException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\UnsetKeyException' => __DIR__ . '/..' . '/symfony/config/Definition/Exception/UnsetKeyException.php',
'Symfony\\Component\\Config\\Definition\\FloatNode' => __DIR__ . '/..' . '/symfony/config/Definition/FloatNode.php',
'Symfony\\Component\\Config\\Definition\\IntegerNode' => __DIR__ . '/..' . '/symfony/config/Definition/IntegerNode.php',
'Symfony\\Component\\Config\\Definition\\NodeInterface' => __DIR__ . '/..' . '/symfony/config/Definition/NodeInterface.php',
'Symfony\\Component\\Config\\Definition\\NumericNode' => __DIR__ . '/..' . '/symfony/config/Definition/NumericNode.php',
'Symfony\\Component\\Config\\Definition\\Processor' => __DIR__ . '/..' . '/symfony/config/Definition/Processor.php',
'Symfony\\Component\\Config\\Definition\\PrototypeNodeInterface' => __DIR__ . '/..' . '/symfony/config/Definition/PrototypeNodeInterface.php',
'Symfony\\Component\\Config\\Definition\\PrototypedArrayNode' => __DIR__ . '/..' . '/symfony/config/Definition/PrototypedArrayNode.php',
'Symfony\\Component\\Config\\Definition\\ScalarNode' => __DIR__ . '/..' . '/symfony/config/Definition/ScalarNode.php',
'Symfony\\Component\\Config\\Definition\\VariableNode' => __DIR__ . '/..' . '/symfony/config/Definition/VariableNode.php',
'Symfony\\Component\\Config\\Exception\\FileLoaderImportCircularReferenceException' => __DIR__ . '/..' . '/symfony/config/Exception/FileLoaderImportCircularReferenceException.php',
'Symfony\\Component\\Config\\Exception\\FileLoaderLoadException' => __DIR__ . '/..' . '/symfony/config/Exception/FileLoaderLoadException.php',
'Symfony\\Component\\Config\\FileLocator' => __DIR__ . '/..' . '/symfony/config/FileLocator.php',
'Symfony\\Component\\Config\\FileLocatorInterface' => __DIR__ . '/..' . '/symfony/config/FileLocatorInterface.php',
'Symfony\\Component\\Config\\Loader\\DelegatingLoader' => __DIR__ . '/..' . '/symfony/config/Loader/DelegatingLoader.php',
'Symfony\\Component\\Config\\Loader\\FileLoader' => __DIR__ . '/..' . '/symfony/config/Loader/FileLoader.php',
'Symfony\\Component\\Config\\Loader\\Loader' => __DIR__ . '/..' . '/symfony/config/Loader/Loader.php',
'Symfony\\Component\\Config\\Loader\\LoaderInterface' => __DIR__ . '/..' . '/symfony/config/Loader/LoaderInterface.php',
'Symfony\\Component\\Config\\Loader\\LoaderResolver' => __DIR__ . '/..' . '/symfony/config/Loader/LoaderResolver.php',
'Symfony\\Component\\Config\\Loader\\LoaderResolverInterface' => __DIR__ . '/..' . '/symfony/config/Loader/LoaderResolverInterface.php',
'Symfony\\Component\\Config\\ResourceCheckerConfigCache' => __DIR__ . '/..' . '/symfony/config/ResourceCheckerConfigCache.php',
'Symfony\\Component\\Config\\ResourceCheckerConfigCacheFactory' => __DIR__ . '/..' . '/symfony/config/ResourceCheckerConfigCacheFactory.php',
'Symfony\\Component\\Config\\ResourceCheckerInterface' => __DIR__ . '/..' . '/symfony/config/ResourceCheckerInterface.php',
'Symfony\\Component\\Config\\Resource\\DirectoryResource' => __DIR__ . '/..' . '/symfony/config/Resource/DirectoryResource.php',
'Symfony\\Component\\Config\\Resource\\FileExistenceResource' => __DIR__ . '/..' . '/symfony/config/Resource/FileExistenceResource.php',
'Symfony\\Component\\Config\\Resource\\FileResource' => __DIR__ . '/..' . '/symfony/config/Resource/FileResource.php',
'Symfony\\Component\\Config\\Resource\\ResourceInterface' => __DIR__ . '/..' . '/symfony/config/Resource/ResourceInterface.php',
'Symfony\\Component\\Config\\Resource\\SelfCheckingResourceChecker' => __DIR__ . '/..' . '/symfony/config/Resource/SelfCheckingResourceChecker.php',
'Symfony\\Component\\Config\\Resource\\SelfCheckingResourceInterface' => __DIR__ . '/..' . '/symfony/config/Resource/SelfCheckingResourceInterface.php',
'Symfony\\Component\\Config\\Util\\XmlUtils' => __DIR__ . '/..' . '/symfony/config/Util/XmlUtils.php',
'Symfony\\Component\\Console\\Application' => __DIR__ . '/..' . '/symfony/console/Application.php',
'Symfony\\Component\\Console\\Command\\Command' => __DIR__ . '/..' . '/symfony/console/Command/Command.php',
'Symfony\\Component\\Console\\Command\\HelpCommand' => __DIR__ . '/..' . '/symfony/console/Command/HelpCommand.php',
'Symfony\\Component\\Console\\Command\\ListCommand' => __DIR__ . '/..' . '/symfony/console/Command/ListCommand.php',
'Symfony\\Component\\Console\\ConsoleEvents' => __DIR__ . '/..' . '/symfony/console/ConsoleEvents.php',
'Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => __DIR__ . '/..' . '/symfony/console/Descriptor/ApplicationDescription.php',
'Symfony\\Component\\Console\\Descriptor\\Descriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/Descriptor.php',
'Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => __DIR__ . '/..' . '/symfony/console/Descriptor/DescriptorInterface.php',
'Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/JsonDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/MarkdownDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/TextDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/XmlDescriptor.php',
'Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleCommandEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleExceptionEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleExceptionEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleTerminateEvent.php',
'Symfony\\Component\\Console\\Exception\\CommandNotFoundException' => __DIR__ . '/..' . '/symfony/console/Exception/CommandNotFoundException.php',
'Symfony\\Component\\Console\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/console/Exception/ExceptionInterface.php',
'Symfony\\Component\\Console\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/console/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Console\\Exception\\InvalidOptionException' => __DIR__ . '/..' . '/symfony/console/Exception/InvalidOptionException.php',
'Symfony\\Component\\Console\\Exception\\LogicException' => __DIR__ . '/..' . '/symfony/console/Exception/LogicException.php',
'Symfony\\Component\\Console\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/console/Exception/RuntimeException.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatter' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatter.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyle.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyleInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyleStack.php',
'Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => __DIR__ . '/..' . '/symfony/console/Helper/DebugFormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\DescriptorHelper' => __DIR__ . '/..' . '/symfony/console/Helper/DescriptorHelper.php',
'Symfony\\Component\\Console\\Helper\\FormatterHelper' => __DIR__ . '/..' . '/symfony/console/Helper/FormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\Helper' => __DIR__ . '/..' . '/symfony/console/Helper/Helper.php',
'Symfony\\Component\\Console\\Helper\\HelperInterface' => __DIR__ . '/..' . '/symfony/console/Helper/HelperInterface.php',
'Symfony\\Component\\Console\\Helper\\HelperSet' => __DIR__ . '/..' . '/symfony/console/Helper/HelperSet.php',
'Symfony\\Component\\Console\\Helper\\InputAwareHelper' => __DIR__ . '/..' . '/symfony/console/Helper/InputAwareHelper.php',
'Symfony\\Component\\Console\\Helper\\ProcessHelper' => __DIR__ . '/..' . '/symfony/console/Helper/ProcessHelper.php',
'Symfony\\Component\\Console\\Helper\\ProgressBar' => __DIR__ . '/..' . '/symfony/console/Helper/ProgressBar.php',
'Symfony\\Component\\Console\\Helper\\ProgressIndicator' => __DIR__ . '/..' . '/symfony/console/Helper/ProgressIndicator.php',
'Symfony\\Component\\Console\\Helper\\QuestionHelper' => __DIR__ . '/..' . '/symfony/console/Helper/QuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\SymfonyQuestionHelper' => __DIR__ . '/..' . '/symfony/console/Helper/SymfonyQuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\Table' => __DIR__ . '/..' . '/symfony/console/Helper/Table.php',
'Symfony\\Component\\Console\\Helper\\TableCell' => __DIR__ . '/..' . '/symfony/console/Helper/TableCell.php',
'Symfony\\Component\\Console\\Helper\\TableSeparator' => __DIR__ . '/..' . '/symfony/console/Helper/TableSeparator.php',
'Symfony\\Component\\Console\\Helper\\TableStyle' => __DIR__ . '/..' . '/symfony/console/Helper/TableStyle.php',
'Symfony\\Component\\Console\\Input\\ArgvInput' => __DIR__ . '/..' . '/symfony/console/Input/ArgvInput.php',
'Symfony\\Component\\Console\\Input\\ArrayInput' => __DIR__ . '/..' . '/symfony/console/Input/ArrayInput.php',
'Symfony\\Component\\Console\\Input\\Input' => __DIR__ . '/..' . '/symfony/console/Input/Input.php',
'Symfony\\Component\\Console\\Input\\InputArgument' => __DIR__ . '/..' . '/symfony/console/Input/InputArgument.php',
'Symfony\\Component\\Console\\Input\\InputAwareInterface' => __DIR__ . '/..' . '/symfony/console/Input/InputAwareInterface.php',
'Symfony\\Component\\Console\\Input\\InputDefinition' => __DIR__ . '/..' . '/symfony/console/Input/InputDefinition.php',
'Symfony\\Component\\Console\\Input\\InputInterface' => __DIR__ . '/..' . '/symfony/console/Input/InputInterface.php',
'Symfony\\Component\\Console\\Input\\InputOption' => __DIR__ . '/..' . '/symfony/console/Input/InputOption.php',
'Symfony\\Component\\Console\\Input\\StringInput' => __DIR__ . '/..' . '/symfony/console/Input/StringInput.php',
'Symfony\\Component\\Console\\Logger\\ConsoleLogger' => __DIR__ . '/..' . '/symfony/console/Logger/ConsoleLogger.php',
'Symfony\\Component\\Console\\Output\\BufferedOutput' => __DIR__ . '/..' . '/symfony/console/Output/BufferedOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutput' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleOutputInterface.php',
'Symfony\\Component\\Console\\Output\\NullOutput' => __DIR__ . '/..' . '/symfony/console/Output/NullOutput.php',
'Symfony\\Component\\Console\\Output\\Output' => __DIR__ . '/..' . '/symfony/console/Output/Output.php',
'Symfony\\Component\\Console\\Output\\OutputInterface' => __DIR__ . '/..' . '/symfony/console/Output/OutputInterface.php',
'Symfony\\Component\\Console\\Output\\StreamOutput' => __DIR__ . '/..' . '/symfony/console/Output/StreamOutput.php',
'Symfony\\Component\\Console\\Question\\ChoiceQuestion' => __DIR__ . '/..' . '/symfony/console/Question/ChoiceQuestion.php',
'Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => __DIR__ . '/..' . '/symfony/console/Question/ConfirmationQuestion.php',
'Symfony\\Component\\Console\\Question\\Question' => __DIR__ . '/..' . '/symfony/console/Question/Question.php',
'Symfony\\Component\\Console\\Style\\OutputStyle' => __DIR__ . '/..' . '/symfony/console/Style/OutputStyle.php',
'Symfony\\Component\\Console\\Style\\StyleInterface' => __DIR__ . '/..' . '/symfony/console/Style/StyleInterface.php',
'Symfony\\Component\\Console\\Style\\SymfonyStyle' => __DIR__ . '/..' . '/symfony/console/Style/SymfonyStyle.php',
'Symfony\\Component\\Console\\Tester\\ApplicationTester' => __DIR__ . '/..' . '/symfony/console/Tester/ApplicationTester.php',
'Symfony\\Component\\Console\\Tester\\CommandTester' => __DIR__ . '/..' . '/symfony/console/Tester/CommandTester.php',
'Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/ContainerAwareEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface' => __DIR__ . '/..' . '/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener' => __DIR__ . '/..' . '/symfony/event-dispatcher/Debug/WrappedListener.php',
'Symfony\\Component\\EventDispatcher\\DependencyInjection\\RegisterListenersPass' => __DIR__ . '/..' . '/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php',
'Symfony\\Component\\EventDispatcher\\Event' => __DIR__ . '/..' . '/symfony/event-dispatcher/Event.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/EventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcherInterface' => __DIR__ . '/..' . '/symfony/event-dispatcher/EventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface' => __DIR__ . '/..' . '/symfony/event-dispatcher/EventSubscriberInterface.php',
'Symfony\\Component\\EventDispatcher\\GenericEvent' => __DIR__ . '/..' . '/symfony/event-dispatcher/GenericEvent.php',
'Symfony\\Component\\EventDispatcher\\ImmutableEventDispatcher' => __DIR__ . '/..' . '/symfony/event-dispatcher/ImmutableEventDispatcher.php',
'Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/filesystem/Exception/ExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/FileNotFoundException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/IOException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => __DIR__ . '/..' . '/symfony/filesystem/Exception/IOExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Filesystem' => __DIR__ . '/..' . '/symfony/filesystem/Filesystem.php',
'Symfony\\Component\\Filesystem\\LockHandler' => __DIR__ . '/..' . '/symfony/filesystem/LockHandler.php',
'Symfony\\Component\\Finder\\Comparator\\Comparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/Comparator.php',
'Symfony\\Component\\Finder\\Comparator\\DateComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/DateComparator.php',
'Symfony\\Component\\Finder\\Comparator\\NumberComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/NumberComparator.php',
'Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => __DIR__ . '/..' . '/symfony/finder/Exception/AccessDeniedException.php',
'Symfony\\Component\\Finder\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/finder/Exception/ExceptionInterface.php',
'Symfony\\Component\\Finder\\Finder' => __DIR__ . '/..' . '/symfony/finder/Finder.php',
'Symfony\\Component\\Finder\\Glob' => __DIR__ . '/..' . '/symfony/finder/Glob.php',
'Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/CustomFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DateRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DepthRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FileTypeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilecontentFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilenameFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/PathFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SizeRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SortableIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SortableIterator.php',
'Symfony\\Component\\Finder\\SplFileInfo' => __DIR__ . '/..' . '/symfony/finder/SplFileInfo.php',
'Symfony\\Component\\Process\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/process/Exception/ExceptionInterface.php',
'Symfony\\Component\\Process\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/process/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Process\\Exception\\LogicException' => __DIR__ . '/..' . '/symfony/process/Exception/LogicException.php',
'Symfony\\Component\\Process\\Exception\\ProcessFailedException' => __DIR__ . '/..' . '/symfony/process/Exception/ProcessFailedException.php',
'Symfony\\Component\\Process\\Exception\\ProcessTimedOutException' => __DIR__ . '/..' . '/symfony/process/Exception/ProcessTimedOutException.php',
'Symfony\\Component\\Process\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/process/Exception/RuntimeException.php',
'Symfony\\Component\\Process\\ExecutableFinder' => __DIR__ . '/..' . '/symfony/process/ExecutableFinder.php',
'Symfony\\Component\\Process\\InputStream' => __DIR__ . '/..' . '/symfony/process/InputStream.php',
'Symfony\\Component\\Process\\PhpExecutableFinder' => __DIR__ . '/..' . '/symfony/process/PhpExecutableFinder.php',
'Symfony\\Component\\Process\\PhpProcess' => __DIR__ . '/..' . '/symfony/process/PhpProcess.php',
'Symfony\\Component\\Process\\Pipes\\AbstractPipes' => __DIR__ . '/..' . '/symfony/process/Pipes/AbstractPipes.php',
'Symfony\\Component\\Process\\Pipes\\PipesInterface' => __DIR__ . '/..' . '/symfony/process/Pipes/PipesInterface.php',
'Symfony\\Component\\Process\\Pipes\\UnixPipes' => __DIR__ . '/..' . '/symfony/process/Pipes/UnixPipes.php',
'Symfony\\Component\\Process\\Pipes\\WindowsPipes' => __DIR__ . '/..' . '/symfony/process/Pipes/WindowsPipes.php',
'Symfony\\Component\\Process\\Process' => __DIR__ . '/..' . '/symfony/process/Process.php',
'Symfony\\Component\\Process\\ProcessBuilder' => __DIR__ . '/..' . '/symfony/process/ProcessBuilder.php',
'Symfony\\Component\\Process\\ProcessUtils' => __DIR__ . '/..' . '/symfony/process/ProcessUtils.php',
'Symfony\\Component\\Stopwatch\\Section' => __DIR__ . '/..' . '/symfony/stopwatch/Section.php',
'Symfony\\Component\\Stopwatch\\Stopwatch' => __DIR__ . '/..' . '/symfony/stopwatch/Stopwatch.php',
'Symfony\\Component\\Stopwatch\\StopwatchEvent' => __DIR__ . '/..' . '/symfony/stopwatch/StopwatchEvent.php',
'Symfony\\Component\\Stopwatch\\StopwatchPeriod' => __DIR__ . '/..' . '/symfony/stopwatch/StopwatchPeriod.php',
'Symfony\\Component\\Yaml\\Dumper' => __DIR__ . '/..' . '/symfony/yaml/Dumper.php',
'Symfony\\Component\\Yaml\\Escaper' => __DIR__ . '/..' . '/symfony/yaml/Escaper.php',
'Symfony\\Component\\Yaml\\Exception\\DumpException' => __DIR__ . '/..' . '/symfony/yaml/Exception/DumpException.php',
'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/yaml/Exception/ExceptionInterface.php',
'Symfony\\Component\\Yaml\\Exception\\ParseException' => __DIR__ . '/..' . '/symfony/yaml/Exception/ParseException.php',
'Symfony\\Component\\Yaml\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/yaml/Exception/RuntimeException.php',
'Symfony\\Component\\Yaml\\Inline' => __DIR__ . '/..' . '/symfony/yaml/Inline.php',
'Symfony\\Component\\Yaml\\Parser' => __DIR__ . '/..' . '/symfony/yaml/Parser.php',
'Symfony\\Component\\Yaml\\Unescaper' => __DIR__ . '/..' . '/symfony/yaml/Unescaper.php',
'Symfony\\Component\\Yaml\\Yaml' => __DIR__ . '/..' . '/symfony/yaml/Yaml.php',
'Symfony\\Polyfill\\Mbstring\\Mbstring' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/Mbstring.php',
'Text_Template' => __DIR__ . '/..' . '/phpunit/php-text-template/src/Template.php',
'Webmozart\\Assert\\Assert' => __DIR__ . '/..' . '/webmozart/assert/src/Assert.php',
'phpDocumentor\\Reflection\\DocBlock' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock.php',
'phpDocumentor\\Reflection\\DocBlockFactory' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlockFactory.php',
'phpDocumentor\\Reflection\\DocBlockFactoryInterface' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlockFactoryInterface.php',
'phpDocumentor\\Reflection\\DocBlock\\Description' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Description.php',
'phpDocumentor\\Reflection\\DocBlock\\DescriptionFactory' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/DescriptionFactory.php',
'phpDocumentor\\Reflection\\DocBlock\\Serializer' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Serializer.php',
'phpDocumentor\\Reflection\\DocBlock\\StandardTagFactory' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/StandardTagFactory.php',
'phpDocumentor\\Reflection\\DocBlock\\Tag' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tag.php',
'phpDocumentor\\Reflection\\DocBlock\\TagFactory' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/TagFactory.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Author' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Author.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\BaseTag' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/BaseTag.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Covers' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Covers.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Deprecated' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Deprecated.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Example' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Example.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Factory\\StaticMethod' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Factory/StaticMethod.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Factory\\Strategy' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Factory/Strategy.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Formatter' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Formatter.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Formatter\\PassthroughFormatter' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Formatter/PassthroughFormatter.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Generic' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Generic.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Link' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Link.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Method' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Method.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Param' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Param.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Property' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Property.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\PropertyRead' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/PropertyRead.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\PropertyWrite' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/PropertyWrite.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Return_' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Return_.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\See' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/See.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Since' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Since.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Source' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Source.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Throws' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Throws.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Uses' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Uses.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Var_' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Var_.php',
'phpDocumentor\\Reflection\\DocBlock\\Tags\\Version' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/Tags/Version.php',
'phpDocumentor\\Reflection\\Element' => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src/Element.php',
'phpDocumentor\\Reflection\\ExampleFinder' => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src/DocBlock/ExampleFinder.php',
'phpDocumentor\\Reflection\\File' => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src/File.php',
'phpDocumentor\\Reflection\\Fqsen' => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src/Fqsen.php',
'phpDocumentor\\Reflection\\FqsenResolver' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/FqsenResolver.php',
'phpDocumentor\\Reflection\\Location' => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src/Location.php',
'phpDocumentor\\Reflection\\Project' => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src/Project.php',
'phpDocumentor\\Reflection\\ProjectFactory' => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src/ProjectFactory.php',
'phpDocumentor\\Reflection\\Type' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Type.php',
'phpDocumentor\\Reflection\\TypeResolver' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/TypeResolver.php',
'phpDocumentor\\Reflection\\Types\\Array_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Array_.php',
'phpDocumentor\\Reflection\\Types\\Boolean' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Boolean.php',
'phpDocumentor\\Reflection\\Types\\Callable_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Callable_.php',
'phpDocumentor\\Reflection\\Types\\Compound' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Compound.php',
'phpDocumentor\\Reflection\\Types\\Context' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Context.php',
'phpDocumentor\\Reflection\\Types\\ContextFactory' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/ContextFactory.php',
'phpDocumentor\\Reflection\\Types\\Float_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Float_.php',
'phpDocumentor\\Reflection\\Types\\Integer' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Integer.php',
'phpDocumentor\\Reflection\\Types\\Mixed' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Mixed.php',
'phpDocumentor\\Reflection\\Types\\Null_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Null_.php',
'phpDocumentor\\Reflection\\Types\\Object_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Object_.php',
'phpDocumentor\\Reflection\\Types\\Resource' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Resource.php',
'phpDocumentor\\Reflection\\Types\\Scalar' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Scalar.php',
'phpDocumentor\\Reflection\\Types\\Self_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Self_.php',
'phpDocumentor\\Reflection\\Types\\Static_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Static_.php',
'phpDocumentor\\Reflection\\Types\\String_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/String_.php',
'phpDocumentor\\Reflection\\Types\\This' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/This.php',
'phpDocumentor\\Reflection\\Types\\Void_' => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src/Types/Void_.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit9d67f5014a965adc352c6ef25d43195e::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit9d67f5014a965adc352c6ef25d43195e::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit9d67f5014a965adc352c6ef25d43195e::$prefixesPsr0;
$loader->classMap = ComposerStaticInit9d67f5014a965adc352c6ef25d43195e::$classMap;
}, null, ClassLoader::class);
}
}
<?php
class ComposerAutoloaderInit9d67f5014a965adc352c6ef25d43195e
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit9d67f5014a965adc352c6ef25d43195e', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit9d67f5014a965adc352c6ef25d43195e', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION');
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit9d67f5014a965adc352c6ef25d43195e::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit9d67f5014a965adc352c6ef25d43195e::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire9d67f5014a965adc352c6ef25d43195e($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire9d67f5014a965adc352c6ef25d43195e($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
<?php
namespace Composer\Autoload;
class ClassLoader
{
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
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
);
}
}
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
$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) {
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
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;
}
}
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
public function getUseIncludePath()
{
return $this->useIncludePath;
}
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
public function findFile($class)
{
if ('\\' == $class[0]) {
$class = substr($class, 1);
}
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
$file = $this->findFileWithExtension($class, '.php');
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (false === $file) {
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
if (0 === strpos($class, $prefix)) {
foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
return $file;
}
}
}
}
}
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
if (false !== $pos = strrpos($class, '\\')) {
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
$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;
}
}
}
}
}
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
function includeFile($file)
{
include $file;
}
<?php
namespace SebastianBergmann;
class Version
{
private $path;
private $release;
private $version;
public function __construct($release, $path)
{
$this->release = $release;
$this->path = $path;
}
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;
}
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;
}
}
#!/usr/bin/env php
<?php
$functions = require __DIR__ . '/arginfo.php';
$resourceFunctions = [];
foreach ($functions as $function => $arguments) {
foreach ($arguments as $argument) {
if ($argument == 'resource') {
$resourceFunctions[] = $function;
}
}
}
$resourceFunctions = array_unique($resourceFunctions);
sort($resourceFunctions);
$buffer = <<<EOT
<?php
/*
* 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;
class ResourceOperations
{
/**
* @return string[]
*/
public static function getFunctions()
{
return [
EOT;
foreach ($resourceFunctions as $function) {
$buffer .= sprintf(" '%s',\n", $function);
}
$buffer .= <<< EOT
];
}
}
EOT;
file_put_contents(__DIR__ . '/../src/ResourceOperations.php', $buffer);
<?php
namespace SebastianBergmann\ResourceOperations;
class ResourceOperations
{
public static function getFunctions()
{
return [
'Directory::close',
'Directory::read',
'Directory::rewind',
'HttpResponse::getRequestBodyStream',
'HttpResponse::getStream',
'MongoGridFSCursor::__construct',
'MongoGridFSFile::getResource',
'MysqlndUhConnection::stmtInit',
'MysqlndUhConnection::storeResult',
'MysqlndUhConnection::useResult',
'PDF_new',
'PDO::pgsqlLOBOpen',
'RarEntry::getStream',
'SQLite3::openBlob',
'XMLWriter::openMemory',
'XMLWriter::openURI',
'ZipArchive::getStream',
'bbcode_create',
'bzopen',
'crack_opendict',
'cubrid_connect',
'cubrid_connect_with_url',
'cubrid_get_query_timeout',
'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_pconnect',
'cubrid_pconnect_with_url',
'cubrid_prepare',
'cubrid_query',
'cubrid_set_query_timeout',
'cubrid_unbuffered_query',
'curl_copy_handle',
'curl_getinfo',
'curl_init',
'curl_multi_add_handle',
'curl_multi_close',
'curl_multi_exec',
'curl_multi_getcontent',
'curl_multi_info_read',
'curl_multi_init',
'curl_multi_remove_handle',
'curl_multi_select',
'curl_multi_setopt',
'curl_pause',
'curl_reset',
'curl_setopt',
'curl_setopt_array',
'curl_share_close',
'curl_share_init',
'curl_share_setopt',
'curl_unescape',
'cyrus_connect',
'db2_column_privileges',
'db2_columns',
'db2_connect',
'db2_exec',
'db2_foreign_keys',
'db2_next_result',
'db2_pconnect',
'db2_prepare',
'db2_primary_keys',
'db2_procedure_columns',
'db2_procedures',
'db2_special_columns',
'db2_statistics',
'db2_table_privileges',
'db2_tables',
'dba_fetch',
'dba_fetch 1',
'dba_open',
'dba_popen',
'dbplus_aql',
'dbplus_open',
'dbplus_rcreate',
'dbplus_ropen',
'dbplus_rquery',
'dbplus_sql',
'deflate_init',
'dio_open',
'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_free_dict',
'enchant_broker_init',
'enchant_broker_request_dict',
'enchant_broker_request_pwl_dict',
'event_base_new',
'event_base_reinit',
'event_buffer_new',
'event_new',
'event_priority_set',
'event_timer_set',
'expect_popen',
'fam_monitor_collection',
'fam_monitor_directory',
'fam_monitor_file',
'fam_open',
'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_connect',
'fbsql_db_query',
'fbsql_list_dbs',
'fbsql_list_fields',
'fbsql_list_tables',
'fbsql_pconnect',
'fbsql_query',
'fdf_create',
'fdf_open',
'fdf_open_string',
'finfo::buffer',
'finfo_buffer',
'finfo_close',
'finfo_file',
'finfo_open',
'finfo_set_flags',
'fopen',
'fsockopen',
'ftp_alloc',
'ftp_cdup',
'ftp_chdir',
'ftp_chmod',
'ftp_close',
'ftp_connect',
'ftp_delete',
'ftp_exec',
'ftp_fget',
'ftp_fput',
'ftp_get',
'ftp_get_option',
'ftp_login',
'ftp_mdtm',
'ftp_mkdir',
'ftp_nb_continue',
'ftp_nb_fget',
'ftp_nb_fput',
'ftp_nb_get',
'ftp_nb_put',
'ftp_nlist',
'ftp_pasv',
'ftp_put',
'ftp_pwd',
'ftp_raw',
'ftp_rawlist',
'ftp_rename',
'ftp_rmdir',
'ftp_set_option',
'ftp_site',
'ftp_size',
'ftp_ssl_connect',
'ftp_systype',
'gnupg_init',
'gupnp_context_new',
'gupnp_control_point_new',
'gupnp_device_info_get_service',
'gupnp_root_device_new',
'gzopen',
'hash_copy',
'hash_final',
'hash_init',
'hash_update',
'hash_update_file',
'hash_update_stream',
'http_get_request_body_stream',
'ibase_blob_create',
'ibase_blob_open',
'ibase_blob_open 1',
'ibase_connect',
'ibase_pconnect',
'ibase_prepare',
'ibase_service_attach',
'ibase_set_event_handler',
'ibase_set_event_handler 1',
'ibase_trans',
'ifx_connect',
'ifx_pconnect',
'ifx_prepare',
'ifx_query',
'imageaffine',
'imageconvolution',
'imagecreate',
'imagecreatefromgd',
'imagecreatefromgd2',
'imagecreatefromgd2part',
'imagecreatefromgif',
'imagecreatefromjpeg',
'imagecreatefrompng',
'imagecreatefromstring',
'imagecreatefromwbmp',
'imagecreatefromwebp',
'imagecreatefromxbm',
'imagecreatefromxpm',
'imagecreatetruecolor',
'imagegrabscreen',
'imagegrabwindow',
'imagepalettetotruecolor',
'imagepsloadfont',
'imagerotate',
'imagescale',
'imap_open',
'inflate_init',
'ingres_connect',
'ingres_pconnect',
'inotify_init',
'kadm5_init_with_password',
'ldap_connect',
'ldap_first_entry',
'ldap_first_reference',
'ldap_list',
'ldap_next_entry',
'ldap_next_reference',
'ldap_read',
'ldap_search',
'm_initconn',
'mailparse_msg_create',
'mailparse_msg_get_part',
'mailparse_msg_parse_file',
'maxdb::use_result',
'maxdb_connect',
'maxdb_embedded_connect',
'maxdb_init',
'maxdb_stmt::result_metadata',
'maxdb_stmt_result_metadata',
'maxdb_use_result',
'mcrypt_module_open',
'msg_get_queue',
'msql_connect',
'msql_db_query',
'msql_list_dbs',
'msql_list_fields',
'msql_list_tables',
'msql_pconnect',
'msql_query',
'mssql_connect',
'mssql_init',
'mssql_pconnect',
'mysql_connect',
'mysql_db_query',
'mysql_list_dbs',
'mysql_list_fields',
'mysql_list_processes',
'mysql_list_tables',
'mysql_pconnect',
'mysql_query',
'mysql_unbuffered_query',
'mysqlnd_uh_convert_to_mysqlnd',
'ncurses_new_panel',
'ncurses_newpad',
'ncurses_newwin',
'ncurses_panel_above',
'ncurses_panel_below',
'ncurses_panel_window',
'newt_button',
'newt_button_bar',
'newt_checkbox',
'newt_checkbox_tree',
'newt_checkbox_tree_multi',
'newt_compact_button',
'newt_create_grid',
'newt_entry',
'newt_form',
'newt_form_get_current',
'newt_grid_basic_window',
'newt_grid_h_close_stacked',
'newt_grid_h_stacked',
'newt_grid_simple_window',
'newt_grid_v_close_stacked',
'newt_grid_v_stacked',
'newt_label',
'newt_listbox',
'newt_listitem',
'newt_radio_get_current',
'newt_radiobutton',
'newt_run_form',
'newt_scale',
'newt_textbox',
'newt_textbox_reflowed',
'newt_vertical_scrollbar',
'oci_connect',
'oci_get_implicit_resultset',
'oci_new_connect',
'oci_new_cursor',
'oci_parse',
'oci_pconnect',
'odbc_columnprivileges',
'odbc_columns',
'odbc_connect',
'odbc_exec',
'odbc_foreignkeys',
'odbc_gettypeinfo',
'odbc_pconnect',
'odbc_prepare',
'odbc_primarykeys',
'odbc_procedurecolumns',
'odbc_procedures',
'odbc_specialcolumns',
'odbc_statistics',
'odbc_tableprivileges',
'odbc_tables',
'openal_buffer_create',
'openal_context_create',
'openal_device_open',
'openal_source_create',
'openal_stream',
'openssl_csr_new',
'openssl_csr_sign',
'openssl_pkey_get_private',
'openssl_pkey_get_public',
'openssl_pkey_new',
'openssl_x509_read',
'pfsockopen',
'pg_cancel_query',
'pg_client_encoding',
'pg_close',
'pg_connect',
'pg_connect_poll',
'pg_connection_busy',
'pg_connection_reset',
'pg_connection_status',
'pg_consume_input',
'pg_copy_from',
'pg_copy_to',
'pg_dbname',
'pg_end_copy',
'pg_escape_bytea',
'pg_escape_identifier',
'pg_escape_identifier 1',
'pg_escape_literal',
'pg_escape_string',
'pg_execute',
'pg_execute 1',
'pg_flush',
'pg_free_result',
'pg_get_notify',
'pg_get_pid',
'pg_get_result',
'pg_host',
'pg_last_error',
'pg_last_notice',
'pg_lo_create',
'pg_lo_export',
'pg_lo_import',
'pg_lo_open',
'pg_lo_unlink',
'pg_options',
'pg_parameter_status',
'pg_pconnect',
'pg_ping',
'pg_port',
'pg_prepare',
'pg_prepare 1',
'pg_put_line',
'pg_query',
'pg_query 1',
'pg_query_params',
'pg_query_params 1',
'pg_send_execute',
'pg_send_prepare',
'pg_send_query',
'pg_send_query_params',
'pg_set_client_encoding',
'pg_set_client_encoding 1',
'pg_set_error_verbosity',
'pg_socket',
'pg_trace',
'pg_transaction_status',
'pg_tty',
'pg_untrace',
'pg_version',
'php_user_filter::filter',
'popen',
'proc_open',
'ps_new',
'px_new',
'radius_acct_open',
'radius_auth_open',
'radius_salt_encrypt_attr',
'rpm_open',
'sem_get',
'shm_attach',
'socket_accept',
'socket_create',
'socket_create_listen',
'socket_recvmsg',
'socket_sendmsg',
'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_connect',
'ssh2_exec',
'ssh2_fetch_stream',
'ssh2_publickey_init',
'ssh2_sftp',
'ssh2_sftp_chmod',
'ssh2_shell',
'ssh2_tunnel',
'stomp_connect',
'streamWrapper::stream_cast',
'stream_bucket_new',
'stream_context_create',
'stream_context_get_default',
'stream_context_set_default',
'stream_filter_append',
'stream_filter_prepend',
'stream_socket_accept',
'stream_socket_client',
'stream_socket_server',
'svn_fs_apply_text',
'svn_fs_begin_txn2',
'svn_fs_file_contents',
'svn_fs_revision_root',
'svn_fs_txn_root',
'svn_repos_create',
'svn_repos_fs',
'svn_repos_fs_begin_txn_for_commit',
'svn_repos_open',
'sybase_connect',
'sybase_pconnect',
'sybase_unbuffered_query',
'tmpfile',
'udm_alloc_agent',
'udm_alloc_agent_array',
'udm_find',
'unlink',
'w32api_init_dtype',
'wddx_packet_start',
'xml_parser_create',
'xml_parser_create_ns',
'xml_parser_free',
'xml_parser_get_option',
'xml_parser_set_option',
'xmlrpc_server_create',
'xmlwriter_open_memory',
'xmlwriter_open_uri',
'xslt_create',
'zip_open',
'zip_read',
];
}
}
<?php
namespace SebastianBergmann\RecursionContext;
final class Context
{
private $arrays;
private $objects;
public function __construct()
{
$this->arrays = array();
$this->objects = new \SplObjectStorage;
}
public function add(&$value)
{
if (is_array($value)) {
return $this->addArray($value);
}
else if (is_object($value)) {
return $this->addObject($value);
}
throw new InvalidArgumentException(
'Only arrays and objects are supported'
);
}
public function contains(&$value)
{
if (is_array($value)) {
return $this->containsArray($value);
}
else if (is_object($value)) {
return $this->containsObject($value);
}
throw new InvalidArgumentException(
'Only arrays and objects are supported'
);
}
private function addArray(array &$array)
{
$key = $this->containsArray($array);
if ($key !== false) {
return $key;
}
$this->arrays[] = &$array;
return count($this->arrays) - 1;
}
private function addObject($object)
{
if (!$this->objects->contains($object)) {
$this->objects->attach($object);
}
return spl_object_hash($object);
}
private function containsArray(array &$array)
{
$keys = array_keys($this->arrays, $array, true);
$hash = '_Key_' . microtime(true);
foreach ($keys as $key) {
$this->arrays[$key][$hash] = $hash;
if (isset($array[$hash]) && $array[$hash] === $hash) {
unset($this->arrays[$key][$hash]);
return $key;
}
unset($this->arrays[$key][$hash]);
}
return false;
}
private function containsObject($value)
{
if ($this->objects->contains($value)) {
return spl_object_hash($value);
}
return false;
}
}
<?php
namespace SebastianBergmann\RecursionContext;
interface Exception
{
}
<?php
namespace SebastianBergmann\RecursionContext;
final class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
namespace SebastianBergmann\ObjectEnumerator;
use SebastianBergmann\RecursionContext\Context;
class Enumerator
{
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;
}
$processed->add($variable);
if (is_array($variable)) {
foreach ($variable as $element) {
if (!is_array($element) && !is_object($element)) {
continue;
}
$objects = array_merge(
$objects,
$this->enumerate($element, $processed)
);
}
} else {
$objects[] = $variable;
$reflector = new \ReflectionObject($variable);
foreach ($reflector->getProperties() as $attribute) {
$attribute->setAccessible(true);
$value = $attribute->getValue($variable);
if (!is_array($value) && !is_object($value)) {
continue;
}
$objects = array_merge(
$objects,
$this->enumerate($value, $processed)
);
}
}
return $objects;
}
}
<?php
namespace SebastianBergmann\ObjectEnumerator;
interface Exception
{
}
<?php
namespace SebastianBergmann\ObjectEnumerator;
class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
namespace SebastianBergmann\GlobalState;
use ReflectionClass;
class Blacklist
{
private $globalVariables = array();
private $classes = array();
private $classNamePrefixes = array();
private $parentClasses = array();
private $interfaces = array();
private $staticAttributes = array();
public function addGlobalVariable($variableName)
{
$this->globalVariables[$variableName] = true;
}
public function addClass($className)
{
$this->classes[] = $className;
}
public function addSubclassesOf($className)
{
$this->parentClasses[] = $className;
}
public function addImplementorsOf($interfaceName)
{
$this->interfaces[] = $interfaceName;
}
public function addClassNamePrefix($classNamePrefix)
{
$this->classNamePrefixes[] = $classNamePrefix;
}
public function addStaticAttribute($className, $attributeName)
{
if (!isset($this->staticAttributes[$className])) {
$this->staticAttributes[$className] = array();
}
$this->staticAttributes[$className][$attributeName] = true;
}
public function isGlobalVariableBlacklisted($variableName)
{
return isset($this->globalVariables[$variableName]);
}
public function isStaticAttributeBlacklisted($className, $attributeName)
{
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
namespace SebastianBergmann\GlobalState;
class CodeExporter
{
public function constants(Snapshot $snapshot)
{
$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 iniSettings(Snapshot $snapshot)
{
$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)
{
if (is_scalar($variable) || is_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)
{
$result = true;
foreach ($array as $element) {
if (is_array($element)) {
$result = self::arrayOnlyContainsScalars($element);
} elseif (!is_scalar($element) && !is_null($element)) {
$result = false;
}
if ($result === false) {
break;
}
}
return $result;
}
}
<?php
namespace SebastianBergmann\GlobalState;
interface Exception
{
}
<?php
namespace SebastianBergmann\GlobalState;
use ReflectionProperty;
class Restorer
{
public function restoreFunctions(Snapshot $snapshot)
{
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);
}
}
public function restoreGlobalVariables(Snapshot $snapshot)
{
$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 (isset($globalVariables[$key])) {
$GLOBALS[$key] = $globalVariables[$key];
} else {
unset($GLOBALS[$key]);
}
}
}
}
public function restoreStaticAttributes(Snapshot $snapshot)
{
$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]);
}
}
}
private function restoreSuperGlobalArray(Snapshot $snapshot, $superGlobalArray)
{
$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
namespace SebastianBergmann\GlobalState;
class RuntimeException extends \RuntimeException implements Exception
{
}
<?php
namespace SebastianBergmann\GlobalState;
use ReflectionClass;
use Serializable;
class Snapshot
{
private $blacklist;
private $globalVariables = array();
private $superGlobalArrays = array();
private $superGlobalVariables = array();
private $staticAttributes = array();
private $iniSettings = array();
private $includedFiles = array();
private $constants = array();
private $functions = array();
private $interfaces = array();
private $classes = array();
private $traits = array();
public function __construct(Blacklist $blacklist = null, $includeGlobalVariables = true, $includeStaticAttributes = true, $includeConstants = true, $includeFunctions = true, $includeClasses = true, $includeInterfaces = true, $includeTraits = true, $includeIniSettings = true, $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 (function_exists('get_declared_traits')) {
$this->traits = get_declared_traits();
}
}
public function blacklist()
{
return $this->blacklist;
}
public function globalVariables()
{
return $this->globalVariables;
}
public function superGlobalVariables()
{
return $this->superGlobalVariables;
}
public function superGlobalArrays()
{
return $this->superGlobalArrays;
}
public function staticAttributes()
{
return $this->staticAttributes;
}
public function iniSettings()
{
return $this->iniSettings;
}
public function includedFiles()
{
return $this->includedFiles;
}
public function constants()
{
return $this->constants;
}
public function functions()
{
return $this->functions;
}
public function interfaces()
{
return $this->interfaces;
}
public function classes()
{
return $this->classes;
}
public function traits()
{
return $this->traits;
}
private function snapshotConstants()
{
$constants = get_defined_constants(true);
if (isset($constants['user'])) {
$this->constants = $constants['user'];
}
}
private function snapshotFunctions()
{
$functions = get_defined_functions();
$this->functions = $functions['user'];
}
private function snapshotClasses()
{
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);
}
private function snapshotInterfaces()
{
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);
}
private function snapshotGlobals()
{
$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)) {
$this->globalVariables[$key] = unserialize(serialize($GLOBALS[$key]));
}
}
}
private function snapshotSuperGlobalArray($superGlobalArray)
{
$this->superGlobalVariables[$superGlobalArray] = array();
if (isset($GLOBALS[$superGlobalArray]) && is_array($GLOBALS[$superGlobalArray])) {
foreach ($GLOBALS[$superGlobalArray] as $key => $value) {
$this->superGlobalVariables[$superGlobalArray][$key] = unserialize(serialize($value));
}
}
}
private function snapshotStaticAttributes()
{
foreach ($this->classes as $className) {
$class = new ReflectionClass($className);
$snapshot = array();
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)) {
$snapshot[$name] = unserialize(serialize($value));
}
}
}
if (!empty($snapshot)) {
$this->staticAttributes[$className] = $snapshot;
}
}
}
private function setupSuperGlobalArrays()
{
$this->superGlobalArrays = array(
'_ENV',
'_POST',
'_GET',
'_COOKIE',
'_SERVER',
'_FILES',
'_REQUEST'
);
if (ini_get('register_long_arrays') == '1') {
$this->superGlobalArrays = array_merge(
$this->superGlobalArrays,
array(
'HTTP_ENV_VARS',
'HTTP_POST_VARS',
'HTTP_GET_VARS',
'HTTP_COOKIE_VARS',
'HTTP_SERVER_VARS',
'HTTP_POST_FILES'
)
);
}
}
private function canBeSerialized($variable)
{
if (!is_object($variable)) {
return !is_resource($variable);
}
if ($variable instanceof \stdClass) {
return true;
}
$class = new ReflectionClass($variable);
do {
if ($class->isInternal()) {
return $variable instanceof Serializable;
}
} while ($class = $class->getParentClass());
return true;
}
}
<?php
namespace SebastianBergmann\Exporter;
use SebastianBergmann\RecursionContext\Context;
class Exporter
{
public function export($value, $indentation = 0)
{
return $this->recursiveExport($value, $indentation);
}
public function shortenedRecursiveExport(&$data, Context $context = null)
{
$result = array();
$exporter = new self();
if (!$context) {
$context = new Context;
}
$context->add($data);
foreach ($data 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);
}
public function shortenedExport($value)
{
if (is_string($value)) {
$string = $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 str_replace("\n", '\n', $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);
}
public function toArray($value)
{
if (!is_object($value)) {
return (array) $value;
}
$array = array();
foreach ((array) $value as $key => $val) {
if (preg_match('/^\0.+\0(.+)$/', $key, $matches)) {
$key = $matches[1];
}
if ($key === "\0gcdata") {
continue;
}
$array[$key] = $val;
}
if ($value instanceof \SplObjectStorage) {
if (property_exists('\SplObjectStorage', '__storage')) {
unset($array['__storage']);
} elseif (property_exists('\SplObjectStorage', 'storage')) {
unset($array['storage']);
}
if (property_exists('\SplObjectStorage', '__key')) {
unset($array['__key']);
}
foreach ($value as $key => $val) {
$array[spl_object_hash($val)] = array(
'obj' => $val,
'inf' => $value->getInfo(),
);
}
}
return $array;
}
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) && floatval(intval($value)) === $value) {
return "$value.0";
}
if (is_resource($value)) {
return sprintf(
'resource(%d) of type (%s)',
$value,
get_resource_type($value)
);
}
if (is_string($value)) {
if (preg_match('/[^\x09-\x0d\x1b\x20-\xff]/', $value)) {
return 'Binary String: 0x' . bin2hex($value);
}
return "'" .
str_replace(array("\r\n", "\n\r", "\r"), array("\n", "\n", "\n"), $value) .
"'";
}
$whitespace = str_repeat(' ', 4 * $indentation);
if (!$processed) {
$processed = new Context;
}
if (is_array($value)) {
if (($key = $processed->contains($value)) !== false) {
return 'Array &' . $key;
}
$key = $processed->add($value);
$values = '';
if (count($value) > 0) {
foreach ($value 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);
}
}
<?php
namespace SebastianBergmann\Environment;
class Console
{
const STDIN = 0;
const STDOUT = 1;
const STDERR = 2;
public function hasColorSupport()
{
if (DIRECTORY_SEPARATOR == '\\') {
return false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI') || 'xterm' === getenv('TERM');
}
if (!defined('STDOUT')) {
return false;
}
return $this->isInteractive(STDOUT);
}
public function getNumberOfColumns()
{
if (DIRECTORY_SEPARATOR == '\\') {
$columns = 80;
if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
$columns = $matches[1];
} elseif (function_exists('proc_open')) {
$process = proc_open(
'mode CON',
array(
1 => array('pipe', 'w'),
2 => array('pipe', 'w')
),
$pipes,
null,
null,
array('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;
}
if (!$this->isInteractive(self::STDIN)) {
return 80;
}
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;
}
public function isInteractive($fileDescriptor = self::STDOUT)
{
return function_exists('posix_isatty') && @posix_isatty($fileDescriptor);
}
}
<?php
namespace SebastianBergmann\Environment;
class Runtime
{
private static $binary;
public function canCollectCodeCoverage()
{
return $this->hasXdebug() || $this->hasPHPDBGCodeCoverage();
}
public function getBinary()
{
if (self::$binary === null && $this->isHHVM()) {
if ((self::$binary = getenv('PHP_BINARY')) === false) {
self::$binary = PHP_BINARY;
}
self::$binary = escapeshellarg(self::$binary) . ' --php';
}
if (self::$binary === null && defined('PHP_BINARY')) {
if (PHP_BINARY !== '') {
self::$binary = escapeshellarg(PHP_BINARY);
}
}
if (self::$binary === null) {
if (PHP_SAPI == 'cli' && isset($_SERVER['_'])) {
if (strpos($_SERVER['_'], 'phpunit') !== false) {
$file = file($_SERVER['_']);
if (strpos($file[0], ' ') !== false) {
$tmp = explode(' ', $file[0]);
self::$binary = escapeshellarg(trim($tmp[1]));
} else {
self::$binary = escapeshellarg(ltrim(trim($file[0]), '#!'));
}
} elseif (strpos(basename($_SERVER['_']), 'php') !== false) {
self::$binary = escapeshellarg($_SERVER['_']);
}
}
}
if (self::$binary === null) {
$possibleBinaryLocations = array(
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;
}
}
}
if (self::$binary === null) {
self::$binary = 'php';
}
return self::$binary;
}
public function getNameWithVersion()
{
return $this->getName() . ' ' . $this->getVersion();
}
public function getName()
{
if ($this->isHHVM()) {
return 'HHVM';
} elseif ($this->isPHPDBG()) {
return 'PHPDBG';
} else {
return 'PHP';
}
}
public function getVendorUrl()
{
if ($this->isHHVM()) {
return 'http://hhvm.com/';
} else {
return 'https://secure.php.net/';
}
}
public function getVersion()
{
if ($this->isHHVM()) {
return HHVM_VERSION;
} else {
return PHP_VERSION;
}
}
public function hasXdebug()
{
return ($this->isPHP() || $this->isHHVM()) && extension_loaded('xdebug');
}
public function isHHVM()
{
return defined('HHVM_VERSION');
}
public function isPHP()
{
return !$this->isHHVM() && !$this->isPHPDBG();
}
public function isPHPDBG()
{
return PHP_SAPI === 'phpdbg' && !$this->isHHVM();
}
public function hasPHPDBGCodeCoverage()
{
return $this->isPHPDBG() && function_exists('phpdbg_start_oplog');
}
}
<?php
namespace SebastianBergmann\Diff;
class Chunk
{
private $start;
private $startRange;
private $end;
private $endRange;
private $lines;
public function __construct($start = 0, $startRange = 1, $end = 0, $endRange = 1, array $lines = array())
{
$this->start = (int) $start;
$this->startRange = (int) $startRange;
$this->end = (int) $end;
$this->endRange = (int) $endRange;
$this->lines = $lines;
}
public function getStart()
{
return $this->start;
}
public function getStartRange()
{
return $this->startRange;
}
public function getEnd()
{
return $this->end;
}
public function getEndRange()
{
return $this->endRange;
}
public function getLines()
{
return $this->lines;
}
public function setLines(array $lines)
{
$this->lines = $lines;
}
}
<?php
namespace SebastianBergmann\Diff;
class Diff
{
private $from;
private $to;
private $chunks;
public function __construct($from, $to, array $chunks = array())
{
$this->from = $from;
$this->to = $to;
$this->chunks = $chunks;
}
public function getFrom()
{
return $this->from;
}
public function getTo()
{
return $this->to;
}
public function getChunks()
{
return $this->chunks;
}
public function setChunks(array $chunks)
{
$this->chunks = $chunks;
}
}
<?php
namespace SebastianBergmann\Diff;
use SebastianBergmann\Diff\LCS\LongestCommonSubsequence;
use SebastianBergmann\Diff\LCS\TimeEfficientImplementation;
use SebastianBergmann\Diff\LCS\MemoryEfficientImplementation;
class Differ
{
private $header;
private $showNonDiffLines;
public function __construct($header = "--- Original\n+++ New\n", $showNonDiffLines = true)
{
$this->header = $header;
$this->showNonDiffLines = $showNonDiffLines;
}
public function diff($from, $to, LongestCommonSubsequence $lcs = null)
{
if (!is_array($from) && !is_string($from)) {
$from = (string) $from;
}
if (!is_array($to) && !is_string($to)) {
$to = (string) $to;
}
$buffer = $this->header;
$diff = $this->diffToArray($from, $to, $lcs);
$inOld = false;
$i = 0;
$old = array();
foreach ($diff as $line) {
if ($line[1] === 0 ) {
if ($inOld === false) {
$inOld = $i;
}
} elseif ($inOld !== false) {
if (($i - $inOld) > 5) {
$old[$inOld] = $i - 1;
}
$inOld = false;
}
++$i;
}
$start = isset($old[0]) ? $old[0] : 0;
$end = count($diff);
if ($tmp = array_search($end, $old)) {
$end = $tmp;
}
$newChunk = true;
for ($i = $start; $i < $end; $i++) {
if (isset($old[$i])) {
$buffer .= "\n";
$newChunk = true;
$i = $old[$i];
}
if ($newChunk) {
if ($this->showNonDiffLines === true) {
$buffer .= "@@ @@\n";
}
$newChunk = false;
}
if ($diff[$i][1] === 1 ) {
$buffer .= '+' . $diff[$i][0] . "\n";
} elseif ($diff[$i][1] === 2 ) {
$buffer .= '-' . $diff[$i][0] . "\n";
} elseif ($this->showNonDiffLines === true) {
$buffer .= ' ' . $diff[$i][0] . "\n";
}
}
return $buffer;
}
public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
{
preg_match_all('(\r\n|\r|\n)', $from, $fromMatches);
preg_match_all('(\r\n|\r|\n)', $to, $toMatches);
if (is_string($from)) {
$from = preg_split('(\r\n|\r|\n)', $from);
}
if (is_string($to)) {
$to = preg_split('(\r\n|\r|\n)', $to);
}
$start = array();
$end = array();
$fromLength = count($from);
$toLength = count($to);
$length = min($fromLength, $toLength);
for ($i = 0; $i < $length; ++$i) {
if ($from[$i] === $to[$i]) {
$start[] = $from[$i];
unset($from[$i], $to[$i]);
} else {
break;
}
}
$length -= $i;
for ($i = 1; $i < $length; ++$i) {
if ($from[$fromLength - $i] === $to[$toLength - $i]) {
array_unshift($end, $from[$fromLength - $i]);
unset($from[$fromLength - $i], $to[$toLength - $i]);
} else {
break;
}
}
if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}
$common = $lcs->calculate(array_values($from), array_values($to));
$diff = array();
if (isset($fromMatches[0]) && $toMatches[0] &&
count($fromMatches[0]) === count($toMatches[0]) &&
$fromMatches[0] !== $toMatches[0]) {
$diff[] = array(
'#Warning: Strings contain different line endings!', 0
);
}
foreach ($start as $token) {
$diff[] = array($token, 0 );
}
reset($from);
reset($to);
foreach ($common as $token) {
while ((($fromToken = reset($from)) !== $token)) {
$diff[] = array(array_shift($from), 2 );
}
while ((($toToken = reset($to)) !== $token)) {
$diff[] = array(array_shift($to), 1 );
}
$diff[] = array($token, 0 );
array_shift($from);
array_shift($to);
}
while (($token = array_shift($from)) !== null) {
$diff[] = array($token, 2 );
}
while (($token = array_shift($to)) !== null) {
$diff[] = array($token, 1 );
}
foreach ($end as $token) {
$diff[] = array($token, 0 );
}
return $diff;
}
private function selectLcsImplementation(array $from, array $to)
{
$memoryLimit = 100 * 1024 * 1024;
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
return new MemoryEfficientImplementation;
}
return new TimeEfficientImplementation;
}
private function calculateEstimatedFootprint(array $from, array $to)
{
$itemSize = PHP_INT_SIZE == 4 ? 76 : 144;
return $itemSize * pow(min(count($from), count($to)), 2);
}
}
<?php
namespace SebastianBergmann\Diff\LCS;
interface LongestCommonSubsequence
{
public function calculate(array $from, array $to);
}
<?php
namespace SebastianBergmann\Diff\LCS;
class MemoryEfficientImplementation implements LongestCommonSubsequence
{
public function calculate(array $from, array $to)
{
$cFrom = count($from);
$cTo = count($to);
if ($cFrom == 0) {
return array();
} elseif ($cFrom == 1) {
if (in_array($from[0], $to)) {
return array($from[0]);
} else {
return array();
}
} else {
$i = intval($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)
{
$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;
}
}
<?php
namespace SebastianBergmann\Diff\LCS;
class TimeEfficientImplementation implements LongestCommonSubsequence
{
public function calculate(array $from, array $to)
{
$common = array();
$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
namespace SebastianBergmann\Diff;
class Line
{
const ADDED = 1;
const REMOVED = 2;
const UNCHANGED = 3;
private $type;
private $content;
public function __construct($type = self::UNCHANGED, $content = '')
{
$this->type = $type;
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function getType()
{
return $this->type;
}
}
<?php
namespace SebastianBergmann\Diff;
class Parser
{
public function parse($string)
{
$lines = preg_split('(\r\n|\r|\n)', $string);
$lineCount = count($lines);
$diffs = array();
$diff = null;
$collected = array();
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 = array();
}
$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 (count($collected) && ($diff !== null)) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
}
return $diffs;
}
private function parseFileDiff(Diff $diff, array $lines)
{
$chunks = array();
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(
$match['start'],
isset($match['startrange']) ? max(1, $match['startrange']) : 1,
$match['end'],
isset($match['endrange']) ? max(1, $match['endrange']) : 1
);
$chunks[] = $chunk;
$diffLines = array();
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 (isset($chunk)) {
$chunk->setLines($diffLines);
}
}
}
$diff->setChunks($chunks);
}
}
<?php
namespace SebastianBergmann\Comparator;
class ArrayComparator extends Comparator
{
public function accepts($expected, $actual)
{
return is_array($expected) && is_array($actual);
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
{
if ($canonicalize) {
sort($expected);
sort($actual);
}
$remaining = $actual;
$expString = $actString = "Array (\n";
$equal = true;
foreach ($expected as $key => $value) {
unset($remaining[$key]);
if (!array_key_exists($key, $actual)) {
$expString .= 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);
$expString .= sprintf(
" %s => %s\n",
$this->exporter->export($key),
$this->exporter->shortenedExport($value)
);
$actString .= sprintf(
" %s => %s\n",
$this->exporter->export($key),
$this->exporter->shortenedExport($actual[$key])
);
} catch (ComparisonFailure $e) {
$expString .= sprintf(
" %s => %s\n",
$this->exporter->export($key),
$e->getExpectedAsString()
? $this->indent($e->getExpectedAsString())
: $this->exporter->shortenedExport($e->getExpected())
);
$actString .= 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) {
$actString .= sprintf(
" %s => %s\n",
$this->exporter->export($key),
$this->exporter->shortenedExport($value)
);
$equal = false;
}
$expString .= ')';
$actString .= ')';
if (!$equal) {
throw new ComparisonFailure(
$expected,
$actual,
$expString,
$actString,
false,
'Failed asserting that two arrays are equal.'
);
}
}
protected function indent($lines)
{
return trim(str_replace("\n", "\n ", $lines));
}
}
<?php
namespace SebastianBergmann\Comparator;
use SebastianBergmann\Exporter\Exporter;
abstract class Comparator
{
protected $factory;
protected $exporter;
public function __construct()
{
$this->exporter = new Exporter;
}
public function setFactory(Factory $factory)
{
$this->factory = $factory;
}
abstract public function accepts($expected, $actual);
abstract public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false);
}
<?php
namespace SebastianBergmann\Comparator;
use SebastianBergmann\Diff\Differ;
class ComparisonFailure extends \RuntimeException
{
protected $expected;
protected $actual;
protected $expectedAsString;
protected $actualAsString;
protected $identical;
protected $message;
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;
}
public function getActualAsString()
{
return $this->actualAsString;
}
public function getExpectedAsString()
{
return $this->expectedAsString;
}
public function getDiff()
{
if (!$this->actualAsString && !$this->expectedAsString) {
return '';
}
$differ = new Differ("\n--- Expected\n+++ Actual\n");
return $differ->diff($this->expectedAsString, $this->actualAsString);
}
public function toString()
{
return $this->message . $this->getDiff();
}
}
<?php
namespace SebastianBergmann\Comparator;
use DOMDocument;
use DOMNode;
class DOMNodeComparator extends ObjectComparator
{
public function accepts($expected, $actual)
{
return $expected instanceof DOMNode && $actual instanceof DOMNode;
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
{
$expectedAsString = $this->nodeToText($expected, true, $ignoreCase);
$actualAsString = $this->nodeToText($actual, true, $ignoreCase);
if ($expectedAsString !== $actualAsString) {
if ($expected instanceof DOMDocument) {
$type = 'documents';
} else {
$type = 'nodes';
}
throw new ComparisonFailure(
$expected,
$actual,
$expectedAsString,
$actualAsString,
false,
sprintf("Failed asserting that two DOM %s are equal.\n", $type)
);
}
}
private function nodeToText(DOMNode $node, $canonicalize, $ignoreCase)
{
if ($canonicalize) {
$document = new DOMDocument;
$document->loadXML($node->C14N());
$node = $document;
}
if ($node instanceof DOMDocument) {
$document = $node;
} else {
$document = $node->ownerDocument;
}
$document->formatOutput = true;
$document->normalizeDocument();
if ($node instanceof DOMDocument) {
$text = $node->saveXML();
} else {
$text = $document->saveXML($node);
}
if ($ignoreCase) {
$text = strtolower($text);
}
return $text;
}
}
<?php
namespace SebastianBergmann\Comparator;
class DateTimeComparator extends ObjectComparator
{
public function accepts($expected, $actual)
{
return ($expected instanceof \DateTime || $expected instanceof \DateTimeInterface) &&
($actual instanceof \DateTime || $actual instanceof \DateTimeInterface);
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
{
$delta = new \DateInterval(sprintf('PT%sS', abs($delta)));
$expectedLower = clone $expected;
$expectedUpper = clone $expected;
if ($actual < $expectedLower->sub($delta) ||
$actual > $expectedUpper->add($delta)) {
throw new ComparisonFailure(
$expected,
$actual,
$this->dateTimeToString($expected),
$this->dateTimeToString($actual),
false,
'Failed asserting that two DateTime objects are equal.'
);
}
}
protected function dateTimeToString($datetime)
{
$string = $datetime->format(\DateTime::ISO8601);
return $string ? $string : 'Invalid DateTimeInterface object';
}
}
<?php
namespace SebastianBergmann\Comparator;
class DoubleComparator extends NumericComparator
{
const EPSILON = 0.0000000001;
public function accepts($expected, $actual)
{
return (is_double($expected) || is_double($actual)) && is_numeric($expected) && is_numeric($actual);
}
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
namespace SebastianBergmann\Comparator;
class ExceptionComparator extends ObjectComparator
{
public function accepts($expected, $actual)
{
return $expected instanceof \Exception && $actual instanceof \Exception;
}
protected function toArray($object)
{
$array = parent::toArray($object);
unset(
$array['file'],
$array['line'],
$array['trace'],
$array['string'],
$array['xdebug_message']
);
return $array;
}
}
<?php
namespace SebastianBergmann\Comparator;
class Factory
{
private $comparators = array();
private static $instance;
public function __construct()
{
$this->register(new TypeComparator);
$this->register(new ScalarComparator);
$this->register(new NumericComparator);
$this->register(new DoubleComparator);
$this->register(new ArrayComparator);
$this->register(new ResourceComparator);
$this->register(new ObjectComparator);
$this->register(new ExceptionComparator);
$this->register(new SplObjectStorageComparator);
$this->register(new DOMNodeComparator);
$this->register(new MockObjectComparator);
$this->register(new DateTimeComparator);
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self;
}
return self::$instance;
}
public function getComparatorFor($expected, $actual)
{
foreach ($this->comparators as $comparator) {
if ($comparator->accepts($expected, $actual)) {
return $comparator;
}
}
}
public function register(Comparator $comparator)
{
array_unshift($this->comparators, $comparator);
$comparator->setFactory($this);
}
public function unregister(Comparator $comparator)
{
foreach ($this->comparators as $key => $_comparator) {
if ($comparator === $_comparator) {
unset($this->comparators[$key]);
}
}
}
}
<?php
namespace SebastianBergmann\Comparator;
class MockObjectComparator extends ObjectComparator
{
public function accepts($expected, $actual)
{
return $expected instanceof \PHPUnit_Framework_MockObject_MockObject && $actual instanceof \PHPUnit_Framework_MockObject_MockObject;
}
protected function toArray($object)
{
$array = parent::toArray($object);
unset($array['__phpunit_invocationMocker']);
return $array;
}
}<?php
namespace SebastianBergmann\Comparator;
class NumericComparator extends ScalarComparator
{
public function accepts($expected, $actual)
{
return is_numeric($expected) && is_numeric($actual) &&
!(is_double($expected) || is_double($actual)) &&
!(is_string($expected) && is_string($actual));
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
{
if (is_infinite($actual) && is_infinite($expected)) {
return;
}
if ((is_infinite($actual) xor is_infinite($expected)) ||
(is_nan($actual) or 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
namespace SebastianBergmann\Comparator;
class ObjectComparator extends ArrayComparator
{
public function accepts($expected, $actual)
{
return is_object($expected) && is_object($actual);
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
{
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)
)
);
}
if (in_array(array($actual, $expected), $processed, true) ||
in_array(array($expected, $actual), $processed, true)) {
return;
}
$processed[] = array($actual, $expected);
if ($actual !== $expected) {
try {
parent::assertEquals(
$this->toArray($expected),
$this->toArray($actual),
$delta,
$canonicalize,
$ignoreCase,
$processed
);
} catch (ComparisonFailure $e) {
throw new ComparisonFailure(
$expected,
$actual,
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.'
);
}
}
}
protected function toArray($object)
{
return $this->exporter->toArray($object);
}
}
<?php
namespace SebastianBergmann\Comparator;
class ResourceComparator extends Comparator
{
public function accepts($expected, $actual)
{
return is_resource($expected) && is_resource($actual);
}
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
namespace SebastianBergmann\Comparator;
class ScalarComparator extends Comparator
{
public function accepts($expected, $actual)
{
return ((is_scalar($expected) xor null === $expected) &&
(is_scalar($actual) xor null === $actual))
|| (is_string($expected) && is_object($actual) && method_exists($actual, '__toString'))
|| (is_object($expected) && method_exists($expected, '__toString') && is_string($actual));
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
{
$expectedToCompare = $expected;
$actualToCompare = $actual;
if (is_string($expected) || is_string($actual)) {
$expectedToCompare = (string) $expectedToCompare;
$actualToCompare = (string) $actualToCompare;
if ($ignoreCase) {
$expectedToCompare = strtolower($expectedToCompare);
$actualToCompare = strtolower($actualToCompare);
}
}
if ($expectedToCompare != $actualToCompare) {
if (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.'
);
}
throw new ComparisonFailure(
$expected,
$actual,
'',
'',
false,
sprintf(
'Failed asserting that %s matches expected %s.',
$this->exporter->export($actual),
$this->exporter->export($expected)
)
);
}
}
}
<?php
namespace SebastianBergmann\Comparator;
class SplObjectStorageComparator extends Comparator
{
public function accepts($expected, $actual)
{
return $expected instanceof \SplObjectStorage && $actual instanceof \SplObjectStorage;
}
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.'
);
}
}
}
}
<?php
namespace SebastianBergmann\Comparator;
class TypeComparator extends Comparator
{
public function accepts($expected, $actual)
{
return true;
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
{
if (gettype($expected) != gettype($actual)) {
throw new ComparisonFailure(
$expected,
$actual,
'',
'',
false,
sprintf(
'%s does not match expected type "%s".',
$this->exporter->shortenedExport($actual),
gettype($expected)
)
);
}
}
}
<?php
namespace SebastianBergmann\CodeUnitReverseLookup;
class Wizard
{
private $lookupTable = [];
private $processedClasses = [];
private $processedFunctions = [];
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;
}
}
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;
}
}
}
<?php
namespace Doctrine\Instantiator\Exception;
interface ExceptionInterface
{
}
<?php
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
public static function fromNonExistingClass($className)
{
if (interface_exists($className)) {
return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
}
if (PHP_VERSION_ID >= 50400 && trait_exists($className)) {
return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
}
return new self(sprintf('The provided class "%s" does not exist', $className));
}
public static function fromAbstractClass(ReflectionClass $reflectionClass)
{
return new self(sprintf(
'The provided class "%s" is abstract, and can not be instantiated',
$reflectionClass->getName()
));
}
}
<?php
namespace Doctrine\Instantiator\Exception;
use Exception;
use ReflectionClass;
use UnexpectedValueException as BaseUnexpectedValueException;
class UnexpectedValueException extends BaseUnexpectedValueException implements ExceptionInterface
{
public static function fromSerializationTriggeredException(ReflectionClass $reflectionClass, Exception $exception)
{
return new self(
sprintf(
'An exception was raised while trying to instantiate an instance of "%s" via un-serialization',
$reflectionClass->getName()
),
0,
$exception
);
}
public static function fromUncleanUnSerialization(
ReflectionClass $reflectionClass,
$errorString,
$errorCode,
$errorFile,
$errorLine
) {
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;
use Closure;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use Exception;
use ReflectionClass;
final class Instantiator implements InstantiatorInterface
{
const SERIALIZATION_FORMAT_USE_UNSERIALIZER = 'C';
const SERIALIZATION_FORMAT_AVOID_UNSERIALIZER = 'O';
private static $cachedInstantiators = array();
private static $cachedCloneables = array();
public function instantiate($className)
{
if (isset(self::$cachedCloneables[$className])) {
return clone self::$cachedCloneables[$className];
}
if (isset(self::$cachedInstantiators[$className])) {
$factory = self::$cachedInstantiators[$className];
return $factory();
}
return $this->buildAndCacheFromFactory($className);
}
private function buildAndCacheFromFactory($className)
{
$factory = self::$cachedInstantiators[$className] = $this->buildFactory($className);
$instance = $factory();
if ($this->isSafeToClone(new ReflectionClass($instance))) {
self::$cachedCloneables[$className] = clone $instance;
}
return $instance;
}
private function buildFactory($className)
{
$reflectionClass = $this->getReflectionClass($className);
if ($this->isInstantiableViaReflection($reflectionClass)) {
return function () use ($reflectionClass) {
return $reflectionClass->newInstanceWithoutConstructor();
};
}
$serializedString = sprintf(
'%s:%d:"%s":0:{}',
$this->getSerializationFormat($reflectionClass),
strlen($className),
$className
);
$this->checkIfUnSerializationIsSupported($reflectionClass, $serializedString);
return function () use ($serializedString) {
return unserialize($serializedString);
};
}
private function getReflectionClass($className)
{
if (! class_exists($className)) {
throw InvalidArgumentException::fromNonExistingClass($className);
}
$reflection = new ReflectionClass($className);
if ($reflection->isAbstract()) {
throw InvalidArgumentException::fromAbstractClass($reflection);
}
return $reflection;
}
private function checkIfUnSerializationIsSupported(ReflectionClass $reflectionClass, $serializedString)
{
set_error_handler(function ($code, $message, $file, $line) use ($reflectionClass, & $error) {
$error = UnexpectedValueException::fromUncleanUnSerialization(
$reflectionClass,
$message,
$code,
$file,
$line
);
});
$this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString);
restore_error_handler();
if ($error) {
throw $error;
}
}
private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, $serializedString)
{
try {
unserialize($serializedString);
} catch (Exception $exception) {
restore_error_handler();
throw UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $exception);
}
}
private function isInstantiableViaReflection(ReflectionClass $reflectionClass)
{
if (\PHP_VERSION_ID >= 50600) {
return ! ($this->hasInternalAncestors($reflectionClass) && $reflectionClass->isFinal());
}
return \PHP_VERSION_ID >= 50400 && ! $this->hasInternalAncestors($reflectionClass);
}
private function hasInternalAncestors(ReflectionClass $reflectionClass)
{
do {
if ($reflectionClass->isInternal()) {
return true;
}
} while ($reflectionClass = $reflectionClass->getParentClass());
return false;
}
private function getSerializationFormat(ReflectionClass $reflectionClass)
{
if ($this->isPhpVersionWithBrokenSerializationFormat()
&& $reflectionClass->implementsInterface('Serializable')
) {
return self::SERIALIZATION_FORMAT_USE_UNSERIALIZER;
}
return self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER;
}
private function isPhpVersionWithBrokenSerializationFormat()
{
return PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513;
}
private function isSafeToClone(ReflectionClass $reflection)
{
if (method_exists($reflection, 'isCloneable') && ! $reflection->isCloneable()) {
return false;
}
return ! $reflection->hasMethod('__clone');
}
}
<?php
namespace Doctrine\Instantiator;
interface InstantiatorInterface
{
public function instantiate($className);
}
<?php
class Text_Template
{
protected $template = '';
protected $openDelimiter = '{';
protected $closeDelimiter = '}';
protected $values = array();
public function __construct($file = '', $openDelimiter = '{', $closeDelimiter = '}')
{
$this->setFile($file);
$this->openDelimiter = $openDelimiter;
$this->closeDelimiter = $closeDelimiter;
}
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.'
);
}
}
public function setVar(array $values, $merge = TRUE)
{
if (!$merge || empty($this->values)) {
$this->values = $values;
} else {
$this->values = array_merge($this->values, $values);
}
}
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);
}
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
)
)
);
}
}
}
<?php
interface PHPUnit_Framework_MockObject_Builder_Identity
{
public function id($id);
}
<?php
class PHPUnit_Framework_MockObject_Builder_InvocationMocker implements PHPUnit_Framework_MockObject_Builder_MethodNameMatch
{
protected $collection;
protected $matcher;
private $configurableMethods = [];
public function __construct(PHPUnit_Framework_MockObject_Stub_MatcherCollection $collection, PHPUnit_Framework_MockObject_Matcher_Invocation $invocationMatcher, array $configurableMethods)
{
$this->collection = $collection;
$this->matcher = new PHPUnit_Framework_MockObject_Matcher(
$invocationMatcher
);
$this->collection->addMatcher($this->matcher);
$this->configurableMethods = $configurableMethods;
}
public function getMatcher()
{
return $this->matcher;
}
public function id($id)
{
$this->collection->registerId($id, $this);
return $this;
}
public function will(PHPUnit_Framework_MockObject_Stub $stub)
{
$this->matcher->stub = $stub;
return $this;
}
public function willReturn($value, ...$nextValues)
{
$stub = count($nextValues) === 0 ?
new PHPUnit_Framework_MockObject_Stub_Return($value) :
new PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls(
array_merge([$value], $nextValues)
);
return $this->will($stub);
}
public function willReturnReference(&$reference)
{
$stub = new PHPUnit_Framework_MockObject_Stub_ReturnReference($reference);
return $this->will($stub);
}
public function willReturnMap(array $valueMap)
{
$stub = new PHPUnit_Framework_MockObject_Stub_ReturnValueMap(
$valueMap
);
return $this->will($stub);
}
public function willReturnArgument($argumentIndex)
{
$stub = new PHPUnit_Framework_MockObject_Stub_ReturnArgument(
$argumentIndex
);
return $this->will($stub);
}
public function willReturnCallback($callback)
{
$stub = new PHPUnit_Framework_MockObject_Stub_ReturnCallback(
$callback
);
return $this->will($stub);
}
public function willReturnSelf()
{
$stub = new PHPUnit_Framework_MockObject_Stub_ReturnSelf;
return $this->will($stub);
}
public function willReturnOnConsecutiveCalls(...$values)
{
$stub = new PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls($values);
return $this->will($stub);
}
public function willThrowException(Exception $exception)
{
$stub = new PHPUnit_Framework_MockObject_Stub_Exception($exception);
return $this->will($stub);
}
public function after($id)
{
$this->matcher->afterMatchBuilderId = $id;
return $this;
}
private function canDefineParameters()
{
if ($this->matcher->methodNameMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'Method name matcher is not defined, cannot define parameter ' .
'matcher without one'
);
}
if ($this->matcher->parametersMatcher !== null) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'Parameter matcher is already defined, cannot redefine'
);
}
}
public function with(...$arguments)
{
$this->canDefineParameters();
$this->matcher->parametersMatcher = new PHPUnit_Framework_MockObject_Matcher_Parameters($arguments);
return $this;
}
public function withConsecutive(...$arguments)
{
$this->canDefineParameters();
$this->matcher->parametersMatcher = new PHPUnit_Framework_MockObject_Matcher_ConsecutiveParameters($arguments);
return $this;
}
public function withAnyParameters()
{
$this->canDefineParameters();
$this->matcher->parametersMatcher = new PHPUnit_Framework_MockObject_Matcher_AnyParameters;
return $this;
}
public function method($constraint)
{
if ($this->matcher->methodNameMatcher !== null) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'Method name matcher is already defined, cannot redefine'
);
}
if (is_string($constraint) && !in_array(strtolower($constraint), $this->configurableMethods)) {
throw new PHPUnit_Framework_MockObject_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->methodNameMatcher = new PHPUnit_Framework_MockObject_Matcher_MethodName($constraint);
return $this;
}
}
<?php
interface PHPUnit_Framework_MockObject_Builder_Match extends PHPUnit_Framework_MockObject_Builder_Stub
{
public function after($id);
}
<?php
interface PHPUnit_Framework_MockObject_Builder_MethodNameMatch extends PHPUnit_Framework_MockObject_Builder_ParametersMatch
{
public function method($name);
}
<?php
interface PHPUnit_Framework_MockObject_Builder_Namespace
{
public function lookupId($id);
public function registerId($id, PHPUnit_Framework_MockObject_Builder_Match $builder);
}
<?php
interface PHPUnit_Framework_MockObject_Builder_ParametersMatch extends PHPUnit_Framework_MockObject_Builder_Match
{
public function with(...$arguments);
public function withAnyParameters();
}
<?php
interface PHPUnit_Framework_MockObject_Builder_Stub extends PHPUnit_Framework_MockObject_Builder_Identity
{
public function will(PHPUnit_Framework_MockObject_Stub $stub);
}
<?php
class PHPUnit_Framework_MockObject_BadMethodCallException extends BadMethodCallException implements PHPUnit_Framework_MockObject_Exception
{
}
<?php
interface PHPUnit_Framework_MockObject_Exception
{
}
<?php
class PHPUnit_Framework_MockObject_RuntimeException extends RuntimeException implements PHPUnit_Framework_MockObject_Exception
{
}
<?php
use Doctrine\Instantiator\Instantiator;
use Doctrine\Instantiator\Exception\InvalidArgumentException as InstantiatorInvalidArgumentException;
use Doctrine\Instantiator\Exception\UnexpectedValueException as InstantiatorUnexpectedValueException;
class PHPUnit_Framework_MockObject_Generator
{
private static $cache = [];
private static $templates = [];
private $legacyBlacklistedMethodNames = [
'__CLASS__' => true,
'__DIR__' => true,
'__FILE__' => true,
'__FUNCTION__' => true,
'__LINE__' => true,
'__METHOD__' => true,
'__NAMESPACE__' => true,
'__TRAIT__' => true,
'__clone' => true,
'__halt_compiler' => true,
'abstract' => true,
'and' => true,
'array' => true,
'as' => true,
'break' => true,
'callable' => true,
'case' => true,
'catch' => true,
'class' => true,
'clone' => true,
'const' => true,
'continue' => true,
'declare' => true,
'default' => true,
'die' => true,
'do' => true,
'echo' => true,
'else' => true,
'elseif' => true,
'empty' => true,
'enddeclare' => true,
'endfor' => true,
'endforeach' => true,
'endif' => true,
'endswitch' => true,
'endwhile' => true,
'eval' => true,
'exit' => true,
'expects' => true,
'extends' => true,
'final' => true,
'for' => true,
'foreach' => true,
'function' => true,
'global' => true,
'goto' => true,
'if' => true,
'implements' => true,
'include' => true,
'include_once' => true,
'instanceof' => true,
'insteadof' => true,
'interface' => true,
'isset' => true,
'list' => true,
'namespace' => true,
'new' => true,
'or' => true,
'print' => true,
'private' => true,
'protected' => true,
'public' => true,
'require' => true,
'require_once' => true,
'return' => true,
'static' => true,
'switch' => true,
'throw' => true,
'trait' => true,
'try' => true,
'unset' => true,
'use' => true,
'var' => true,
'while' => true,
'xor' => true
];
private $blacklistedMethodNames = [
'__CLASS__' => true,
'__DIR__' => true,
'__FILE__' => true,
'__FUNCTION__' => true,
'__LINE__' => true,
'__METHOD__' => true,
'__NAMESPACE__' => true,
'__TRAIT__' => true,
'__clone' => true,
'__halt_compiler' => true,
];
public function getMock($type, $methods = [], array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $cloneArguments = true, $callOriginalMethods = false, $proxyTarget = null, $allowMockingUnknownTypes = true)
{
if (!is_array($type) && !is_string($type)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'array or string');
}
if (!is_string($mockClassName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(4, 'string');
}
if (!is_array($methods) && !is_null($methods)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'array', $methods);
}
if ($type === 'Traversable' || $type === '\\Traversable') {
$type = 'Iterator';
}
if (is_array($type)) {
$type = array_unique(
array_map(
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 PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Cannot stub or mock class or interface "%s" which does not exist',
$_type
)
);
}
}
} else {
if (!class_exists($type, $callAutoload) &&
!interface_exists($type, $callAutoload)
) {
throw new PHPUnit_Framework_MockObject_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]*~', $method)) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Cannot stub or mock method with invalid name "%s"',
$method
)
);
}
}
if ($methods != array_unique($methods)) {
throw new PHPUnit_Framework_MockObject_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)) {
$reflect = new ReflectionClass($mockClassName);
if (!$reflect->implementsInterface('PHPUnit_Framework_MockObject_MockObject')) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Class "%s" already exists.',
$mockClassName
)
);
}
}
if ($callOriginalConstructor === false && $callOriginalMethods === true) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'Proxying to original methods requires invoking the original constructor'
);
}
$mock = $this->generate(
$type,
$methods,
$mockClassName,
$callOriginalClone,
$callAutoload,
$cloneArguments,
$callOriginalMethods
);
return $this->getObject(
$mock['code'],
$mock['mockClassName'],
$type,
$callOriginalConstructor,
$callAutoload,
$arguments,
$callOriginalMethods,
$proxyTarget
);
}
private function getObject($code, $className, $type = '', $callOriginalConstructor = false, $callAutoload = false, array $arguments = [], $callOriginalMethods = false, $proxyTarget = null)
{
$this->evalClass($code, $className);
if ($callOriginalConstructor &&
is_string($type) &&
!interface_exists($type, $callAutoload)) {
if (count($arguments) == 0) {
$object = new $className;
} else {
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
}
} else {
try {
$instantiator = new Instantiator;
$object = $instantiator->instantiate($className);
} catch (InstantiatorUnexpectedValueException $exception) {
if ($exception->getPrevious()) {
$exception = $exception->getPrevious();
}
throw new PHPUnit_Framework_MockObject_RuntimeException(
$exception->getMessage()
);
} catch (InstantiatorInvalidArgumentException $exception) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
$exception->getMessage()
);
}
}
if ($callOriginalMethods) {
if (!is_object($proxyTarget)) {
if (count($arguments) == 0) {
$proxyTarget = new $type;
} else {
$class = new ReflectionClass($type);
$proxyTarget = $class->newInstanceArgs($arguments);
}
}
$object->__phpunit_setOriginalObject($proxyTarget);
}
return $object;
}
private function evalClass($code, $className)
{
if (!class_exists($className, false)) {
eval($code);
}
}
public function getMockForAbstractClass($originalClassName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = true)
{
if (!is_string($originalClassName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($mockClassName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'string');
}
if (class_exists($originalClassName, $callAutoload) ||
interface_exists($originalClassName, $callAutoload)) {
$reflector = new ReflectionClass($originalClassName);
$methods = $mockedMethods;
foreach ($reflector->getMethods() as $method) {
if ($method->isAbstract() && !in_array($method->getName(), $methods)) {
$methods[] = $method->getName();
}
}
if (empty($methods)) {
$methods = null;
}
return $this->getMock(
$originalClassName,
$methods,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$cloneArguments
);
} else {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf('Class "%s" does not exist.', $originalClassName)
);
}
}
public function getMockForTrait($traitName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = true)
{
if (!is_string($traitName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($mockClassName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'string');
}
if (!trait_exists($traitName, $callAutoload)) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Trait "%s" does not exist.',
$traitName
)
);
}
$className = $this->generateClassName(
$traitName,
'',
'Trait_'
);
$templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;
$classTemplate = $this->getTemplate($templateDir . 'trait_class.tpl');
$classTemplate->setVar(
[
'prologue' => 'abstract ',
'class_name' => $className['className'],
'trait_name' => $traitName
]
);
$this->evalClass(
$classTemplate->render(),
$className['className']
);
return $this->getMockForAbstractClass($className['className'], $arguments, $mockClassName, $callOriginalConstructor, $callOriginalClone, $callAutoload, $mockedMethods, $cloneArguments);
}
public function getObjectForTrait($traitName, array $arguments = [], $traitClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true)
{
if (!is_string($traitName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($traitClassName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'string');
}
if (!trait_exists($traitName, $callAutoload)) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Trait "%s" does not exist.',
$traitName
)
);
}
$className = $this->generateClassName(
$traitName,
$traitClassName,
'Trait_'
);
$templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;
$classTemplate = $this->getTemplate($templateDir . 'trait_class.tpl');
$classTemplate->setVar(
[
'prologue' => '',
'class_name' => $className['className'],
'trait_name' => $traitName
]
);
return $this->getObject(
$classTemplate->render(),
$className['className']
);
}
public function generate($type, array $methods = null, $mockClassName = '', $callOriginalClone = true, $callAutoload = true, $cloneArguments = true, $callOriginalMethods = false)
{
if (is_array($type)) {
sort($type);
}
if ($mockClassName == '') {
$key = md5(
is_array($type) ? implode('_', $type) : $type .
serialize($methods) .
serialize($callOriginalClone) .
serialize($cloneArguments) .
serialize($callOriginalMethods)
);
if (isset(self::$cache[$key])) {
return self::$cache[$key];
}
}
$mock = $this->generateMock(
$type,
$methods,
$mockClassName,
$callOriginalClone,
$callAutoload,
$cloneArguments,
$callOriginalMethods
);
if (isset($key)) {
self::$cache[$key] = $mock;
}
return $mock;
}
public function generateClassFromWsdl($wsdlFile, $className, array $methods = [], array $options = [])
{
if (!extension_loaded('soap')) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'The SOAP extension is required to generate a mock object from WSDL.'
);
}
$options = array_merge($options, ['cache_wsdl' => WSDL_CACHE_NONE]);
$client = new SoapClient($wsdlFile, $options);
$_methods = array_unique($client->__getFunctions());
unset($client);
sort($_methods);
$templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;
$methodTemplate = $this->getTemplate($templateDir . 'wsdl_method.tpl');
$methodsBuffer = '';
foreach ($_methods as $method) {
$nameStart = strpos($method, ' ') + 1;
$nameEnd = strpos($method, '(');
$name = substr($method, $nameStart, $nameEnd - $nameStart);
if (empty($methods) || in_array($name, $methods)) {
$args = explode(
',',
substr(
$method,
$nameEnd + 1,
strpos($method, ')') - $nameEnd - 1
)
);
$numArgs = count($args);
for ($i = 0; $i < $numArgs; $i++) {
$args[$i] = substr($args[$i], strpos($args[$i], '$'));
}
$methodTemplate->setVar(
[
'method_name' => $name,
'arguments' => implode(', ', $args)
]
);
$methodsBuffer .= $methodTemplate->render();
}
}
$optionsBuffer = 'array(';
foreach ($options as $key => $value) {
$optionsBuffer .= $key . ' => ' . $value;
}
$optionsBuffer .= ')';
$classTemplate = $this->getTemplate($templateDir . '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();
}
private function generateMock($type, $methods, $mockClassName, $callOriginalClone, $callAutoload, $cloneArguments, $callOriginalMethods)
{
$methodReflections = [];
$templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;
$classTemplate = $this->getTemplate($templateDir . 'mocked_class.tpl');
$additionalInterfaces = [];
$cloneTemplate = '';
$isClass = false;
$isInterface = false;
$isMultipleInterfaces = false;
if (is_array($type)) {
foreach ($type as $_type) {
if (!interface_exists($_type, $callAutoload)) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Interface "%s" does not exist.',
$_type
)
);
}
$isMultipleInterfaces = true;
$additionalInterfaces[] = $_type;
$typeClass = new ReflectionClass($this->generateClassName(
$_type,
$mockClassName,
'Mock_'
)['fullClassName']
);
foreach ($this->getClassMethods($_type) as $method) {
if (in_array($method, $methods)) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Duplicate method "%s" not allowed.',
$method
)
);
}
$methodReflections[$method] = $typeClass->getMethod($method);
$methods[] = $method;
}
}
}
$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}";
}
$cloneTemplate = $this->getTemplate($templateDir . 'mocked_clone.tpl');
} else {
$class = new ReflectionClass($mockClassName['fullClassName']);
if ($class->isFinal()) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Class "%s" is declared "final" and cannot be mocked.',
$mockClassName['fullClassName']
)
);
}
if ($class->hasMethod('__clone')) {
$cloneMethod = $class->getMethod('__clone');
if (!$cloneMethod->isFinal()) {
if ($callOriginalClone && !$isInterface) {
$cloneTemplate = $this->getTemplate($templateDir . 'unmocked_clone.tpl');
} else {
$cloneTemplate = $this->getTemplate($templateDir . 'mocked_clone.tpl');
}
}
} else {
$cloneTemplate = $this->getTemplate($templateDir . 'mocked_clone.tpl');
}
}
if (is_object($cloneTemplate)) {
$cloneTemplate = $cloneTemplate->render();
}
if (is_array($methods) && empty($methods) &&
($isClass || $isInterface)) {
$methods = $this->getClassMethods($mockClassName['fullClassName']);
}
if (!is_array($methods)) {
$methods = [];
}
$mockedMethods = '';
$configurable = [];
foreach ($methods as $methodName) {
if ($methodName != '__construct' && $methodName != '__clone') {
$configurable[] = strtolower($methodName);
}
}
if (isset($class)) {
if ($isInterface && $class->implementsInterface('Traversable') &&
!$class->implementsInterface('Iterator') &&
!$class->implementsInterface('IteratorAggregate')) {
$additionalInterfaces[] = 'Iterator';
$methods = array_merge($methods, $this->getClassMethods('Iterator'));
}
foreach ($methods as $methodName) {
try {
$method = $class->getMethod($methodName);
if ($this->canMockMethod($method)) {
$mockedMethods .= $this->generateMockedMethodDefinitionFromExisting(
$templateDir,
$method,
$cloneArguments,
$callOriginalMethods
);
}
} catch (ReflectionException $e) {
$mockedMethods .= $this->generateMockedMethodDefinition(
$templateDir,
$mockClassName['fullClassName'],
$methodName,
$cloneArguments
);
}
}
} elseif ($isMultipleInterfaces) {
foreach ($methods as $methodName) {
if ($this->canMockMethod($methodReflections[$methodName])) {
$mockedMethods .= $this->generateMockedMethodDefinitionFromExisting(
$templateDir,
$methodReflections[$methodName],
$cloneArguments,
$callOriginalMethods
);
}
}
} else {
foreach ($methods as $methodName) {
$mockedMethods .= $this->generateMockedMethodDefinition(
$templateDir,
$mockClassName['fullClassName'],
$methodName,
$cloneArguments
);
}
}
$method = '';
if (!in_array('method', $methods) && (!isset($class) || !$class->hasMethod('method'))) {
$methodTemplate = $this->getTemplate($templateDir . 'mocked_class_method.tpl');
$method = $methodTemplate->render();
}
$classTemplate->setVar(
[
'prologue' => isset($prologue) ? $prologue : '',
'epilogue' => isset($epilogue) ? $epilogue : '',
'class_declaration' => $this->generateMockClassDeclaration(
$mockClassName,
$isInterface,
$additionalInterfaces
),
'clone' => $cloneTemplate,
'mock_class_name' => $mockClassName['className'],
'mocked_methods' => $mockedMethods,
'method' => $method,
'configurable' => '[' . implode(', ', array_map(function ($m) { return '\'' . $m . '\'';}, $configurable)) . ']'
]
);
return [
'code' => $classTemplate->render(),
'mockClassName' => $mockClassName['className']
];
}
private function generateClassName($type, $className, $prefix)
{
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(microtime()), 0, 8);
} while (class_exists($className, false));
}
return [
'className' => $className,
'originalClassName' => $type,
'fullClassName' => $fullClassName,
'namespaceName' => $namespaceName
];
}
private function generateMockClassDeclaration(array $mockClassName, $isInterface, array $additionalInterfaces = [])
{
$buffer = 'class ';
$additionalInterfaces[] = 'PHPUnit_Framework_MockObject_MockObject';
$interfaces = implode(', ', $additionalInterfaces);
if ($isInterface) {
$buffer .= sprintf(
'%s implements %s',
$mockClassName['className'],
$interfaces
);
if (!in_array($mockClassName['originalClassName'], $additionalInterfaces)) {
$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 generateMockedMethodDefinitionFromExisting($templateDir, ReflectionMethod $method, $cloneArguments, $callOriginalMethods)
{
if ($method->isPrivate()) {
$modifier = 'private';
} elseif ($method->isProtected()) {
$modifier = 'protected';
} else {
$modifier = 'public';
}
if ($method->isStatic()) {
$modifier .= ' static';
}
if ($method->returnsReference()) {
$reference = '&';
} else {
$reference = '';
}
if ($this->hasReturnType($method)) {
$returnType = (string) $method->getReturnType();
} else {
$returnType = '';
}
if (preg_match('#\*[ \t]*+@deprecated[ \t]*+(.*?)\r?+\n[ \t]*+\*(?:[ \t]*+@|/$)#s', $method->getDocComment(), $deprecation)) {
$deprecation = trim(preg_replace('#[ \t]*\r?\n[ \t]*+\*[ \t]*+#', ' ', $deprecation[1]));
} else {
$deprecation = false;
}
return $this->generateMockedMethodDefinition(
$templateDir,
$method->getDeclaringClass()->getName(),
$method->getName(),
$cloneArguments,
$modifier,
$this->getMethodParameters($method),
$this->getMethodParameters($method, true),
$returnType,
$reference,
$callOriginalMethods,
$method->isStatic(),
$deprecation
);
}
private function generateMockedMethodDefinition($templateDir, $className, $methodName, $cloneArguments = true, $modifier = 'public', $arguments_decl = '', $arguments_call = '', $return_type = '', $reference = '', $callOriginalMethods = false, $static = false, $deprecation = false)
{
if ($static) {
$templateFile = 'mocked_static_method.tpl';
} else {
$templateFile = sprintf(
'%s_method.tpl',
$callOriginalMethods ? 'proxied' : 'mocked'
);
}
if ($return_type === 'self') {
$return_type = $className;
}
if (false !== $deprecation) {
$deprecation = "The $className::$methodName method is deprecated ($deprecation).";
$deprecationTemplate = $this->getTemplate($templateDir . 'deprecation.tpl');
$deprecationTemplate->setVar(
[
'deprecation' => var_export($deprecation, true),
]
);
$deprecation = $deprecationTemplate->render();
}
$template = $this->getTemplate($templateDir . $templateFile);
$template->setVar(
[
'arguments_decl' => $arguments_decl,
'arguments_call' => $arguments_call,
'return_delim' => $return_type ? ': ' : '',
'return_type' => $return_type,
'arguments_count' => !empty($arguments_call) ? count(explode(',', $arguments_call)) : 0,
'class_name' => $className,
'method_name' => $methodName,
'modifier' => $modifier,
'reference' => $reference,
'clone_arguments' => $cloneArguments ? 'true' : 'false',
'deprecation' => $deprecation
]
);
return $template->render();
}
private function canMockMethod(ReflectionMethod $method)
{
if ($method->isConstructor() ||
$method->isFinal() ||
$method->isPrivate() ||
$this->isMethodNameBlacklisted($method->getName())) {
return false;
}
return true;
}
private function isMethodNameBlacklisted($name)
{
if (PHP_MAJOR_VERSION < 7 && isset($this->legacyBlacklistedMethodNames[$name])) {
return true;
}
if (PHP_MAJOR_VERSION >= 7 && isset($this->blacklistedMethodNames[$name])) {
return true;
}
return false;
}
private function getMethodParameters(ReflectionMethod $method, $forCall = false)
{
$parameters = [];
foreach ($method->getParameters() as $i => $parameter) {
$name = '$' . $parameter->getName();
if ($name === '$' || $name === '$...') {
$name = '$arg' . $i;
}
if ($this->isVariadic($parameter)) {
if ($forCall) {
continue;
} else {
$name = '...' . $name;
}
}
$default = '';
$reference = '';
$typeDeclaration = '';
if (!$forCall) {
if ($this->hasType($parameter) && (string) $parameter->getType() !== 'self') {
$typeDeclaration = (string) $parameter->getType() . ' ';
} elseif ($parameter->isArray()) {
$typeDeclaration = 'array ';
} elseif ($parameter->isCallable()) {
$typeDeclaration = 'callable ';
} else {
try {
$class = $parameter->getClass();
} catch (ReflectionException $e) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'Cannot mock %s::%s() because a class or ' .
'interface used in the signature is not loaded',
$method->getDeclaringClass()->getName(),
$method->getName()
),
0,
$e
);
}
if ($class !== null) {
$typeDeclaration = $class->getName() . ' ';
}
}
if (!$this->isVariadic($parameter)) {
if ($parameter->isDefaultValueAvailable()) {
$value = $parameter->getDefaultValue();
$default = ' = ' . var_export($value, true);
} elseif ($parameter->isOptional()) {
$default = ' = null';
}
}
}
if ($parameter->isPassedByReference()) {
$reference = '&';
}
$parameters[] = $typeDeclaration . $reference . $name . $default;
}
return implode(', ', $parameters);
}
private function isVariadic(ReflectionParameter $parameter)
{
return method_exists(ReflectionParameter::class, 'isVariadic') && $parameter->isVariadic();
}
private function hasType(ReflectionParameter $parameter)
{
return method_exists(ReflectionParameter::class, 'hasType') && $parameter->hasType();
}
private function hasReturnType(ReflectionMethod $method)
{
return method_exists(ReflectionMethod::class, 'hasReturnType') && $method->hasReturnType();
}
public function getClassMethods($className)
{
$class = new ReflectionClass($className);
$methods = [];
foreach ($class->getMethods() as $method) {
if ($method->isPublic() || $method->isAbstract()) {
$methods[] = $method->getName();
}
}
return $methods;
}
private function getTemplate($filename)
{
if (!isset(self::$templates[$filename])) {
self::$templates[$filename] = new Text_Template($filename);
}
return self::$templates[$filename];
}
}
<?php
interface PHPUnit_Framework_MockObject_Invocation
{
public function generateReturnValue();
}
<?php
class PHPUnit_Framework_MockObject_Invocation_Object extends PHPUnit_Framework_MockObject_Invocation_Static
{
public $object;
public function __construct($className, $methodName, array $parameters, $returnType, $object, $cloneObjects = false)
{
parent::__construct($className, $methodName, $parameters, $returnType, $cloneObjects);
$this->object = $object;
}
}
<?php
use SebastianBergmann\Exporter\Exporter;
class PHPUnit_Framework_MockObject_Invocation_Static implements PHPUnit_Framework_MockObject_Invocation, PHPUnit_Framework_SelfDescribing
{
protected static $uncloneableExtensions = [
'mysqli' => true,
'SQLite' => true,
'sqlite3' => true,
'tidy' => true,
'xmlwriter' => true,
'xsl' => true
];
protected static $uncloneableClasses = [
'Closure',
'COMPersistHelper',
'IteratorIterator',
'RecursiveIteratorIterator',
'SplFileObject',
'PDORow',
'ZipArchive'
];
public $className;
public $methodName;
public $parameters;
public $returnType;
public function __construct($className, $methodName, array $parameters, $returnType, $cloneObjects = false)
{
$this->className = $className;
$this->methodName = $methodName;
$this->parameters = $parameters;
$this->returnType = $returnType;
if (!$cloneObjects) {
return;
}
foreach ($this->parameters as $key => $value) {
if (is_object($value)) {
$this->parameters[$key] = $this->cloneObject($value);
}
}
}
public function toString()
{
$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 generateReturnValue()
{
switch ($this->returnType) {
case '': return;
case 'string': return '';
case 'float': return 0.0;
case 'int': return 0;
case 'bool': return false;
case 'array': return [];
case 'callable':
case 'Closure':
return function () {};
case 'Traversable':
case 'Generator':
$generator = function () { yield; };
return $generator();
default:
$generator = new PHPUnit_Framework_MockObject_Generator;
return $generator->getMock($this->returnType, [], [], '', false);
}
}
protected function cloneObject($original)
{
$cloneable = null;
$object = new ReflectionObject($original);
if ($object->isInternal() &&
isset(self::$uncloneableExtensions[$object->getExtensionName()])) {
$cloneable = false;
}
if ($cloneable === null) {
foreach (self::$uncloneableClasses as $class) {
if ($original instanceof $class) {
$cloneable = false;
break;
}
}
}
if ($cloneable === null && method_exists($object, 'isCloneable')) {
$cloneable = $object->isCloneable();
}
if ($cloneable === null && $object->hasMethod('__clone')) {
$method = $object->getMethod('__clone');
$cloneable = $method->isPublic();
}
if ($cloneable === null) {
$cloneable = true;
}
if ($cloneable) {
try {
return clone $original;
} catch (Exception $e) {
return $original;
}
} else {
return $original;
}
}
}
<?php
class PHPUnit_Framework_MockObject_InvocationMocker implements PHPUnit_Framework_MockObject_Stub_MatcherCollection, PHPUnit_Framework_MockObject_Invokable, PHPUnit_Framework_MockObject_Builder_Namespace
{
protected $matchers = [];
protected $builderMap = [];
private $configurableMethods = [];
public function __construct(array $configurableMethods)
{
$this->configurableMethods = $configurableMethods;
}
public function addMatcher(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher)
{
$this->matchers[] = $matcher;
}
public function hasMatchers()
{
foreach ($this->matchers as $matcher) {
if ($matcher->hasMatchers()) {
return true;
}
}
return false;
}
public function lookupId($id)
{
if (isset($this->builderMap[$id])) {
return $this->builderMap[$id];
}
return;
}
public function registerId($id, PHPUnit_Framework_MockObject_Builder_Match $builder)
{
if (isset($this->builderMap[$id])) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'Match builder with id <' . $id . '> is already registered.'
);
}
$this->builderMap[$id] = $builder;
}
public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher)
{
return new PHPUnit_Framework_MockObject_Builder_InvocationMocker(
$this,
$matcher,
$this->configurableMethods
);
}
public function invoke(PHPUnit_Framework_MockObject_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;
} elseif (strtolower($invocation->methodName) == '__tostring') {
return '';
}
return $invocation->generateReturnValue();
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
foreach ($this->matchers as $matcher) {
if (!$matcher->matches($invocation)) {
return false;
}
}
return true;
}
public function verify()
{
foreach ($this->matchers as $matcher) {
$matcher->verify();
}
}
}
<?php
interface PHPUnit_Framework_MockObject_Invokable extends PHPUnit_Framework_MockObject_Verifiable
{
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation);
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation);
}
<?php
class PHPUnit_Framework_MockObject_Matcher implements PHPUnit_Framework_MockObject_Matcher_Invocation
{
public $invocationMatcher;
public $afterMatchBuilderId = null;
public $afterMatchBuilderIsInvoked = false;
public $methodNameMatcher = null;
public $parametersMatcher = null;
public $stub = null;
public function __construct(PHPUnit_Framework_MockObject_Matcher_Invocation $invocationMatcher)
{
$this->invocationMatcher = $invocationMatcher;
}
public function toString()
{
$list = [];
if ($this->invocationMatcher !== null) {
$list[] = $this->invocationMatcher->toString();
}
if ($this->methodNameMatcher !== null) {
$list[] = 'where ' . $this->methodNameMatcher->toString();
}
if ($this->parametersMatcher !== null) {
$list[] = 'and ' . $this->parametersMatcher->toString();
}
if ($this->afterMatchBuilderId !== null) {
$list[] = 'after ' . $this->afterMatchBuilderId;
}
if ($this->stub !== null) {
$list[] = 'will ' . $this->stub->toString();
}
return implode(' ', $list);
}
public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation)
{
if ($this->invocationMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'No invocation matcher is set'
);
}
if ($this->methodNameMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException('No method matcher is set');
}
if ($this->afterMatchBuilderId !== null) {
$builder = $invocation->object
->__phpunit_getInvocationMocker()
->lookupId($this->afterMatchBuilderId);
if (!$builder) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'No builder found for match builder identification <%s>',
$this->afterMatchBuilderId
)
);
}
$matcher = $builder->getMatcher();
if ($matcher && $matcher->invocationMatcher->hasBeenInvoked()) {
$this->afterMatchBuilderIsInvoked = true;
}
}
$this->invocationMatcher->invoked($invocation);
try {
if ($this->parametersMatcher !== null &&
!$this->parametersMatcher->matches($invocation)) {
$this->parametersMatcher->verify();
}
} catch (PHPUnit_Framework_ExpectationFailedException $e) {
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf(
"Expectation failed for %s when %s\n%s",
$this->methodNameMatcher->toString(),
$this->invocationMatcher->toString(),
$e->getMessage()
),
$e->getComparisonFailure()
);
}
if ($this->stub) {
return $this->stub->invoke($invocation);
}
return $invocation->generateReturnValue();
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
if ($this->afterMatchBuilderId !== null) {
$builder = $invocation->object
->__phpunit_getInvocationMocker()
->lookupId($this->afterMatchBuilderId);
if (!$builder) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
sprintf(
'No builder found for match builder identification <%s>',
$this->afterMatchBuilderId
)
);
}
$matcher = $builder->getMatcher();
if (!$matcher) {
return false;
}
if (!$matcher->invocationMatcher->hasBeenInvoked()) {
return false;
}
}
if ($this->invocationMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'No invocation matcher is set'
);
}
if ($this->methodNameMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException('No method matcher is set');
}
if (!$this->invocationMatcher->matches($invocation)) {
return false;
}
try {
if (!$this->methodNameMatcher->matches($invocation)) {
return false;
}
} catch (PHPUnit_Framework_ExpectationFailedException $e) {
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf(
"Expectation failed for %s when %s\n%s",
$this->methodNameMatcher->toString(),
$this->invocationMatcher->toString(),
$e->getMessage()
),
$e->getComparisonFailure()
);
}
return true;
}
public function verify()
{
if ($this->invocationMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'No invocation matcher is set'
);
}
if ($this->methodNameMatcher === null) {
throw new PHPUnit_Framework_MockObject_RuntimeException('No method matcher is set');
}
try {
$this->invocationMatcher->verify();
if ($this->parametersMatcher === null) {
$this->parametersMatcher = new PHPUnit_Framework_MockObject_Matcher_AnyParameters;
}
$invocationIsAny = $this->invocationMatcher instanceof PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount;
$invocationIsNever = $this->invocationMatcher instanceof PHPUnit_Framework_MockObject_Matcher_InvokedCount && $this->invocationMatcher->isNever();
if (!$invocationIsAny && !$invocationIsNever) {
$this->parametersMatcher->verify();
}
} catch (PHPUnit_Framework_ExpectationFailedException $e) {
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf(
"Expectation failed for %s when %s.\n%s",
$this->methodNameMatcher->toString(),
$this->invocationMatcher->toString(),
PHPUnit_Framework_TestFailure::exceptionToString($e)
)
);
}
}
public function hasMatchers()
{
if ($this->invocationMatcher !== null &&
!$this->invocationMatcher instanceof PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount) {
return true;
}
return false;
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder
{
public function toString()
{
return 'invoked zero or more times';
}
public function verify()
{
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_AnyParameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation
{
public function toString()
{
return 'with any parameters';
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
return true;
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_ConsecutiveParameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation
{
private $parameterGroups = [];
private $invocations = [];
public function __construct(array $parameterGroups)
{
foreach ($parameterGroups as $index => $parameters) {
foreach ($parameters as $parameter) {
if (!$parameter instanceof PHPUnit_Framework_Constraint) {
$parameter = new PHPUnit_Framework_Constraint_IsEqual($parameter);
}
$this->parameterGroups[$index][] = $parameter;
}
}
}
public function toString()
{
$text = 'with consecutive parameters';
return $text;
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
$this->invocations[] = $invocation;
$callIndex = count($this->invocations) - 1;
$this->verifyInvocation($invocation, $callIndex);
return false;
}
public function verify()
{
foreach ($this->invocations as $callIndex => $invocation) {
$this->verifyInvocation($invocation, $callIndex);
}
}
private function verifyInvocation(PHPUnit_Framework_MockObject_Invocation $invocation, $callIndex)
{
if (isset($this->parameterGroups[$callIndex])) {
$parameters = $this->parameterGroups[$callIndex];
} else {
return;
}
if ($invocation === null) {
throw new PHPUnit_Framework_ExpectationFailedException(
'Mocked method does not exist.'
);
}
if (count($invocation->parameters) < count($parameters)) {
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf(
'Parameter count for invocation %s is too low.',
$invocation->toString()
)
);
}
foreach ($parameters as $i => $parameter) {
$parameter->evaluate(
$invocation->parameters[$i],
sprintf(
'Parameter %s for invocation #%d %s does not match expected ' .
'value.',
$i,
$callIndex,
$invocation->toString()
)
);
}
}
}
<?php
interface PHPUnit_Framework_MockObject_Matcher_Invocation extends PHPUnit_Framework_SelfDescribing, PHPUnit_Framework_MockObject_Verifiable
{
public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation);
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation);
}
<?php
class PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex implements PHPUnit_Framework_MockObject_Matcher_Invocation
{
protected $sequenceIndex;
protected $currentIndex = -1;
public function __construct($sequenceIndex)
{
$this->sequenceIndex = $sequenceIndex;
}
public function toString()
{
return 'invoked at sequence index ' . $this->sequenceIndex;
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
$this->currentIndex++;
return $this->currentIndex == $this->sequenceIndex;
}
public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation)
{
}
public function verify()
{
if ($this->currentIndex < $this->sequenceIndex) {
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf(
'The expected invocation at index %s was never reached.',
$this->sequenceIndex
)
);
}
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder
{
private $requiredInvocations;
public function __construct($requiredInvocations)
{
$this->requiredInvocations = $requiredInvocations;
}
public function toString()
{
return 'invoked at least ' . $this->requiredInvocations . ' times';
}
public function verify()
{
$count = $this->getInvocationCount();
if ($count < $this->requiredInvocations) {
throw new PHPUnit_Framework_ExpectationFailedException(
'Expected invocation at least ' . $this->requiredInvocations .
' times but it occurred ' . $count . ' time(s).'
);
}
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder
{
public function toString()
{
return 'invoked at least once';
}
public function verify()
{
$count = $this->getInvocationCount();
if ($count < 1) {
throw new PHPUnit_Framework_ExpectationFailedException(
'Expected invocation at least once but it never occurred.'
);
}
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_InvokedAtMostCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder
{
private $allowedInvocations;
public function __construct($allowedInvocations)
{
$this->allowedInvocations = $allowedInvocations;
}
public function toString()
{
return 'invoked at most ' . $this->allowedInvocations . ' times';
}
public function verify()
{
$count = $this->getInvocationCount();
if ($count > $this->allowedInvocations) {
throw new PHPUnit_Framework_ExpectationFailedException(
'Expected invocation at most ' . $this->allowedInvocations .
' times but it occurred ' . $count . ' time(s).'
);
}
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_InvokedCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder
{
protected $expectedCount;
public function __construct($expectedCount)
{
$this->expectedCount = $expectedCount;
}
public function isNever()
{
return $this->expectedCount == 0;
}
public function toString()
{
return 'invoked ' . $this->expectedCount . ' time(s)';
}
public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation)
{
parent::invoked($invocation);
$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 PHPUnit_Framework_ExpectationFailedException($message);
}
}
public function verify()
{
$count = $this->getInvocationCount();
if ($count !== $this->expectedCount) {
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf(
'Method was expected to be called %d times, ' .
'actually called %d times.',
$this->expectedCount,
$count
)
);
}
}
}
<?php
abstract class PHPUnit_Framework_MockObject_Matcher_InvokedRecorder implements PHPUnit_Framework_MockObject_Matcher_Invocation
{
protected $invocations = [];
public function getInvocationCount()
{
return count($this->invocations);
}
public function getInvocations()
{
return $this->invocations;
}
public function hasBeenInvoked()
{
return count($this->invocations) > 0;
}
public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation)
{
$this->invocations[] = $invocation;
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
return true;
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_MethodName extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation
{
protected $constraint;
public function __construct($constraint)
{
if (!$constraint instanceof PHPUnit_Framework_Constraint) {
if (!is_string($constraint)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_IsEqual(
$constraint,
0,
10,
false,
true
);
}
$this->constraint = $constraint;
}
public function toString()
{
return 'method name ' . $this->constraint->toString();
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
return $this->constraint->evaluate($invocation->methodName, '', true);
}
}
<?php
class PHPUnit_Framework_MockObject_Matcher_Parameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation
{
protected $parameters = [];
protected $invocation;
private $parameterVerificationResult;
public function __construct(array $parameters)
{
foreach ($parameters as $parameter) {
if (!($parameter instanceof PHPUnit_Framework_Constraint)) {
$parameter = new PHPUnit_Framework_Constraint_IsEqual(
$parameter
);
}
$this->parameters[] = $parameter;
}
}
public function toString()
{
$text = 'with parameter';
foreach ($this->parameters as $index => $parameter) {
if ($index > 0) {
$text .= ' and';
}
$text .= ' ' . $index . ' ' . $parameter->toString();
}
return $text;
}
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
$this->invocation = $invocation;
$this->parameterVerificationResult = null;
try {
$this->parameterVerificationResult = $this->verify();
return $this->parameterVerificationResult;
} catch (PHPUnit_Framework_ExpectationFailedException $e) {
$this->parameterVerificationResult = $e;
throw $this->parameterVerificationResult;
}
}
public function verify()
{
if (isset($this->parameterVerificationResult)) {
return $this->guardAgainstDuplicateEvaluationOfParameterConstraints();
}
if ($this->invocation === null) {
throw new PHPUnit_Framework_ExpectationFailedException(
'Mocked method does not exist.'
);
}
if (count($this->invocation->parameters) < count($this->parameters)) {
$message = 'Parameter count for invocation %s is too low.';
if (count($this->parameters) === 1 &&
get_class($this->parameters[0]) === 'PHPUnit_Framework_Constraint_IsAnything') {
$message .= "\nTo allow 0 or more parameters with any value, omit ->with() or use ->withAnyParameters() instead.";
}
throw new PHPUnit_Framework_ExpectationFailedException(
sprintf($message, $this->invocation->toString())
);
}
foreach ($this->parameters as $i => $parameter) {
$parameter->evaluate(
$this->invocation->parameters[$i],
sprintf(
'Parameter %s for invocation %s does not match expected ' .
'value.',
$i,
$this->invocation->toString()
)
);
}
return true;
}
private function guardAgainstDuplicateEvaluationOfParameterConstraints()
{
if ($this->parameterVerificationResult instanceof Exception) {
throw $this->parameterVerificationResult;
}
return (bool) $this->parameterVerificationResult;
}
}
<?php
abstract class PHPUnit_Framework_MockObject_Matcher_StatelessInvocation implements PHPUnit_Framework_MockObject_Matcher_Invocation
{
public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation)
{
}
public function verify()
{
}
}
<?php
class PHPUnit_Framework_MockObject_MockBuilder
{
private $testCase;
private $type;
private $methods = [];
private $methodsExcept = [];
private $mockClassName = '';
private $constructorArgs = [];
private $originalConstructor = true;
private $originalClone = true;
private $autoload = true;
private $cloneArguments = false;
private $callOriginalMethods = false;
private $proxyTarget = null;
private $allowMockingUnknownTypes = true;
private $generator;
public function __construct(PHPUnit_Framework_TestCase $testCase, $type)
{
$this->testCase = $testCase;
$this->type = $type;
$this->generator = new PHPUnit_Framework_MockObject_Generator;
}
public function getMock()
{
$object = $this->generator->getMock(
$this->type,
$this->methods,
$this->constructorArgs,
$this->mockClassName,
$this->originalConstructor,
$this->originalClone,
$this->autoload,
$this->cloneArguments,
$this->callOriginalMethods,
$this->proxyTarget,
$this->allowMockingUnknownTypes
);
$this->testCase->registerMockObject($object);
return $object;
}
public function getMockForAbstractClass()
{
$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;
}
public function getMockForTrait()
{
$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;
}
public function setMethods(array $methods = null)
{
$this->methods = $methods;
return $this;
}
public function setMethodsExcept(array $methods = [])
{
$this->methodsExcept = $methods;
$this->setMethods(
array_diff(
$this->generator->getClassMethods($this->type),
$this->methodsExcept
)
);
return $this;
}
public function setConstructorArgs(array $args)
{
$this->constructorArgs = $args;
return $this;
}
public function setMockClassName($name)
{
$this->mockClassName = $name;
return $this;
}
public function disableOriginalConstructor()
{
$this->originalConstructor = false;
return $this;
}
public function enableOriginalConstructor()
{
$this->originalConstructor = true;
return $this;
}
public function disableOriginalClone()
{
$this->originalClone = false;
return $this;
}
public function enableOriginalClone()
{
$this->originalClone = true;
return $this;
}
public function disableAutoload()
{
$this->autoload = false;
return $this;
}
public function enableAutoload()
{
$this->autoload = true;
return $this;
}
public function disableArgumentCloning()
{
$this->cloneArguments = false;
return $this;
}
public function enableArgumentCloning()
{
$this->cloneArguments = true;
return $this;
}
public function enableProxyingToOriginalMethods()
{
$this->callOriginalMethods = true;
return $this;
}
public function disableProxyingToOriginalMethods()
{
$this->callOriginalMethods = false;
$this->proxyTarget = null;
return $this;
}
public function setProxyTarget($object)
{
$this->proxyTarget = $object;
return $this;
}
public function allowMockingUnknownTypes()
{
$this->allowMockingUnknownTypes = true;
return $this;
}
public function disallowMockingUnknownTypes()
{
$this->allowMockingUnknownTypes = false;
return $this;
}
}
<?php
interface PHPUnit_Framework_MockObject_MockObject
{
public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher);
public function __phpunit_setOriginalObject($originalObject);
public function __phpunit_getInvocationMocker();
public function __phpunit_verify();
public function __phpunit_hasMatchers();
}
<?php
interface PHPUnit_Framework_MockObject_Stub extends PHPUnit_Framework_SelfDescribing
{
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation);
}
<?php
use SebastianBergmann\Exporter\Exporter;
class PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls implements PHPUnit_Framework_MockObject_Stub
{
protected $stack;
protected $value;
public function __construct($stack)
{
$this->stack = $stack;
}
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
$this->value = array_shift($this->stack);
if ($this->value instanceof PHPUnit_Framework_MockObject_Stub) {
$this->value = $this->value->invoke($invocation);
}
return $this->value;
}
public function toString()
{
$exporter = new Exporter;
return sprintf(
'return user-specified value %s',
$exporter->export($this->value)
);
}
}
<?php
use SebastianBergmann\Exporter\Exporter;
class PHPUnit_Framework_MockObject_Stub_Exception implements PHPUnit_Framework_MockObject_Stub
{
protected $exception;
public function __construct($exception)
{
if (!$exception instanceof Throwable && !$exception instanceof Exception) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'Exception must be an instance of Throwable (PHP 7) or Exception (PHP 5)'
);
}
$this->exception = $exception;
}
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
throw $this->exception;
}
public function toString()
{
$exporter = new Exporter;
return sprintf(
'raise user-specified exception %s',
$exporter->export($this->exception)
);
}
}
<?php
interface PHPUnit_Framework_MockObject_Stub_MatcherCollection
{
public function addMatcher(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher);
}
<?php
use SebastianBergmann\Exporter\Exporter;
class PHPUnit_Framework_MockObject_Stub_Return implements PHPUnit_Framework_MockObject_Stub
{
protected $value;
public function __construct($value)
{
$this->value = $value;
}
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
return $this->value;
}
public function toString()
{
$exporter = new Exporter;
return sprintf(
'return user-specified value %s',
$exporter->export($this->value)
);
}
}
<?php
class PHPUnit_Framework_MockObject_Stub_ReturnArgument extends PHPUnit_Framework_MockObject_Stub_Return
{
protected $argumentIndex;
public function __construct($argumentIndex)
{
$this->argumentIndex = $argumentIndex;
}
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
if (isset($invocation->parameters[$this->argumentIndex])) {
return $invocation->parameters[$this->argumentIndex];
} else {
return;
}
}
public function toString()
{
return sprintf('return argument #%d', $this->argumentIndex);
}
}
<?php
class PHPUnit_Framework_MockObject_Stub_ReturnCallback implements PHPUnit_Framework_MockObject_Stub
{
protected $callback;
public function __construct($callback)
{
$this->callback = $callback;
}
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
return call_user_func_array($this->callback, $invocation->parameters);
}
public function toString()
{
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]
);
} else {
return 'return result of user defined callback ' . $this->callback .
' with the passed arguments';
}
}
}
<?php
class PHPUnit_Framework_MockObject_Stub_ReturnReference extends PHPUnit_Framework_MockObject_Stub_Return
{
public function __construct(&$value)
{
$this->value = &$value;
}
}
<?php
class PHPUnit_Framework_MockObject_Stub_ReturnSelf implements PHPUnit_Framework_MockObject_Stub
{
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
if (!$invocation instanceof PHPUnit_Framework_MockObject_Invocation_Object) {
throw new PHPUnit_Framework_MockObject_RuntimeException(
'The current object can only be returned when mocking an ' .
'object, not a static class.'
);
}
return $invocation->object;
}
public function toString()
{
return 'return the current object';
}
}
<?php
class PHPUnit_Framework_MockObject_Stub_ReturnValueMap implements PHPUnit_Framework_MockObject_Stub
{
protected $valueMap;
public function __construct(array $valueMap)
{
$this->valueMap = $valueMap;
}
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation)
{
$parameterCount = count($invocation->parameters);
foreach ($this->valueMap as $map) {
if (!is_array($map) || $parameterCount != count($map) - 1) {
continue;
}
$return = array_pop($map);
if ($invocation->parameters === $map) {
return $return;
}
}
return;
}
public function toString()
{
return 'return value from a map';
}
}
<?php
interface PHPUnit_Framework_MockObject_Verifiable
{
public function verify();
}
<?php
class PHP_Timer
{
private static $times = array(
'hour' => 3600000,
'minute' => 60000,
'second' => 1000
);
private static $startTimes = array();
public static $requestTime;
public static function start()
{
array_push(self::$startTimes, microtime(true));
}
public static function stop()
{
return microtime(true) - array_pop(self::$startTimes);
}
public static function secondsToTimeString($time)
{
$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';
}
public static function timeSinceStartOfRequest()
{
return self::secondsToTimeString(microtime(true) - self::$requestTime);
}
public static function resourceUsage()
{
return sprintf(
'Time: %s, Memory: %4.2fMB',
self::timeSinceStartOfRequest(),
memory_get_peak_usage(true) / 1048576
);
}
}
if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME_FLOAT'];
} elseif (isset($_SERVER['REQUEST_TIME'])) {
PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME'];
} else {
PHP_Timer::$requestTime = microtime(true);
}
<?php
class File_Iterator_Facade
{
public function getFilesAsArray($paths, $suffixes = '', $prefixes = '', array $exclude = array(), $commonPath = FALSE)
{
if (is_string($paths)) {
$paths = array($paths);
}
$factory = new File_Iterator_Factory;
$iterator = $factory->getFileIterator(
$paths, $suffixes, $prefixes, $exclude
);
$files = array();
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 array(
'commonPath' => $this->getCommonPath($files),
'files' => $files
);
} else {
return $files;
}
}
protected function getCommonPath(array $files)
{
$count = count($files);
if ($count == 0) {
return '';
}
if ($count == 1) {
return dirname($files[0]) . DIRECTORY_SEPARATOR;
}
$_files = array();
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;
}
}
<?php
class File_Iterator_Factory
{
public function getFileIterator($paths, $suffixes = '', $prefixes = '', array $exclude = array())
{
if (is_string($paths)) {
$paths = array($paths);
}
$paths = $this->getPathsAfterResolvingWildcards($paths);
$exclude = $this->getPathsAfterResolvingWildcards($exclude);
if (is_string($prefixes)) {
if ($prefixes != '') {
$prefixes = array($prefixes);
} else {
$prefixes = array();
}
}
if (is_string($suffixes)) {
if ($suffixes != '') {
$suffixes = array($suffixes);
} else {
$suffixes = array();
}
}
$iterator = new AppendIterator;
foreach ($paths as $path) {
if (is_dir($path)) {
$iterator->append(
new File_Iterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::FOLLOW_SYMLINKS)
),
$suffixes,
$prefixes,
$exclude,
$path
)
);
}
}
return $iterator;
}
protected function getPathsAfterResolvingWildcards(array $paths)
{
$_paths = array();
foreach ($paths as $path) {
if ($locals = glob($path, GLOB_ONLYDIR)) {
$_paths = array_merge($_paths, $locals);
} else {
$_paths[] = $path;
}
}
return $_paths;
}
}
<?php
class File_Iterator extends FilterIterator
{
const PREFIX = 0;
const SUFFIX = 1;
protected $suffixes = array();
protected $prefixes = array();
protected $exclude = array();
protected $basepath;
public function __construct(Iterator $iterator, array $suffixes = array(), array $prefixes = array(), array $exclude = array(), $basepath = NULL)
{
$exclude = array_filter(array_map('realpath', $exclude));
if ($basepath !== NULL) {
$basepath = realpath($basepath);
}
if ($basepath === FALSE) {
$basepath = NULL;
} else {
foreach ($exclude as &$_exclude) {
$_exclude = str_replace($basepath, '', $_exclude);
}
}
$this->prefixes = $prefixes;
$this->suffixes = $suffixes;
$this->exclude = $exclude;
$this->basepath = $basepath;
parent::__construct($iterator);
}
public function accept()
{
$current = $this->getInnerIterator()->current();
$filename = $current->getFilename();
$realpath = $current->getRealPath();
if ($this->basepath !== NULL) {
$realpath = str_replace($this->basepath, '', $realpath);
}
if (preg_match('=/\.[^/]*/=', $realpath)) {
return FALSE;
}
return $this->acceptPath($realpath) &&
$this->acceptPrefix($filename) &&
$this->acceptSuffix($filename);
}
protected function acceptPath($path)
{
foreach ($this->exclude as $exclude) {
if (strpos($path, $exclude) === 0) {
return FALSE;
}
}
return TRUE;
}
protected function acceptPrefix($filename)
{
return $this->acceptSubString($filename, $this->prefixes, self::PREFIX);
}
protected function acceptSuffix($filename)
{
return $this->acceptSubString($filename, $this->suffixes, self::SUFFIX);
}
protected function acceptSubString($filename, array $subStrings, $type)
{
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
abstract class PHP_Token
{
protected $text;
protected $line;
protected $tokenStream;
protected $id;
public function __construct($text, $line, PHP_Token_Stream $tokenStream, $id)
{
$this->text = $text;
$this->line = $line;
$this->tokenStream = $tokenStream;
$this->id = $id;
}
public function __toString()
{
return $this->text;
}
public function getLine()
{
return $this->line;
}
}
abstract class PHP_TokenWithScope extends PHP_Token
{
protected $endTokenId;
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) {
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];
}
}
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_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;
}
public function getEndLine()
{
return $this->tokenStream[$this->getEndTokenId()]->getLine();
}
}
abstract class PHP_TokenWithScopeAndVisibility extends PHP_TokenWithScope
{
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_', '', get_class($tokens[$i]))
);
}
if (isset($tokens[$i]) &&
!($tokens[$i] instanceof PHP_Token_STATIC ||
$tokens[$i] instanceof PHP_Token_FINAL ||
$tokens[$i] instanceof PHP_Token_ABSTRACT)) {
break;
}
}
}
public function getKeywords()
{
$keywords = array();
$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_', '', get_class($tokens[$i]))
);
}
}
return implode(',', $keywords);
}
}
abstract class PHP_Token_Includes extends PHP_Token
{
protected $name;
protected $type;
public function getName()
{
if ($this->name === null) {
$this->process();
}
return $this->name;
}
public function getType()
{
if ($this->type === null) {
$this->process();
}
return $this->type;
}
private function process()
{
$tokens = $this->tokenStream->tokens();
if ($tokens[$this->id+2] instanceof PHP_Token_CONSTANT_ENCAPSED_STRING) {
$this->name = trim($tokens[$this->id+2], "'\"");
$this->type = strtolower(
str_replace('PHP_Token_', '', get_class($tokens[$this->id]))
);
}
}
}
class PHP_Token_FUNCTION extends PHP_TokenWithScopeAndVisibility
{
protected $arguments;
protected $ccn;
protected $name;
protected $signature;
public function getArguments()
{
if ($this->arguments !== null) {
return $this->arguments;
}
$this->arguments = array();
$tokens = $this->tokenStream->tokens();
$typeDeclaration = null;
$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;
}
public function getName()
{
if ($this->name !== null) {
return $this->name;
}
$tokens = $this->tokenStream->tokens();
for ($i = $this->id + 1; $i < count($tokens); $i++) {
if ($tokens[$i] instanceof PHP_Token_STRING) {
$this->name = (string)$tokens[$i];
break;
} elseif ($tokens[$i] instanceof PHP_Token_AMPERSAND &&
$tokens[$i+1] instanceof PHP_Token_STRING) {
$this->name = (string)$tokens[$i+1];
break;
} elseif ($tokens[$i] instanceof PHP_Token_OPEN_BRACKET) {
$this->name = 'anonymous function';
break;
}
}
if ($this->name != 'anonymous function') {
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;
}
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':
case 'PHP_Token_ELSEIF':
case 'PHP_Token_FOR':
case 'PHP_Token_FOREACH':
case 'PHP_Token_WHILE':
case 'PHP_Token_CASE':
case 'PHP_Token_CATCH':
case 'PHP_Token_BOOLEAN_AND':
case 'PHP_Token_LOGICAL_AND':
case 'PHP_Token_BOOLEAN_OR':
case 'PHP_Token_LOGICAL_OR':
case 'PHP_Token_QUESTION_MARK':
$this->ccn++;
break;
}
}
return $this->ccn;
}
public function getSignature()
{
if ($this->signature !== null) {
return $this->signature;
}
if ($this->getName() == 'anonymous function') {
$this->signature = 'anonymous function';
$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;
}
}
class PHP_Token_INTERFACE extends PHP_TokenWithScopeAndVisibility
{
protected $interfaces;
public function getName()
{
return (string)$this->tokenStream[$this->id + 2];
}
public function hasParent()
{
return $this->tokenStream[$this->id + 4] instanceof PHP_Token_EXTENDS;
}
public function getPackage()
{
$className = $this->getName();
$docComment = $this->getDocblock();
$result = array(
'namespace' => '',
'fullPackage' => '',
'category' => '',
'package' => '',
'subpackage' => ''
);
for ($i = $this->id; $i; --$i) {
if ($this->tokenStream[$i] instanceof PHP_Token_NAMESPACE) {
$result['namespace'] = $this->tokenStream[$i]->getName();
break;
}
}
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;
}
protected function arrayToName(array $parts, $join = '\\')
{
$result = '';
if (count($parts) > 1) {
array_pop($parts);
$result = join($join, $parts);
}
return $result;
}
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;
}
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);
}
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;
}
}
class PHP_Token_ABSTRACT extends PHP_Token {}
class PHP_Token_AMPERSAND extends PHP_Token {}
class PHP_Token_AND_EQUAL extends PHP_Token {}
class PHP_Token_ARRAY extends PHP_Token {}
class PHP_Token_ARRAY_CAST extends PHP_Token {}
class PHP_Token_AS extends PHP_Token {}
class PHP_Token_AT extends PHP_Token {}
class PHP_Token_BACKTICK extends PHP_Token {}
class PHP_Token_BAD_CHARACTER extends PHP_Token {}
class PHP_Token_BOOLEAN_AND extends PHP_Token {}
class PHP_Token_BOOLEAN_OR extends PHP_Token {}
class PHP_Token_BOOL_CAST extends PHP_Token {}
class PHP_Token_BREAK extends PHP_Token {}
class PHP_Token_CARET extends PHP_Token {}
class PHP_Token_CASE extends PHP_Token {}
class PHP_Token_CATCH extends PHP_Token {}
class PHP_Token_CHARACTER extends PHP_Token {}
class PHP_Token_CLASS extends PHP_Token_INTERFACE
{
public function getName()
{
$next = $this->tokenStream[$this->id + 1];
if ($next instanceof PHP_Token_WHITESPACE) {
$next = $this->tokenStream[$this->id + 2];
}
if ($next instanceof PHP_Token_STRING) {
return (string) $next;
}
if ($next instanceof PHP_Token_OPEN_CURLY ||
$next instanceof PHP_Token_EXTENDS ||
$next instanceof PHP_Token_IMPLEMENTS) {
return 'anonymous class';
}
}
}
class PHP_Token_CLASS_C extends PHP_Token {}
class PHP_Token_CLASS_NAME_CONSTANT extends PHP_Token {}
class PHP_Token_CLONE extends PHP_Token {}
class PHP_Token_CLOSE_BRACKET extends PHP_Token {}
class PHP_Token_CLOSE_CURLY extends PHP_Token {}
class PHP_Token_CLOSE_SQUARE extends PHP_Token {}
class PHP_Token_CLOSE_TAG extends PHP_Token {}
class PHP_Token_COLON extends PHP_Token {}
class PHP_Token_COMMA extends PHP_Token {}
class PHP_Token_COMMENT extends PHP_Token {}
class PHP_Token_CONCAT_EQUAL extends PHP_Token {}
class PHP_Token_CONST extends PHP_Token {}
class PHP_Token_CONSTANT_ENCAPSED_STRING extends PHP_Token {}
class PHP_Token_CONTINUE extends PHP_Token {}
class PHP_Token_CURLY_OPEN extends PHP_Token {}
class PHP_Token_DEC extends PHP_Token {}
class PHP_Token_DECLARE extends PHP_Token {}
class PHP_Token_DEFAULT extends PHP_Token {}
class PHP_Token_DIV extends PHP_Token {}
class PHP_Token_DIV_EQUAL extends PHP_Token {}
class PHP_Token_DNUMBER extends PHP_Token {}
class PHP_Token_DO extends PHP_Token {}
class PHP_Token_DOC_COMMENT extends PHP_Token {}
class PHP_Token_DOLLAR extends PHP_Token {}
class PHP_Token_DOLLAR_OPEN_CURLY_BRACES extends PHP_Token {}
class PHP_Token_DOT extends PHP_Token {}
class PHP_Token_DOUBLE_ARROW extends PHP_Token {}
class PHP_Token_DOUBLE_CAST extends PHP_Token {}
class PHP_Token_DOUBLE_COLON extends PHP_Token {}
class PHP_Token_DOUBLE_QUOTES extends PHP_Token {}
class PHP_Token_ECHO extends PHP_Token {}
class PHP_Token_ELSE extends PHP_Token {}
class PHP_Token_ELSEIF extends PHP_Token {}
class PHP_Token_EMPTY extends PHP_Token {}
class PHP_Token_ENCAPSED_AND_WHITESPACE extends PHP_Token {}
class PHP_Token_ENDDECLARE extends PHP_Token {}
class PHP_Token_ENDFOR extends PHP_Token {}
class PHP_Token_ENDFOREACH extends PHP_Token {}
class PHP_Token_ENDIF extends PHP_Token {}
class PHP_Token_ENDSWITCH extends PHP_Token {}
class PHP_Token_ENDWHILE extends PHP_Token {}
class PHP_Token_END_HEREDOC extends PHP_Token {}
class PHP_Token_EQUAL extends PHP_Token {}
class PHP_Token_EVAL extends PHP_Token {}
class PHP_Token_EXCLAMATION_MARK extends PHP_Token {}
class PHP_Token_EXIT extends PHP_Token {}
class PHP_Token_EXTENDS extends PHP_Token {}
class PHP_Token_FILE extends PHP_Token {}
class PHP_Token_FINAL extends PHP_Token {}
class PHP_Token_FOR extends PHP_Token {}
class PHP_Token_FOREACH extends PHP_Token {}
class PHP_Token_FUNC_C extends PHP_Token {}
class PHP_Token_GLOBAL extends PHP_Token {}
class PHP_Token_GT extends PHP_Token {}
class PHP_Token_IF extends PHP_Token {}
class PHP_Token_IMPLEMENTS extends PHP_Token {}
class PHP_Token_INC extends PHP_Token {}
class PHP_Token_INCLUDE extends PHP_Token_Includes {}
class PHP_Token_INCLUDE_ONCE extends PHP_Token_Includes {}
class PHP_Token_INLINE_HTML extends PHP_Token {}
class PHP_Token_INSTANCEOF extends PHP_Token {}
class PHP_Token_INT_CAST extends PHP_Token {}
class PHP_Token_ISSET extends PHP_Token {}
class PHP_Token_IS_EQUAL extends PHP_Token {}
class PHP_Token_IS_GREATER_OR_EQUAL extends PHP_Token {}
class PHP_Token_IS_IDENTICAL extends PHP_Token {}
class PHP_Token_IS_NOT_EQUAL extends PHP_Token {}
class PHP_Token_IS_NOT_IDENTICAL extends PHP_Token {}
class PHP_Token_IS_SMALLER_OR_EQUAL extends PHP_Token {}
class PHP_Token_LINE extends PHP_Token {}
class PHP_Token_LIST extends PHP_Token {}
class PHP_Token_LNUMBER extends PHP_Token {}
class PHP_Token_LOGICAL_AND extends PHP_Token {}
class PHP_Token_LOGICAL_OR extends PHP_Token {}
class PHP_Token_LOGICAL_XOR extends PHP_Token {}
class PHP_Token_LT extends PHP_Token {}
class PHP_Token_METHOD_C extends PHP_Token {}
class PHP_Token_MINUS extends PHP_Token {}
class PHP_Token_MINUS_EQUAL extends PHP_Token {}
class PHP_Token_MOD_EQUAL extends PHP_Token {}
class PHP_Token_MULT extends PHP_Token {}
class PHP_Token_MUL_EQUAL extends PHP_Token {}
class PHP_Token_NEW extends PHP_Token {}
class PHP_Token_NUM_STRING extends PHP_Token {}
class PHP_Token_OBJECT_CAST extends PHP_Token {}
class PHP_Token_OBJECT_OPERATOR extends PHP_Token {}
class PHP_Token_OPEN_BRACKET extends PHP_Token {}
class PHP_Token_OPEN_CURLY extends PHP_Token {}
class PHP_Token_OPEN_SQUARE extends PHP_Token {}
class PHP_Token_OPEN_TAG extends PHP_Token {}
class PHP_Token_OPEN_TAG_WITH_ECHO extends PHP_Token {}
class PHP_Token_OR_EQUAL extends PHP_Token {}
class PHP_Token_PAAMAYIM_NEKUDOTAYIM extends PHP_Token {}
class PHP_Token_PERCENT extends PHP_Token {}
class PHP_Token_PIPE extends PHP_Token {}
class PHP_Token_PLUS extends PHP_Token {}
class PHP_Token_PLUS_EQUAL extends PHP_Token {}
class PHP_Token_PRINT extends PHP_Token {}
class PHP_Token_PRIVATE extends PHP_Token {}
class PHP_Token_PROTECTED extends PHP_Token {}
class PHP_Token_PUBLIC extends PHP_Token {}
class PHP_Token_QUESTION_MARK extends PHP_Token {}
class PHP_Token_REQUIRE extends PHP_Token_Includes {}
class PHP_Token_REQUIRE_ONCE extends PHP_Token_Includes {}
class PHP_Token_RETURN extends PHP_Token {}
class PHP_Token_SEMICOLON extends PHP_Token {}
class PHP_Token_SL extends PHP_Token {}
class PHP_Token_SL_EQUAL extends PHP_Token {}
class PHP_Token_SR extends PHP_Token {}
class PHP_Token_SR_EQUAL extends PHP_Token {}
class PHP_Token_START_HEREDOC extends PHP_Token {}
class PHP_Token_STATIC extends PHP_Token {}
class PHP_Token_STRING extends PHP_Token {}
class PHP_Token_STRING_CAST extends PHP_Token {}
class PHP_Token_STRING_VARNAME extends PHP_Token {}
class PHP_Token_SWITCH extends PHP_Token {}
class PHP_Token_THROW extends PHP_Token {}
class PHP_Token_TILDE extends PHP_Token {}
class PHP_Token_TRY extends PHP_Token {}
class PHP_Token_UNSET extends PHP_Token {}
class PHP_Token_UNSET_CAST extends PHP_Token {}
class PHP_Token_USE extends PHP_Token {}
class PHP_Token_VAR extends PHP_Token {}
class PHP_Token_VARIABLE extends PHP_Token {}
class PHP_Token_WHILE extends PHP_Token {}
class PHP_Token_WHITESPACE extends PHP_Token {}
class PHP_Token_XOR_EQUAL extends PHP_Token {}
class PHP_Token_HALT_COMPILER extends PHP_Token {}
class PHP_Token_DIR extends PHP_Token {}
class PHP_Token_GOTO extends PHP_Token {}
class PHP_Token_NAMESPACE extends PHP_TokenWithScope
{
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;
}
}
class PHP_Token_NS_C extends PHP_Token {}
class PHP_Token_NS_SEPARATOR extends PHP_Token {}
class PHP_Token_CALLABLE extends PHP_Token {}
class PHP_Token_INSTEADOF extends PHP_Token {}
class PHP_Token_TRAIT extends PHP_Token_INTERFACE {}
class PHP_Token_TRAIT_C extends PHP_Token {}
class PHP_Token_FINALLY extends PHP_Token {}
class PHP_Token_YIELD extends PHP_Token {}
class PHP_Token_ELLIPSIS extends PHP_Token {}
class PHP_Token_POW extends PHP_Token {}
class PHP_Token_POW_EQUAL extends PHP_Token {}
class PHP_Token_COALESCE extends PHP_Token {}
class PHP_Token_SPACESHIP extends PHP_Token {}
class PHP_Token_YIELD_FROM extends PHP_Token {}
class PHP_Token_ASYNC extends PHP_Token {}
class PHP_Token_AWAIT extends PHP_Token {}
class PHP_Token_COMPILER_HALT_OFFSET extends PHP_Token {}
class PHP_Token_ENUM extends PHP_Token {}
class PHP_Token_EQUALS extends PHP_Token {}
class PHP_Token_IN extends PHP_Token {}
class PHP_Token_JOIN extends PHP_Token {}
class PHP_Token_LAMBDA_ARROW extends PHP_Token {}
class PHP_Token_LAMBDA_CP extends PHP_Token {}
class PHP_Token_LAMBDA_OP extends PHP_Token {}
class PHP_Token_ONUMBER extends PHP_Token {}
class PHP_Token_SHAPE extends PHP_Token {}
class PHP_Token_TYPE extends PHP_Token {}
class PHP_Token_TYPELIST_GT extends PHP_Token {}
class PHP_Token_TYPELIST_LT extends PHP_Token {}
class PHP_Token_WHERE extends PHP_Token {}
class PHP_Token_XHP_ATTRIBUTE extends PHP_Token {}
class PHP_Token_XHP_CATEGORY extends PHP_Token {}
class PHP_Token_XHP_CATEGORY_LABEL extends PHP_Token {}
class PHP_Token_XHP_CHILDREN extends PHP_Token {}
class PHP_Token_XHP_LABEL extends PHP_Token {}
class PHP_Token_XHP_REQUIRED extends PHP_Token {}
class PHP_Token_XHP_TAG_GT extends PHP_Token {}
class PHP_Token_XHP_TAG_LT extends PHP_Token {}
class PHP_Token_XHP_TEXT extends PHP_Token {}
<?php
class PHP_Token_Stream implements ArrayAccess, Countable, SeekableIterator
{
protected static $customTokens = array(
'(' => 'PHP_Token_OPEN_BRACKET',
')' => 'PHP_Token_CLOSE_BRACKET',
'[' => 'PHP_Token_OPEN_SQUARE',
']' => 'PHP_Token_CLOSE_SQUARE',
'{' => 'PHP_Token_OPEN_CURLY',
'}' => 'PHP_Token_CLOSE_CURLY',
';' => 'PHP_Token_SEMICOLON',
'.' => 'PHP_Token_DOT',
',' => 'PHP_Token_COMMA',
'=' => 'PHP_Token_EQUAL',
'<' => 'PHP_Token_LT',
'>' => 'PHP_Token_GT',
'+' => 'PHP_Token_PLUS',
'-' => 'PHP_Token_MINUS',
'*' => 'PHP_Token_MULT',
'/' => 'PHP_Token_DIV',
'?' => 'PHP_Token_QUESTION_MARK',
'!' => 'PHP_Token_EXCLAMATION_MARK',
':' => 'PHP_Token_COLON',
'"' => 'PHP_Token_DOUBLE_QUOTES',
'@' => 'PHP_Token_AT',
'&' => 'PHP_Token_AMPERSAND',
'%' => 'PHP_Token_PERCENT',
'|' => 'PHP_Token_PIPE',
'$' => 'PHP_Token_DOLLAR',
'^' => 'PHP_Token_CARET',
'~' => 'PHP_Token_TILDE',
'`' => 'PHP_Token_BACKTICK'
);
protected $filename;
protected $tokens = array();
protected $position = 0;
protected $linesOfCode = array('loc' => 0, 'cloc' => 0, 'ncloc' => 0);
protected $classes;
protected $functions;
protected $includes;
protected $interfaces;
protected $traits;
protected $lineToFunctionMap = array();
public function __construct($sourceCode)
{
if (is_file($sourceCode)) {
$this->filename = $sourceCode;
$sourceCode = file_get_contents($sourceCode);
}
$this->scan($sourceCode);
}
public function __destruct()
{
$this->tokens = array();
}
public function __toString()
{
$buffer = '';
foreach ($this as $token) {
$buffer .= $token;
}
return $buffer;
}
public function getFilename()
{
return $this->filename;
}
protected function scan($sourceCode)
{
$line = 1;
$tokens = token_get_all($sourceCode);
$numTokens = count($tokens);
$lastNonWhitespaceTokenWasDoubleColon = false;
for ($i = 0; $i < $numTokens; ++$i) {
$token = $tokens[$i];
unset($tokens[$i]);
if (is_array($token)) {
$name = substr(token_name($token[0]), 2);
$text = $token[1];
if ($lastNonWhitespaceTokenWasDoubleColon && $name == 'CLASS') {
$name = 'CLASS_NAME_CONSTANT';
}
$tokenClass = 'PHP_Token_' . $name;
} else {
$text = $token;
$tokenClass = self::$customTokens[$token];
}
$this->tokens[] = new $tokenClass($text, $line, $this, $i);
$lines = substr_count($text, "\n");
$line += $lines;
if ($tokenClass == 'PHP_Token_HALT_COMPILER') {
break;
} elseif ($tokenClass == 'PHP_Token_COMMENT' ||
$tokenClass == 'PHP_Token_DOC_COMMENT') {
$this->linesOfCode['cloc'] += $lines + 1;
}
if ($name == 'DOUBLE_COLON') {
$lastNonWhitespaceTokenWasDoubleColon = true;
} elseif ($name != 'WHITESPACE') {
$lastNonWhitespaceTokenWasDoubleColon = false;
}
}
$this->linesOfCode['loc'] = substr_count($sourceCode, "\n");
$this->linesOfCode['ncloc'] = $this->linesOfCode['loc'] -
$this->linesOfCode['cloc'];
}
public function count()
{
return count($this->tokens);
}
public function tokens()
{
return $this->tokens;
}
public function getClasses()
{
if ($this->classes !== null) {
return $this->classes;
}
$this->parse();
return $this->classes;
}
public function getFunctions()
{
if ($this->functions !== null) {
return $this->functions;
}
$this->parse();
return $this->functions;
}
public function getInterfaces()
{
if ($this->interfaces !== null) {
return $this->interfaces;
}
$this->parse();
return $this->interfaces;
}
public function getTraits()
{
if ($this->traits !== null) {
return $this->traits;
}
$this->parse();
return $this->traits;
}
public function getIncludes($categorize = false, $category = null)
{
if ($this->includes === null) {
$this->includes = array(
'require_once' => array(),
'require' => array(),
'include_once' => array(),
'include' => array()
);
foreach ($this->tokens as $token) {
switch (get_class($token)) {
case 'PHP_Token_REQUIRE_ONCE':
case 'PHP_Token_REQUIRE':
case 'PHP_Token_INCLUDE_ONCE':
case 'PHP_Token_INCLUDE':
$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;
}
public function getFunctionForLine($line)
{
$this->parse();
if (isset($this->lineToFunctionMap[$line])) {
return $this->lineToFunctionMap[$line];
}
}
protected function parse()
{
$this->interfaces = array();
$this->classes = array();
$this->traits = array();
$this->functions = array();
$class = array();
$classEndLine = array();
$trait = false;
$traitEndLine = false;
$interface = false;
$interfaceEndLine = false;
foreach ($this->tokens as $token) {
switch (get_class($token)) {
case 'PHP_Token_HALT_COMPILER':
return;
case 'PHP_Token_INTERFACE':
$interface = $token->getName();
$interfaceEndLine = $token->getEndLine();
$this->interfaces[$interface] = array(
'methods' => array(),
'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':
case 'PHP_Token_TRAIT':
$tmp = array(
'methods' => array(),
'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 ($class[count($class)-1] != 'anonymous class') {
$this->classes[$class[count($class)-1]] = $tmp;
}
} else {
$trait = $token->getName();
$traitEndLine = $token->getEndLine();
$this->traits[$trait] = $tmp;
}
break;
case 'PHP_Token_FUNCTION':
$name = $token->getName();
$tmp = array(
'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) && $class[count($class)-1] != 'anonymous class') {
$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':
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;
}
}
}
public function getLinesOfCode()
{
return $this->linesOfCode;
}
public function rewind()
{
$this->position = 0;
}
public function valid()
{
return isset($this->tokens[$this->position]);
}
public function key()
{
return $this->position;
}
public function current()
{
return $this->tokens[$this->position];
}
public function next()
{
$this->position++;
}
public function offsetExists($offset)
{
return isset($this->tokens[$offset]);
}
public function offsetGet($offset)
{
if (!$this->offsetExists($offset)) {
throw new OutOfBoundsException(
sprintf(
'No token at position "%s"',
$offset
)
);
}
return $this->tokens[$offset];
}
public function offsetSet($offset, $value)
{
$this->tokens[$offset] = $value;
}
public function offsetUnset($offset)
{
if (!$this->offsetExists($offset)) {
throw new OutOfBoundsException(
sprintf(
'No token at position "%s"',
$offset
)
);
}
unset($this->tokens[$offset]);
}
public function seek($position)
{
$this->position = $position;
if (!$this->valid()) {
throw new OutOfBoundsException(
sprintf(
'No token at position "%s"',
$this->position
)
);
}
}
private function addFunctionToMap($name, $startLine, $endLine)
{
for ($line = $startLine; $line <= $endLine; $line++) {
$this->lineToFunctionMap[$line] = $name;
}
}
}
<?php
class PHP_Token_Stream_CachingFactory
{
protected static $cache = array();
public static function get($filename)
{
if (!isset(self::$cache[$filename])) {
self::$cache[$filename] = new PHP_Token_Stream($filename);
}
return self::$cache[$filename];
}
public static function clear($filename = null)
{
if (is_string($filename)) {
unset(self::$cache[$filename]);
} else {
self::$cache = array();
}
}
}
<?php
namespace SebastianBergmann\CodeCoverage;
use SebastianBergmann\CodeCoverage\Driver\Driver;
use SebastianBergmann\CodeCoverage\Driver\Xdebug;
use SebastianBergmann\CodeCoverage\Driver\HHVM;
use SebastianBergmann\CodeCoverage\Driver\PHPDBG;
use SebastianBergmann\CodeCoverage\Node\Builder;
use SebastianBergmann\CodeCoverage\Node\Directory;
use SebastianBergmann\CodeUnitReverseLookup\Wizard;
use SebastianBergmann\Environment\Runtime;
class CodeCoverage
{
private $driver;
private $filter;
private $wizard;
private $cacheTokens = false;
private $checkForUnintentionallyCoveredCode = false;
private $forceCoversAnnotation = false;
private $checkForUnexecutedCoveredCode = false;
private $checkForMissingCoversAnnotation = false;
private $addUncoveredFilesFromWhitelist = true;
private $processUncoveredFilesFromWhitelist = false;
private $ignoreDeprecatedCode = false;
private $currentId;
private $data = [];
private $ignoredLines = [];
private $disableIgnoredLines = false;
private $tests = [];
private $unintentionallyCoveredSubclassesWhitelist = [];
private $isInitialized = false;
private $shouldCheckForDeadAndUnused = true;
public function __construct(Driver $driver = null, Filter $filter = null)
{
if ($driver === null) {
$driver = $this->selectDriver();
}
if ($filter === null) {
$filter = new Filter;
}
$this->driver = $driver;
$this->filter = $filter;
$this->wizard = new Wizard;
}
public function getReport()
{
$builder = new Builder;
return $builder->build($this);
}
public function clear()
{
$this->isInitialized = false;
$this->currentId = null;
$this->data = [];
$this->tests = [];
}
public function filter()
{
return $this->filter;
}
public function getData($raw = false)
{
if (!$raw && $this->addUncoveredFilesFromWhitelist) {
$this->addUncoveredFilesFromWhitelist();
}
return $this->data;
}
public function setData(array $data)
{
$this->data = $data;
}
public function getTests()
{
return $this->tests;
}
public function setTests(array $tests)
{
$this->tests = $tests;
}
public function start($id, $clear = false)
{
if (!is_bool($clear)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
if ($clear) {
$this->clear();
}
if ($this->isInitialized === false) {
$this->initializeData();
}
$this->currentId = $id;
$this->driver->start($this->shouldCheckForDeadAndUnused);
}
public function stop($append = true, $linesToBeCovered = [], array $linesToBeUsed = [])
{
if (!is_bool($append)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
if (!is_array($linesToBeCovered) && $linesToBeCovered !== false) {
throw InvalidArgumentException::create(
2,
'array or false'
);
}
$data = $this->driver->stop();
$this->append($data, null, $append, $linesToBeCovered, $linesToBeUsed);
$this->currentId = null;
return $data;
}
public function append(array $data, $id = null, $append = true, $linesToBeCovered = [], array $linesToBeUsed = [])
{
if ($id === null) {
$id = $this->currentId;
}
if ($id === null) {
throw new RuntimeException;
}
$this->applyListsFilter($data);
$this->applyIgnoredLinesFilter($data);
$this->initializeFilesThatAreSeenTheFirstTime($data);
if (!$append) {
return;
}
if ($id != 'UNCOVERED_FILES_FROM_WHITELIST') {
$this->applyCoversAnnotationFilter(
$data,
$linesToBeCovered,
$linesToBeUsed
);
}
if (empty($data)) {
return;
}
$size = 'unknown';
$status = null;
if ($id instanceof \PHPUnit_Framework_TestCase) {
$_size = $id->getSize();
if ($_size == \PHPUnit_Util_Test::SMALL) {
$size = 'small';
} elseif ($_size == \PHPUnit_Util_Test::MEDIUM) {
$size = 'medium';
} elseif ($_size == \PHPUnit_Util_Test::LARGE) {
$size = 'large';
}
$status = $id->getStatus();
$id = get_class($id) . '::' . $id->getName();
} elseif ($id instanceof \PHPUnit_Extensions_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;
}
}
}
}
}
public function merge(CodeCoverage $that)
{
$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;
}
foreach ($lines as $line => $data) {
if ($data !== null) {
if (!isset($this->data[$file][$line])) {
$this->data[$file][$line] = $data;
} else {
$this->data[$file][$line] = array_unique(
array_merge($this->data[$file][$line], $data)
);
}
}
}
}
$this->tests = array_merge($this->tests, $that->getTests());
}
public function setCacheTokens($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->cacheTokens = $flag;
}
public function getCacheTokens()
{
return $this->cacheTokens;
}
public function setCheckForUnintentionallyCoveredCode($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->checkForUnintentionallyCoveredCode = $flag;
}
public function setForceCoversAnnotation($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->forceCoversAnnotation = $flag;
}
public function setCheckForMissingCoversAnnotation($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->checkForMissingCoversAnnotation = $flag;
}
public function setCheckForUnexecutedCoveredCode($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->checkForUnexecutedCoveredCode = $flag;
}
public function setMapTestClassNameToCoveredClassName($flag)
{
}
public function setAddUncoveredFilesFromWhitelist($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->addUncoveredFilesFromWhitelist = $flag;
}
public function setProcessUncoveredFilesFromWhitelist($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->processUncoveredFilesFromWhitelist = $flag;
}
public function setDisableIgnoredLines($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->disableIgnoredLines = $flag;
}
public function setIgnoreDeprecatedCode($flag)
{
if (!is_bool($flag)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
$this->ignoreDeprecatedCode = $flag;
}
public function setUnintentionallyCoveredSubclassesWhitelist(array $whitelist)
{
$this->unintentionallyCoveredSubclassesWhitelist = $whitelist;
}
private function applyCoversAnnotationFilter(array &$data, $linesToBeCovered, array $linesToBeUsed)
{
if ($linesToBeCovered === false ||
($this->forceCoversAnnotation && empty($linesToBeCovered))) {
if ($this->checkForMissingCoversAnnotation) {
throw new MissingCoversAnnotationException;
}
$data = [];
return;
}
if (empty($linesToBeCovered)) {
return;
}
if ($this->checkForUnintentionallyCoveredCode) {
$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 applyListsFilter(array &$data)
{
foreach (array_keys($data) as $filename) {
if ($this->filter->isFiltered($filename)) {
unset($data[$filename]);
}
}
}
private function applyIgnoredLinesFilter(array &$data)
{
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)
{
foreach ($data as $file => $lines) {
if ($this->filter->isFile($file) && !isset($this->data[$file])) {
$this->data[$file] = [];
foreach ($lines as $k => $v) {
$this->data[$file][$k] = $v == -2 ? null : [];
}
}
}
}
private function addUncoveredFilesFromWhitelist()
{
$data = [];
$uncoveredFiles = array_diff(
$this->filter->getWhitelist(),
array_keys($this->data)
);
foreach ($uncoveredFiles as $uncoveredFile) {
if (!file_exists($uncoveredFile)) {
continue;
}
if (!$this->processUncoveredFilesFromWhitelist) {
$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($filename)
{
if (!is_string($filename)) {
throw InvalidArgumentException::create(
1,
'string'
);
}
if (!isset($this->ignoredLines[$filename])) {
$this->ignoredLines[$filename] = [];
if ($this->disableIgnoredLines) {
return $this->ignoredLines[$filename];
}
$ignore = false;
$stop = false;
$lines = file($filename);
$numLines = count($lines);
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);
}
$classes = array_merge($tokens->getClasses(), $tokens->getTraits());
$tokens = $tokens->tokens();
foreach ($tokens as $token) {
switch (get_class($token)) {
case 'PHP_Token_COMMENT':
case 'PHP_Token_DOC_COMMENT':
$_token = trim($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($token, "\n");
if (0 !== strpos($_token, $_line)) {
$start++;
}
for ($i = $start; $i < $end; $i++) {
$this->ignoredLines[$filename][] = $i;
}
if (isset($lines[$i-1]) && 0 === strpos($_token, '/*') && '*/' === substr(trim($lines[$i-1]), -2)) {
$this->ignoredLines[$filename][] = $i;
}
}
break;
case 'PHP_Token_INTERFACE':
case 'PHP_Token_TRAIT':
case 'PHP_Token_CLASS':
case 'PHP_Token_FUNCTION':
$docblock = $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;
}
} elseif ($token instanceof \PHP_Token_INTERFACE ||
$token instanceof \PHP_Token_TRAIT ||
$token instanceof \PHP_Token_CLASS) {
if (empty($classes[$token->getName()]['methods'])) {
for ($i = $token->getLine();
$i <= $token->getEndLine();
$i++) {
$this->ignoredLines[$filename][] = $i;
}
} else {
$firstMethod = array_shift(
$classes[$token->getName()]['methods']
);
do {
$lastMethod = array_pop(
$classes[$token->getName()]['methods']
);
} while ($lastMethod !== null &&
substr($lastMethod['signature'], 0, 18) == 'anonymous function');
if ($lastMethod === null) {
$lastMethod = $firstMethod;
}
for ($i = $token->getLine();
$i < $firstMethod['startLine'];
$i++) {
$this->ignoredLines[$filename][] = $i;
}
for ($i = $token->getEndLine();
$i > $lastMethod['endLine'];
$i--) {
$this->ignoredLines[$filename][] = $i;
}
}
}
break;
case 'PHP_Token_NAMESPACE':
$this->ignoredLines[$filename][] = $token->getEndLine();
case 'PHP_Token_DECLARE':
case 'PHP_Token_OPEN_TAG':
case 'PHP_Token_CLOSE_TAG':
case 'PHP_Token_USE':
$this->ignoredLines[$filename][] = $token->getLine();
break;
}
if ($ignore) {
$this->ignoredLines[$filename][] = $token->getLine();
if ($stop) {
$ignore = false;
$stop = false;
}
}
}
$this->ignoredLines[$filename][] = $numLines + 1;
$this->ignoredLines[$filename] = array_unique(
$this->ignoredLines[$filename]
);
sort($this->ignoredLines[$filename]);
}
return $this->ignoredLines[$filename];
}
private function performUnintentionallyCoveredCodeCheck(array &$data, array $linesToBeCovered, array $linesToBeUsed)
{
$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
);
}
}
private function performUnexecutedCoveredCodeCheck(array &$data, array $linesToBeCovered, array $linesToBeUsed)
{
$expectedLines = $this->getAllowedLines(
$linesToBeCovered,
$linesToBeUsed
);
foreach ($data as $file => $_data) {
foreach (array_keys($_data) as $line) {
if (!isset($expectedLines[$file][$line])) {
continue;
}
unset($expectedLines[$file][$line]);
}
}
$message = '';
foreach ($expectedLines as $file => $lines) {
if (empty($lines)) {
continue;
}
foreach (array_keys($lines) as $line) {
$message .= sprintf('- %s:%d' . PHP_EOL, $file, $line);
}
}
if (!empty($message)) {
throw new CoveredCodeNotExecutedException($message);
}
}
private function getAllowedLines(array $linesToBeCovered, array $linesToBeUsed)
{
$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;
}
private function selectDriver()
{
$runtime = new Runtime;
if (!$runtime->canCollectCodeCoverage()) {
throw new RuntimeException('No code coverage driver available');
}
if ($runtime->isHHVM()) {
return new HHVM;
} elseif ($runtime->isPHPDBG()) {
return new PHPDBG;
} else {
return new Xdebug;
}
}
private function processUnintentionallyCoveredUnits(array $unintentionallyCoveredUnits)
{
$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);
}
protected function initializeData()
{
$this->isInitialized = true;
if ($this->processUncoveredFilesFromWhitelist) {
$this->shouldCheckForDeadAndUnused = false;
$this->driver->start(true);
foreach ($this->filter->getWhitelist() as $file) {
if ($this->filter->isFile($file)) {
include_once($file);
}
}
$data = [];
$coverage = $this->driver->stop();
foreach ($coverage 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');
}
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Driver;
interface Driver
{
const LINE_EXECUTED = 1;
const LINE_NOT_EXECUTED = -1;
const LINE_NOT_EXECUTABLE = -2;
public function start($determineUnusedAndDead = true);
public function stop();
}
<?php
namespace SebastianBergmann\CodeCoverage\Driver;
class HHVM extends Xdebug
{
public function start($determineUnusedAndDead = true)
{
xdebug_start_code_coverage();
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Driver;
use SebastianBergmann\CodeCoverage\RuntimeException;
class PHPDBG implements Driver
{
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'
);
}
}
public function start($determineUnusedAndDead = true)
{
phpdbg_start_oplog();
}
public function stop()
{
static $fetchedLines = [];
$dbgData = phpdbg_end_oplog();
if ($fetchedLines == []) {
$sourceLines = phpdbg_get_executable();
} else {
$newFiles = array_diff(
get_included_files(),
array_keys($fetchedLines)
);
if ($newFiles) {
$sourceLines = phpdbg_get_executable(
['files' => $newFiles]
);
} else {
$sourceLines = [];
}
}
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);
}
private function detectExecutedLines(array $sourceLines, array $dbgData)
{
foreach ($dbgData as $file => $coveredLines) {
foreach ($coveredLines as $lineNo => $numExecuted) {
if (isset($sourceLines[$file][$lineNo])) {
$sourceLines[$file][$lineNo] = self::LINE_EXECUTED;
}
}
}
return $sourceLines;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Driver;
use SebastianBergmann\CodeCoverage\RuntimeException;
class Xdebug implements Driver
{
private $cacheNumLines = [];
public function __construct()
{
if (!extension_loaded('xdebug')) {
throw new RuntimeException('This driver requires Xdebug');
}
if (version_compare(phpversion('xdebug'), '2.2.1', '>=') &&
!ini_get('xdebug.coverage_enable')) {
throw new RuntimeException(
'xdebug.coverage_enable=On has to be set in php.ini'
);
}
}
public function start($determineUnusedAndDead = true)
{
if ($determineUnusedAndDead) {
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
} else {
xdebug_start_code_coverage();
}
}
public function stop()
{
$data = xdebug_get_code_coverage();
xdebug_stop_code_coverage();
return $this->cleanup($data);
}
private function cleanup(array $data)
{
foreach (array_keys($data) as $file) {
unset($data[$file][0]);
if (strpos($file, 'xdebug://debug-eval') !== 0 && file_exists($file)) {
$numLines = $this->getNumberOfLinesInFile($file);
foreach (array_keys($data[$file]) as $line) {
if ($line > $numLines) {
unset($data[$file][$line]);
}
}
}
}
return $data;
}
private function getNumberOfLinesInFile($file)
{
if (!isset($this->cacheNumLines[$file])) {
$buffer = file_get_contents($file);
$lines = substr_count($buffer, "\n");
if (substr($buffer, -1) !== "\n") {
$lines++;
}
$this->cacheNumLines[$file] = $lines;
}
return $this->cacheNumLines[$file];
}
}
<?php
namespace SebastianBergmann\CodeCoverage;
class CoveredCodeNotExecutedException extends RuntimeException
{
}
<?php
namespace SebastianBergmann\CodeCoverage;
interface Exception
{
}
<?php
namespace SebastianBergmann\CodeCoverage;
class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
public static function create($argument, $type, $value = null)
{
$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
namespace SebastianBergmann\CodeCoverage;
class MissingCoversAnnotationException extends RuntimeException
{
}
<?php
namespace SebastianBergmann\CodeCoverage;
class RuntimeException extends \RuntimeException implements Exception
{
}
<?php
namespace SebastianBergmann\CodeCoverage;
class UnintentionallyCoveredCodeException extends RuntimeException
{
private $unintentionallyCoveredUnits = [];
public function __construct(array $unintentionallyCoveredUnits)
{
$this->unintentionallyCoveredUnits = $unintentionallyCoveredUnits;
parent::__construct($this->toString());
}
public function getUnintentionallyCoveredUnits()
{
return $this->unintentionallyCoveredUnits;
}
private function toString()
{
$message = '';
foreach ($this->unintentionallyCoveredUnits as $unit) {
$message .= '- ' . $unit . "\n";
}
return $message;
}
}
<?php
namespace SebastianBergmann\CodeCoverage;
class Filter
{
private $whitelistedFiles = [];
public function addDirectoryToWhitelist($directory, $suffix = '.php', $prefix = '')
{
$facade = new \File_Iterator_Facade;
$files = $facade->getFilesAsArray($directory, $suffix, $prefix);
foreach ($files as $file) {
$this->addFileToWhitelist($file);
}
}
public function addFileToWhitelist($filename)
{
$this->whitelistedFiles[realpath($filename)] = true;
}
public function addFilesToWhitelist(array $files)
{
foreach ($files as $file) {
$this->addFileToWhitelist($file);
}
}
public function removeDirectoryFromWhitelist($directory, $suffix = '.php', $prefix = '')
{
$facade = new \File_Iterator_Facade;
$files = $facade->getFilesAsArray($directory, $suffix, $prefix);
foreach ($files as $file) {
$this->removeFileFromWhitelist($file);
}
}
public function removeFileFromWhitelist($filename)
{
$filename = realpath($filename);
unset($this->whitelistedFiles[$filename]);
}
public function isFile($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) {
return false;
}
return file_exists($filename);
}
public function isFiltered($filename)
{
if (!$this->isFile($filename)) {
return true;
}
$filename = realpath($filename);
return !isset($this->whitelistedFiles[$filename]);
}
public function getWhitelist()
{
return array_keys($this->whitelistedFiles);
}
public function hasWhitelist()
{
return !empty($this->whitelistedFiles);
}
public function getWhitelistedFiles()
{
return $this->whitelistedFiles;
}
public function setWhitelistedFiles($whitelistedFiles)
{
$this->whitelistedFiles = $whitelistedFiles;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Node;
use SebastianBergmann\CodeCoverage\Util;
abstract class AbstractNode implements \Countable
{
private $name;
private $path;
private $pathArray;
private $parent;
private $id;
public function __construct($name, AbstractNode $parent = null)
{
if (substr($name, -1) == '/') {
$name = substr($name, 0, -1);
}
$this->name = $name;
$this->parent = $parent;
}
public function getName()
{
return $this->name;
}
public function getId()
{
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()
{
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() . '/' . $this->name;
}
}
return $this->path;
}
public function getPathAsArray()
{
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()
{
return $this->parent;
}
public function getTestedClassesPercent($asString = true)
{
return Util::percent(
$this->getNumTestedClasses(),
$this->getNumClasses(),
$asString
);
}
public function getTestedTraitsPercent($asString = true)
{
return Util::percent(
$this->getNumTestedTraits(),
$this->getNumTraits(),
$asString
);
}
public function getTestedClassesAndTraitsPercent($asString = true)
{
return Util::percent(
$this->getNumTestedClassesAndTraits(),
$this->getNumClassesAndTraits(),
$asString
);
}
public function getTestedMethodsPercent($asString = true)
{
return Util::percent(
$this->getNumTestedMethods(),
$this->getNumMethods(),
$asString
);
}
public function getLineExecutedPercent($asString = true)
{
return Util::percent(
$this->getNumExecutedLines(),
$this->getNumExecutableLines(),
$asString
);
}
public function getNumClassesAndTraits()
{
return $this->getNumClasses() + $this->getNumTraits();
}
public function getNumTestedClassesAndTraits()
{
return $this->getNumTestedClasses() + $this->getNumTestedTraits();
}
public function getClassesAndTraits()
{
return array_merge($this->getClasses(), $this->getTraits());
}
abstract public function getClasses();
abstract public function getTraits();
abstract public function getFunctions();
abstract public function getLinesOfCode();
abstract public function getNumExecutableLines();
abstract public function getNumExecutedLines();
abstract public function getNumClasses();
abstract public function getNumTestedClasses();
abstract public function getNumTraits();
abstract public function getNumTestedTraits();
abstract public function getNumMethods();
abstract public function getNumTestedMethods();
abstract public function getNumFunctions();
abstract public function getNumTestedFunctions();
}
<?php
namespace SebastianBergmann\CodeCoverage\Node;
use SebastianBergmann\CodeCoverage\CodeCoverage;
class Builder
{
public function build(CodeCoverage $coverage)
{
$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, $cacheTokens)
{
foreach ($items as $key => $value) {
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);
}
}
}
private function buildDirectoryStructure($files)
{
$result = [];
foreach ($files as $path => $file) {
$path = explode('/', $path);
$pointer = &$result;
$max = count($path);
for ($i = 0; $i < $max; $i++) {
if ($i == ($max - 1)) {
$type = '/f';
} else {
$type = '';
}
$pointer = &$pointer[$path[$i] . $type];
}
$pointer = $file;
}
return $result;
}
private function reducePaths(&$files)
{
if (empty($files)) {
return '.';
}
$commonPath = '';
$paths = array_keys($files);
if (count($files) == 1) {
$commonPath = dirname($paths[0]) . '/';
$files[basename($paths[0])] = $files[$paths[0]];
unset($files[$paths[0]]);
return $commonPath;
}
$max = count($paths);
for ($i = 0; $i < $max; $i++) {
if (strpos($paths[$i], 'phar://') === 0) {
$paths[$i] = substr($paths[$i], 7);
$paths[$i] = strtr($paths[$i], '/', DIRECTORY_SEPARATOR);
}
$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('/', $paths[$i])] = $files[$original[$i]];
unset($files[$original[$i]]);
}
ksort($files);
return substr($commonPath, 0, -1);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Node;
use SebastianBergmann\CodeCoverage\InvalidArgumentException;
class Directory extends AbstractNode implements \IteratorAggregate
{
private $children = [];
private $directories = [];
private $files = [];
private $classes;
private $traits;
private $functions;
private $linesOfCode = null;
private $numFiles = -1;
private $numExecutableLines = -1;
private $numExecutedLines = -1;
private $numClasses = -1;
private $numTestedClasses = -1;
private $numTraits = -1;
private $numTestedTraits = -1;
private $numMethods = -1;
private $numTestedMethods = -1;
private $numFunctions = -1;
private $numTestedFunctions = -1;
public function count()
{
if ($this->numFiles == -1) {
$this->numFiles = 0;
foreach ($this->children as $child) {
$this->numFiles += count($child);
}
}
return $this->numFiles;
}
public function getIterator()
{
return new \RecursiveIteratorIterator(
new Iterator($this),
\RecursiveIteratorIterator::SELF_FIRST
);
}
public function addDirectory($name)
{
$directory = new self($name, $this);
$this->children[] = $directory;
$this->directories[] = &$this->children[count($this->children) - 1];
return $directory;
}
public function addFile($name, array $coverageData, array $testData, $cacheTokens)
{
$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;
}
public function getDirectories()
{
return $this->directories;
}
public function getFiles()
{
return $this->files;
}
public function getChildNodes()
{
return $this->children;
}
public function getClasses()
{
if ($this->classes === null) {
$this->classes = [];
foreach ($this->children as $child) {
$this->classes = array_merge(
$this->classes,
$child->getClasses()
);
}
}
return $this->classes;
}
public function getTraits()
{
if ($this->traits === null) {
$this->traits = [];
foreach ($this->children as $child) {
$this->traits = array_merge(
$this->traits,
$child->getTraits()
);
}
}
return $this->traits;
}
public function getFunctions()
{
if ($this->functions === null) {
$this->functions = [];
foreach ($this->children as $child) {
$this->functions = array_merge(
$this->functions,
$child->getFunctions()
);
}
}
return $this->functions;
}
public function getLinesOfCode()
{
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;
}
public function getNumExecutableLines()
{
if ($this->numExecutableLines == -1) {
$this->numExecutableLines = 0;
foreach ($this->children as $child) {
$this->numExecutableLines += $child->getNumExecutableLines();
}
}
return $this->numExecutableLines;
}
public function getNumExecutedLines()
{
if ($this->numExecutedLines == -1) {
$this->numExecutedLines = 0;
foreach ($this->children as $child) {
$this->numExecutedLines += $child->getNumExecutedLines();
}
}
return $this->numExecutedLines;
}
public function getNumClasses()
{
if ($this->numClasses == -1) {
$this->numClasses = 0;
foreach ($this->children as $child) {
$this->numClasses += $child->getNumClasses();
}
}
return $this->numClasses;
}
public function getNumTestedClasses()
{
if ($this->numTestedClasses == -1) {
$this->numTestedClasses = 0;
foreach ($this->children as $child) {
$this->numTestedClasses += $child->getNumTestedClasses();
}
}
return $this->numTestedClasses;
}
public function getNumTraits()
{
if ($this->numTraits == -1) {
$this->numTraits = 0;
foreach ($this->children as $child) {
$this->numTraits += $child->getNumTraits();
}
}
return $this->numTraits;
}
public function getNumTestedTraits()
{
if ($this->numTestedTraits == -1) {
$this->numTestedTraits = 0;
foreach ($this->children as $child) {
$this->numTestedTraits += $child->getNumTestedTraits();
}
}
return $this->numTestedTraits;
}
public function getNumMethods()
{
if ($this->numMethods == -1) {
$this->numMethods = 0;
foreach ($this->children as $child) {
$this->numMethods += $child->getNumMethods();
}
}
return $this->numMethods;
}
public function getNumTestedMethods()
{
if ($this->numTestedMethods == -1) {
$this->numTestedMethods = 0;
foreach ($this->children as $child) {
$this->numTestedMethods += $child->getNumTestedMethods();
}
}
return $this->numTestedMethods;
}
public function getNumFunctions()
{
if ($this->numFunctions == -1) {
$this->numFunctions = 0;
foreach ($this->children as $child) {
$this->numFunctions += $child->getNumFunctions();
}
}
return $this->numFunctions;
}
public function getNumTestedFunctions()
{
if ($this->numTestedFunctions == -1) {
$this->numTestedFunctions = 0;
foreach ($this->children as $child) {
$this->numTestedFunctions += $child->getNumTestedFunctions();
}
}
return $this->numTestedFunctions;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Node;
use SebastianBergmann\CodeCoverage\InvalidArgumentException;
class File extends AbstractNode
{
private $coverageData;
private $testData;
private $numExecutableLines = 0;
private $numExecutedLines = 0;
private $classes = [];
private $traits = [];
private $functions = [];
private $linesOfCode = [];
private $numTestedTraits = 0;
private $numTestedClasses = 0;
private $numMethods = null;
private $numTestedMethods = null;
private $numTestedFunctions = null;
private $startLines = [];
private $endLines = [];
private $cacheTokens;
public function __construct($name, AbstractNode $parent, array $coverageData, array $testData, $cacheTokens)
{
if (!is_bool($cacheTokens)) {
throw InvalidArgumentException::create(
1,
'boolean'
);
}
parent::__construct($name, $parent);
$this->coverageData = $coverageData;
$this->testData = $testData;
$this->cacheTokens = $cacheTokens;
$this->calculateStatistics();
}
public function count()
{
return 1;
}
public function getCoverageData()
{
return $this->coverageData;
}
public function getTestData()
{
return $this->testData;
}
public function getClasses()
{
return $this->classes;
}
public function getTraits()
{
return $this->traits;
}
public function getFunctions()
{
return $this->functions;
}
public function getLinesOfCode()
{
return $this->linesOfCode;
}
public function getNumExecutableLines()
{
return $this->numExecutableLines;
}
public function getNumExecutedLines()
{
return $this->numExecutedLines;
}
public function getNumClasses()
{
return count($this->classes);
}
public function getNumTestedClasses()
{
return $this->numTestedClasses;
}
public function getNumTraits()
{
return count($this->traits);
}
public function getNumTestedTraits()
{
return $this->numTestedTraits;
}
public function getNumMethods()
{
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;
}
public function getNumTestedMethods()
{
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;
}
public function getNumFunctions()
{
return count($this->functions);
}
public function getNumTestedFunctions()
{
if ($this->numTestedFunctions === null) {
$this->numTestedFunctions = 0;
foreach ($this->functions as $function) {
if ($function['executableLines'] > 0 &&
$function['coverage'] == 100) {
$this->numTestedFunctions++;
}
}
}
return $this->numTestedFunctions;
}
protected function calculateStatistics()
{
$classStack = $functionStack = [];
if ($this->cacheTokens) {
$tokens = \PHP_Token_Stream_CachingFactory::get($this->getPath());
} else {
$tokens = new \PHP_Token_Stream($this->getPath());
}
$this->processClasses($tokens);
$this->processTraits($tokens);
$this->processFunctions($tokens);
$this->linesOfCode = $tokens->getLinesOfCode();
unset($tokens);
for ($lineNumber = 1; $lineNumber <= $this->linesOfCode['loc']; $lineNumber++) {
if (isset($this->startLines[$lineNumber])) {
if (isset($this->startLines[$lineNumber]['className'])) {
if (isset($currentClass)) {
$classStack[] = &$currentClass;
}
$currentClass = &$this->startLines[$lineNumber];
}
elseif (isset($this->startLines[$lineNumber]['traitName'])) {
$currentTrait = &$this->startLines[$lineNumber];
}
elseif (isset($this->startLines[$lineNumber]['methodName'])) {
$currentMethod = &$this->startLines[$lineNumber];
}
elseif (isset($this->startLines[$lineNumber]['functionName'])) {
if (isset($currentFunction)) {
$functionStack[] = &$currentFunction;
}
$currentFunction = &$this->startLines[$lineNumber];
}
}
if (isset($this->coverageData[$lineNumber])) {
if (isset($currentClass)) {
$currentClass['executableLines']++;
}
if (isset($currentTrait)) {
$currentTrait['executableLines']++;
}
if (isset($currentMethod)) {
$currentMethod['executableLines']++;
}
if (isset($currentFunction)) {
$currentFunction['executableLines']++;
}
$this->numExecutableLines++;
if (count($this->coverageData[$lineNumber]) > 0) {
if (isset($currentClass)) {
$currentClass['executedLines']++;
}
if (isset($currentTrait)) {
$currentTrait['executedLines']++;
}
if (isset($currentMethod)) {
$currentMethod['executedLines']++;
}
if (isset($currentFunction)) {
$currentFunction['executedLines']++;
}
$this->numExecutedLines++;
}
}
if (isset($this->endLines[$lineNumber])) {
if (isset($this->endLines[$lineNumber]['className'])) {
unset($currentClass);
if ($classStack) {
end($classStack);
$key = key($classStack);
$currentClass = &$classStack[$key];
unset($classStack[$key]);
}
}
elseif (isset($this->endLines[$lineNumber]['traitName'])) {
unset($currentTrait);
}
elseif (isset($this->endLines[$lineNumber]['methodName'])) {
unset($currentMethod);
}
elseif (isset($this->endLines[$lineNumber]['functionName'])) {
unset($currentFunction);
if ($functionStack) {
end($functionStack);
$key = key($functionStack);
$currentFunction = &$functionStack[$key];
unset($functionStack[$key]);
}
}
}
}
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'];
}
if ($trait['executableLines'] > 0) {
$trait['coverage'] = ($trait['executedLines'] /
$trait['executableLines']) * 100;
} else {
$trait['coverage'] = 100;
}
if ($trait['coverage'] == 100) {
$this->numTestedClasses++;
}
$trait['crap'] = $this->crap(
$trait['ccn'],
$trait['coverage']
);
}
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'];
}
if ($class['executableLines'] > 0) {
$class['coverage'] = ($class['executedLines'] /
$class['executableLines']) * 100;
} else {
$class['coverage'] = 100;
}
if ($class['coverage'] == 100) {
$this->numTestedClasses++;
}
$class['crap'] = $this->crap(
$class['ccn'],
$class['coverage']
);
}
}
protected function processClasses(\PHP_Token_Stream $tokens)
{
$classes = $tokens->getClasses();
unset($tokens);
$link = $this->getId() . '.html#';
foreach ($classes as $className => $class) {
$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']
];
$this->startLines[$class['startLine']] = &$this->classes[$className];
$this->endLines[$class['endLine']] = &$this->classes[$className];
foreach ($class['methods'] as $methodName => $method) {
$this->classes[$className]['methods'][$methodName] = $this->newMethod($methodName, $method, $link);
$this->startLines[$method['startLine']] = &$this->classes[$className]['methods'][$methodName];
$this->endLines[$method['endLine']] = &$this->classes[$className]['methods'][$methodName];
}
}
}
protected function processTraits(\PHP_Token_Stream $tokens)
{
$traits = $tokens->getTraits();
unset($tokens);
$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']
];
$this->startLines[$trait['startLine']] = &$this->traits[$traitName];
$this->endLines[$trait['endLine']] = &$this->traits[$traitName];
foreach ($trait['methods'] as $methodName => $method) {
$this->traits[$traitName]['methods'][$methodName] = $this->newMethod($methodName, $method, $link);
$this->startLines[$method['startLine']] = &$this->traits[$traitName]['methods'][$methodName];
$this->endLines[$method['endLine']] = &$this->traits[$traitName]['methods'][$methodName];
}
}
}
protected function processFunctions(\PHP_Token_Stream $tokens)
{
$functions = $tokens->getFunctions();
unset($tokens);
$link = $this->getId() . '.html#';
foreach ($functions as $functionName => $function) {
$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']
];
$this->startLines[$function['startLine']] = &$this->functions[$functionName];
$this->endLines[$function['endLine']] = &$this->functions[$functionName];
}
}
protected function crap($ccn, $coverage)
{
if ($coverage == 0) {
return (string) (pow($ccn, 2) + $ccn);
}
if ($coverage >= 95) {
return (string) $ccn;
}
return sprintf(
'%01.2F',
pow($ccn, 2) * pow(1 - $coverage/100, 3) + $ccn
);
}
private function newMethod($methodName, array $method, $link)
{
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
namespace SebastianBergmann\CodeCoverage\Node;
class Iterator implements \RecursiveIterator
{
private $position;
private $nodes;
public function __construct(Directory $node)
{
$this->nodes = $node->getChildNodes();
}
public function rewind()
{
$this->position = 0;
}
public function valid()
{
return $this->position < count($this->nodes);
}
public function key()
{
return $this->position;
}
public function current()
{
return $this->valid() ? $this->nodes[$this->position] : null;
}
public function next()
{
$this->position++;
}
public function getChildren()
{
return new self(
$this->nodes[$this->position]
);
}
public function hasChildren()
{
return $this->nodes[$this->position] instanceof Directory;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\File;
class Clover
{
public function process(CodeCoverage $coverage, $target = null, $name = null)
{
$xmlDocument = new \DOMDocument('1.0', 'UTF-8');
$xmlDocument->formatOutput = true;
$xmlCoverage = $xmlDocument->createElement('coverage');
$xmlCoverage->setAttribute('generated', (int) $_SERVER['REQUEST_TIME']);
$xmlDocument->appendChild($xmlCoverage);
$xmlProject = $xmlDocument->createElement('project');
$xmlProject->setAttribute('timestamp', (int) $_SERVER['REQUEST_TIME']);
if (is_string($name)) {
$xmlProject->setAttribute('name', $name);
}
$xmlCoverage->appendChild($xmlProject);
$packages = [];
$report = $coverage->getReport();
unset($coverage);
foreach ($report as $item) {
if (!$item instanceof File) {
continue;
}
$xmlFile = $xmlDocument->createElement('file');
$xmlFile->setAttribute('name', $item->getPath());
$classes = $item->getClassesAndTraits();
$coverage = $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($coverage[$line]) && ($coverage[$line] !== null)) {
$methodCount = max($methodCount, count($coverage[$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', $class['ccn']);
$xmlMetrics->setAttribute('methods', $classMethods);
$xmlMetrics->setAttribute('coveredmethods', $coveredMethods);
$xmlMetrics->setAttribute('conditionals', 0);
$xmlMetrics->setAttribute('coveredconditionals', 0);
$xmlMetrics->setAttribute('statements', $classStatements);
$xmlMetrics->setAttribute('coveredstatements', $coveredClassStatements);
$xmlMetrics->setAttribute('elements', $classMethods + $classStatements );
$xmlMetrics->setAttribute('coveredelements', $coveredMethods + $coveredClassStatements );
$xmlClass->appendChild($xmlMetrics);
}
foreach ($coverage 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', $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', $data['ccn']);
}
if (isset($data['crap'])) {
$xmlLine->setAttribute('crap', $data['crap']);
}
$xmlLine->setAttribute('count', $data['count']);
$xmlFile->appendChild($xmlLine);
}
$linesOfCode = $item->getLinesOfCode();
$xmlMetrics = $xmlDocument->createElement('metrics');
$xmlMetrics->setAttribute('loc', $linesOfCode['loc']);
$xmlMetrics->setAttribute('ncloc', $linesOfCode['ncloc']);
$xmlMetrics->setAttribute('classes', $item->getNumClassesAndTraits());
$xmlMetrics->setAttribute('methods', $item->getNumMethods());
$xmlMetrics->setAttribute('coveredmethods', $item->getNumTestedMethods());
$xmlMetrics->setAttribute('conditionals', 0);
$xmlMetrics->setAttribute('coveredconditionals', 0);
$xmlMetrics->setAttribute('statements', $item->getNumExecutableLines());
$xmlMetrics->setAttribute('coveredstatements', $item->getNumExecutedLines());
$xmlMetrics->setAttribute('elements', $item->getNumMethods() + $item->getNumExecutableLines() );
$xmlMetrics->setAttribute('coveredelements', $item->getNumTestedMethods() + $item->getNumExecutedLines() );
$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', count($report));
$xmlMetrics->setAttribute('loc', $linesOfCode['loc']);
$xmlMetrics->setAttribute('ncloc', $linesOfCode['ncloc']);
$xmlMetrics->setAttribute('classes', $report->getNumClassesAndTraits());
$xmlMetrics->setAttribute('methods', $report->getNumMethods());
$xmlMetrics->setAttribute('coveredmethods', $report->getNumTestedMethods());
$xmlMetrics->setAttribute('conditionals', 0);
$xmlMetrics->setAttribute('coveredconditionals', 0);
$xmlMetrics->setAttribute('statements', $report->getNumExecutableLines());
$xmlMetrics->setAttribute('coveredstatements', $report->getNumExecutedLines());
$xmlMetrics->setAttribute('elements', $report->getNumMethods() + $report->getNumExecutableLines() );
$xmlMetrics->setAttribute('coveredelements', $report->getNumTestedMethods() + $report->getNumExecutedLines() );
$xmlProject->appendChild($xmlMetrics);
$buffer = $xmlDocument->saveXML();
if ($target !== null) {
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
file_put_contents($target, $buffer);
}
return $buffer;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\CodeCoverage\InvalidArgumentException;
class Crap4j
{
private $threshold;
public function __construct($threshold = 30)
{
if (!is_int($threshold)) {
throw InvalidArgumentException::create(
1,
'integer'
);
}
$this->threshold = $threshold;
}
public function process(CodeCoverage $coverage, $target = null, $name = null)
{
$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', (int) $_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', $this->roundValue($method['crap'])));
$methodNode->appendChild($document->createElement('complexity', $method['ccn']));
$methodNode->appendChild($document->createElement('coverage', $this->roundValue($method['coverage'])));
$methodNode->appendChild($document->createElement('crapLoad', round($crapLoad)));
$methodsNode->appendChild($methodNode);
}
}
}
$stats->appendChild($document->createElement('name', 'Method Crap Stats'));
$stats->appendChild($document->createElement('methodCount', $fullMethodCount));
$stats->appendChild($document->createElement('crapMethodCount', $fullCrapMethodCount));
$stats->appendChild($document->createElement('crapLoad', round($fullCrapLoad)));
$stats->appendChild($document->createElement('totalCrap', $fullCrap));
if ($fullMethodCount > 0) {
$crapMethodPercent = $this->roundValue((100 * $fullCrapMethodCount) / $fullMethodCount);
} else {
$crapMethodPercent = 0;
}
$stats->appendChild($document->createElement('crapMethodPercent', $crapMethodPercent));
$root->appendChild($stats);
$root->appendChild($methodsNode);
$buffer = $document->saveXML();
if ($target !== null) {
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
file_put_contents($target, $buffer);
}
return $buffer;
}
private function getCrapLoad($crapValue, $cyclomaticComplexity, $coveragePercent)
{
$crapLoad = 0;
if ($crapValue >= $this->threshold) {
$crapLoad += $cyclomaticComplexity * (1.0 - $coveragePercent / 100);
$crapLoad += $cyclomaticComplexity / $this->threshold;
}
return $crapLoad;
}
private function roundValue($value)
{
return round($value, 2);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Html;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
class Facade
{
private $templatePath;
private $generator;
private $lowUpperBound;
private $highLowerBound;
public function __construct($lowUpperBound = 50, $highLowerBound = 90, $generator = '')
{
$this->generator = $generator;
$this->highLowerBound = $highLowerBound;
$this->lowUpperBound = $lowUpperBound;
$this->templatePath = __DIR__ . '/Renderer/Template/';
}
public function process(CodeCoverage $coverage, $target)
{
$target = $this->getDirectory($target);
$report = $coverage->getReport();
unset($coverage);
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 (!file_exists($target . $id)) {
mkdir($target . $id, 0777, true);
}
$directory->render($node, $target . $id . '/index.html');
$dashboard->render($node, $target . $id . '/dashboard.html');
} else {
$dir = dirname($target . $id);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$file->render($node, $target . $id . '.html');
}
}
$this->copyFiles($target);
}
private function copyFiles($target)
{
$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');
$dir = $this->getDirectory($target . 'fonts');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.eot', $dir . 'glyphicons-halflings-regular.eot');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.svg', $dir . 'glyphicons-halflings-regular.svg');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.ttf', $dir . 'glyphicons-halflings-regular.ttf');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.woff', $dir . 'glyphicons-halflings-regular.woff');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.woff2', $dir . 'glyphicons-halflings-regular.woff2');
$dir = $this->getDirectory($target . 'js');
copy($this->templatePath . 'js/bootstrap.min.js', $dir . 'bootstrap.min.js');
copy($this->templatePath . 'js/d3.min.js', $dir . 'd3.min.js');
copy($this->templatePath . 'js/holder.min.js', $dir . 'holder.min.js');
copy($this->templatePath . 'js/html5shiv.min.js', $dir . 'html5shiv.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/respond.min.js', $dir . 'respond.min.js');
}
private function getDirectory($directory)
{
if (substr($directory, -1, 1) != DIRECTORY_SEPARATOR) {
$directory .= DIRECTORY_SEPARATOR;
}
if (is_dir($directory)) {
return $directory;
}
if (@mkdir($directory, 0777, true)) {
return $directory;
}
throw new RuntimeException(
sprintf(
'Directory "%s" does not exist.',
$directory
)
);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Html;
use SebastianBergmann\CodeCoverage\Node\AbstractNode;
use SebastianBergmann\CodeCoverage\Node\File as FileNode;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
use SebastianBergmann\Environment\Runtime;
use SebastianBergmann\Version;
abstract class Renderer
{
protected $templatePath;
protected $generator;
protected $date;
protected $lowUpperBound;
protected $highLowerBound;
protected $version;
public function __construct($templatePath, $generator, $date, $lowUpperBound, $highLowerBound)
{
$version = new Version('4.0.1', dirname(dirname(dirname(dirname(__DIR__)))));
$this->templatePath = $templatePath;
$this->generator = $generator;
$this->date = $date;
$this->lowUpperBound = $lowUpperBound;
$this->highLowerBound = $highLowerBound;
$this->version = $version->getVersion();
}
protected function renderItemTemplate(\Text_Template $template, array $data)
{
$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 = 'success';
$classesNumber = '0' . $numSeparator . '0';
$classesBar = $this->getCoverageBar(100);
}
if ($data['numMethods'] > 0) {
$methodsLevel = $this->getColorLevel($data['testedMethodsPercent']);
$methodsNumber = $data['numTestedMethods'] . $numSeparator .
$data['numMethods'];
$methodsBar = $this->getCoverageBar(
$data['testedMethodsPercent']
);
} else {
$methodsLevel = 'success';
$methodsNumber = '0' . $numSeparator . '0';
$methodsBar = $this->getCoverageBar(100);
$data['testedMethodsPercentAsString'] = '100.00%';
}
if ($data['numExecutableLines'] > 0) {
$linesLevel = $this->getColorLevel($data['linesExecutedPercent']);
$linesNumber = $data['numExecutedLines'] . $numSeparator .
$data['numExecutableLines'];
$linesBar = $this->getCoverageBar(
$data['linesExecutedPercent']
);
} else {
$linesLevel = 'success';
$linesNumber = '0' . $numSeparator . '0';
$linesBar = $this->getCoverageBar(100);
$data['linesExecutedPercentAsString'] = '100.00%';
}
$template->setVar(
[
'icon' => isset($data['icon']) ? $data['icon'] : '',
'crap' => isset($data['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' => isset($data['testedClassesPercentAsString']) ? $data['testedClassesPercentAsString'] : '',
'classes_level' => $classesLevel,
'classes_number' => $classesNumber
]
);
return $template->render();
}
protected function setCommonTemplateVariables(\Text_Template $template, AbstractNode $node)
{
$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)
{
$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)
{
$buffer = sprintf(
' <li class="active">%s</li>' . "\n",
$node->getName()
);
if ($node instanceof DirectoryNode) {
$buffer .= ' <li>(<a href="dashboard.html">Dashboard</a>)</li>' . "\n";
}
return $buffer;
}
protected function getInactiveBreadcrumb(AbstractNode $node, $pathToRoot)
{
return sprintf(
' <li><a href="%sindex.html">%s</a></li>' . "\n",
$pathToRoot,
$node->getName()
);
}
protected function getPathToRoot(AbstractNode $node)
{
$id = $node->getId();
$depth = substr_count($id, '/');
if ($id != 'index' &&
$node instanceof DirectoryNode) {
$depth++;
}
return str_repeat('../', $depth);
}
protected function getCoverageBar($percent)
{
$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($percent)
{
if ($percent <= $this->lowUpperBound) {
return 'danger';
} elseif ($percent > $this->lowUpperBound &&
$percent < $this->highLowerBound) {
return 'warning';
} else {
return 'success';
}
}
private function getRuntimeString()
{
$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')
);
}
return $buffer;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Html;
use SebastianBergmann\CodeCoverage\Node\AbstractNode;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
class Dashboard extends Renderer
{
public function render(DirectoryNode $node, $file)
{
$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);
}
protected function complexity(array $classes, $baseLink)
{
$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'])
];
}
protected function coverageDistribution(array $classes)
{
$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']))
];
}
protected function insufficientCoverage(array $classes, $baseLink)
{
$leastTestedClasses = [];
$leastTestedMethods = [];
$result = ['class' => '', 'method' => ''];
foreach ($classes as $className => $class) {
foreach ($class['methods'] as $methodName => $method) {
if ($method['coverage'] < $this->highLowerBound) {
if ($className != '*') {
$key = $className . '::' . $methodName;
} else {
$key = $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) {
list($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;
}
protected function projectRisks(array $classes, $baseLink)
{
$classRisks = [];
$methodRisks = [];
$result = ['class' => '', 'method' => ''];
foreach ($classes as $className => $class) {
foreach ($class['methods'] as $methodName => $method) {
if ($method['coverage'] < $this->highLowerBound &&
$method['ccn'] > 1) {
if ($className != '*') {
$key = $className . '::' . $methodName;
} else {
$key = $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) {
list($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)
{
return sprintf(
' <li><a href="index.html">%s</a></li>' . "\n" .
' <li class="active">(Dashboard)</li>' . "\n",
$node->getName()
);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Html;
use SebastianBergmann\CodeCoverage\Node\AbstractNode as Node;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
class Directory extends Renderer
{
public function render(DirectoryNode $node, $file)
{
$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, $total = false)
{
$data = [
'numClasses' => $node->getNumClassesAndTraits(),
'numTestedClasses' => $node->getNumTestedClassesAndTraits(),
'numMethods' => $node->getNumMethods(),
'numTestedMethods' => $node->getNumTestedMethods(),
'linesExecutedPercent' => $node->getLineExecutedPercent(false),
'linesExecutedPercentAsString' => $node->getLineExecutedPercent(),
'numExecutedLines' => $node->getNumExecutedLines(),
'numExecutableLines' => $node->getNumExecutableLines(),
'testedMethodsPercent' => $node->getTestedMethodsPercent(false),
'testedMethodsPercentAsString' => $node->getTestedMethodsPercent(),
'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()
);
$data['icon'] = '<span class="glyphicon glyphicon-folder-open"></span> ';
} else {
$data['name'] = sprintf(
'<a href="%s.html">%s</a>',
$node->getName(),
$node->getName()
);
$data['icon'] = '<span class="glyphicon glyphicon-file"></span> ';
}
}
return $this->renderItemTemplate(
new \Text_Template($this->templatePath . 'directory_item.html', '{{', '}}'),
$data
);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Html;
use SebastianBergmann\CodeCoverage\Node\File as FileNode;
use SebastianBergmann\CodeCoverage\Util;
class File extends Renderer
{
private $htmlspecialcharsFlags;
public function __construct($templatePath, $generator, $date, $lowUpperBound, $highLowerBound)
{
parent::__construct(
$templatePath,
$generator,
$date,
$lowUpperBound,
$highLowerBound
);
$this->htmlspecialcharsFlags = ENT_COMPAT;
$this->htmlspecialcharsFlags = $this->htmlspecialcharsFlags | ENT_HTML401 | ENT_SUBSTITUTE;
}
public function render(FileNode $node, $file)
{
$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)
{
$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->getNumMethods(),
'numTestedMethods' => $node->getNumTestedMethods(),
'linesExecutedPercent' => $node->getLineExecutedPercent(false),
'linesExecutedPercentAsString' => $node->getLineExecutedPercent(),
'numExecutedLines' => $node->getNumExecutedLines(),
'numExecutableLines' => $node->getNumExecutableLines(),
'testedMethodsPercent' => $node->getTestedMethodsPercent(false),
'testedMethodsPercentAsString' => $node->getTestedMethodsPercent(),
'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)
{
if (empty($items)) {
return '';
}
$buffer = '';
foreach ($items as $name => $item) {
$numMethods = count($item['methods']);
$numTestedMethods = 0;
foreach ($item['methods'] as $method) {
if ($method['executedLines'] == $method['executableLines']) {
$numTestedMethods++;
}
}
$buffer .= $this->renderItemTemplate(
$template,
[
'name' => $name,
'numClasses' => 1,
'numTestedClasses' => $numTestedMethods == $numMethods ? 1 : 0,
'numMethods' => $numMethods,
'numTestedMethods' => $numTestedMethods,
'linesExecutedPercent' => Util::percent(
$item['executedLines'],
$item['executableLines'],
false
),
'linesExecutedPercentAsString' => Util::percent(
$item['executedLines'],
$item['executableLines'],
true
),
'numExecutedLines' => $item['executedLines'],
'numExecutableLines' => $item['executableLines'],
'testedMethodsPercent' => Util::percent(
$numTestedMethods,
$numMethods,
false
),
'testedMethodsPercentAsString' => Util::percent(
$numTestedMethods,
$numMethods,
true
),
'testedClassesPercent' => Util::percent(
$numTestedMethods == $numMethods ? 1 : 0,
1,
false
),
'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)
{
if (empty($functions)) {
return '';
}
$buffer = '';
foreach ($functions as $function) {
$buffer .= $this->renderFunctionOrMethodItem(
$template,
$function
);
}
return $buffer;
}
protected function renderFunctionOrMethodItem(\Text_Template $template, array $item, $indent = '')
{
$numTestedItems = $item['executedLines'] == $item['executableLines'] ? 1 : 0;
return $this->renderItemTemplate(
$template,
[
'name' => sprintf(
'%s<a href="#%d"><abbr title="%s">%s</abbr></a>',
$indent,
$item['startLine'],
htmlspecialchars($item['signature']),
isset($item['functionName']) ? $item['functionName'] : $item['methodName']
),
'numMethods' => 1,
'numTestedMethods' => $numTestedItems,
'linesExecutedPercent' => Util::percent(
$item['executedLines'],
$item['executableLines'],
false
),
'linesExecutedPercentAsString' => Util::percent(
$item['executedLines'],
$item['executableLines'],
true
),
'numExecutedLines' => $item['executedLines'],
'numExecutableLines' => $item['executableLines'],
'testedMethodsPercent' => Util::percent(
$numTestedItems,
1,
false
),
'testedMethodsPercentAsString' => Util::percent(
$numTestedItems,
1,
true
),
'crap' => $item['crap']
]
);
}
protected function renderSource(FileNode $node)
{
$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 = count($coverageData[$i]);
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)
);
}
$popoverContent .= '</ul>';
$trClass = ' class="' . $lineCss . ' popin"';
}
}
if (!empty($popoverTitle)) {
$popover = sprintf(
' data-title="%s" data-content="%s" data-placement="bottom" data-html="true"',
$popoverTitle,
htmlspecialchars($popoverContent)
);
} else {
$popover = '';
}
$lines .= sprintf(
' <tr%s%s><td><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;
}
protected function loadFile($file)
{
$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)
);
$stringFlag = !$stringFlag;
} else {
$result[$i] .= sprintf(
'<span class="keyword">%s</span>',
htmlspecialchars($token)
);
}
continue;
}
list($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;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report;
use SebastianBergmann\CodeCoverage\CodeCoverage;
class PHP
{
public function process(CodeCoverage $coverage, $target = null)
{
$filter = $coverage->filter();
$output = 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), 1),
var_export($coverage->getTests(), 1),
var_export($filter->getWhitelistedFiles(), 1)
);
if ($target !== null) {
return file_put_contents($target, $output);
} else {
return $output;
}
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\CodeCoverage\Util;
class Text
{
private $lowUpperBound;
private $highLowerBound;
private $showUncoveredFiles;
private $showOnlySummary;
private $colors = [
'green' => "\x1b[30;42m",
'yellow' => "\x1b[30;43m",
'red' => "\x1b[37;41m",
'header' => "\x1b[1;37;40m",
'reset' => "\x1b[0m",
'eol' => "\x1b[2K",
];
public function __construct($lowUpperBound = 50, $highLowerBound = 90, $showUncoveredFiles = false, $showOnlySummary = false)
{
$this->lowUpperBound = $lowUpperBound;
$this->highLowerBound = $highLowerBound;
$this->showUncoveredFiles = $showUncoveredFiles;
$this->showOnlySummary = $showOnlySummary;
}
public function process(CodeCoverage $coverage, $showColors = false)
{
$output = PHP_EOL . PHP_EOL;
$report = $coverage->getReport();
unset($coverage);
$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'] = $this->colors['reset'];
$colors['header'] = $this->colors['header'];
$colors['eol'] = $this->colors['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++;
}
}
if (!empty($class['package']['namespace'])) {
$namespace = '\\' . $class['package']['namespace'] . '::';
} elseif (!empty($class['package']['fullPackage'])) {
$namespace = '@' . $class['package']['fullPackage'] . '::';
} else {
$namespace = '';
}
$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 ($classInfo['statementsCovered'] != 0 ||
$this->showUncoveredFiles) {
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;
}
protected function getCoverageColor($numberOfCoveredElements, $totalNumberOfElements)
{
$coverage = Util::percent(
$numberOfCoveredElements,
$totalNumberOfElements
);
if ($coverage >= $this->highLowerBound) {
return $this->colors['green'];
} elseif ($coverage > $this->lowUpperBound) {
return $this->colors['yellow'];
}
return $this->colors['red'];
}
protected function printCoverageCounts($numberOfCoveredElements, $totalNumberOfElements, $precision)
{
$format = '%' . $precision . 's';
return Util::percent(
$numberOfCoveredElements,
$totalNumberOfElements,
true,
true
) .
' (' . sprintf($format, $numberOfCoveredElements) . '/' .
sprintf($format, $totalNumberOfElements) . ')';
}
private function format($color, $padding, $string)
{
$reset = $color ? $this->colors['reset'] : '';
return $color . str_pad($string, $padding) . $reset . PHP_EOL;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
use SebastianBergmann\CodeCoverage\RuntimeException;
class Coverage
{
private $writer;
private $contextNode;
private $finalized = false;
public function __construct(\DOMElement $context, $line)
{
$this->contextNode = $context;
$this->writer = new \XMLWriter;
$this->writer->openMemory();
$this->writer->startElementNs(null, $context->nodeName, 'http://schema.phpunit.de/coverage/1.0');
$this->writer->writeAttribute('nr', $line);
}
public function addTest($test)
{
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()
{
$this->writer->endElement();
$fragment = $this->contextNode->ownerDocument->createDocumentFragment();
$fragment->appendXML($this->writer->outputMemory());
$this->contextNode->parentNode->replaceChild(
$fragment,
$this->contextNode
);
$this->finalized = true;
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Directory extends Node
{
}
<?php
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;
class Facade
{
private $target;
private $project;
public function process(CodeCoverage $coverage, $target)
{
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->processTests($coverage->getTests());
$this->processDirectory($report, $this->project);
$index = $this->project->asDom();
$index->formatOutput = true;
$index->preserveWhiteSpace = false;
$index->save($target . '/index.xml');
}
private function initTargetDirectory($directory)
{
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 (!@mkdir($directory, 0777, true)) {
throw new RuntimeException(
"'$directory' could not be created."
);
}
}
private function processDirectory(DirectoryNode $directory, Node $context)
{
$dirObject = $context->addDirectory($directory->getName());
$this->setTotals($directory, $dirObject->getTotals());
foreach ($directory as $node) {
if ($node instanceof DirectoryNode) {
$this->processDirectory($node, $dirObject);
continue;
}
if ($node instanceof FileNode) {
$this->processFile($node, $dirObject);
continue;
}
throw new RuntimeException(
'Unknown node type for XML report'
);
}
}
private function processFile(FileNode $file, Directory $context)
{
$fileObject = $context->addFile(
$file->getName(),
$file->getId() . '.xml'
);
$this->setTotals($file, $fileObject->getTotals());
$fileReport = new Report($file->getName());
$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($line);
foreach ($tests as $test) {
$coverage->addTest($test);
}
$coverage->finalize();
}
$this->initTargetDirectory(
$this->target . dirname($file->getId()) . '/'
);
$fileDom = $fileReport->asDom();
$fileDom->formatOutput = true;
$fileDom->preserveWhiteSpace = false;
$fileDom->save($this->target . $file->getId() . '.xml');
}
private function processUnit($unit, Report $report)
{
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($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($method['startLine'], $method['endLine']);
$methodObject->setCrap($method['crap']);
$methodObject->setTotals(
$method['executableLines'],
$method['executedLines'],
$method['coverage']
);
}
}
private function processFunction($function, Report $report)
{
$functionObject = $report->getFunctionObject($function['functionName']);
$functionObject->setSignature($function['signature']);
$functionObject->setLines($function['startLine']);
$functionObject->setCrap($function['crap']);
$functionObject->setTotals($function['executableLines'], $function['executedLines'], $function['coverage']);
}
private function processTests(array $tests)
{
$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)
{
$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()
);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class File
{
protected $dom;
protected $contextNode;
public function __construct(\DOMElement $context)
{
$this->dom = $context->ownerDocument;
$this->contextNode = $context;
}
public function getTotals()
{
$totalsContainer = $this->contextNode->firstChild;
if (!$totalsContainer) {
$totalsContainer = $this->contextNode->appendChild(
$this->dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'totals'
)
);
}
return new Totals($totalsContainer);
}
public function getLineCoverage($line)
{
$coverage = $this->contextNode->getElementsByTagNameNS(
'http://schema.phpunit.de/coverage/1.0',
'coverage'
)->item(0);
if (!$coverage) {
$coverage = $this->contextNode->appendChild(
$this->dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'coverage'
)
);
}
$lineNode = $coverage->appendChild(
$this->dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'line'
)
);
return new Coverage($lineNode, $line);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Method
{
private $contextNode;
public function __construct(\DOMElement $context, $name)
{
$this->contextNode = $context;
$this->setName($name);
}
private function setName($name)
{
$this->contextNode->setAttribute('name', $name);
}
public function setSignature($signature)
{
$this->contextNode->setAttribute('signature', $signature);
}
public function setLines($start, $end = null)
{
$this->contextNode->setAttribute('start', $start);
if ($end !== null) {
$this->contextNode->setAttribute('end', $end);
}
}
public function setTotals($executable, $executed, $coverage)
{
$this->contextNode->setAttribute('executable', $executable);
$this->contextNode->setAttribute('executed', $executed);
$this->contextNode->setAttribute('coverage', $coverage);
}
public function setCrap($crap)
{
$this->contextNode->setAttribute('crap', $crap);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Node
{
private $dom;
private $contextNode;
public function __construct(\DOMElement $context)
{
$this->setContextNode($context);
}
protected function setContextNode(\DOMElement $context)
{
$this->dom = $context->ownerDocument;
$this->contextNode = $context;
}
public function getDom()
{
return $this->dom;
}
protected function getContextNode()
{
return $this->contextNode;
}
public function getTotals()
{
$totalsContainer = $this->getContextNode()->firstChild;
if (!$totalsContainer) {
$totalsContainer = $this->getContextNode()->appendChild(
$this->dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'totals'
)
);
}
return new Totals($totalsContainer);
}
public function addDirectory($name)
{
$dirNode = $this->getDom()->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'directory'
);
$dirNode->setAttribute('name', $name);
$this->getContextNode()->appendChild($dirNode);
return new Directory($dirNode);
}
public function addFile($name, $href)
{
$fileNode = $this->getDom()->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'file'
);
$fileNode->setAttribute('name', $name);
$fileNode->setAttribute('href', $href);
$this->getContextNode()->appendChild($fileNode);
return new File($fileNode);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Project extends Node
{
public function __construct($name)
{
$this->init();
$this->setProjectName($name);
}
private function init()
{
$dom = new \DOMDocument;
$dom->loadXML('<?xml version="1.0" ?><phpunit xmlns="http://schema.phpunit.de/coverage/1.0"><project/></phpunit>');
$this->setContextNode(
$dom->getElementsByTagNameNS(
'http://schema.phpunit.de/coverage/1.0',
'project'
)->item(0)
);
}
private function setProjectName($name)
{
$this->getContextNode()->setAttribute('name', $name);
}
public function getTests()
{
$testsNode = $this->getContextNode()->getElementsByTagNameNS(
'http://schema.phpunit.de/coverage/1.0',
'tests'
)->item(0);
if (!$testsNode) {
$testsNode = $this->getContextNode()->appendChild(
$this->getDom()->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'tests'
)
);
}
return new Tests($testsNode);
}
public function asDom()
{
return $this->getDom();
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Report extends File
{
public function __construct($name)
{
$this->dom = new \DOMDocument;
$this->dom->loadXML('<?xml version="1.0" ?><phpunit xmlns="http://schema.phpunit.de/coverage/1.0"><file /></phpunit>');
$this->contextNode = $this->dom->getElementsByTagNameNS(
'http://schema.phpunit.de/coverage/1.0',
'file'
)->item(0);
$this->setName($name);
}
private function setName($name)
{
$this->contextNode->setAttribute('name', $name);
}
public function asDom()
{
return $this->dom;
}
public function getFunctionObject($name)
{
$node = $this->contextNode->appendChild(
$this->dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'function'
)
);
return new Method($node, $name);
}
public function getClassObject($name)
{
return $this->getUnitObject('class', $name);
}
public function getTraitObject($name)
{
return $this->getUnitObject('trait', $name);
}
private function getUnitObject($tagName, $name)
{
$node = $this->contextNode->appendChild(
$this->dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
$tagName
)
);
return new Unit($node, $name);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Tests
{
private $contextNode;
private $codeMap = [
0 => 'PASSED',
1 => 'SKIPPED',
2 => 'INCOMPLETE',
3 => 'FAILURE',
4 => 'ERROR',
5 => 'RISKY',
6 => 'WARNING'
];
public function __construct(\DOMElement $context)
{
$this->contextNode = $context;
}
public function addTest($test, array $result)
{
$node = $this->contextNode->appendChild(
$this->contextNode->ownerDocument->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'test'
)
);
$node->setAttribute('name', $test);
$node->setAttribute('size', $result['size']);
$node->setAttribute('result', (int) $result['status']);
$node->setAttribute('status', $this->codeMap[(int) $result['status']]);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
use SebastianBergmann\CodeCoverage\Util;
class Totals
{
private $container;
private $linesNode;
private $methodsNode;
private $functionsNode;
private $classesNode;
private $traitsNode;
public function __construct(\DOMElement $container)
{
$this->container = $container;
$dom = $container->ownerDocument;
$this->linesNode = $dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'lines'
);
$this->methodsNode = $dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'methods'
);
$this->functionsNode = $dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'functions'
);
$this->classesNode = $dom->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'classes'
);
$this->traitsNode = $dom->createElementNS(
'http://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()
{
return $this->container;
}
public function setNumLines($loc, $cloc, $ncloc, $executable, $executed)
{
$this->linesNode->setAttribute('total', $loc);
$this->linesNode->setAttribute('comments', $cloc);
$this->linesNode->setAttribute('code', $ncloc);
$this->linesNode->setAttribute('executable', $executable);
$this->linesNode->setAttribute('executed', $executed);
$this->linesNode->setAttribute(
'percent',
Util::percent($executed, $executable, true)
);
}
public function setNumClasses($count, $tested)
{
$this->classesNode->setAttribute('count', $count);
$this->classesNode->setAttribute('tested', $tested);
$this->classesNode->setAttribute(
'percent',
Util::percent($tested, $count, true)
);
}
public function setNumTraits($count, $tested)
{
$this->traitsNode->setAttribute('count', $count);
$this->traitsNode->setAttribute('tested', $tested);
$this->traitsNode->setAttribute(
'percent',
Util::percent($tested, $count, true)
);
}
public function setNumMethods($count, $tested)
{
$this->methodsNode->setAttribute('count', $count);
$this->methodsNode->setAttribute('tested', $tested);
$this->methodsNode->setAttribute(
'percent',
Util::percent($tested, $count, true)
);
}
public function setNumFunctions($count, $tested)
{
$this->functionsNode->setAttribute('count', $count);
$this->functionsNode->setAttribute('tested', $tested);
$this->functionsNode->setAttribute(
'percent',
Util::percent($tested, $count, true)
);
}
}
<?php
namespace SebastianBergmann\CodeCoverage\Report\Xml;
class Unit
{
private $contextNode;
public function __construct(\DOMElement $context, $name)
{
$this->contextNode = $context;
$this->setName($name);
}
private function setName($name)
{
$this->contextNode->setAttribute('name', $name);
}
public function setLines($start, $executable, $executed)
{
$this->contextNode->setAttribute('start', $start);
$this->contextNode->setAttribute('executable', $executable);
$this->contextNode->setAttribute('executed', $executed);
}
public function setCrap($crap)
{
$this->contextNode->setAttribute('crap', $crap);
}
public function setPackage($full, $package, $sub, $category)
{
$node = $this->contextNode->getElementsByTagNameNS(
'http://schema.phpunit.de/coverage/1.0',
'package'
)->item(0);
if (!$node) {
$node = $this->contextNode->appendChild(
$this->contextNode->ownerDocument->createElementNS(
'http://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($namespace)
{
$node = $this->contextNode->getElementsByTagNameNS(
'http://schema.phpunit.de/coverage/1.0',
'namespace'
)->item(0);
if (!$node) {
$node = $this->contextNode->appendChild(
$this->contextNode->ownerDocument->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'namespace'
)
);
}
$node->setAttribute('name', $namespace);
}
public function addMethod($name)
{
$node = $this->contextNode->appendChild(
$this->contextNode->ownerDocument->createElementNS(
'http://schema.phpunit.de/coverage/1.0',
'method'
)
);
return new Method($node, $name);
}
}
<?php
namespace SebastianBergmann\CodeCoverage;
class Util
{
public static function percent($a, $b, $asString = false, $fixedWidth = false)
{
if ($asString && $b == 0) {
return '';
}
if ($b > 0) {
$percent = ($a / $b) * 100;
} else {
$percent = 100;
}
if ($asString) {
if ($fixedWidth) {
return sprintf('%6.2F%%', $percent);
}
return sprintf('%01.2F%%', $percent);
} else {
return $percent;
}
}
}
<?php
interface PHPUnit_Exception
{
}
<?php
class PHPUnit_Extensions_GroupTestSuite extends PHPUnit_Framework_TestSuite
{
public function __construct(PHPUnit_Framework_TestSuite $suite, array $groups)
{
$groupSuites = [];
$name = $suite->getName();
foreach ($groups as $group) {
$groupSuites[$group] = new PHPUnit_Framework_TestSuite($name . ' - ' . $group);
$this->addTest($groupSuites[$group]);
}
$tests = new RecursiveIteratorIterator(
new PHPUnit_Util_TestSuiteIterator($suite),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($tests as $test) {
if ($test instanceof PHPUnit_Framework_TestCase) {
$testGroups = PHPUnit_Util_Test::getGroups(
get_class($test),
$test->getName(false)
);
foreach ($groups as $group) {
foreach ($testGroups as $testGroup) {
if ($group == $testGroup) {
$groupSuites[$group]->addTest($test);
}
}
}
}
}
}
}
<?php
class PHPUnit_Extensions_PhptTestCase implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing
{
private $filename;
private $phpUtil;
private $settings = [
'allow_url_fopen=1',
'auto_append_file=',
'auto_prepend_file=',
'disable_functions=',
'display_errors=1',
'docref_root=',
'docref_ext=.html',
'error_append_string=',
'error_prepend_string=',
'error_reporting=-1',
'html_errors=0',
'log_errors=0',
'magic_quotes_runtime=0',
'output_handler=',
'open_basedir=',
'output_buffering=Off',
'report_memleaks=0',
'report_zend_debug=0',
'safe_mode=0',
'track_errors=1',
'xdebug.default_enable=0'
];
public function __construct($filename, $phpUtil = null)
{
if (!is_string($filename)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_file($filename)) {
throw new PHPUnit_Framework_Exception(
sprintf(
'File "%s" does not exist.',
$filename
)
);
}
$this->filename = $filename;
$this->phpUtil = $phpUtil ?: PHPUnit_Util_PHP::factory();
}
public function count()
{
return 1;
}
private function assertPhptExpectation(array $sections, $output)
{
$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]));
$assertion = $sectionAssertion;
$expected = $sectionName == 'EXPECTREGEX' ? "/{$sectionContent}/" : $sectionContent;
break;
}
}
PHPUnit_Framework_Assert::$assertion($expected, $actual);
}
public function run(PHPUnit_Framework_TestResult $result = null)
{
$sections = $this->parse();
$code = $this->render($sections['FILE']);
if ($result === null) {
$result = new PHPUnit_Framework_TestResult;
}
$skip = false;
$xfail = false;
$time = 0;
$settings = $this->settings;
$result->startTest($this);
if (isset($sections['INI'])) {
$settings = array_merge($settings, $this->parseIniSection($sections['INI']));
}
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());
}
if (isset($sections['SKIPIF'])) {
$jobResult = $this->phpUtil->runJob($sections['SKIPIF'], $settings);
if (!strncasecmp('skip', ltrim($jobResult['stdout']), 4)) {
if (preg_match('/^\s*skip\s*(.+)\s*/i', $jobResult['stdout'], $message)) {
$message = substr($message[1], 2);
} else {
$message = '';
}
$result->addFailure($this, new PHPUnit_Framework_SkippedTestError($message), 0);
$skip = true;
}
}
if (isset($sections['XFAIL'])) {
$xfail = trim($sections['XFAIL']);
}
if (!$skip) {
if (isset($sections['STDIN'])) {
$this->phpUtil->setStdin($sections['STDIN']);
}
if (isset($sections['ARGS'])) {
$this->phpUtil->setArgs($sections['ARGS']);
}
PHP_Timer::start();
$jobResult = $this->phpUtil->runJob($code, $settings);
$time = PHP_Timer::stop();
try {
$this->assertPhptExpectation($sections, $jobResult['stdout']);
} catch (PHPUnit_Framework_AssertionFailedError $e) {
if ($xfail !== false) {
$result->addFailure(
$this,
new PHPUnit_Framework_IncompleteTestError(
$xfail,
0,
$e
),
$time
);
} else {
$result->addFailure($this, $e, $time);
}
} catch (Throwable $t) {
$result->addError($this, $t, $time);
} catch (Exception $e) {
$result->addError($this, $e, $time);
}
if ($result->allCompletelyImplemented() && $xfail !== false) {
$result->addFailure(
$this,
new PHPUnit_Framework_IncompleteTestError(
'XFAIL section but test passes'
),
$time
);
}
$this->phpUtil->setStdin('');
$this->phpUtil->setArgs('');
if (isset($sections['CLEAN'])) {
$cleanCode = $this->render($sections['CLEAN']);
$this->phpUtil->runJob($cleanCode, $this->settings);
}
}
$result->endTest($this, $time);
return $result;
}
public function getName()
{
return $this->toString();
}
public function toString()
{
return $this->filename;
}
private function parse()
{
$sections = [];
$section = '';
$allowExternalSections = [
'FILE',
'EXPECT',
'EXPECTF',
'EXPECTREGEX'
];
$requiredSections = [
'FILE',
[
'EXPECT',
'EXPECTF',
'EXPECTREGEX'
]
];
$unsupportedSections = [
'REDIRECTTEST',
'REQUEST',
'POST',
'PUT',
'POST_RAW',
'GZIP_POST',
'DEFLATE_POST',
'GET',
'COOKIE',
'HEADERS',
'CGI',
'EXPECTHEADERS',
'EXTENSIONS',
'PHPDBG'
];
foreach (file($this->filename) as $line) {
if (preg_match('/^--([_A-Z]+)--/', $line, $result)) {
$section = $result[1];
$sections[$section] = '';
continue;
} elseif (empty($section)) {
throw new PHPUnit_Framework_Exception('Invalid PHPT file');
}
$sections[$section] .= $line;
}
if (isset($sections['FILEEOF'])) {
$sections['FILE'] = rtrim($sections['FILEEOF'], "\r\n");
unset($sections['FILEEOF']);
}
$testDirectory = dirname($this->filename) . DIRECTORY_SEPARATOR;
foreach ($allowExternalSections as $section) {
if (isset($sections[$section . '_EXTERNAL'])) {
$externalFilename = str_replace('..', '', trim($sections[$section . '_EXTERNAL']));
if (!is_file($testDirectory . $externalFilename) || !is_readable($testDirectory . $externalFilename)) {
throw new PHPUnit_Framework_Exception(
sprintf(
'Could not load --%s-- %s for PHPT file',
$section . '_EXTERNAL',
$testDirectory . $externalFilename
)
);
}
$sections[$section] = file_get_contents($testDirectory . $externalFilename);
unset($sections[$section . '_EXTERNAL']);
}
}
$isValid = true;
foreach ($requiredSections as $section) {
if (is_array($section)) {
$foundSection = false;
foreach ($section as $anySection) {
if (isset($sections[$anySection])) {
$foundSection = true;
break;
}
}
if (!$foundSection) {
$isValid = false;
break;
}
} else {
if (!isset($sections[$section])) {
$isValid = false;
break;
}
}
}
if (!$isValid) {
throw new PHPUnit_Framework_Exception('Invalid PHPT file');
}
foreach ($unsupportedSections as $section) {
if (isset($sections[$section])) {
throw new PHPUnit_Framework_Exception(
'PHPUnit does not support this PHPT file'
);
}
}
return $sections;
}
private function render($code)
{
return str_replace(
[
'__DIR__',
'__FILE__'
],
[
"'" . dirname($this->filename) . "'",
"'" . $this->filename . "'"
],
$code
);
}
private function cleanupForCoverage()
{
$files = $this->getCoverageFiles();
$coverage = @unserialize(file_get_contents($files['coverage']));
foreach ($files as $file) {
@unlink($file);
}
return $coverage;
}
protected function parseIniSection($content)
{
return preg_split('/\n|\r/', $content, -1, PREG_SPLIT_NO_EMPTY);
}
protected function parseEnvSection($content)
{
$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;
}
}
<?php
class PHPUnit_Extensions_PhptTestSuite extends PHPUnit_Framework_TestSuite
{
public function __construct($directory)
{
if (is_string($directory) && is_dir($directory)) {
$this->setName($directory);
$facade = new File_Iterator_Facade;
$files = $facade->getFilesAsArray($directory, '.phpt');
foreach ($files as $file) {
$this->addTestFile($file);
}
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'directory name');
}
}
}
<?php
class PHPUnit_Extensions_RepeatedTest extends PHPUnit_Extensions_TestDecorator
{
protected $processIsolation = false;
protected $timesRepeat = 1;
public function __construct(PHPUnit_Framework_Test $test, $timesRepeat = 1, $processIsolation = false)
{
parent::__construct($test);
if (is_integer($timesRepeat) &&
$timesRepeat >= 0) {
$this->timesRepeat = $timesRepeat;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'positive integer'
);
}
$this->processIsolation = $processIsolation;
}
public function count()
{
return $this->timesRepeat * count($this->test);
}
public function run(PHPUnit_Framework_TestResult $result = null)
{
if ($result === null) {
$result = $this->createResult();
}
for ($i = 0; $i < $this->timesRepeat && !$result->shouldStop(); $i++) {
if ($this->test instanceof PHPUnit_Framework_TestSuite) {
$this->test->setRunTestInSeparateProcess($this->processIsolation);
}
$this->test->run($result);
}
return $result;
}
}
<?php
class PHPUnit_Extensions_TestDecorator extends PHPUnit_Framework_Assert implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing
{
protected $test = null;
public function __construct(PHPUnit_Framework_Test $test)
{
$this->test = $test;
}
public function toString()
{
return $this->test->toString();
}
public function basicRun(PHPUnit_Framework_TestResult $result)
{
$this->test->run($result);
}
public function count()
{
return count($this->test);
}
protected function createResult()
{
return new PHPUnit_Framework_TestResult;
}
public function getTest()
{
return $this->test;
}
public function run(PHPUnit_Framework_TestResult $result = null)
{
if ($result === null) {
$result = $this->createResult();
}
$this->basicRun($result);
return $result;
}
}
<?php
abstract class PHPUnit_Extensions_TicketListener implements PHPUnit_Framework_TestListener
{
protected $ticketCounts = [];
protected $ran = false;
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function startTest(PHPUnit_Framework_Test $test)
{
if (!$test instanceof PHPUnit_Framework_WarningTestCase) {
if ($this->ran) {
return;
}
$name = $test->getName(false);
$tickets = PHPUnit_Util_Test::getTickets(get_class($test), $name);
foreach ($tickets as $ticket) {
$this->ticketCounts[$ticket][$name] = 1;
}
$this->ran = true;
}
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if (!$test instanceof PHPUnit_Framework_WarningTestCase) {
if ($test->getStatus() == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) {
$ifStatus = ['assigned', 'new', 'reopened'];
$newStatus = 'closed';
$message = 'Automatically closed by PHPUnit (test passed).';
$resolution = 'fixed';
$cumulative = true;
} elseif ($test->getStatus() == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
$ifStatus = ['closed'];
$newStatus = 'reopened';
$message = 'Automatically reopened by PHPUnit (test failed).';
$resolution = '';
$cumulative = false;
} else {
return;
}
$name = $test->getName(false);
$tickets = PHPUnit_Util_Test::getTickets(get_class($test), $name);
foreach ($tickets as $ticket) {
if ($test->getStatus() == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) {
unset($this->ticketCounts[$ticket][$name]);
}
if ($cumulative) {
if (count($this->ticketCounts[$ticket]) > 0) {
$adjustTicket = false;
} else {
$adjustTicket = true;
}
} else {
$adjustTicket = true;
}
$ticketInfo = $this->getTicketInfo($ticket);
if ($adjustTicket && in_array($ticketInfo['status'], $ifStatus)) {
$this->updateTicket($ticket, $newStatus, $message, $resolution);
}
}
}
}
abstract protected function getTicketInfo($ticketId = null);
abstract protected function updateTicket($ticketId, $newStatus, $message, $resolution);
}
<?php
namespace PHPUnit\Framework;
use PHPUnit_Framework_TestCase;
class TestCase extends PHPUnit_Framework_TestCase
{
}
<?php
abstract class PHPUnit_Framework_Assert
{
private static $count = 0;
public static function assertArrayHasKey($key, $array, $message = '')
{
if (!(is_integer($key) || is_string($key))) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'integer or string'
);
}
if (!(is_array($array) || $array instanceof ArrayAccess)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array or ArrayAccess'
);
}
$constraint = new PHPUnit_Framework_Constraint_ArrayHasKey($key);
static::assertThat($array, $constraint, $message);
}
public static function assertArraySubset($subset, $array, $strict = false, $message = '')
{
if (!is_array($subset)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'array or ArrayAccess'
);
}
if (!is_array($array)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array or ArrayAccess'
);
}
$constraint = new PHPUnit_Framework_Constraint_ArraySubset($subset, $strict);
static::assertThat($array, $constraint, $message);
}
public static function assertArrayNotHasKey($key, $array, $message = '')
{
if (!(is_integer($key) || is_string($key))) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'integer or string'
);
}
if (!(is_array($array) || $array instanceof ArrayAccess)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array or ArrayAccess'
);
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_ArrayHasKey($key)
);
static::assertThat($array, $constraint, $message);
}
public static function assertContains($needle, $haystack, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
if (is_array($haystack) ||
is_object($haystack) && $haystack instanceof Traversable) {
$constraint = new PHPUnit_Framework_Constraint_TraversableContains(
$needle,
$checkForObjectIdentity,
$checkForNonObjectIdentity
);
} elseif (is_string($haystack)) {
if (!is_string($needle)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'string'
);
}
$constraint = new PHPUnit_Framework_Constraint_StringContains(
$needle,
$ignoreCase
);
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array, traversable or string'
);
}
static::assertThat($haystack, $constraint, $message);
}
public static function assertAttributeContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
static::assertContains(
$needle,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message,
$ignoreCase,
$checkForObjectIdentity,
$checkForNonObjectIdentity
);
}
public static function assertNotContains($needle, $haystack, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
if (is_array($haystack) ||
is_object($haystack) && $haystack instanceof Traversable) {
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_TraversableContains(
$needle,
$checkForObjectIdentity,
$checkForNonObjectIdentity
)
);
} elseif (is_string($haystack)) {
if (!is_string($needle)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'string'
);
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_StringContains(
$needle,
$ignoreCase
)
);
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array, traversable or string'
);
}
static::assertThat($haystack, $constraint, $message);
}
public static function assertAttributeNotContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
static::assertNotContains(
$needle,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message,
$ignoreCase,
$checkForObjectIdentity,
$checkForNonObjectIdentity
);
}
public static function assertContainsOnly($type, $haystack, $isNativeType = null, $message = '')
{
if (!(is_array($haystack) ||
is_object($haystack) && $haystack instanceof Traversable)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array or traversable'
);
}
if ($isNativeType == null) {
$isNativeType = PHPUnit_Util_Type::isType($type);
}
static::assertThat(
$haystack,
new PHPUnit_Framework_Constraint_TraversableContainsOnly(
$type,
$isNativeType
),
$message
);
}
public static function assertContainsOnlyInstancesOf($classname, $haystack, $message = '')
{
if (!(is_array($haystack) ||
is_object($haystack) && $haystack instanceof Traversable)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array or traversable'
);
}
static::assertThat(
$haystack,
new PHPUnit_Framework_Constraint_TraversableContainsOnly(
$classname,
false
),
$message
);
}
public static function assertAttributeContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = null, $message = '')
{
static::assertContainsOnly(
$type,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$isNativeType,
$message
);
}
public static function assertNotContainsOnly($type, $haystack, $isNativeType = null, $message = '')
{
if (!(is_array($haystack) ||
is_object($haystack) && $haystack instanceof Traversable)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
2,
'array or traversable'
);
}
if ($isNativeType == null) {
$isNativeType = PHPUnit_Util_Type::isType($type);
}
static::assertThat(
$haystack,
new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_TraversableContainsOnly(
$type,
$isNativeType
)
),
$message
);
}
public static function assertAttributeNotContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = null, $message = '')
{
static::assertNotContainsOnly(
$type,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$isNativeType,
$message
);
}
public static function assertCount($expectedCount, $haystack, $message = '')
{
if (!is_int($expectedCount)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'integer');
}
if (!$haystack instanceof Countable &&
!$haystack instanceof Traversable &&
!is_array($haystack)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'countable or traversable');
}
static::assertThat(
$haystack,
new PHPUnit_Framework_Constraint_Count($expectedCount),
$message
);
}
public static function assertAttributeCount($expectedCount, $haystackAttributeName, $haystackClassOrObject, $message = '')
{
static::assertCount(
$expectedCount,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
public static function assertNotCount($expectedCount, $haystack, $message = '')
{
if (!is_int($expectedCount)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'integer');
}
if (!$haystack instanceof Countable &&
!$haystack instanceof Traversable &&
!is_array($haystack)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'countable or traversable');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_Count($expectedCount)
);
static::assertThat($haystack, $constraint, $message);
}
public static function assertAttributeNotCount($expectedCount, $haystackAttributeName, $haystackClassOrObject, $message = '')
{
static::assertNotCount(
$expectedCount,
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
$constraint = new PHPUnit_Framework_Constraint_IsEqual(
$expected,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
static::assertThat($actual, $constraint, $message);
}
public static function assertAttributeEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
static::assertEquals(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
}
public static function assertNotEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_IsEqual(
$expected,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
)
);
static::assertThat($actual, $constraint, $message);
}
public static function assertAttributeNotEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
static::assertNotEquals(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
}
public static function assertEmpty($actual, $message = '')
{
static::assertThat($actual, static::isEmpty(), $message);
}
public static function assertAttributeEmpty($haystackAttributeName, $haystackClassOrObject, $message = '')
{
static::assertEmpty(
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
public static function assertNotEmpty($actual, $message = '')
{
static::assertThat($actual, static::logicalNot(static::isEmpty()), $message);
}
public static function assertAttributeNotEmpty($haystackAttributeName, $haystackClassOrObject, $message = '')
{
static::assertNotEmpty(
static::readAttribute($haystackClassOrObject, $haystackAttributeName),
$message
);
}
public static function assertGreaterThan($expected, $actual, $message = '')
{
static::assertThat($actual, static::greaterThan($expected), $message);
}
public static function assertAttributeGreaterThan($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
static::assertGreaterThan(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
public static function assertGreaterThanOrEqual($expected, $actual, $message = '')
{
static::assertThat(
$actual,
static::greaterThanOrEqual($expected),
$message
);
}
public static function assertAttributeGreaterThanOrEqual($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
static::assertGreaterThanOrEqual(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
public static function assertLessThan($expected, $actual, $message = '')
{
static::assertThat($actual, static::lessThan($expected), $message);
}
public static function assertAttributeLessThan($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
static::assertLessThan(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
public static function assertLessThanOrEqual($expected, $actual, $message = '')
{
static::assertThat($actual, static::lessThanOrEqual($expected), $message);
}
public static function assertAttributeLessThanOrEqual($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
static::assertLessThanOrEqual(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
public static function assertFileEquals($expected, $actual, $message = '', $canonicalize = false, $ignoreCase = false)
{
static::assertFileExists($expected, $message);
static::assertFileExists($actual, $message);
static::assertEquals(
file_get_contents($expected),
file_get_contents($actual),
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
public static function assertFileNotEquals($expected, $actual, $message = '', $canonicalize = false, $ignoreCase = false)
{
static::assertFileExists($expected, $message);
static::assertFileExists($actual, $message);
static::assertNotEquals(
file_get_contents($expected),
file_get_contents($actual),
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
public static function assertStringEqualsFile($expectedFile, $actualString, $message = '', $canonicalize = false, $ignoreCase = false)
{
static::assertFileExists($expectedFile, $message);
static::assertEquals(
file_get_contents($expectedFile),
$actualString,
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
public static function assertStringNotEqualsFile($expectedFile, $actualString, $message = '', $canonicalize = false, $ignoreCase = false)
{
static::assertFileExists($expectedFile, $message);
static::assertNotEquals(
file_get_contents($expectedFile),
$actualString,
$message,
0,
10,
$canonicalize,
$ignoreCase
);
}
public static function assertFileExists($filename, $message = '')
{
if (!is_string($filename)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_FileExists;
static::assertThat($filename, $constraint, $message);
}
public static function assertFileNotExists($filename, $message = '')
{
if (!is_string($filename)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_FileExists
);
static::assertThat($filename, $constraint, $message);
}
public static function assertTrue($condition, $message = '')
{
static::assertThat($condition, static::isTrue(), $message);
}
public static function assertNotTrue($condition, $message = '')
{
static::assertThat($condition, static::logicalNot(static::isTrue()), $message);
}
public static function assertFalse($condition, $message = '')
{
static::assertThat($condition, static::isFalse(), $message);
}
public static function assertNotFalse($condition, $message = '')
{
static::assertThat($condition, static::logicalNot(static::isFalse()), $message);
}
public static function assertNull($actual, $message = '')
{
static::assertThat($actual, static::isNull(), $message);
}
public static function assertNotNull($actual, $message = '')
{
static::assertThat($actual, static::logicalNot(static::isNull()), $message);
}
public static function assertFinite($actual, $message = '')
{
static::assertThat($actual, static::isFinite(), $message);
}
public static function assertInfinite($actual, $message = '')
{
static::assertThat($actual, static::isInfinite(), $message);
}
public static function assertNan($actual, $message = '')
{
static::assertThat($actual, static::isNan(), $message);
}
public static function assertClassHasAttribute($attributeName, $className, $message = '')
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!is_string($className) || !class_exists($className)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name', $className);
}
$constraint = new PHPUnit_Framework_Constraint_ClassHasAttribute(
$attributeName
);
static::assertThat($className, $constraint, $message);
}
public static function assertClassNotHasAttribute($attributeName, $className, $message = '')
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!is_string($className) || !class_exists($className)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name', $className);
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_ClassHasAttribute($attributeName)
);
static::assertThat($className, $constraint, $message);
}
public static function assertClassHasStaticAttribute($attributeName, $className, $message = '')
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!is_string($className) || !class_exists($className)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name', $className);
}
$constraint = new PHPUnit_Framework_Constraint_ClassHasStaticAttribute(
$attributeName
);
static::assertThat($className, $constraint, $message);
}
public static function assertClassNotHasStaticAttribute($attributeName, $className, $message = '')
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!is_string($className) || !class_exists($className)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name', $className);
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_ClassHasStaticAttribute(
$attributeName
)
);
static::assertThat($className, $constraint, $message);
}
public static function assertObjectHasAttribute($attributeName, $object, $message = '')
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!is_object($object)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'object');
}
$constraint = new PHPUnit_Framework_Constraint_ObjectHasAttribute(
$attributeName
);
static::assertThat($object, $constraint, $message);
}
public static function assertObjectNotHasAttribute($attributeName, $object, $message = '')
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'valid attribute name');
}
if (!is_object($object)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'object');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_ObjectHasAttribute($attributeName)
);
static::assertThat($object, $constraint, $message);
}
public static function assertSame($expected, $actual, $message = '')
{
if (is_bool($expected) && is_bool($actual)) {
static::assertEquals($expected, $actual, $message);
} else {
$constraint = new PHPUnit_Framework_Constraint_IsIdentical(
$expected
);
static::assertThat($actual, $constraint, $message);
}
}
public static function assertAttributeSame($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
static::assertSame(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
public static function assertNotSame($expected, $actual, $message = '')
{
if (is_bool($expected) && is_bool($actual)) {
static::assertNotEquals($expected, $actual, $message);
} else {
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_IsIdentical($expected)
);
static::assertThat($actual, $constraint, $message);
}
}
public static function assertAttributeNotSame($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
static::assertNotSame(
$expected,
static::readAttribute($actualClassOrObject, $actualAttributeName),
$message
);
}
public static function assertInstanceOf($expected, $actual, $message = '')
{
if (!(is_string($expected) && (class_exists($expected) || interface_exists($expected)))) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'class or interface name');
}
$constraint = new PHPUnit_Framework_Constraint_IsInstanceOf(
$expected
);
static::assertThat($actual, $constraint, $message);
}
public static function assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
static::assertInstanceOf(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
public static function assertNotInstanceOf($expected, $actual, $message = '')
{
if (!(is_string($expected) && (class_exists($expected) || interface_exists($expected)))) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'class or interface name');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_IsInstanceOf($expected)
);
static::assertThat($actual, $constraint, $message);
}
public static function assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
static::assertNotInstanceOf(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
public static function assertInternalType($expected, $actual, $message = '')
{
if (!is_string($expected)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_IsType(
$expected
);
static::assertThat($actual, $constraint, $message);
}
public static function assertAttributeInternalType($expected, $attributeName, $classOrObject, $message = '')
{
static::assertInternalType(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
public static function assertNotInternalType($expected, $actual, $message = '')
{
if (!is_string($expected)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_IsType($expected)
);
static::assertThat($actual, $constraint, $message);
}
public static function assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message = '')
{
static::assertNotInternalType(
$expected,
static::readAttribute($classOrObject, $attributeName),
$message
);
}
public static function assertRegExp($pattern, $string, $message = '')
{
if (!is_string($pattern)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_PCREMatch($pattern);
static::assertThat($string, $constraint, $message);
}
public static function assertNotRegExp($pattern, $string, $message = '')
{
if (!is_string($pattern)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_PCREMatch($pattern)
);
static::assertThat($string, $constraint, $message);
}
public static function assertSameSize($expected, $actual, $message = '')
{
if (!$expected instanceof Countable &&
!$expected instanceof Traversable &&
!is_array($expected)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'countable or traversable');
}
if (!$actual instanceof Countable &&
!$actual instanceof Traversable &&
!is_array($actual)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'countable or traversable');
}
static::assertThat(
$actual,
new PHPUnit_Framework_Constraint_SameSize($expected),
$message
);
}
public static function assertNotSameSize($expected, $actual, $message = '')
{
if (!$expected instanceof Countable &&
!$expected instanceof Traversable &&
!is_array($expected)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'countable or traversable');
}
if (!$actual instanceof Countable &&
!$actual instanceof Traversable &&
!is_array($actual)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'countable or traversable');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_SameSize($expected)
);
static::assertThat($actual, $constraint, $message);
}
public static function assertStringMatchesFormat($format, $string, $message = '')
{
if (!is_string($format)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_StringMatches($format);
static::assertThat($string, $constraint, $message);
}
public static function assertStringNotMatchesFormat($format, $string, $message = '')
{
if (!is_string($format)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_StringMatches($format)
);
static::assertThat($string, $constraint, $message);
}
public static function assertStringMatchesFormatFile($formatFile, $string, $message = '')
{
static::assertFileExists($formatFile, $message);
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_StringMatches(
file_get_contents($formatFile)
);
static::assertThat($string, $constraint, $message);
}
public static function assertStringNotMatchesFormatFile($formatFile, $string, $message = '')
{
static::assertFileExists($formatFile, $message);
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_StringMatches(
file_get_contents($formatFile)
)
);
static::assertThat($string, $constraint, $message);
}
public static function assertStringStartsWith($prefix, $string, $message = '')
{
if (!is_string($prefix)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_StringStartsWith(
$prefix
);
static::assertThat($string, $constraint, $message);
}
public static function assertStringStartsNotWith($prefix, $string, $message = '')
{
if (!is_string($prefix)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_StringStartsWith($prefix)
);
static::assertThat($string, $constraint, $message);
}
public static function assertStringEndsWith($suffix, $string, $message = '')
{
if (!is_string($suffix)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_StringEndsWith($suffix);
static::assertThat($string, $constraint, $message);
}
public static function assertStringEndsNotWith($suffix, $string, $message = '')
{
if (!is_string($suffix)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!is_string($string)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_Not(
new PHPUnit_Framework_Constraint_StringEndsWith($suffix)
);
static::assertThat($string, $constraint, $message);
}
public static function assertXmlFileEqualsXmlFile($expectedFile, $actualFile, $message = '')
{
$expected = PHPUnit_Util_XML::loadFile($expectedFile);
$actual = PHPUnit_Util_XML::loadFile($actualFile);
static::assertEquals($expected, $actual, $message);
}
public static function assertXmlFileNotEqualsXmlFile($expectedFile, $actualFile, $message = '')
{
$expected = PHPUnit_Util_XML::loadFile($expectedFile);
$actual = PHPUnit_Util_XML::loadFile($actualFile);
static::assertNotEquals($expected, $actual, $message);
}
public static function assertXmlStringEqualsXmlFile($expectedFile, $actualXml, $message = '')
{
$expected = PHPUnit_Util_XML::loadFile($expectedFile);
$actual = PHPUnit_Util_XML::load($actualXml);
static::assertEquals($expected, $actual, $message);
}
public static function assertXmlStringNotEqualsXmlFile($expectedFile, $actualXml, $message = '')
{
$expected = PHPUnit_Util_XML::loadFile($expectedFile);
$actual = PHPUnit_Util_XML::load($actualXml);
static::assertNotEquals($expected, $actual, $message);
}
public static function assertXmlStringEqualsXmlString($expectedXml, $actualXml, $message = '')
{
$expected = PHPUnit_Util_XML::load($expectedXml);
$actual = PHPUnit_Util_XML::load($actualXml);
static::assertEquals($expected, $actual, $message);
}
public static function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, $message = '')
{
$expected = PHPUnit_Util_XML::load($expectedXml);
$actual = PHPUnit_Util_XML::load($actualXml);
static::assertNotEquals($expected, $actual, $message);
}
public static function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, $checkAttributes = false, $message = '')
{
$tmp = new DOMDocument;
$expectedElement = $tmp->importNode($expectedElement, true);
$tmp = new DOMDocument;
$actualElement = $tmp->importNode($actualElement, true);
unset($tmp);
static::assertEquals(
$expectedElement->tagName,
$actualElement->tagName,
$message
);
if ($checkAttributes) {
static::assertEquals(
$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
);
if (!$actualAttribute) {
static::fail(
sprintf(
'%s%sCould not find attribute "%s" on node "%s"',
$message,
!empty($message) ? "\n" : '',
$expectedAttribute->name,
$expectedElement->tagName
)
);
}
}
}
PHPUnit_Util_XML::removeCharacterDataNodes($expectedElement);
PHPUnit_Util_XML::removeCharacterDataNodes($actualElement);
static::assertEquals(
$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
);
}
}
public static function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '')
{
self::$count += count($constraint);
$constraint->evaluate($value, $message);
}
public static function assertJson($actualJson, $message = '')
{
if (!is_string($actualJson)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
static::assertThat($actualJson, static::isJson(), $message);
}
public static function assertJsonStringEqualsJsonString($expectedJson, $actualJson, $message = '')
{
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
$expected = json_decode($expectedJson);
$actual = json_decode($actualJson);
static::assertEquals($expected, $actual, $message);
}
public static function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, $message = '')
{
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
$expected = json_decode($expectedJson);
$actual = json_decode($actualJson);
static::assertNotEquals($expected, $actual, $message);
}
public static function assertJsonStringEqualsJsonFile($expectedFile, $actualJson, $message = '')
{
static::assertFileExists($expectedFile, $message);
$expectedJson = file_get_contents($expectedFile);
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
$constraint = new PHPUnit_Framework_Constraint_JsonMatches(
$expectedJson
);
static::assertThat($actualJson, $constraint, $message);
}
public static function assertJsonStringNotEqualsJsonFile($expectedFile, $actualJson, $message = '')
{
static::assertFileExists($expectedFile, $message);
$expectedJson = file_get_contents($expectedFile);
static::assertJson($expectedJson, $message);
static::assertJson($actualJson, $message);
$constraint = new PHPUnit_Framework_Constraint_JsonMatches(
$expectedJson
);
static::assertThat($actualJson, new PHPUnit_Framework_Constraint_Not($constraint), $message);
}
public static function assertJsonFileEqualsJsonFile($expectedFile, $actualFile, $message = '')
{
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 PHPUnit_Framework_Constraint_JsonMatches(
$expectedJson
);
$constraintActual = new PHPUnit_Framework_Constraint_JsonMatches($actualJson);
static::assertThat($expectedJson, $constraintActual, $message);
static::assertThat($actualJson, $constraintExpected, $message);
}
public static function assertJsonFileNotEqualsJsonFile($expectedFile, $actualFile, $message = '')
{
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 PHPUnit_Framework_Constraint_JsonMatches(
$expectedJson
);
$constraintActual = new PHPUnit_Framework_Constraint_JsonMatches($actualJson);
static::assertThat($expectedJson, new PHPUnit_Framework_Constraint_Not($constraintActual), $message);
static::assertThat($actualJson, new PHPUnit_Framework_Constraint_Not($constraintExpected), $message);
}
public static function logicalAnd()
{
$constraints = func_get_args();
$constraint = new PHPUnit_Framework_Constraint_And;
$constraint->setConstraints($constraints);
return $constraint;
}
public static function logicalOr()
{
$constraints = func_get_args();
$constraint = new PHPUnit_Framework_Constraint_Or;
$constraint->setConstraints($constraints);
return $constraint;
}
public static function logicalNot(PHPUnit_Framework_Constraint $constraint)
{
return new PHPUnit_Framework_Constraint_Not($constraint);
}
public static function logicalXor()
{
$constraints = func_get_args();
$constraint = new PHPUnit_Framework_Constraint_Xor;
$constraint->setConstraints($constraints);
return $constraint;
}
public static function anything()
{
return new PHPUnit_Framework_Constraint_IsAnything;
}
public static function isTrue()
{
return new PHPUnit_Framework_Constraint_IsTrue;
}
public static function callback($callback)
{
return new PHPUnit_Framework_Constraint_Callback($callback);
}
public static function isFalse()
{
return new PHPUnit_Framework_Constraint_IsFalse;
}
public static function isJson()
{
return new PHPUnit_Framework_Constraint_IsJson;
}
public static function isNull()
{
return new PHPUnit_Framework_Constraint_IsNull;
}
public static function isFinite()
{
return new PHPUnit_Framework_Constraint_IsFinite;
}
public static function isInfinite()
{
return new PHPUnit_Framework_Constraint_IsInfinite;
}
public static function isNan()
{
return new PHPUnit_Framework_Constraint_IsNan;
}
public static function attribute(PHPUnit_Framework_Constraint $constraint, $attributeName)
{
return new PHPUnit_Framework_Constraint_Attribute(
$constraint,
$attributeName
);
}
public static function contains($value, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return new PHPUnit_Framework_Constraint_TraversableContains($value, $checkForObjectIdentity, $checkForNonObjectIdentity);
}
public static function containsOnly($type)
{
return new PHPUnit_Framework_Constraint_TraversableContainsOnly($type);
}
public static function containsOnlyInstancesOf($classname)
{
return new PHPUnit_Framework_Constraint_TraversableContainsOnly($classname, false);
}
public static function arrayHasKey($key)
{
return new PHPUnit_Framework_Constraint_ArrayHasKey($key);
}
public static function equalTo($value, $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return new PHPUnit_Framework_Constraint_IsEqual(
$value,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
);
}
public static function attributeEqualTo($attributeName, $value, $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return static::attribute(
static::equalTo(
$value,
$delta,
$maxDepth,
$canonicalize,
$ignoreCase
),
$attributeName
);
}
public static function isEmpty()
{
return new PHPUnit_Framework_Constraint_IsEmpty;
}
public static function fileExists()
{
return new PHPUnit_Framework_Constraint_FileExists;
}
public static function greaterThan($value)
{
return new PHPUnit_Framework_Constraint_GreaterThan($value);
}
public static function greaterThanOrEqual($value)
{
return static::logicalOr(
new PHPUnit_Framework_Constraint_IsEqual($value),
new PHPUnit_Framework_Constraint_GreaterThan($value)
);
}
public static function classHasAttribute($attributeName)
{
return new PHPUnit_Framework_Constraint_ClassHasAttribute(
$attributeName
);
}
public static function classHasStaticAttribute($attributeName)
{
return new PHPUnit_Framework_Constraint_ClassHasStaticAttribute(
$attributeName
);
}
public static function objectHasAttribute($attributeName)
{
return new PHPUnit_Framework_Constraint_ObjectHasAttribute(
$attributeName
);
}
public static function identicalTo($value)
{
return new PHPUnit_Framework_Constraint_IsIdentical($value);
}
public static function isInstanceOf($className)
{
return new PHPUnit_Framework_Constraint_IsInstanceOf($className);
}
public static function isType($type)
{
return new PHPUnit_Framework_Constraint_IsType($type);
}
public static function lessThan($value)
{
return new PHPUnit_Framework_Constraint_LessThan($value);
}
public static function lessThanOrEqual($value)
{
return static::logicalOr(
new PHPUnit_Framework_Constraint_IsEqual($value),
new PHPUnit_Framework_Constraint_LessThan($value)
);
}
public static function matchesRegularExpression($pattern)
{
return new PHPUnit_Framework_Constraint_PCREMatch($pattern);
}
public static function matches($string)
{
return new PHPUnit_Framework_Constraint_StringMatches($string);
}
public static function stringStartsWith($prefix)
{
return new PHPUnit_Framework_Constraint_StringStartsWith($prefix);
}
public static function stringContains($string, $case = true)
{
return new PHPUnit_Framework_Constraint_StringContains($string, $case);
}
public static function stringEndsWith($suffix)
{
return new PHPUnit_Framework_Constraint_StringEndsWith($suffix);
}
public static function countOf($count)
{
return new PHPUnit_Framework_Constraint_Count($count);
}
public static function fail($message = '')
{
throw new PHPUnit_Framework_AssertionFailedError($message);
}
public static function readAttribute($classOrObject, $attributeName)
{
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'valid attribute name');
}
if (is_string($classOrObject)) {
if (!class_exists($classOrObject)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'class name'
);
}
return static::getStaticAttribute(
$classOrObject,
$attributeName
);
} elseif (is_object($classOrObject)) {
return static::getObjectAttribute(
$classOrObject,
$attributeName
);
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'class name or object'
);
}
}
public static function getStaticAttribute($className, $attributeName)
{
if (!is_string($className)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (!class_exists($className)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'class name');
}
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'valid attribute name');
}
$class = new ReflectionClass($className);
while ($class) {
$attributes = $class->getStaticProperties();
if (array_key_exists($attributeName, $attributes)) {
return $attributes[$attributeName];
}
$class = $class->getParentClass();
}
throw new PHPUnit_Framework_Exception(
sprintf(
'Attribute "%s" not found in class.',
$attributeName
)
);
}
public static function getObjectAttribute($object, $attributeName)
{
if (!is_object($object)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'object');
}
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
if (!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'valid attribute name');
}
try {
$attribute = new ReflectionProperty($object, $attributeName);
} catch (ReflectionException $e) {
$reflector = new ReflectionObject($object);
while ($reflector = $reflector->getParentClass()) {
try {
$attribute = $reflector->getProperty($attributeName);
break;
} catch (ReflectionException $e) {
}
}
}
if (isset($attribute)) {
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
$attribute->setAccessible(true);
$value = $attribute->getValue($object);
$attribute->setAccessible(false);
return $value;
}
throw new PHPUnit_Framework_Exception(
sprintf(
'Attribute "%s" not found in object.',
$attributeName
)
);
}
public static function markTestIncomplete($message = '')
{
throw new PHPUnit_Framework_IncompleteTestError($message);
}
public static function markTestSkipped($message = '')
{
throw new PHPUnit_Framework_SkippedTestError($message);
}
public static function getCount()
{
return self::$count;
}
public static function resetCount()
{
self::$count = 0;
}
}
<?php
function any()
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::any',
func_get_args()
);
}
function anything()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::anything',
func_get_args()
);
}
function arrayHasKey($key)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::arrayHasKey',
func_get_args()
);
}
function assertArrayHasKey($key, $array, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertArrayHasKey',
func_get_args()
);
}
function assertArraySubset($subset, $array, $strict = false, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertArraySubset',
func_get_args()
);
}
function assertArrayNotHasKey($key, $array, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertArrayNotHasKey',
func_get_args()
);
}
function assertAttributeContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeContains',
func_get_args()
);
}
function assertAttributeContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = null, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeContainsOnly',
func_get_args()
);
}
function assertAttributeCount($expectedCount, $haystackAttributeName, $haystackClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeCount',
func_get_args()
);
}
function assertAttributeEmpty($haystackAttributeName, $haystackClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeEmpty',
func_get_args()
);
}
function assertAttributeEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeEquals',
func_get_args()
);
}
function assertAttributeGreaterThan($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeGreaterThan',
func_get_args()
);
}
function assertAttributeGreaterThanOrEqual($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeGreaterThanOrEqual',
func_get_args()
);
}
function assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeInstanceOf',
func_get_args()
);
}
function assertAttributeInternalType($expected, $attributeName, $classOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeInternalType',
func_get_args()
);
}
function assertAttributeLessThan($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeLessThan',
func_get_args()
);
}
function assertAttributeLessThanOrEqual($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeLessThanOrEqual',
func_get_args()
);
}
function assertAttributeNotContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotContains',
func_get_args()
);
}
function assertAttributeNotContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = null, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotContainsOnly',
func_get_args()
);
}
function assertAttributeNotCount($expectedCount, $haystackAttributeName, $haystackClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotCount',
func_get_args()
);
}
function assertAttributeNotEmpty($haystackAttributeName, $haystackClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotEmpty',
func_get_args()
);
}
function assertAttributeNotEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotEquals',
func_get_args()
);
}
function assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotInstanceOf',
func_get_args()
);
}
function assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotInternalType',
func_get_args()
);
}
function assertAttributeNotSame($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeNotSame',
func_get_args()
);
}
function assertAttributeSame($expected, $actualAttributeName, $actualClassOrObject, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeSame',
func_get_args()
);
}
function assertClassHasAttribute($attributeName, $className, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertClassHasAttribute',
func_get_args()
);
}
function assertClassHasStaticAttribute($attributeName, $className, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertClassHasStaticAttribute',
func_get_args()
);
}
function assertClassNotHasAttribute($attributeName, $className, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertClassNotHasAttribute',
func_get_args()
);
}
function assertClassNotHasStaticAttribute($attributeName, $className, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertClassNotHasStaticAttribute',
func_get_args()
);
}
function assertContains($needle, $haystack, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertContains',
func_get_args()
);
}
function assertContainsOnly($type, $haystack, $isNativeType = null, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertContainsOnly',
func_get_args()
);
}
function assertContainsOnlyInstancesOf($classname, $haystack, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertContainsOnlyInstancesOf',
func_get_args()
);
}
function assertCount($expectedCount, $haystack, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertCount',
func_get_args()
);
}
function assertEmpty($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertEmpty',
func_get_args()
);
}
function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, $checkAttributes = false, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertEqualXMLStructure',
func_get_args()
);
}
function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertEquals',
func_get_args()
);
}
function assertNotTrue($condition, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotTrue',
func_get_args()
);
}
function assertFalse($condition, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertFalse',
func_get_args()
);
}
function assertFileEquals($expected, $actual, $message = '', $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertFileEquals',
func_get_args()
);
}
function assertFileExists($filename, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertFileExists',
func_get_args()
);
}
function assertFileNotEquals($expected, $actual, $message = '', $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertFileNotEquals',
func_get_args()
);
}
function assertFileNotExists($filename, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertFileNotExists',
func_get_args()
);
}
function assertGreaterThan($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertGreaterThan',
func_get_args()
);
}
function assertGreaterThanOrEqual($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertGreaterThanOrEqual',
func_get_args()
);
}
function assertInstanceOf($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertInstanceOf',
func_get_args()
);
}
function assertInternalType($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertInternalType',
func_get_args()
);
}
function assertJson($actualJson, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJson',
func_get_args()
);
}
function assertJsonFileEqualsJsonFile($expectedFile, $actualFile, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJsonFileEqualsJsonFile',
func_get_args()
);
}
function assertJsonFileNotEqualsJsonFile($expectedFile, $actualFile, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJsonFileNotEqualsJsonFile',
func_get_args()
);
}
function assertJsonStringEqualsJsonFile($expectedFile, $actualJson, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJsonStringEqualsJsonFile',
func_get_args()
);
}
function assertJsonStringEqualsJsonString($expectedJson, $actualJson, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJsonStringEqualsJsonString',
func_get_args()
);
}
function assertJsonStringNotEqualsJsonFile($expectedFile, $actualJson, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJsonStringNotEqualsJsonFile',
func_get_args()
);
}
function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertJsonStringNotEqualsJsonString',
func_get_args()
);
}
function assertLessThan($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertLessThan',
func_get_args()
);
}
function assertLessThanOrEqual($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertLessThanOrEqual',
func_get_args()
);
}
function assertFinite($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertFinite',
func_get_args()
);
}
function assertInfinite($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertInfinite',
func_get_args()
);
}
function assertNan($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNan',
func_get_args()
);
}
function assertNotContains($needle, $haystack, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotContains',
func_get_args()
);
}
function assertNotContainsOnly($type, $haystack, $isNativeType = null, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotContainsOnly',
func_get_args()
);
}
function assertNotCount($expectedCount, $haystack, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotCount',
func_get_args()
);
}
function assertNotEmpty($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotEmpty',
func_get_args()
);
}
function assertNotEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotEquals',
func_get_args()
);
}
function assertNotInstanceOf($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotInstanceOf',
func_get_args()
);
}
function assertNotInternalType($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotInternalType',
func_get_args()
);
}
function assertNotFalse($condition, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotFalse',
func_get_args()
);
}
function assertNotNull($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotNull',
func_get_args()
);
}
function assertNotRegExp($pattern, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotRegExp',
func_get_args()
);
}
function assertNotSame($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotSame',
func_get_args()
);
}
function assertNotSameSize($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNotSameSize',
func_get_args()
);
}
function assertNull($actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertNull',
func_get_args()
);
}
function assertObjectHasAttribute($attributeName, $object, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertObjectHasAttribute',
func_get_args()
);
}
function assertObjectNotHasAttribute($attributeName, $object, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertObjectNotHasAttribute',
func_get_args()
);
}
function assertRegExp($pattern, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertRegExp',
func_get_args()
);
}
function assertSame($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertSame',
func_get_args()
);
}
function assertSameSize($expected, $actual, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertSameSize',
func_get_args()
);
}
function assertStringEndsNotWith($suffix, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringEndsNotWith',
func_get_args()
);
}
function assertStringEndsWith($suffix, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringEndsWith',
func_get_args()
);
}
function assertStringEqualsFile($expectedFile, $actualString, $message = '', $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringEqualsFile',
func_get_args()
);
}
function assertStringMatchesFormat($format, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringMatchesFormat',
func_get_args()
);
}
function assertStringMatchesFormatFile($formatFile, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringMatchesFormatFile',
func_get_args()
);
}
function assertStringNotEqualsFile($expectedFile, $actualString, $message = '', $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringNotEqualsFile',
func_get_args()
);
}
function assertStringNotMatchesFormat($format, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringNotMatchesFormat',
func_get_args()
);
}
function assertStringNotMatchesFormatFile($formatFile, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringNotMatchesFormatFile',
func_get_args()
);
}
function assertStringStartsNotWith($prefix, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringStartsNotWith',
func_get_args()
);
}
function assertStringStartsWith($prefix, $string, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertStringStartsWith',
func_get_args()
);
}
function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertThat',
func_get_args()
);
}
function assertTrue($condition, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertTrue',
func_get_args()
);
}
function assertXmlFileEqualsXmlFile($expectedFile, $actualFile, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertXmlFileEqualsXmlFile',
func_get_args()
);
}
function assertXmlFileNotEqualsXmlFile($expectedFile, $actualFile, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertXmlFileNotEqualsXmlFile',
func_get_args()
);
}
function assertXmlStringEqualsXmlFile($expectedFile, $actualXml, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertXmlStringEqualsXmlFile',
func_get_args()
);
}
function assertXmlStringEqualsXmlString($expectedXml, $actualXml, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertXmlStringEqualsXmlString',
func_get_args()
);
}
function assertXmlStringNotEqualsXmlFile($expectedFile, $actualXml, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertXmlStringNotEqualsXmlFile',
func_get_args()
);
}
function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, $message = '')
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertXmlStringNotEqualsXmlString',
func_get_args()
);
}
function at($index)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::at',
func_get_args()
);
}
function atLeastOnce()
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::atLeastOnce',
func_get_args()
);
}
function attribute(PHPUnit_Framework_Constraint $constraint, $attributeName)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::attribute',
func_get_args()
);
}
function attributeEqualTo($attributeName, $value, $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::attributeEqualTo',
func_get_args()
);
}
function callback($callback)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::callback',
func_get_args()
);
}
function classHasAttribute($attributeName)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::classHasAttribute',
func_get_args()
);
}
function classHasStaticAttribute($attributeName)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::classHasStaticAttribute',
func_get_args()
);
}
function contains($value, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::contains',
func_get_args()
);
}
function containsOnly($type)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::containsOnly',
func_get_args()
);
}
function containsOnlyInstancesOf($classname)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::containsOnlyInstancesOf',
func_get_args()
);
}
function equalTo($value, $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::equalTo',
func_get_args()
);
}
function exactly($count)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::exactly',
func_get_args()
);
}
function fileExists()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::fileExists',
func_get_args()
);
}
function greaterThan($value)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::greaterThan',
func_get_args()
);
}
function greaterThanOrEqual($value)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::greaterThanOrEqual',
func_get_args()
);
}
function identicalTo($value)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::identicalTo',
func_get_args()
);
}
function isEmpty()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isEmpty',
func_get_args()
);
}
function isFalse()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isFalse',
func_get_args()
);
}
function isInstanceOf($className)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isInstanceOf',
func_get_args()
);
}
function isJson()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isJson',
func_get_args()
);
}
function isNull()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isNull',
func_get_args()
);
}
function isTrue()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isTrue',
func_get_args()
);
}
function isType($type)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::isType',
func_get_args()
);
}
function lessThan($value)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::lessThan',
func_get_args()
);
}
function lessThanOrEqual($value)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::lessThanOrEqual',
func_get_args()
);
}
function logicalAnd()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::logicalAnd',
func_get_args()
);
}
function logicalNot(PHPUnit_Framework_Constraint $constraint)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::logicalNot',
func_get_args()
);
}
function logicalOr()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::logicalOr',
func_get_args()
);
}
function logicalXor()
{
return call_user_func_array(
'PHPUnit_Framework_Assert::logicalXor',
func_get_args()
);
}
function matches($string)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::matches',
func_get_args()
);
}
function matchesRegularExpression($pattern)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::matchesRegularExpression',
func_get_args()
);
}
function never()
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::never',
func_get_args()
);
}
function objectHasAttribute($attributeName)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::objectHasAttribute',
func_get_args()
);
}
function onConsecutiveCalls()
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::onConsecutiveCalls',
func_get_args()
);
}
function once()
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::once',
func_get_args()
);
}
function returnArgument($argumentIndex)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::returnArgument',
func_get_args()
);
}
function returnCallback($callback)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::returnCallback',
func_get_args()
);
}
function returnSelf()
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::returnSelf',
func_get_args()
);
}
function returnValue($value)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::returnValue',
func_get_args()
);
}
function returnValueMap(array $valueMap)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::returnValueMap',
func_get_args()
);
}
function stringContains($string, $case = true)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::stringContains',
func_get_args()
);
}
function stringEndsWith($suffix)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::stringEndsWith',
func_get_args()
);
}
function stringStartsWith($prefix)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::stringStartsWith',
func_get_args()
);
}
function throwException(Exception $exception)
{
return call_user_func_array(
'PHPUnit_Framework_TestCase::throwException',
func_get_args()
);
}
<?php
class PHPUnit_Framework_AssertionFailedError extends PHPUnit_Framework_Exception implements PHPUnit_Framework_SelfDescribing
{
public function toString()
{
return $this->getMessage();
}
}
<?php
abstract class PHPUnit_Framework_BaseTestListener implements PHPUnit_Framework_TestListener
{
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function startTest(PHPUnit_Framework_Test $test)
{
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
}
}
<?php
class PHPUnit_Framework_CodeCoverageException extends PHPUnit_Framework_Exception
{
}
<?php
use SebastianBergmann\Exporter\Exporter;
abstract class PHPUnit_Framework_Constraint implements Countable, PHPUnit_Framework_SelfDescribing
{
protected $exporter;
public function __construct()
{
$this->exporter = new Exporter;
}
public function evaluate($other, $description = '', $returnResult = false)
{
$success = false;
if ($this->matches($other)) {
$success = true;
}
if ($returnResult) {
return $success;
}
if (!$success) {
$this->fail($other, $description);
}
}
protected function matches($other)
{
return false;
}
public function count()
{
return 1;
}
protected function fail($other, $description, SebastianBergmann\Comparator\ComparisonFailure $comparisonFailure = null)
{
$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 PHPUnit_Framework_ExpectationFailedException(
$failureDescription,
$comparisonFailure
);
}
protected function additionalFailureDescription($other)
{
return '';
}
protected function failureDescription($other)
{
return $this->exporter->export($other) . ' ' . $this->toString();
}
}
<?php
class PHPUnit_Framework_Constraint_And extends PHPUnit_Framework_Constraint
{
protected $constraints = [];
protected $lastConstraint = null;
public function setConstraints(array $constraints)
{
$this->constraints = [];
foreach ($constraints as $constraint) {
if (!($constraint instanceof PHPUnit_Framework_Constraint)) {
throw new PHPUnit_Framework_Exception(
'All parameters to ' . __CLASS__ .
' must be a constraint object.'
);
}
$this->constraints[] = $constraint;
}
}
public function evaluate($other, $description = '', $returnResult = false)
{
$success = true;
$constraint = null;
foreach ($this->constraints as $constraint) {
if (!$constraint->evaluate($other, $description, true)) {
$success = false;
break;
}
}
if ($returnResult) {
return $success;
}
if (!$success) {
$this->fail($other, $description);
}
}
public function toString()
{
$text = '';
foreach ($this->constraints as $key => $constraint) {
if ($key > 0) {
$text .= ' and ';
}
$text .= $constraint->toString();
}
return $text;
}
public function count()
{
$count = 0;
foreach ($this->constraints as $constraint) {
$count += count($constraint);
}
return $count;
}
}
<?php
class PHPUnit_Framework_Constraint_ArrayHasKey extends PHPUnit_Framework_Constraint
{
protected $key;
public function __construct($key)
{
parent::__construct();
$this->key = $key;
}
protected function matches($other)
{
if (is_array($other)) {
return array_key_exists($this->key, $other);
}
if ($other instanceof ArrayAccess) {
return $other->offsetExists($this->key);
}
return false;
}
public function toString()
{
return 'has the key ' . $this->exporter->export($this->key);
}
protected function failureDescription($other)
{
return 'an array ' . $this->toString();
}
}
<?php
class PHPUnit_Framework_Constraint_ArraySubset extends PHPUnit_Framework_Constraint
{
protected $subset;
protected $strict;
public function __construct($subset, $strict = false)
{
parent::__construct();
$this->strict = $strict;
$this->subset = $subset;
}
protected function matches($other)
{
$patched = array_replace_recursive($other, $this->subset);
if ($this->strict) {
return $other === $patched;
} else {
return $other == $patched;
}
}
public function toString()
{
return 'has the subset ' . $this->exporter->export($this->subset);
}
protected function failureDescription($other)
{
return 'an array ' . $this->toString();
}
}
<?php
class PHPUnit_Framework_Constraint_Attribute extends PHPUnit_Framework_Constraint_Composite
{
protected $attributeName;
public function __construct(PHPUnit_Framework_Constraint $constraint, $attributeName)
{
parent::__construct($constraint);
$this->attributeName = $attributeName;
}
public function evaluate($other, $description = '', $returnResult = false)
{
return parent::evaluate(
PHPUnit_Framework_Assert::readAttribute(
$other,
$this->attributeName
),
$description,
$returnResult
);
}
public function toString()
{
return 'attribute "' . $this->attributeName . '" ' .
$this->innerConstraint->toString();
}
protected function failureDescription($other)
{
return $this->toString();
}
}
<?php
class PHPUnit_Framework_Constraint_Callback extends PHPUnit_Framework_Constraint
{
private $callback;
public function __construct($callback)
{
if (!is_callable($callback)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'callable'
);
}
parent::__construct();
$this->callback = $callback;
}
protected function matches($other)
{
return call_user_func($this->callback, $other);
}
public function toString()
{
return 'is accepted by specified callback';
}
}
<?php
class PHPUnit_Framework_Constraint_ClassHasAttribute extends PHPUnit_Framework_Constraint
{
protected $attributeName;
public function __construct($attributeName)
{
parent::__construct();
$this->attributeName = $attributeName;
}
protected function matches($other)
{
$class = new ReflectionClass($other);
return $class->hasProperty($this->attributeName);
}
public function toString()
{
return sprintf(
'has attribute "%s"',
$this->attributeName
);
}
protected function failureDescription($other)
{
return sprintf(
'%sclass "%s" %s',
is_object($other) ? 'object of ' : '',
is_object($other) ? get_class($other) : $other,
$this->toString()
);
}
}
<?php
class PHPUnit_Framework_Constraint_ClassHasStaticAttribute extends PHPUnit_Framework_Constraint_ClassHasAttribute
{
protected function matches($other)
{
$class = new ReflectionClass($other);
if ($class->hasProperty($this->attributeName)) {
$attribute = $class->getProperty($this->attributeName);
return $attribute->isStatic();
} else {
return false;
}
}
public function toString()
{
return sprintf(
'has static attribute "%s"',
$this->attributeName
);
}
}
<?php
abstract class PHPUnit_Framework_Constraint_Composite extends PHPUnit_Framework_Constraint
{
protected $innerConstraint;
public function __construct(PHPUnit_Framework_Constraint $innerConstraint)
{
parent::__construct();
$this->innerConstraint = $innerConstraint;
}
public function evaluate($other, $description = '', $returnResult = false)
{
try {
return $this->innerConstraint->evaluate(
$other,
$description,
$returnResult
);
} catch (PHPUnit_Framework_ExpectationFailedException $e) {
$this->fail($other, $description);
}
}
public function count()
{
return count($this->innerConstraint);
}
}
<?php
class PHPUnit_Framework_Constraint_Count extends PHPUnit_Framework_Constraint
{
protected $expectedCount = 0;
public function __construct($expected)
{
parent::__construct();
$this->expectedCount = $expected;
}
protected function matches($other)
{
return $this->expectedCount === $this->getCountOf($other);
}
protected function getCountOf($other)
{
if ($other instanceof Countable || is_array($other)) {
return count($other);
} elseif ($other instanceof Traversable) {
if ($other instanceof IteratorAggregate) {
$iterator = $other->getIterator();
} else {
$iterator = $other;
}
$key = $iterator->key();
$count = iterator_count($iterator);
if ($key !== null) {
$iterator->rewind();
while ($iterator->valid() && $key !== $iterator->key()) {
$iterator->next();
}
}
return $count;
}
}
protected function failureDescription($other)
{
return sprintf(
'actual size %d matches expected size %d',
$this->getCountOf($other),
$this->expectedCount
);
}
public function toString()
{
return sprintf(
'count matches %d',
$this->expectedCount
);
}
}
<?php
class PHPUnit_Framework_Constraint_Exception extends PHPUnit_Framework_Constraint
{
protected $className;
public function __construct($className)
{
parent::__construct();
$this->className = $className;
}
protected function matches($other)
{
return $other instanceof $this->className;
}
protected function failureDescription($other)
{
if ($other !== null) {
$message = '';
if ($other instanceof Exception || $other instanceof Throwable) {
$message = '. Message was: "' . $other->getMessage() . '" at'
. "\n" . PHPUnit_Util_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
);
}
public function toString()
{
return sprintf(
'exception of type "%s"',
$this->className
);
}
}
<?php
class PHPUnit_Framework_Constraint_ExceptionCode extends PHPUnit_Framework_Constraint
{
protected $expectedCode;
public function __construct($expected)
{
parent::__construct();
$this->expectedCode = $expected;
}
protected function matches($other)
{
return (string) $other->getCode() == (string) $this->expectedCode;
}
protected function failureDescription($other)
{
return sprintf(
'%s is equal to expected exception code %s',
$this->exporter->export($other->getCode()),
$this->exporter->export($this->expectedCode)
);
}
public function toString()
{
return 'exception code is ';
}
}
<?php
class PHPUnit_Framework_Constraint_ExceptionMessage extends PHPUnit_Framework_Constraint
{
protected $expectedMessage;
public function __construct($expected)
{
parent::__construct();
$this->expectedMessage = $expected;
}
protected function matches($other)
{
return strpos($other->getMessage(), $this->expectedMessage) !== false;
}
protected function failureDescription($other)
{
return sprintf(
"exception message '%s' contains '%s'",
$other->getMessage(),
$this->expectedMessage
);
}
public function toString()
{
return 'exception message contains ';
}
}
<?php
class PHPUnit_Framework_Constraint_ExceptionMessageRegExp extends PHPUnit_Framework_Constraint
{
protected $expectedMessageRegExp;
public function __construct($expected)
{
parent::__construct();
$this->expectedMessageRegExp = $expected;
}
protected function matches($other)
{
$match = PHPUnit_Util_Regex::pregMatchSafe($this->expectedMessageRegExp, $other->getMessage());
if (false === $match) {
throw new PHPUnit_Framework_Exception(
"Invalid expected exception message regex given: '{$this->expectedMessageRegExp}'"
);
}
return 1 === $match;
}
protected function failureDescription($other)
{
return sprintf(
"exception message '%s' matches '%s'",
$other->getMessage(),
$this->expectedMessageRegExp
);
}
public function toString()
{
return 'exception message matches ';
}
}
<?php
class PHPUnit_Framework_Constraint_FileExists extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return file_exists($other);
}
protected function failureDescription($other)
{
return sprintf(
'file "%s" exists',
$other
);
}
public function toString()
{
return 'file exists';
}
}
<?php
class PHPUnit_Framework_Constraint_GreaterThan extends PHPUnit_Framework_Constraint
{
protected $value;
public function __construct($value)
{
parent::__construct();
$this->value = $value;
}
protected function matches($other)
{
return $this->value < $other;
}
public function toString()
{
return 'is greater than ' . $this->exporter->export($this->value);
}
}
<?php
class PHPUnit_Framework_Constraint_IsAnything extends PHPUnit_Framework_Constraint
{
public function evaluate($other, $description = '', $returnResult = false)
{
return $returnResult ? true : null;
}
public function toString()
{
return 'is anything';
}
public function count()
{
return 0;
}
}
<?php
class PHPUnit_Framework_Constraint_IsEmpty extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
if ($other instanceof Countable) {
return count($other) === 0;
}
return empty($other);
}
public function toString()
{
return 'is empty';
}
protected function failureDescription($other)
{
$type = gettype($other);
return sprintf(
'%s %s %s',
$type[0] == 'a' || $type[0] == 'o' ? 'an' : 'a',
$type,
$this->toString()
);
}
}
<?php
class PHPUnit_Framework_Constraint_IsEqual extends PHPUnit_Framework_Constraint
{
protected $value;
protected $delta = 0.0;
protected $maxDepth = 10;
protected $canonicalize = false;
protected $ignoreCase = false;
protected $lastFailure;
public function __construct($value, $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
parent::__construct();
if (!is_numeric($delta)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'numeric');
}
if (!is_int($maxDepth)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'integer');
}
if (!is_bool($canonicalize)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(4, 'boolean');
}
if (!is_bool($ignoreCase)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(5, 'boolean');
}
$this->value = $value;
$this->delta = $delta;
$this->maxDepth = $maxDepth;
$this->canonicalize = $canonicalize;
$this->ignoreCase = $ignoreCase;
}
public function evaluate($other, $description = '', $returnResult = false)
{
if ($this->value === $other) {
return true;
}
$comparatorFactory = SebastianBergmann\Comparator\Factory::getInstance();
try {
$comparator = $comparatorFactory->getComparatorFor(
$this->value,
$other
);
$comparator->assertEquals(
$this->value,
$other,
$this->delta,
$this->canonicalize,
$this->ignoreCase
);
} catch (SebastianBergmann\Comparator\ComparisonFailure $f) {
if ($returnResult) {
return false;
}
throw new PHPUnit_Framework_ExpectationFailedException(
trim($description . "\n" . $f->getMessage()),
$f
);
}
return true;
}
public function toString()
{
$delta = '';
if (is_string($this->value)) {
if (strpos($this->value, "\n") !== false) {
return 'is equal to <text>';
} else {
return sprintf(
'is equal to <string:%s>',
$this->value
);
}
} else {
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
class PHPUnit_Framework_Constraint_IsFalse extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return $other === false;
}
public function toString()
{
return 'is false';
}
}
<?php
class PHPUnit_Framework_Constraint_IsFinite extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return is_finite($other);
}
public function toString()
{
return 'is finite';
}
}
<?php
class PHPUnit_Framework_Constraint_IsIdentical extends PHPUnit_Framework_Constraint
{
const EPSILON = 0.0000000001;
protected $value;
public function __construct($value)
{
parent::__construct();
$this->value = $value;
}
public function evaluate($other, $description = '', $returnResult = false)
{
if (is_double($this->value) && is_double($other) &&
!is_infinite($this->value) && !is_infinite($other) &&
!is_nan($this->value) && !is_nan($other)) {
$success = abs($this->value - $other) < self::EPSILON;
} else {
$success = $this->value === $other;
}
if ($returnResult) {
return $success;
}
if (!$success) {
$f = null;
if (is_string($this->value) && is_string($other)) {
$f = new SebastianBergmann\Comparator\ComparisonFailure(
$this->value,
$other,
$this->value,
$other
);
}
$this->fail($other, $description, $f);
}
}
protected function failureDescription($other)
{
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';
}
return parent::failureDescription($other);
}
public function toString()
{
if (is_object($this->value)) {
return 'is identical to an object of class "' .
get_class($this->value) . '"';
} else {
return 'is identical to ' .
$this->exporter->export($this->value);
}
}
}
<?php
class PHPUnit_Framework_Constraint_IsInfinite extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return is_infinite($other);
}
public function toString()
{
return 'is infinite';
}
}
<?php
class PHPUnit_Framework_Constraint_IsInstanceOf extends PHPUnit_Framework_Constraint
{
protected $className;
public function __construct($className)
{
parent::__construct();
$this->className = $className;
}
protected function matches($other)
{
return ($other instanceof $this->className);
}
protected function failureDescription($other)
{
return sprintf(
'%s is an instance of %s "%s"',
$this->exporter->shortenedExport($other),
$this->getType(),
$this->className
);
}
public function toString()
{
return sprintf(
'is instance of %s "%s"',
$this->getType(),
$this->className
);
}
private function getType()
{
try {
$reflection = new ReflectionClass($this->className);
if ($reflection->isInterface()) {
return 'interface';
}
} catch (ReflectionException $e) {
}
return 'class';
}
}
<?php
class PHPUnit_Framework_Constraint_IsJson extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
if ($other === '') {
return false;
}
json_decode($other);
if (json_last_error()) {
return false;
}
return true;
}
protected function failureDescription($other)
{
if ($other === '') {
return 'an empty string is valid JSON';
}
json_decode($other);
$error = PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider::determineJsonError(
json_last_error()
);
return sprintf(
'%s is valid JSON (%s)',
$this->exporter->shortenedExport($other),
$error
);
}
public function toString()
{
return 'is valid JSON';
}
}
<?php
class PHPUnit_Framework_Constraint_IsNan extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return is_nan($other);
}
public function toString()
{
return 'is nan';
}
}
<?php
class PHPUnit_Framework_Constraint_IsNull extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return $other === null;
}
public function toString()
{
return 'is null';
}
}
<?php
class PHPUnit_Framework_Constraint_IsTrue extends PHPUnit_Framework_Constraint
{
protected function matches($other)
{
return $other === true;
}
public function toString()
{
return 'is true';
}
}
<?php
class PHPUnit_Framework_Constraint_IsType extends PHPUnit_Framework_Constraint
{
const TYPE_ARRAY = 'array';
const TYPE_BOOL = 'bool';
const TYPE_FLOAT = 'float';
const TYPE_INT = 'int';
const TYPE_NULL = 'null';
const TYPE_NUMERIC = 'numeric';
const TYPE_OBJECT = 'object';
const TYPE_RESOURCE = 'resource';
const TYPE_STRING = 'string';
const TYPE_SCALAR = 'scalar';
const TYPE_CALLABLE = 'callable';
protected $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
];
protected $type;
public function __construct($type)
{
parent::__construct();
if (!isset($this->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;
}
protected function matches($other)
{
switch ($this->type) {
case 'numeric':
return is_numeric($other);
case 'integer':
case 'int':
return is_integer($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 is_null($other);
case 'array':
return is_array($other);
case 'object':
return is_object($other);
case 'resource':
return is_resource($other) || is_string(@get_resource_type($other));
case 'scalar':
return is_scalar($other);
case 'callable':
return is_callable($other);
}
}
public function toString()
{
return sprintf(
'is of type "%s"',
$this->type
);
}
}
<?php
class PHPUnit_Framework_Constraint_JsonMatches extends PHPUnit_Framework_Constraint
{
protected $value;
public function __construct($value)
{
parent::__construct();
$this->value = $value;
}
protected function matches($other)
{
$decodedOther = json_decode($other);
if (json_last_error()) {
return false;
}
$decodedValue = json_decode($this->value);
if (json_last_error()) {
return false;
}
return $decodedOther == $decodedValue;
}
public function toString()
{
return sprintf(
'matches JSON string "%s"',
$this->value
);
}
}
<?php
class PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider
{
public static function determineJsonError($error, $prefix = '')
{
switch ($error) {
case JSON_ERROR_NONE:
return;
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';
}
}
public static function translateTypeToPrefix($type)
{
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
class PHPUnit_Framework_Constraint_LessThan extends PHPUnit_Framework_Constraint
{
protected $value;
public function __construct($value)
{
parent::__construct();
$this->value = $value;
}
protected function matches($other)
{
return $this->value > $other;
}
public function toString()
{
return 'is less than ' . $this->exporter->export($this->value);
}
}
<?php
class PHPUnit_Framework_Constraint_Not extends PHPUnit_Framework_Constraint
{
protected $constraint;
public function __construct($constraint)
{
parent::__construct();
if (!($constraint instanceof PHPUnit_Framework_Constraint)) {
$constraint = new PHPUnit_Framework_Constraint_IsEqual($constraint);
}
$this->constraint = $constraint;
}
public static function negate($string)
{
return str_replace(
[
'contains ',
'exists',
'has ',
'is ',
'are ',
'matches ',
'starts with ',
'ends with ',
'reference ',
'not not '
],
[
'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 '
],
$string
);
}
public function evaluate($other, $description = '', $returnResult = false)
{
$success = !$this->constraint->evaluate($other, $description, true);
if ($returnResult) {
return $success;
}
if (!$success) {
$this->fail($other, $description);
}
}
protected function failureDescription($other)
{
switch (get_class($this->constraint)) {
case 'PHPUnit_Framework_Constraint_And':
case 'PHPUnit_Framework_Constraint_Not':
case 'PHPUnit_Framework_Constraint_Or':
return 'not( ' . $this->constraint->failureDescription($other) . ' )';
default:
return self::negate(
$this->constraint->failureDescription($other)
);
}
}
public function toString()
{
switch (get_class($this->constraint)) {
case 'PHPUnit_Framework_Constraint_And':
case 'PHPUnit_Framework_Constraint_Not':
case 'PHPUnit_Framework_Constraint_Or':
return 'not( ' . $this->constraint->toString() . ' )';
default:
return self::negate(
$this->constraint->toString()
);
}
}
public function count()
{
return count($this->constraint);
}
}
<?php
class PHPUnit_Framework_Constraint_ObjectHasAttribute extends PHPUnit_Framework_Constraint_ClassHasAttribute
{
protected function matches($other)
{
$object = new ReflectionObject($other);
return $object->hasProperty($this->attributeName);
}
}
<?php
class PHPUnit_Framework_Constraint_Or extends PHPUnit_Framework_Constraint
{
protected $constraints = [];
public function setConstraints(array $constraints)
{
$this->constraints = [];
foreach ($constraints as $constraint) {
if (!($constraint instanceof PHPUnit_Framework_Constraint)) {
$constraint = new PHPUnit_Framework_Constraint_IsEqual(
$constraint
);
}
$this->constraints[] = $constraint;
}
}
public function evaluate($other, $description = '', $returnResult = false)
{
$success = false;
$constraint = null;
foreach ($this->constraints as $constraint) {
if ($constraint->evaluate($other, $description, true)) {
$success = true;
break;
}
}
if ($returnResult) {
return $success;
}
if (!$success) {
$this->fail($other, $description);
}
}
public function toString()
{
$text = '';
foreach ($this->constraints as $key => $constraint) {
if ($key > 0) {
$text .= ' or ';
}
$text .= $constraint->toString();
}
return $text;
}
public function count()
{
$count = 0;
foreach ($this->constraints as $constraint) {
$count += count($constraint);
}
return $count;
}
}
<?php
class PHPUnit_Framework_Constraint_PCREMatch extends PHPUnit_Framework_Constraint
{
protected $pattern;
public function __construct($pattern)
{
parent::__construct();
$this->pattern = $pattern;
}
protected function matches($other)
{
return preg_match($this->pattern, $other) > 0;
}
public function toString()
{
return sprintf(
'matches PCRE pattern "%s"',
$this->pattern
);
}
}
<?php
class PHPUnit_Framework_Constraint_SameSize extends PHPUnit_Framework_Constraint_Count
{
protected $expectedCount;
public function __construct($expected)
{
parent::__construct($this->getCountOf($expected));
}
}
<?php
class PHPUnit_Framework_Constraint_StringContains extends PHPUnit_Framework_Constraint
{
protected $string;
protected $ignoreCase;
public function __construct($string, $ignoreCase = false)
{
parent::__construct();
$this->string = $string;
$this->ignoreCase = $ignoreCase;
}
protected function matches($other)
{
if ($this->ignoreCase) {
return stripos($other, $this->string) !== false;
} else {
return strpos($other, $this->string) !== false;
}
}
public function toString()
{
if ($this->ignoreCase) {
$string = strtolower($this->string);
} else {
$string = $this->string;
}
return sprintf(
'contains "%s"',
$string
);
}
}
<?php
class PHPUnit_Framework_Constraint_StringEndsWith extends PHPUnit_Framework_Constraint
{
protected $suffix;
public function __construct($suffix)
{
parent::__construct();
$this->suffix = $suffix;
}
protected function matches($other)
{
return substr($other, 0 - strlen($this->suffix)) == $this->suffix;
}
public function toString()
{
return 'ends with "' . $this->suffix . '"';
}
}
<?php
use SebastianBergmann\Diff\Differ;
class PHPUnit_Framework_Constraint_StringMatches extends PHPUnit_Framework_Constraint_PCREMatch
{
protected $string;
public function __construct($string)
{
parent::__construct($string);
$this->pattern = $this->createPatternFromFormat(
preg_replace('/\r\n/', "\n", $string)
);
$this->string = $string;
}
protected function failureDescription($other)
{
return 'format description matches text';
}
protected function additionalFailureDescription($other)
{
$from = preg_split('(\r\n|\r|\n)', $this->string);
$to = preg_split('(\r\n|\r|\n)', $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);
$differ = new Differ("--- Expected\n+++ Actual\n");
return $differ->diff($this->string, $other);
}
protected function createPatternFromFormat($string)
{
$string = str_replace(
[
'%e',
'%s',
'%S',
'%a',
'%A',
'%w',
'%i',
'%d',
'%x',
'%f',
'%c'
],
[
'\\' . DIRECTORY_SEPARATOR,
'[^\r\n]+',
'[^\r\n]*',
'.+',
'.*',
'\s*',
'[+-]?\d+',
'\d+',
'[0-9a-fA-F]+',
'[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?',
'.'
],
preg_quote($string, '/')
);
return '/^' . $string . '$/s';
}
}
<?php
class PHPUnit_Framework_Constraint_StringStartsWith extends PHPUnit_Framework_Constraint
{
protected $prefix;
public function __construct($prefix)
{
parent::__construct();
$this->prefix = $prefix;
}
protected function matches($other)
{
return strpos($other, $this->prefix) === 0;
}
public function toString()
{
return 'starts with "' . $this->prefix . '"';
}
}
<?php
class PHPUnit_Framework_Constraint_TraversableContains extends PHPUnit_Framework_Constraint
{
protected $checkForObjectIdentity;
protected $checkForNonObjectIdentity;
protected $value;
public function __construct($value, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
parent::__construct();
if (!is_bool($checkForObjectIdentity)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'boolean');
}
if (!is_bool($checkForNonObjectIdentity)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'boolean');
}
$this->checkForObjectIdentity = $checkForObjectIdentity;
$this->checkForNonObjectIdentity = $checkForNonObjectIdentity;
$this->value = $value;
}
protected function matches($other)
{
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;
} elseif (!$this->checkForObjectIdentity && $element == $this->value) {
return true;
}
}
} else {
foreach ($other as $element) {
if ($this->checkForNonObjectIdentity && $element === $this->value) {
return true;
} elseif (!$this->checkForNonObjectIdentity && $element == $this->value) {
return true;
}
}
}
return false;
}
public function toString()
{
if (is_string($this->value) && strpos($this->value, "\n") !== false) {
return 'contains "' . $this->value . '"';
} else {
return 'contains ' . $this->exporter->export($this->value);
}
}
protected function failureDescription($other)
{
return sprintf(
'%s %s',
is_array($other) ? 'an array' : 'a traversable',
$this->toString()
);
}
}
<?php
class PHPUnit_Framework_Constraint_TraversableContainsOnly extends PHPUnit_Framework_Constraint
{
protected $constraint;
protected $type;
public function __construct($type, $isNativeType = true)
{
parent::__construct();
if ($isNativeType) {
$this->constraint = new PHPUnit_Framework_Constraint_IsType($type);
} else {
$this->constraint = new PHPUnit_Framework_Constraint_IsInstanceOf(
$type
);
}
$this->type = $type;
}
public function evaluate($other, $description = '', $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);
}
}
public function toString()
{
return 'contains only values of type "' . $this->type . '"';
}
}
<?php
class PHPUnit_Framework_Constraint_Xor extends PHPUnit_Framework_Constraint
{
protected $constraints = [];
public function setConstraints(array $constraints)
{
$this->constraints = [];
foreach ($constraints as $constraint) {
if (!($constraint instanceof PHPUnit_Framework_Constraint)) {
$constraint = new PHPUnit_Framework_Constraint_IsEqual(
$constraint
);
}
$this->constraints[] = $constraint;
}
}
public function evaluate($other, $description = '', $returnResult = false)
{
$success = true;
$lastResult = null;
$constraint = 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);
}
}
public function toString()
{
$text = '';
foreach ($this->constraints as $key => $constraint) {
if ($key > 0) {
$text .= ' xor ';
}
$text .= $constraint->toString();
}
return $text;
}
public function count()
{
$count = 0;
foreach ($this->constraints as $constraint) {
$count += count($constraint);
}
return $count;
}
}
<?php
class PHPUnit_Framework_Error extends PHPUnit_Framework_Exception
{
public function __construct($message, $code, $file, $line, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->file = $file;
$this->line = $line;
}
}
<?php
class PHPUnit_Framework_Error_Deprecated extends PHPUnit_Framework_Error
{
public static $enabled = true;
}
<?php
class PHPUnit_Framework_Error_Notice extends PHPUnit_Framework_Error
{
public static $enabled = true;
}
<?php
class PHPUnit_Framework_Error_Warning extends PHPUnit_Framework_Error
{
public static $enabled = true;
}
<?php
class PHPUnit_Framework_Exception extends RuntimeException implements PHPUnit_Exception
{
protected $serializableTrace;
public function __construct($message = '', $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->serializableTrace = $this->getTrace();
foreach ($this->serializableTrace as $i => $call) {
unset($this->serializableTrace[$i]['args']);
}
}
public function getSerializableTrace()
{
return $this->serializableTrace;
}
public function __toString()
{
$string = PHPUnit_Framework_TestFailure::exceptionToString($this);
if ($trace = PHPUnit_Util_Filter::getFilteredStacktrace($this)) {
$string .= "\n" . $trace;
}
return $string;
}
public function __sleep()
{
return array_keys(get_object_vars($this));
}
}
<?php
class PHPUnit_Framework_ExceptionWrapper extends PHPUnit_Framework_Exception
{
protected $classname;
protected $previous;
public function __construct($e)
{
parent::__construct($e->getMessage(), (int) $e->getCode());
$this->classname = get_class($e);
$this->file = $e->getFile();
$this->line = $e->getLine();
$this->serializableTrace = $e->getTrace();
foreach ($this->serializableTrace as $i => $call) {
unset($this->serializableTrace[$i]['args']);
}
if ($e->getPrevious()) {
$this->previous = new self($e->getPrevious());
}
}
public function getClassname()
{
return $this->classname;
}
public function getPreviousWrapped()
{
return $this->previous;
}
public function __toString()
{
$string = PHPUnit_Framework_TestFailure::exceptionToString($this);
if ($trace = PHPUnit_Util_Filter::getFilteredStacktrace($this)) {
$string .= "\n" . $trace;
}
if ($this->previous) {
$string .= "\nCaused by\n" . $this->previous;
}
return $string;
}
}
<?php
class PHPUnit_Framework_ExpectationFailedException extends PHPUnit_Framework_AssertionFailedError
{
protected $comparisonFailure;
public function __construct($message, SebastianBergmann\Comparator\ComparisonFailure $comparisonFailure = null, Exception $previous = null)
{
$this->comparisonFailure = $comparisonFailure;
parent::__construct($message, 0, $previous);
}
public function getComparisonFailure()
{
return $this->comparisonFailure;
}
}
<?php
interface PHPUnit_Framework_IncompleteTest
{
}
<?php
class PHPUnit_Framework_IncompleteTestCase extends PHPUnit_Framework_TestCase
{
protected $message = '';
protected $backupGlobals = false;
protected $backupStaticAttributes = false;
protected $runTestInSeparateProcess = false;
protected $useErrorHandler = false;
protected $useOutputBuffering = false;
public function __construct($className, $methodName, $message = '')
{
$this->message = $message;
parent::__construct($className . '::' . $methodName);
}
protected function runTest()
{
$this->markTestIncomplete($this->message);
}
public function getMessage()
{
return $this->message;
}
public function toString()
{
return $this->getName();
}
}
<?php
class PHPUnit_Framework_IncompleteTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_IncompleteTest
{
}
<?php
class PHPUnit_Framework_InvalidCoversTargetException extends PHPUnit_Framework_CodeCoverageException
{
}
<?php
class PHPUnit_Framework_OutputError extends PHPUnit_Framework_AssertionFailedError
{
}
<?php
class PHPUnit_Framework_CoveredCodeNotExecutedException extends PHPUnit_Framework_RiskyTestError
{
}
<?php
class PHPUnit_Framework_MissingCoversAnnotationException extends PHPUnit_Framework_RiskyTestError
{
}
<?php
interface PHPUnit_Framework_RiskyTest
{
}
<?php
class PHPUnit_Framework_RiskyTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_RiskyTest
{
}
<?php
interface PHPUnit_Framework_SelfDescribing
{
public function toString();
}
<?php
interface PHPUnit_Framework_SkippedTest
{
}
<?php
class PHPUnit_Framework_SkippedTestCase extends PHPUnit_Framework_TestCase
{
protected $message = '';
protected $backupGlobals = false;
protected $backupStaticAttributes = false;
protected $runTestInSeparateProcess = false;
protected $useErrorHandler = false;
protected $useOutputBuffering = false;
public function __construct($className, $methodName, $message = '')
{
$this->message = $message;
parent::__construct($className . '::' . $methodName);
}
protected function runTest()
{
$this->markTestSkipped($this->message);
}
public function getMessage()
{
return $this->message;
}
public function toString()
{
return $this->getName();
}
}
<?php
class PHPUnit_Framework_SkippedTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_SkippedTest
{
}
<?php
class PHPUnit_Framework_SkippedTestSuiteError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_SkippedTest
{
}
<?php
class PHPUnit_Framework_SyntheticError extends PHPUnit_Framework_AssertionFailedError
{
protected $syntheticFile = '';
protected $syntheticLine = 0;
protected $syntheticTrace = [];
public function __construct($message, $code, $file, $line, $trace)
{
parent::__construct($message, $code);
$this->syntheticFile = $file;
$this->syntheticLine = $line;
$this->syntheticTrace = $trace;
}
public function getSyntheticFile()
{
return $this->syntheticFile;
}
public function getSyntheticLine()
{
return $this->syntheticLine;
}
public function getSyntheticTrace()
{
return $this->syntheticTrace;
}
}
<?php
interface PHPUnit_Framework_Test extends Countable
{
public function run(PHPUnit_Framework_TestResult $result = null);
}
<?php
use SebastianBergmann\GlobalState\Snapshot;
use SebastianBergmann\GlobalState\Restorer;
use SebastianBergmann\GlobalState\Blacklist;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Exporter\Exporter;
use SebastianBergmann\ObjectEnumerator\Enumerator;
use Prophecy\Exception\Prediction\PredictionException;
use Prophecy\Prophet;
use DeepCopy\DeepCopy;
abstract class PHPUnit_Framework_TestCase extends PHPUnit_Framework_Assert implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing
{
protected $backupGlobals = null;
protected $backupGlobalsBlacklist = [];
protected $backupStaticAttributes = null;
protected $backupStaticAttributesBlacklist = [];
protected $runTestInSeparateProcess = null;
protected $preserveGlobalState = true;
private $inIsolation = false;
private $data = [];
private $dataName = '';
private $useErrorHandler = null;
private $expectedException = null;
private $expectedExceptionMessage = '';
private $expectedExceptionMessageRegExp = '';
private $expectedExceptionCode;
private $name = null;
private $dependencies = [];
private $dependencyInput = [];
private $iniSettings = [];
private $locale = [];
private $mockObjects = [];
private $mockObjectGenerator = null;
private $status;
private $statusMessage = '';
private $numAssertions = 0;
private $result;
private $testResult;
private $output = '';
private $outputExpectedRegex = null;
private $outputExpectedString = null;
private $outputCallback = false;
private $outputBufferingActive = false;
private $outputBufferingLevel;
private $snapshot;
private $prophet;
private $beStrictAboutChangesToGlobalState = false;
private $registerMockObjectsFromTestArgumentsRecursively = false;
private $warnings = [];
private $groups = [];
public function __construct($name = null, array $data = [], $dataName = '')
{
if ($name !== null) {
$this->setName($name);
}
$this->data = $data;
$this->dataName = $dataName;
}
public function toString()
{
$class = new ReflectionClass($this);
$buffer = sprintf(
'%s::%s',
$class->name,
$this->getName(false)
);
return $buffer . $this->getDataSetAsString();
}
public function count()
{
return 1;
}
public function getGroups()
{
return $this->groups;
}
public function setGroups(array $groups)
{
$this->groups = $groups;
}
public function getAnnotations()
{
return PHPUnit_Util_Test::parseTestMethodAnnotations(
get_class($this),
$this->name
);
}
public function getName($withDataSet = true)
{
if ($withDataSet) {
return $this->name . $this->getDataSetAsString(false);
} else {
return $this->name;
}
}
public function getSize()
{
return PHPUnit_Util_Test::getSize(
get_class($this),
$this->getName(false)
);
}
public function hasSize()
{
return $this->getSize() !== PHPUnit_Util_Test::UNKNOWN;
}
public function isSmall()
{
return $this->getSize() === PHPUnit_Util_Test::SMALL;
}
public function isMedium()
{
return $this->getSize() === PHPUnit_Util_Test::MEDIUM;
}
public function isLarge()
{
return $this->getSize() === PHPUnit_Util_Test::LARGE;
}
public function getActualOutput()
{
if (!$this->outputBufferingActive) {
return $this->output;
} else {
return ob_get_contents();
}
}
public function hasOutput()
{
if (strlen($this->output) === 0) {
return false;
}
if ($this->hasExpectationOnOutput()) {
return false;
}
return true;
}
public function expectOutputRegex($expectedRegex)
{
if ($this->outputExpectedString !== null) {
throw new PHPUnit_Framework_Exception;
}
if (is_string($expectedRegex) || is_null($expectedRegex)) {
$this->outputExpectedRegex = $expectedRegex;
}
}
public function expectOutputString($expectedString)
{
if ($this->outputExpectedRegex !== null) {
throw new PHPUnit_Framework_Exception;
}
if (is_string($expectedString) || is_null($expectedString)) {
$this->outputExpectedString = $expectedString;
}
}
public function hasPerformedExpectationsOnOutput()
{
return $this->hasExpectationOnOutput();
}
public function hasExpectationOnOutput()
{
return is_string($this->outputExpectedString) || is_string($this->outputExpectedRegex);
}
public function getExpectedException()
{
return $this->expectedException;
}
public function setExpectedException($exception, $message = '', $code = null)
{
$this->expectedException = $exception;
if ($message !== null && $message !== '') {
$this->expectExceptionMessage($message);
}
if ($code !== null) {
$this->expectExceptionCode($code);
}
}
public function setExpectedExceptionRegExp($exception, $messageRegExp = '', $code = null)
{
if (!is_string($messageRegExp)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
$this->expectedException = $exception;
$this->expectedExceptionMessageRegExp = $messageRegExp;
if ($code !== null) {
$this->expectExceptionCode($code);
}
}
public function expectException($exception)
{
if (!is_string($exception)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$this->expectedException = $exception;
}
public function expectExceptionCode($code)
{
if (!is_int($code) && !is_string($code)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'integer or string');
}
$this->expectedExceptionCode = $code;
}
public function expectExceptionMessage($message)
{
if (!is_string($message)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$this->expectedExceptionMessage = $message;
}
public function expectExceptionMessageRegExp($messageRegExp)
{
if (!is_string($messageRegExp)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$this->expectedExceptionMessageRegExp = $messageRegExp;
}
public function setRegisterMockObjectsFromTestArgumentsRecursively($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->registerMockObjectsFromTestArgumentsRecursively = $flag;
}
protected function setExpectedExceptionFromAnnotation()
{
try {
$expectedException = PHPUnit_Util_Test::getExpectedException(
get_class($this),
$this->name
);
if ($expectedException !== false) {
$this->expectException($expectedException['class']);
if ($expectedException['code'] !== null) {
$this->expectExceptionCode($expectedException['code']);
}
if ($expectedException['message'] !== '') {
$this->expectExceptionMessage($expectedException['message']);
} elseif ($expectedException['message_regex'] !== '') {
$this->expectExceptionMessageRegExp($expectedException['message_regex']);
}
}
} catch (ReflectionException $e) {
}
}
public function setUseErrorHandler($useErrorHandler)
{
$this->useErrorHandler = $useErrorHandler;
}
protected function setUseErrorHandlerFromAnnotation()
{
try {
$useErrorHandler = PHPUnit_Util_Test::getErrorHandlerSettings(
get_class($this),
$this->name
);
if ($useErrorHandler !== null) {
$this->setUseErrorHandler($useErrorHandler);
}
} catch (ReflectionException $e) {
}
}
protected function checkRequirements()
{
if (!$this->name || !method_exists($this, $this->name)) {
return;
}
$missingRequirements = PHPUnit_Util_Test::getMissingRequirements(
get_class($this),
$this->name
);
if (!empty($missingRequirements)) {
$this->markTestSkipped(implode(PHP_EOL, $missingRequirements));
}
}
public function getStatus()
{
return $this->status;
}
public function getStatusMessage()
{
return $this->statusMessage;
}
public function hasFailed()
{
$status = $this->getStatus();
return $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE ||
$status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR;
}
public function run(PHPUnit_Framework_TestResult $result = null)
{
if ($result === null) {
$result = $this->createResult();
}
if (!$this instanceof PHPUnit_Framework_WarningTestCase) {
$this->setTestResultObject($result);
$this->setUseErrorHandlerFromAnnotation();
}
if ($this->useErrorHandler !== null) {
$oldErrorHandlerSetting = $result->getConvertErrorsToExceptions();
$result->convertErrorsToExceptions($this->useErrorHandler);
}
if (!$this instanceof PHPUnit_Framework_WarningTestCase && !$this->handleDependencies()) {
return;
}
if ($this->runTestInSeparateProcess === true &&
$this->inIsolation !== true &&
!$this instanceof PHPUnit_Extensions_PhptTestCase) {
$class = new ReflectionClass($this);
$template = new Text_Template(
__DIR__ . '/../Util/PHP/Template/TestCaseMethod.tpl'
);
if ($this->preserveGlobalState) {
$constants = PHPUnit_Util_GlobalState::getConstantsAsString();
$globals = PHPUnit_Util_GlobalState::getGlobalsAsString();
$includedFiles = PHPUnit_Util_GlobalState::getIncludedFilesAsString();
$iniSettings = PHPUnit_Util_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);
$data = "'." . $data . ".'";
$dataName = "'.(" . $dataName . ").'";
$dependencyInput = "'." . $dependencyInput . ".'";
$includePath = "'." . $includePath . ".'";
$codeCoverageFilter = "'." . $codeCoverageFilter . ".'";
$configurationFilePath = (isset($GLOBALS['__PHPUNIT_CONFIGURATION_FILE']) ? $GLOBALS['__PHPUNIT_CONFIGURATION_FILE'] : '');
$template->setVar(
[
'composerAutoload' => $composerAutoload,
'phar' => $phar,
'filename' => $class->getFileName(),
'className' => $class->getName(),
'methodName' => $this->name,
'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
]
);
$this->prepareTemplate($template);
$php = PHPUnit_Util_PHP::factory();
$php->runTestJob($template->render(), $this, $result);
} else {
$result->run($this);
}
if ($this->useErrorHandler !== null) {
$result->convertErrorsToExceptions($oldErrorHandlerSetting);
}
$this->result = null;
return $result;
}
public function runBare()
{
$this->numAssertions = 0;
$this->snapshotGlobalState();
$this->startOutputBuffering();
clearstatcache();
$currentWorkingDirectory = getcwd();
$hookMethods = PHPUnit_Util_Test::getHookMethods(get_class($this));
try {
$hasMetRequirements = false;
$this->checkRequirements();
$hasMetRequirements = true;
if ($this->inIsolation) {
foreach ($hookMethods['beforeClass'] as $method) {
$this->$method();
}
}
$this->setExpectedExceptionFromAnnotation();
foreach ($hookMethods['before'] as $method) {
$this->$method();
}
$this->assertPreConditions();
$this->testResult = $this->runTest();
$this->verifyMockObjects();
$this->assertPostConditions();
if (!empty($this->warnings)) {
throw new PHPUnit_Framework_Warning(
implode(
"\n",
array_unique($this->warnings)
)
);
}
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_PASSED;
} catch (PHPUnit_Framework_IncompleteTest $e) {
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE;
$this->statusMessage = $e->getMessage();
} catch (PHPUnit_Framework_SkippedTest $e) {
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED;
$this->statusMessage = $e->getMessage();
} catch (PHPUnit_Framework_Warning $e) {
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_WARNING;
$this->statusMessage = $e->getMessage();
} catch (PHPUnit_Framework_AssertionFailedError $e) {
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE;
$this->statusMessage = $e->getMessage();
} catch (PredictionException $e) {
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE;
$this->statusMessage = $e->getMessage();
} catch (Throwable $_e) {
$e = $_e;
} catch (Exception $_e) {
$e = $_e;
}
if (isset($_e)) {
$this->status = PHPUnit_Runner_BaseTestRunner::STATUS_ERROR;
$this->statusMessage = $_e->getMessage();
}
$this->mockObjects = [];
$this->prophet = null;
try {
if ($hasMetRequirements) {
foreach ($hookMethods['after'] as $method) {
$this->$method();
}
if ($this->inIsolation) {
foreach ($hookMethods['afterClass'] as $method) {
$this->$method();
}
}
}
} catch (Throwable $_e) {
if (!isset($e)) {
$e = $_e;
}
} catch (Exception $_e) {
if (!isset($e)) {
$e = $_e;
}
}
try {
$this->stopOutputBuffering();
} catch (PHPUnit_Framework_RiskyTestError $_e) {
if (!isset($e)) {
$e = $_e;
}
}
clearstatcache();
if ($currentWorkingDirectory != getcwd()) {
chdir($currentWorkingDirectory);
}
$this->restoreGlobalState();
foreach ($this->iniSettings as $varName => $oldValue) {
ini_set($varName, $oldValue);
}
$this->iniSettings = [];
foreach ($this->locale as $category => $locale) {
setlocale($category, $locale);
}
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;
} catch (Exception $_e) {
$e = $_e;
}
}
if (isset($e)) {
if ($e instanceof PredictionException) {
$e = new PHPUnit_Framework_AssertionFailedError($e->getMessage());
}
$this->onNotSuccessfulTest($e);
}
}
protected function runTest()
{
if ($this->name === null) {
throw new PHPUnit_Framework_Exception(
'PHPUnit_Framework_TestCase::$name must not be null.'
);
}
try {
$class = new ReflectionClass($this);
$method = $class->getMethod($this->name);
} catch (ReflectionException $e) {
$this->fail($e->getMessage());
}
$testArguments = array_merge($this->data, $this->dependencyInput);
$this->registerMockObjectsFromTestArguments($testArguments);
try {
$testResult = $method->invokeArgs($this, $testArguments);
} catch (Throwable $_e) {
$e = $_e;
} catch (Exception $_e) {
$e = $_e;
}
if (isset($e)) {
$checkException = false;
if (is_string($this->expectedException)) {
$checkException = true;
if ($e instanceof PHPUnit_Framework_Exception) {
$checkException = false;
}
$reflector = new ReflectionClass($this->expectedException);
if ($this->expectedException == 'PHPUnit_Framework_Exception' ||
$reflector->isSubclassOf('PHPUnit_Framework_Exception')) {
$checkException = true;
}
}
if ($checkException) {
$this->assertThat(
$e,
new PHPUnit_Framework_Constraint_Exception(
$this->expectedException
)
);
if (is_string($this->expectedExceptionMessage) &&
!empty($this->expectedExceptionMessage)) {
$this->assertThat(
$e,
new PHPUnit_Framework_Constraint_ExceptionMessage(
$this->expectedExceptionMessage
)
);
}
if (is_string($this->expectedExceptionMessageRegExp) &&
!empty($this->expectedExceptionMessageRegExp)) {
$this->assertThat(
$e,
new PHPUnit_Framework_Constraint_ExceptionMessageRegExp(
$this->expectedExceptionMessageRegExp
)
);
}
if ($this->expectedExceptionCode !== null) {
$this->assertThat(
$e,
new PHPUnit_Framework_Constraint_ExceptionCode(
$this->expectedExceptionCode
)
);
}
return;
} else {
throw $e;
}
}
if ($this->expectedException !== null) {
$this->assertThat(
null,
new PHPUnit_Framework_Constraint_Exception(
$this->expectedException
)
);
}
return $testResult;
}
protected function verifyMockObjects()
{
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();
} catch (Throwable $t) {
} catch (Exception $t) {
}
foreach ($this->prophet->getProphecies() as $objectProphecy) {
foreach ($objectProphecy->getMethodProphecies() as $methodProphecies) {
foreach ($methodProphecies as $methodProphecy) {
$this->numAssertions += count($methodProphecy->getCheckedPredictions());
}
}
}
if (isset($t)) {
throw $t;
}
}
}
public function setName($name)
{
$this->name = $name;
}
public function setDependencies(array $dependencies)
{
$this->dependencies = $dependencies;
}
public function hasDependencies()
{
return count($this->dependencies) > 0;
}
public function setDependencyInput(array $dependencyInput)
{
$this->dependencyInput = $dependencyInput;
}
public function setBeStrictAboutChangesToGlobalState($beStrictAboutChangesToGlobalState)
{
$this->beStrictAboutChangesToGlobalState = $beStrictAboutChangesToGlobalState;
}
public function setBackupGlobals($backupGlobals)
{
if (is_null($this->backupGlobals) && is_bool($backupGlobals)) {
$this->backupGlobals = $backupGlobals;
}
}
public function setBackupStaticAttributes($backupStaticAttributes)
{
if (is_null($this->backupStaticAttributes) &&
is_bool($backupStaticAttributes)) {
$this->backupStaticAttributes = $backupStaticAttributes;
}
}
public function setRunTestInSeparateProcess($runTestInSeparateProcess)
{
if (is_bool($runTestInSeparateProcess)) {
if ($this->runTestInSeparateProcess === null) {
$this->runTestInSeparateProcess = $runTestInSeparateProcess;
}
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
}
public function setPreserveGlobalState($preserveGlobalState)
{
if (is_bool($preserveGlobalState)) {
$this->preserveGlobalState = $preserveGlobalState;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
}
public function setInIsolation($inIsolation)
{
if (is_bool($inIsolation)) {
$this->inIsolation = $inIsolation;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
}
public function isInIsolation()
{
return $this->inIsolation;
}
public function getResult()
{
return $this->testResult;
}
public function setResult($result)
{
$this->testResult = $result;
}
public function setOutputCallback($callback)
{
if (!is_callable($callback)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'callback');
}
$this->outputCallback = $callback;
}
public function getTestResultObject()
{
return $this->result;
}
public function setTestResultObject(PHPUnit_Framework_TestResult $result)
{
$this->result = $result;
}
public function registerMockObject(PHPUnit_Framework_MockObject_MockObject $mockObject)
{
$this->mockObjects[] = $mockObject;
}
protected function iniSet($varName, $newValue)
{
if (!is_string($varName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$currentValue = ini_set($varName, $newValue);
if ($currentValue !== false) {
$this->iniSettings[$varName] = $currentValue;
} else {
throw new PHPUnit_Framework_Exception(
sprintf(
'INI setting "%s" could not be set to "%s".',
$varName,
$newValue
)
);
}
}
protected function setLocale()
{
$args = func_get_args();
if (count($args) < 2) {
throw new PHPUnit_Framework_Exception;
}
$category = $args[0];
$locale = $args[1];
$categories = [
LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME
];
if (defined('LC_MESSAGES')) {
$categories[] = LC_MESSAGES;
}
if (!in_array($category, $categories)) {
throw new PHPUnit_Framework_Exception;
}
if (!is_array($locale) && !is_string($locale)) {
throw new PHPUnit_Framework_Exception;
}
$this->locale[$category] = setlocale($category, 0);
$result = call_user_func_array('setlocale', $args);
if ($result === false) {
throw new PHPUnit_Framework_Exception(
'The locale functionality is not implemented on your platform, ' .
'the specified locale does not exist or the category name is ' .
'invalid.'
);
}
}
public function getMockBuilder($className)
{
return new PHPUnit_Framework_MockObject_MockBuilder($this, $className);
}
protected function createMock($originalClassName)
{
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->getMock();
}
protected function createPartialMock($originalClassName, array $methods)
{
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->setMethods(empty($methods) ? null : $methods)
->getMock();
}
protected function getMock($originalClassName, $methods = [], array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $cloneArguments = false, $callOriginalMethods = false, $proxyTarget = null)
{
$this->warnings[] = 'PHPUnit_Framework_TestCase::getMock() is deprecated, use PHPUnit_Framework_TestCase::createMock() or PHPUnit_Framework_TestCase::getMockBuilder() instead';
$mockObject = $this->getMockObjectGenerator()->getMock(
$originalClassName,
$methods,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$cloneArguments,
$callOriginalMethods,
$proxyTarget
);
$this->registerMockObject($mockObject);
return $mockObject;
}
protected function getMockWithoutInvokingTheOriginalConstructor($originalClassName)
{
$this->warnings[] = 'PHPUnit_Framework_TestCase::getMockWithoutInvokingTheOriginalConstructor() is deprecated, use PHPUnit_Framework_TestCase::createMock() instead';
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->getMock();
}
protected function getMockClass($originalClassName, $methods = [], array $arguments = [], $mockClassName = '', $callOriginalConstructor = false, $callOriginalClone = true, $callAutoload = true, $cloneArguments = false)
{
$mock = $this->getMockObjectGenerator()->getMock(
$originalClassName,
$methods,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$cloneArguments
);
return get_class($mock);
}
protected function getMockForAbstractClass($originalClassName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = false)
{
$mockObject = $this->getMockObjectGenerator()->getMockForAbstractClass(
$originalClassName,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$mockedMethods,
$cloneArguments
);
$this->registerMockObject($mockObject);
return $mockObject;
}
protected function getMockFromWsdl($wsdlFile, $originalClassName = '', $mockClassName = '', array $methods = [], $callOriginalConstructor = true, array $options = [])
{
if ($originalClassName === '') {
$originalClassName = str_replace('.wsdl', '', basename($wsdlFile));
}
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;
}
protected function getMockForTrait($traitName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = false)
{
$mockObject = $this->getMockObjectGenerator()->getMockForTrait(
$traitName,
$arguments,
$mockClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$mockedMethods,
$cloneArguments
);
$this->registerMockObject($mockObject);
return $mockObject;
}
protected function getObjectForTrait($traitName, array $arguments = [], $traitClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $cloneArguments = false)
{
return $this->getMockObjectGenerator()->getObjectForTrait(
$traitName,
$arguments,
$traitClassName,
$callOriginalConstructor,
$callOriginalClone,
$callAutoload,
$cloneArguments
);
}
protected function prophesize($classOrInterface = null)
{
return $this->getProphet()->prophesize($classOrInterface);
}
public function addToAssertionCount($count)
{
$this->numAssertions += $count;
}
public function getNumAssertions()
{
return $this->numAssertions;
}
public static function any()
{
return new PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount;
}
public static function never()
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedCount(0);
}
public static function atLeast($requiredInvocations)
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastCount(
$requiredInvocations
);
}
public static function atLeastOnce()
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce;
}
public static function once()
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedCount(1);
}
public static function exactly($count)
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedCount($count);
}
public static function atMost($allowedInvocations)
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedAtMostCount(
$allowedInvocations
);
}
public static function at($index)
{
return new PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex($index);
}
public static function returnValue($value)
{
return new PHPUnit_Framework_MockObject_Stub_Return($value);
}
public static function returnValueMap(array $valueMap)
{
return new PHPUnit_Framework_MockObject_Stub_ReturnValueMap($valueMap);
}
public static function returnArgument($argumentIndex)
{
return new PHPUnit_Framework_MockObject_Stub_ReturnArgument(
$argumentIndex
);
}
public static function returnCallback($callback)
{
return new PHPUnit_Framework_MockObject_Stub_ReturnCallback($callback);
}
public static function returnSelf()
{
return new PHPUnit_Framework_MockObject_Stub_ReturnSelf();
}
public static function throwException($exception)
{
return new PHPUnit_Framework_MockObject_Stub_Exception($exception);
}
public static function onConsecutiveCalls()
{
$args = func_get_args();
return new PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls($args);
}
public function usesDataProvider()
{
return !empty($this->data);
}
public function dataDescription()
{
return is_string($this->dataName) ? $this->dataName : '';
}
protected function getDataSetAsString($includeData = true)
{
$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);
}
$exporter = new Exporter;
if ($includeData) {
$buffer .= sprintf(' (%s)', $exporter->shortenedRecursiveExport($this->data));
}
}
return $buffer;
}
protected function createResult()
{
return new PHPUnit_Framework_TestResult;
}
protected function handleDependencies()
{
if (!empty($this->dependencies) && !$this->inIsolation) {
$className = get_class($this);
$passed = $this->result->passed();
$passedKeys = array_keys($passed);
$numKeys = count($passedKeys);
for ($i = 0; $i < $numKeys; $i++) {
$pos = strpos($passedKeys[$i], ' with data set');
if ($pos !== false) {
$passedKeys[$i] = substr($passedKeys[$i], 0, $pos);
}
}
$passedKeys = array_flip(array_unique($passedKeys));
foreach ($this->dependencies as $dependency) {
$clone = false;
if (strpos($dependency, 'clone ') === 0) {
$clone = true;
$dependency = substr($dependency, strlen('clone '));
} elseif (strpos($dependency, '!clone ') === 0) {
$clone = false;
$dependency = substr($dependency, strlen('!clone '));
}
if (strpos($dependency, '::') === false) {
$dependency = $className . '::' . $dependency;
}
if (!isset($passedKeys[$dependency])) {
$this->result->addError(
$this,
new PHPUnit_Framework_SkippedTestError(
sprintf(
'This test depends on "%s" to pass.',
$dependency
)
),
0
);
return false;
}
if (isset($passed[$dependency])) {
if ($passed[$dependency]['size'] != PHPUnit_Util_Test::UNKNOWN &&
$this->getSize() != PHPUnit_Util_Test::UNKNOWN &&
$passed[$dependency]['size'] > $this->getSize()) {
$this->result->addError(
$this,
new PHPUnit_Framework_SkippedTestError(
'This test depends on a test that is larger than itself.'
),
0
);
return false;
}
if ($clone) {
$deepCopy = new DeepCopy;
$deepCopy->skipUncloneable(false);
$this->dependencyInput[$dependency] = $deepCopy->copy($passed[$dependency]['result']);
} else {
$this->dependencyInput[$dependency] = $passed[$dependency]['result'];
}
} else {
$this->dependencyInput[$dependency] = null;
}
}
}
return true;
}
public static function setUpBeforeClass()
{
}
protected function setUp()
{
}
protected function assertPreConditions()
{
}
protected function assertPostConditions()
{
}
protected function tearDown()
{
}
public static function tearDownAfterClass()
{
}
protected function onNotSuccessfulTest($e)
{
$expected = PHP_MAJOR_VERSION >= 7 ? 'Throwable' : 'Exception';
if ($e instanceof $expected) {
throw $e;
}
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'Throwable or Exception'
);
}
protected function prepareTemplate(Text_Template $template)
{
}
protected function getMockObjectGenerator()
{
if (null === $this->mockObjectGenerator) {
$this->mockObjectGenerator = new PHPUnit_Framework_MockObject_Generator;
}
return $this->mockObjectGenerator;
}
private function startOutputBuffering()
{
ob_start();
$this->outputBufferingActive = true;
$this->outputBufferingLevel = ob_get_level();
}
private function stopOutputBuffering()
{
if (ob_get_level() != $this->outputBufferingLevel) {
while (ob_get_level() >= $this->outputBufferingLevel) {
ob_end_clean();
}
throw new PHPUnit_Framework_RiskyTestError(
'Test code or tested code did not (only) close its own output buffers'
);
}
$output = ob_get_contents();
if ($this->outputCallback === false) {
$this->output = $output;
} else {
$this->output = call_user_func_array(
$this->outputCallback,
[$output]
);
}
ob_end_clean();
$this->outputBufferingActive = false;
$this->outputBufferingLevel = ob_get_level();
}
private function snapshotGlobalState()
{
$backupGlobals = $this->backupGlobals === null || $this->backupGlobals === true;
if ($this->runTestInSeparateProcess || $this->inIsolation ||
(!$backupGlobals && !$this->backupStaticAttributes)) {
return;
}
$this->snapshot = $this->createGlobalStateSnapshot($backupGlobals);
}
private function restoreGlobalState()
{
if (!$this->snapshot instanceof Snapshot) {
return;
}
$backupGlobals = $this->backupGlobals === null || $this->backupGlobals === true;
if ($this->beStrictAboutChangesToGlobalState) {
try {
$this->compareGlobalStateSnapshots(
$this->snapshot,
$this->createGlobalStateSnapshot($backupGlobals)
);
} catch (PHPUnit_Framework_RiskyTestError $rte) {
}
}
$restorer = new Restorer;
if ($backupGlobals) {
$restorer->restoreGlobalVariables($this->snapshot);
}
if ($this->backupStaticAttributes) {
$restorer->restoreStaticAttributes($this->snapshot);
}
$this->snapshot = null;
if (isset($rte)) {
throw $rte;
}
}
private function createGlobalStateSnapshot($backupGlobals)
{
$blacklist = new Blacklist;
foreach ($this->backupGlobalsBlacklist as $globalVariable) {
$blacklist->addGlobalVariable($globalVariable);
}
if (!defined('PHPUNIT_TESTSUITE')) {
$blacklist->addClassNamePrefix('PHPUnit');
$blacklist->addClassNamePrefix('File_Iterator');
$blacklist->addClassNamePrefix('SebastianBergmann\CodeCoverage');
$blacklist->addClassNamePrefix('PHP_Invoker');
$blacklist->addClassNamePrefix('PHP_Timer');
$blacklist->addClassNamePrefix('PHP_Token');
$blacklist->addClassNamePrefix('Symfony');
$blacklist->addClassNamePrefix('Text_Template');
$blacklist->addClassNamePrefix('Doctrine\Instantiator');
foreach ($this->backupStaticAttributesBlacklist as $class => $attributes) {
foreach ($attributes as $attribute) {
$blacklist->addStaticAttribute($class, $attribute);
}
}
}
return new Snapshot(
$blacklist,
$backupGlobals,
$this->backupStaticAttributes,
false,
false,
false,
false,
false,
false,
false
);
}
private function compareGlobalStateSnapshots(Snapshot $before, Snapshot $after)
{
$backupGlobals = $this->backupGlobals === null || $this->backupGlobals === true;
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"
);
}
}
private function compareGlobalStateSnapshotPart(array $before, array $after, $header)
{
if ($before != $after) {
$differ = new Differ($header);
$exporter = new Exporter;
$diff = $differ->diff(
$exporter->export($before),
$exporter->export($after)
);
throw new PHPUnit_Framework_RiskyTestError(
$diff
);
}
}
private function getProphet()
{
if ($this->prophet === null) {
$this->prophet = new Prophet;
}
return $this->prophet;
}
private function shouldInvocationMockerBeReset(PHPUnit_Framework_MockObject_MockObject $mock)
{
$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;
}
foreach ($enumerator->enumerate($this->testResult) as $object) {
if ($mock === $object) {
return false;
}
}
return true;
}
private function registerMockObjectsFromTestArguments(array $testArguments)
{
if ($this->registerMockObjectsFromTestArgumentsRecursively) {
$enumerator = new Enumerator;
foreach ($enumerator->enumerate($testArguments) as $object) {
if ($object instanceof PHPUnit_Framework_MockObject_MockObject) {
$this->registerMockObject($object);
}
}
} else {
foreach ($testArguments as $testArgument) {
if ($testArgument instanceof PHPUnit_Framework_MockObject_MockObject) {
$this->registerMockObject($testArgument);
} elseif (is_array($testArgument)) {
$this->registerMockObjectsFromTestArguments($testArgument);
}
}
}
}
}
<?php
class PHPUnit_Framework_TestFailure
{
private $testName;
protected $failedTest;
protected $thrownException;
public function __construct(PHPUnit_Framework_Test $failedTest, $t)
{
if ($failedTest instanceof PHPUnit_Framework_SelfDescribing) {
$this->testName = $failedTest->toString();
} else {
$this->testName = get_class($failedTest);
}
if (!$failedTest instanceof PHPUnit_Framework_TestCase || !$failedTest->isInIsolation()) {
$this->failedTest = $failedTest;
}
$this->thrownException = $t;
}
public function toString()
{
return sprintf(
'%s: %s',
$this->testName,
$this->thrownException->getMessage()
);
}
public function getExceptionAsString()
{
return self::exceptionToString($this->thrownException);
}
public static function exceptionToString(Exception $e)
{
if ($e instanceof PHPUnit_Framework_SelfDescribing) {
$buffer = $e->toString();
if ($e instanceof PHPUnit_Framework_ExpectationFailedException && $e->getComparisonFailure()) {
$buffer = $buffer . $e->getComparisonFailure()->getDiff();
}
if (!empty($buffer)) {
$buffer = trim($buffer) . "\n";
}
} elseif ($e instanceof PHPUnit_Framework_Error) {
$buffer = $e->getMessage() . "\n";
} elseif ($e instanceof PHPUnit_Framework_ExceptionWrapper) {
$buffer = $e->getClassname() . ': ' . $e->getMessage() . "\n";
} else {
$buffer = get_class($e) . ': ' . $e->getMessage() . "\n";
}
return $buffer;
}
public function getTestName()
{
return $this->testName;
}
public function failedTest()
{
return $this->failedTest;
}
public function thrownException()
{
return $this->thrownException;
}
public function exceptionMessage()
{
return $this->thrownException()->getMessage();
}
public function isFailure()
{
return ($this->thrownException() instanceof PHPUnit_Framework_AssertionFailedError);
}
}
<?php
interface PHPUnit_Framework_TestListener
{
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time);
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time);
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time);
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time);
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time);
public function startTestSuite(PHPUnit_Framework_TestSuite $suite);
public function endTestSuite(PHPUnit_Framework_TestSuite $suite);
public function startTest(PHPUnit_Framework_Test $test);
public function endTest(PHPUnit_Framework_Test $test, $time);
}
<?php
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Exception as CodeCoverageException;
use SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException;
use SebastianBergmann\CodeCoverage\MissingCoversAnnotationException;
use SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException;
use SebastianBergmann\ResourceOperations\ResourceOperations;
class PHPUnit_Framework_TestResult implements Countable
{
protected $passed = [];
protected $errors = [];
protected $failures = [];
protected $warnings = [];
protected $notImplemented = [];
protected $risky = [];
protected $skipped = [];
protected $listeners = [];
protected $runTests = 0;
protected $time = 0;
protected $topTestSuite = null;
protected $codeCoverage;
protected $convertErrorsToExceptions = true;
protected $stop = false;
protected $stopOnError = false;
protected $stopOnFailure = false;
protected $stopOnWarning = false;
protected $beStrictAboutTestsThatDoNotTestAnything = false;
protected $beStrictAboutOutputDuringTests = false;
protected $beStrictAboutTodoAnnotatedTests = false;
protected $beStrictAboutResourceUsageDuringSmallTests = false;
protected $enforceTimeLimit = false;
protected $timeoutForSmallTests = 1;
protected $timeoutForMediumTests = 10;
protected $timeoutForLargeTests = 60;
protected $stopOnRisky = false;
protected $stopOnIncomplete = false;
protected $stopOnSkipped = false;
protected $lastTestFailed = false;
private $registerMockObjectsFromTestArgumentsRecursively = false;
public function addListener(PHPUnit_Framework_TestListener $listener)
{
$this->listeners[] = $listener;
}
public function removeListener(PHPUnit_Framework_TestListener $listener)
{
foreach ($this->listeners as $key => $_listener) {
if ($listener === $_listener) {
unset($this->listeners[$key]);
}
}
}
public function flushListeners()
{
foreach ($this->listeners as $listener) {
if ($listener instanceof PHPUnit_Util_Printer) {
$listener->flush();
}
}
}
public function addError(PHPUnit_Framework_Test $test, $t, $time)
{
if ($t instanceof PHPUnit_Framework_RiskyTest) {
$this->risky[] = new PHPUnit_Framework_TestFailure($test, $t);
$notifyMethod = 'addRiskyTest';
if ($this->stopOnRisky) {
$this->stop();
}
} elseif ($t instanceof PHPUnit_Framework_IncompleteTest) {
$this->notImplemented[] = new PHPUnit_Framework_TestFailure($test, $t);
$notifyMethod = 'addIncompleteTest';
if ($this->stopOnIncomplete) {
$this->stop();
}
} elseif ($t instanceof PHPUnit_Framework_SkippedTest) {
$this->skipped[] = new PHPUnit_Framework_TestFailure($test, $t);
$notifyMethod = 'addSkippedTest';
if ($this->stopOnSkipped) {
$this->stop();
}
} else {
$this->errors[] = new PHPUnit_Framework_TestFailure($test, $t);
$notifyMethod = 'addError';
if ($this->stopOnError || $this->stopOnFailure) {
$this->stop();
}
}
if ($t instanceof Error) {
$t = new PHPUnit_Framework_ExceptionWrapper($t);
}
foreach ($this->listeners as $listener) {
$listener->$notifyMethod($test, $t, $time);
}
$this->lastTestFailed = true;
$this->time += $time;
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
if ($this->stopOnWarning) {
$this->stop();
}
$this->warnings[] = new PHPUnit_Framework_TestFailure($test, $e);
foreach ($this->listeners as $listener) {
if (method_exists($listener, 'addWarning')) {
$listener->addWarning($test, $e, $time);
}
}
$this->time += $time;
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
if ($e instanceof PHPUnit_Framework_RiskyTest ||
$e instanceof PHPUnit_Framework_OutputError) {
$this->risky[] = new PHPUnit_Framework_TestFailure($test, $e);
$notifyMethod = 'addRiskyTest';
if ($this->stopOnRisky) {
$this->stop();
}
} elseif ($e instanceof PHPUnit_Framework_IncompleteTest) {
$this->notImplemented[] = new PHPUnit_Framework_TestFailure($test, $e);
$notifyMethod = 'addIncompleteTest';
if ($this->stopOnIncomplete) {
$this->stop();
}
} elseif ($e instanceof PHPUnit_Framework_SkippedTest) {
$this->skipped[] = new PHPUnit_Framework_TestFailure($test, $e);
$notifyMethod = 'addSkippedTest';
if ($this->stopOnSkipped) {
$this->stop();
}
} else {
$this->failures[] = new PHPUnit_Framework_TestFailure($test, $e);
$notifyMethod = 'addFailure';
if ($this->stopOnFailure) {
$this->stop();
}
}
foreach ($this->listeners as $listener) {
$listener->$notifyMethod($test, $e, $time);
}
$this->lastTestFailed = true;
$this->time += $time;
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
if ($this->topTestSuite === null) {
$this->topTestSuite = $suite;
}
foreach ($this->listeners as $listener) {
$listener->startTestSuite($suite);
}
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
foreach ($this->listeners as $listener) {
$listener->endTestSuite($suite);
}
}
public function startTest(PHPUnit_Framework_Test $test)
{
$this->lastTestFailed = false;
$this->runTests += count($test);
foreach ($this->listeners as $listener) {
$listener->startTest($test);
}
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
foreach ($this->listeners as $listener) {
$listener->endTest($test, $time);
}
if (!$this->lastTestFailed && $test instanceof PHPUnit_Framework_TestCase) {
$class = get_class($test);
$key = $class . '::' . $test->getName();
$this->passed[$key] = [
'result' => $test->getResult(),
'size' => PHPUnit_Util_Test::getSize(
$class,
$test->getName(false)
)
];
$this->time += $time;
}
}
public function allHarmless()
{
return $this->riskyCount() == 0;
}
public function riskyCount()
{
return count($this->risky);
}
public function allCompletelyImplemented()
{
return $this->notImplementedCount() == 0;
}
public function notImplementedCount()
{
return count($this->notImplemented);
}
public function risky()
{
return $this->risky;
}
public function notImplemented()
{
return $this->notImplemented;
}
public function noneSkipped()
{
return $this->skippedCount() == 0;
}
public function skippedCount()
{
return count($this->skipped);
}
public function skipped()
{
return $this->skipped;
}
public function errorCount()
{
return count($this->errors);
}
public function errors()
{
return $this->errors;
}
public function failureCount()
{
return count($this->failures);
}
public function failures()
{
return $this->failures;
}
public function warningCount()
{
return count($this->warnings);
}
public function warnings()
{
return $this->warnings;
}
public function passed()
{
return $this->passed;
}
public function topTestSuite()
{
return $this->topTestSuite;
}
public function getCollectCodeCoverageInformation()
{
return $this->codeCoverage !== null;
}
public function run(PHPUnit_Framework_Test $test)
{
PHPUnit_Framework_Assert::resetCount();
if ($test instanceof PHPUnit_Framework_TestCase) {
$test->setRegisterMockObjectsFromTestArgumentsRecursively(
$this->registerMockObjectsFromTestArgumentsRecursively
);
}
$error = false;
$failure = false;
$warning = false;
$incomplete = false;
$risky = false;
$skipped = false;
$this->startTest($test);
$errorHandlerSet = false;
if ($this->convertErrorsToExceptions) {
$oldErrorHandler = set_error_handler(
['PHPUnit_Util_ErrorHandler', 'handleError'],
E_ALL | E_STRICT
);
if ($oldErrorHandler === null) {
$errorHandlerSet = true;
} else {
restore_error_handler();
}
}
$collectCodeCoverage = $this->codeCoverage !== null &&
!$test instanceof PHPUnit_Framework_WarningTestCase;
if ($collectCodeCoverage) {
$this->codeCoverage->start($test);
}
$monitorFunctions = $this->beStrictAboutResourceUsageDuringSmallTests &&
!$test instanceof PHPUnit_Framework_WarningTestCase &&
$test->getSize() == PHPUnit_Util_Test::SMALL &&
function_exists('xdebug_start_function_monitor');
if ($monitorFunctions) {
xdebug_start_function_monitor(ResourceOperations::getFunctions());
}
PHP_Timer::start();
try {
if (!$test instanceof PHPUnit_Framework_WarningTestCase &&
$test->getSize() != PHPUnit_Util_Test::UNKNOWN &&
$this->enforceTimeLimit &&
extension_loaded('pcntl') && class_exists('PHP_Invoker')) {
switch ($test->getSize()) {
case PHPUnit_Util_Test::SMALL:
$_timeout = $this->timeoutForSmallTests;
break;
case PHPUnit_Util_Test::MEDIUM:
$_timeout = $this->timeoutForMediumTests;
break;
case PHPUnit_Util_Test::LARGE:
$_timeout = $this->timeoutForLargeTests;
break;
}
$invoker = new PHP_Invoker;
$invoker->invoke([$test, 'runBare'], [], $_timeout);
} else {
$test->runBare();
}
} catch (PHPUnit_Framework_MockObject_Exception $e) {
$e = new PHPUnit_Framework_Warning(
$e->getMessage()
);
$warning = true;
} catch (PHPUnit_Framework_AssertionFailedError $e) {
$failure = true;
if ($e instanceof PHPUnit_Framework_RiskyTestError) {
$risky = true;
} elseif ($e instanceof PHPUnit_Framework_IncompleteTestError) {
$incomplete = true;
} elseif ($e instanceof PHPUnit_Framework_SkippedTestError) {
$skipped = true;
}
} catch (AssertionError $e) {
$test->addToAssertionCount(1);
$failure = true;
$frame = $e->getTrace()[0];
$e = new PHPUnit_Framework_AssertionFailedError(
sprintf(
'%s in %s:%s',
$e->getMessage(),
$frame['file'],
$frame['line']
)
);
} catch (PHPUnit_Framework_Warning $e) {
$warning = true;
} catch (PHPUnit_Framework_Exception $e) {
$error = true;
} catch (Throwable $e) {
$e = new PHPUnit_Framework_ExceptionWrapper($e);
$error = true;
} catch (Exception $e) {
$e = new PHPUnit_Framework_ExceptionWrapper($e);
$error = true;
}
$time = PHP_Timer::stop();
$test->addToAssertionCount(PHPUnit_Framework_Assert::getCount());
if ($monitorFunctions) {
$blacklist = new PHPUnit_Util_Blacklist;
$functions = xdebug_get_monitored_functions();
xdebug_stop_function_monitor();
foreach ($functions as $function) {
if (!$blacklist->isBlacklisted($function['filename'])) {
$this->addFailure(
$test,
new PHPUnit_Framework_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 PHPUnit_Framework_TestCase) {
try {
$linesToBeCovered = PHPUnit_Util_Test::getLinesToBeCovered(
get_class($test),
$test->getName(false)
);
$linesToBeUsed = PHPUnit_Util_Test::getLinesToBeUsed(
get_class($test),
$test->getName(false)
);
} catch (PHPUnit_Framework_InvalidCoversTargetException $cce) {
$this->addWarning(
$test,
new PHPUnit_Framework_Warning(
$cce->getMessage()
),
$time
);
}
}
try {
$this->codeCoverage->stop(
$append,
$linesToBeCovered,
$linesToBeUsed
);
} catch (UnintentionallyCoveredCodeException $cce) {
if (!$test->isMedium() && !$test->isLarge()) {
$this->addFailure(
$test,
new PHPUnit_Framework_UnintentionallyCoveredCodeError(
'This test executed code that is not listed as code to be covered or used:' .
PHP_EOL . $cce->getMessage()
),
$time
);
}
} catch (CoveredCodeNotExecutedException $cce) {
$this->addFailure(
$test,
new PHPUnit_Framework_CoveredCodeNotExecutedException(
'This test did not execute all the code that is listed as code to be covered:' .
PHP_EOL . $cce->getMessage()
),
$time
);
} catch (MissingCoversAnnotationException $cce) {
if ($linesToBeCovered !== false) {
$this->addFailure(
$test,
new PHPUnit_Framework_MissingCoversAnnotationException(
'This test does not have a @covers annotation but is expected to have one'
),
$time
);
}
} catch (CodeCoverageException $cce) {
$error = true;
if (!isset($e)) {
$e = $cce;
}
}
}
if ($errorHandlerSet === true) {
restore_error_handler();
}
if ($error === true) {
$this->addError($test, $e, $time);
} elseif ($failure === true) {
$this->addFailure($test, $e, $time);
} elseif ($warning === true) {
$this->addWarning($test, $e, $time);
} elseif ($this->beStrictAboutTestsThatDoNotTestAnything &&
$test->getNumAssertions() == 0) {
$this->addFailure(
$test,
new PHPUnit_Framework_RiskyTestError(
'This test did not perform any assertions'
),
$time
);
} elseif ($this->beStrictAboutOutputDuringTests && $test->hasOutput()) {
$this->addFailure(
$test,
new PHPUnit_Framework_OutputError(
sprintf(
'This test printed output: %s',
$test->getActualOutput()
)
),
$time
);
} elseif ($this->beStrictAboutTodoAnnotatedTests && $test instanceof PHPUnit_Framework_TestCase) {
$annotations = $test->getAnnotations();
if (isset($annotations['method']['todo'])) {
$this->addFailure(
$test,
new PHPUnit_Framework_RiskyTestError(
'Test method is annotated with @todo'
),
$time
);
}
}
$this->endTest($test, $time);
}
public function count()
{
return $this->runTests;
}
public function shouldStop()
{
return $this->stop;
}
public function stop()
{
$this->stop = true;
}
public function getCodeCoverage()
{
return $this->codeCoverage;
}
public function setCodeCoverage(CodeCoverage $codeCoverage)
{
$this->codeCoverage = $codeCoverage;
}
public function convertErrorsToExceptions($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->convertErrorsToExceptions = $flag;
}
public function getConvertErrorsToExceptions()
{
return $this->convertErrorsToExceptions;
}
public function stopOnError($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stopOnError = $flag;
}
public function stopOnFailure($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stopOnFailure = $flag;
}
public function stopOnWarning($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stopOnWarning = $flag;
}
public function beStrictAboutTestsThatDoNotTestAnything($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->beStrictAboutTestsThatDoNotTestAnything = $flag;
}
public function isStrictAboutTestsThatDoNotTestAnything()
{
return $this->beStrictAboutTestsThatDoNotTestAnything;
}
public function beStrictAboutOutputDuringTests($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->beStrictAboutOutputDuringTests = $flag;
}
public function isStrictAboutOutputDuringTests()
{
return $this->beStrictAboutOutputDuringTests;
}
public function beStrictAboutResourceUsageDuringSmallTests($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->beStrictAboutResourceUsageDuringSmallTests = $flag;
}
public function isStrictAboutResourceUsageDuringSmallTests()
{
return $this->beStrictAboutResourceUsageDuringSmallTests;
}
public function enforceTimeLimit($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->enforceTimeLimit = $flag;
}
public function enforcesTimeLimit()
{
return $this->enforceTimeLimit;
}
public function beStrictAboutTodoAnnotatedTests($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->beStrictAboutTodoAnnotatedTests = $flag;
}
public function isStrictAboutTodoAnnotatedTests()
{
return $this->beStrictAboutTodoAnnotatedTests;
}
public function stopOnRisky($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stopOnRisky = $flag;
}
public function stopOnIncomplete($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stopOnIncomplete = $flag;
}
public function stopOnSkipped($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stopOnSkipped = $flag;
}
public function time()
{
return $this->time;
}
public function wasSuccessful()
{
return empty($this->errors) && empty($this->failures) && empty($this->warnings);
}
public function setTimeoutForSmallTests($timeout)
{
if (!is_integer($timeout)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'integer');
}
$this->timeoutForSmallTests = $timeout;
}
public function setTimeoutForMediumTests($timeout)
{
if (!is_integer($timeout)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'integer');
}
$this->timeoutForMediumTests = $timeout;
}
public function setTimeoutForLargeTests($timeout)
{
if (!is_integer($timeout)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'integer');
}
$this->timeoutForLargeTests = $timeout;
}
public function getTimeoutForLargeTests()
{
return $this->timeoutForLargeTests;
}
public function setRegisterMockObjectsFromTestArgumentsRecursively($flag)
{
if (!is_bool($flag)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->registerMockObjectsFromTestArgumentsRecursively = $flag;
}
protected function getHierarchy($className, $asReflectionObjects = false)
{
if ($asReflectionObjects) {
$classes = [new ReflectionClass($className)];
} else {
$classes = [$className];
}
$done = false;
while (!$done) {
if ($asReflectionObjects) {
$class = new ReflectionClass(
$classes[count($classes) - 1]->getName()
);
} else {
$class = new ReflectionClass($classes[count($classes) - 1]);
}
$parent = $class->getParentClass();
if ($parent !== false) {
if ($asReflectionObjects) {
$classes[] = $parent;
} else {
$classes[] = $parent->getName();
}
} else {
$done = true;
}
}
return $classes;
}
}
<?php
class PHPUnit_Framework_TestSuite implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing, IteratorAggregate
{
private $cachedNumTests;
protected $backupGlobals = null;
protected $backupStaticAttributes = null;
private $beStrictAboutChangesToGlobalState = null;
protected $runTestInSeparateProcess = false;
protected $name = '';
protected $groups = [];
protected $tests = [];
protected $numTests = -1;
protected $testCase = false;
protected $foundClasses = [];
private $iteratorFilter = null;
public function __construct($theClass = '', $name = '')
{
$argumentsValid = false;
if (is_object($theClass) &&
$theClass instanceof ReflectionClass) {
$argumentsValid = true;
} elseif (is_string($theClass) &&
$theClass !== '' &&
class_exists($theClass, false)) {
$argumentsValid = true;
if ($name == '') {
$name = $theClass;
}
$theClass = new ReflectionClass($theClass);
} elseif (is_string($theClass)) {
$this->setName($theClass);
return;
}
if (!$argumentsValid) {
throw new PHPUnit_Framework_Exception;
}
if (!$theClass->isSubclassOf('PHPUnit_Framework_TestCase')) {
throw new PHPUnit_Framework_Exception(
'Class "' . $theClass->name . '" does not extend PHPUnit_Framework_TestCase.'
);
}
if ($name != '') {
$this->setName($name);
} else {
$this->setName($theClass->getName());
}
$constructor = $theClass->getConstructor();
if ($constructor !== null &&
!$constructor->isPublic()) {
$this->addTest(
self::warning(
sprintf(
'Class "%s" has no public constructor.',
$theClass->getName()
)
)
);
return;
}
foreach ($theClass->getMethods() as $method) {
$this->addTestMethod($theClass, $method);
}
if (empty($this->tests)) {
$this->addTest(
self::warning(
sprintf(
'No tests found in class "%s".',
$theClass->getName()
)
)
);
}
$this->testCase = true;
}
public function toString()
{
return $this->getName();
}
public function addTest(PHPUnit_Framework_Test $test, $groups = [])
{
$class = new ReflectionClass($test);
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 PHPUnit_Framework_TestCase) {
$test->setGroups($groups);
}
}
}
public function addTestSuite($testClass)
{
if (is_string($testClass) && class_exists($testClass)) {
$testClass = new ReflectionClass($testClass);
}
if (!is_object($testClass)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'class name or object'
);
}
if ($testClass instanceof self) {
$this->addTest($testClass);
} elseif ($testClass instanceof ReflectionClass) {
$suiteMethod = false;
if (!$testClass->isAbstract()) {
if ($testClass->hasMethod(PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME)) {
$method = $testClass->getMethod(
PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME
);
if ($method->isStatic()) {
$this->addTest(
$method->invoke(null, $testClass->getName())
);
$suiteMethod = true;
}
}
}
if (!$suiteMethod && !$testClass->isAbstract()) {
$this->addTest(new self($testClass));
}
} else {
throw new PHPUnit_Framework_Exception;
}
}
public function addTestFile($filename)
{
if (!is_string($filename)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
if (file_exists($filename) && substr($filename, -5) == '.phpt') {
$this->addTest(
new PHPUnit_Extensions_PhptTestCase($filename)
);
return;
}
$classes = get_declared_classes();
$filename = PHPUnit_Util_Fileloader::checkAndLoad($filename);
$newClasses = array_diff(get_declared_classes(), $classes);
if (!empty($newClasses)) {
$this->foundClasses = array_merge($newClasses, $this->foundClasses);
}
$shortname = basename($filename, '.php');
$shortnameRegEx = '/(?:^|_|\\\\)' . preg_quote($shortname, '/') . '$/';
foreach ($this->foundClasses as $i => $className) {
if (preg_match($shortnameRegEx, $className)) {
$class = new ReflectionClass($className);
if ($class->getFileName() == $filename) {
$newClasses = [$className];
unset($this->foundClasses[$i]);
break;
}
}
}
foreach ($newClasses as $className) {
$class = new ReflectionClass($className);
if (!$class->isAbstract()) {
if ($class->hasMethod(PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME)) {
$method = $class->getMethod(
PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME
);
if ($method->isStatic()) {
$this->addTest($method->invoke(null, $className));
}
} elseif ($class->implementsInterface('PHPUnit_Framework_Test')) {
$this->addTestSuite($class);
}
}
}
$this->numTests = -1;
}
public function addTestFiles($filenames)
{
if (!(is_array($filenames) ||
(is_object($filenames) && $filenames instanceof Iterator))) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1,
'array or iterator'
);
}
foreach ($filenames as $filename) {
$this->addTestFile((string) $filename);
}
}
public function count($preferCache = false)
{
if ($preferCache && $this->cachedNumTests !== null) {
$numTests = $this->cachedNumTests;
} else {
$numTests = 0;
foreach ($this as $test) {
$numTests += count($test);
}
$this->cachedNumTests = $numTests;
}
return $numTests;
}
public static function createTest(ReflectionClass $theClass, $name)
{
$className = $theClass->getName();
if (!$theClass->isInstantiable()) {
return self::warning(
sprintf('Cannot instantiate class "%s".', $className)
);
}
$backupSettings = PHPUnit_Util_Test::getBackupSettings(
$className,
$name
);
$preserveGlobalState = PHPUnit_Util_Test::getPreserveGlobalStateSettings(
$className,
$name
);
$runTestInSeparateProcess = PHPUnit_Util_Test::getProcessIsolationSettings(
$className,
$name
);
$constructor = $theClass->getConstructor();
if ($constructor !== null) {
$parameters = $constructor->getParameters();
if (count($parameters) < 2) {
$test = new $className;
}
else {
try {
$data = PHPUnit_Util_Test::getProvidedData(
$className,
$name
);
} catch (PHPUnit_Framework_IncompleteTestError $e) {
$message = sprintf(
'Test for %s::%s marked incomplete by data provider',
$className,
$name
);
$_message = $e->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::incompleteTest($className, $name, $message);
} catch (PHPUnit_Framework_SkippedTestError $e) {
$message = sprintf(
'Test for %s::%s skipped by data provider',
$className,
$name
);
$_message = $e->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::skipTest($className, $name, $message);
} catch (Throwable $_t) {
$t = $_t;
} catch (Exception $_t) {
$t = $_t;
}
if (isset($t)) {
$message = sprintf(
'The data provider specified for %s::%s is invalid.',
$className,
$name
);
$_message = $t->getMessage();
if (!empty($_message)) {
$message .= "\n" . $_message;
}
$data = self::warning($message);
}
if (isset($data)) {
$test = new PHPUnit_Framework_TestSuite_DataProvider(
$className . '::' . $name
);
if (empty($data)) {
$data = self::warning(
sprintf(
'No tests found in suite "%s".',
$test->getName()
)
);
}
$groups = PHPUnit_Util_Test::getGroups($className, $name);
if ($data instanceof PHPUnit_Framework_WarningTestCase ||
$data instanceof PHPUnit_Framework_SkippedTestCase ||
$data instanceof PHPUnit_Framework_IncompleteTestCase) {
$test->addTest($data, $groups);
} else {
foreach ($data as $_dataName => $_data) {
$_test = new $className($name, $_data, $_dataName);
if ($runTestInSeparateProcess) {
$_test->setRunTestInSeparateProcess(true);
if ($preserveGlobalState !== null) {
$_test->setPreserveGlobalState($preserveGlobalState);
}
}
if ($backupSettings['backupGlobals'] !== null) {
$_test->setBackupGlobals(
$backupSettings['backupGlobals']
);
}
if ($backupSettings['backupStaticAttributes'] !== null) {
$_test->setBackupStaticAttributes(
$backupSettings['backupStaticAttributes']
);
}
$test->addTest($_test, $groups);
}
}
} else {
$test = new $className;
}
}
}
if (!isset($test)) {
throw new PHPUnit_Framework_Exception('No valid test provided.');
}
if ($test instanceof PHPUnit_Framework_TestCase) {
$test->setName($name);
if ($runTestInSeparateProcess) {
$test->setRunTestInSeparateProcess(true);
if ($preserveGlobalState !== null) {
$test->setPreserveGlobalState($preserveGlobalState);
}
}
if ($backupSettings['backupGlobals'] !== null) {
$test->setBackupGlobals($backupSettings['backupGlobals']);
}
if ($backupSettings['backupStaticAttributes'] !== null) {
$test->setBackupStaticAttributes(
$backupSettings['backupStaticAttributes']
);
}
}
return $test;
}
protected function createResult()
{
return new PHPUnit_Framework_TestResult;
}
public function getName()
{
return $this->name;
}
public function getGroups()
{
return array_keys($this->groups);
}
public function getGroupDetails()
{
return $this->groups;
}
public function setGroupDetails(array $groups)
{
$this->groups = $groups;
}
public function run(PHPUnit_Framework_TestResult $result = null)
{
if ($result === null) {
$result = $this->createResult();
}
if (count($this) == 0) {
return $result;
}
$hookMethods = PHPUnit_Util_Test::getHookMethods($this->name);
$result->startTestSuite($this);
try {
$this->setUp();
foreach ($hookMethods['beforeClass'] as $beforeClassMethod) {
if ($this->testCase === true &&
class_exists($this->name, false) &&
method_exists($this->name, $beforeClassMethod)) {
if ($missingRequirements = PHPUnit_Util_Test::getMissingRequirements($this->name, $beforeClassMethod)) {
$this->markTestSuiteSkipped(implode(PHP_EOL, $missingRequirements));
}
call_user_func([$this->name, $beforeClassMethod]);
}
}
} catch (PHPUnit_Framework_SkippedTestSuiteError $e) {
$numTests = count($this);
for ($i = 0; $i < $numTests; $i++) {
$result->startTest($this);
$result->addFailure($this, $e, 0);
$result->endTest($this, 0);
}
$this->tearDown();
$result->endTestSuite($this);
return $result;
} catch (Throwable $_t) {
$t = $_t;
} catch (Exception $_t) {
$t = $_t;
}
if (isset($t)) {
$numTests = count($this);
for ($i = 0; $i < $numTests; $i++) {
$result->startTest($this);
$result->addError($this, $t, 0);
$result->endTest($this, 0);
}
$this->tearDown();
$result->endTestSuite($this);
return $result;
}
foreach ($this as $test) {
if ($result->shouldStop()) {
break;
}
if ($test instanceof PHPUnit_Framework_TestCase ||
$test instanceof self) {
$test->setbeStrictAboutChangesToGlobalState($this->beStrictAboutChangesToGlobalState);
$test->setBackupGlobals($this->backupGlobals);
$test->setBackupStaticAttributes($this->backupStaticAttributes);
$test->setRunTestInSeparateProcess($this->runTestInSeparateProcess);
}
$test->run($result);
}
foreach ($hookMethods['afterClass'] as $afterClassMethod) {
if ($this->testCase === true && class_exists($this->name, false) && method_exists($this->name, $afterClassMethod)) {
call_user_func([$this->name, $afterClassMethod]);
}
}
$this->tearDown();
$result->endTestSuite($this);
return $result;
}
public function setRunTestInSeparateProcess($runTestInSeparateProcess)
{
if (is_bool($runTestInSeparateProcess)) {
$this->runTestInSeparateProcess = $runTestInSeparateProcess;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
}
public function runTest(PHPUnit_Framework_Test $test, PHPUnit_Framework_TestResult $result)
{
$test->run($result);
}
public function setName($name)
{
$this->name = $name;
}
public function testAt($index)
{
if (isset($this->tests[$index])) {
return $this->tests[$index];
} else {
return false;
}
}
public function tests()
{
return $this->tests;
}
public function setTests(array $tests)
{
$this->tests = $tests;
}
public function markTestSuiteSkipped($message = '')
{
throw new PHPUnit_Framework_SkippedTestSuiteError($message);
}
protected function addTestMethod(ReflectionClass $class, ReflectionMethod $method)
{
if (!$this->isTestMethod($method)) {
return;
}
$name = $method->getName();
if (!$method->isPublic()) {
$this->addTest(
self::warning(
sprintf(
'Test method "%s" in test class "%s" is not public.',
$name,
$class->getName()
)
)
);
return;
}
$test = self::createTest($class, $name);
if ($test instanceof PHPUnit_Framework_TestCase ||
$test instanceof PHPUnit_Framework_TestSuite_DataProvider) {
$test->setDependencies(
PHPUnit_Util_Test::getDependencies($class->getName(), $name)
);
}
$this->addTest(
$test,
PHPUnit_Util_Test::getGroups($class->getName(), $name)
);
}
public static function isTestMethod(ReflectionMethod $method)
{
if (strpos($method->name, 'test') === 0) {
return true;
}
$docComment = $method->getDocComment();
return strpos($docComment, '@test') !== false ||
strpos($docComment, '@scenario') !== false;
}
protected static function warning($message)
{
return new PHPUnit_Framework_WarningTestCase($message);
}
protected static function skipTest($class, $methodName, $message)
{
return new PHPUnit_Framework_SkippedTestCase($class, $methodName, $message);
}
protected static function incompleteTest($class, $methodName, $message)
{
return new PHPUnit_Framework_IncompleteTestCase($class, $methodName, $message);
}
public function setbeStrictAboutChangesToGlobalState($beStrictAboutChangesToGlobalState)
{
if (is_null($this->beStrictAboutChangesToGlobalState) && is_bool($beStrictAboutChangesToGlobalState)) {
$this->beStrictAboutChangesToGlobalState = $beStrictAboutChangesToGlobalState;
}
}
public function setBackupGlobals($backupGlobals)
{
if (is_null($this->backupGlobals) && is_bool($backupGlobals)) {
$this->backupGlobals = $backupGlobals;
}
}
public function setBackupStaticAttributes($backupStaticAttributes)
{
if (is_null($this->backupStaticAttributes) &&
is_bool($backupStaticAttributes)) {
$this->backupStaticAttributes = $backupStaticAttributes;
}
}
public function getIterator()
{
$iterator = new PHPUnit_Util_TestSuiteIterator($this);
if ($this->iteratorFilter !== null) {
$iterator = $this->iteratorFilter->factory($iterator, $this);
}
return $iterator;
}
public function injectFilter(PHPUnit_Runner_Filter_Factory $filter)
{
$this->iteratorFilter = $filter;
foreach ($this as $test) {
if ($test instanceof self) {
$test->injectFilter($filter);
}
}
}
protected function setUp()
{
}
protected function tearDown()
{
}
}
<?php
class PHPUnit_Framework_TestSuite_DataProvider extends PHPUnit_Framework_TestSuite
{
public function setDependencies(array $dependencies)
{
foreach ($this->tests as $test) {
$test->setDependencies($dependencies);
}
}
}
<?php
class PHPUnit_Framework_UnintentionallyCoveredCodeError extends PHPUnit_Framework_RiskyTestError
{
}
<?php
class PHPUnit_Framework_Warning extends PHPUnit_Framework_Exception implements PHPUnit_Framework_SelfDescribing
{
public function toString()
{
return $this->getMessage();
}
}
<?php
class PHPUnit_Framework_WarningTestCase extends PHPUnit_Framework_TestCase
{
protected $message = '';
protected $backupGlobals = false;
protected $backupStaticAttributes = false;
protected $runTestInSeparateProcess = false;
protected $useErrorHandler = false;
public function __construct($message = '')
{
$this->message = $message;
parent::__construct('Warning');
}
protected function runTest()
{
throw new PHPUnit_Framework_Warning($this->message);
}
public function getMessage()
{
return $this->message;
}
public function toString()
{
return 'Warning';
}
}
<?php
abstract class PHPUnit_Runner_BaseTestRunner
{
const STATUS_PASSED = 0;
const STATUS_SKIPPED = 1;
const STATUS_INCOMPLETE = 2;
const STATUS_FAILURE = 3;
const STATUS_ERROR = 4;
const STATUS_RISKY = 5;
const STATUS_WARNING = 6;
const SUITE_METHODNAME = 'suite';
public function getLoader()
{
return new PHPUnit_Runner_StandardTestSuiteLoader;
}
public function getTest($suiteClassName, $suiteClassFile = '', $suffixes = '')
{
if (is_dir($suiteClassName) &&
!is_file($suiteClassName . '.php') && empty($suiteClassFile)) {
$facade = new File_Iterator_Facade;
$files = $facade->getFilesAsArray(
$suiteClassName,
$suffixes
);
$suite = new PHPUnit_Framework_TestSuite($suiteClassName);
$suite->addTestFiles($files);
return $suite;
}
try {
$testClass = $this->loadSuiteClass(
$suiteClassName,
$suiteClassFile
);
} catch (PHPUnit_Framework_Exception $e) {
$this->runFailed($e->getMessage());
return;
}
try {
$suiteMethod = $testClass->getMethod(self::SUITE_METHODNAME);
if (!$suiteMethod->isStatic()) {
$this->runFailed(
'suite() method must be static.'
);
return;
}
try {
$test = $suiteMethod->invoke(null, $testClass->getName());
} catch (ReflectionException $e) {
$this->runFailed(
sprintf(
"Failed to invoke suite() method.\n%s",
$e->getMessage()
)
);
return;
}
} catch (ReflectionException $e) {
try {
$test = new PHPUnit_Framework_TestSuite($testClass);
} catch (PHPUnit_Framework_Exception $e) {
$test = new PHPUnit_Framework_TestSuite;
$test->setName($suiteClassName);
}
}
$this->clearStatus();
return $test;
}
protected function loadSuiteClass($suiteClassName, $suiteClassFile = '')
{
$loader = $this->getLoader();
return $loader->load($suiteClassName, $suiteClassFile);
}
protected function clearStatus()
{
}
abstract protected function runFailed($message);
}
<?php
class PHPUnit_Runner_Exception extends RuntimeException implements PHPUnit_Exception
{
}
<?php
class PHPUnit_Runner_Filter_Factory
{
private $filters = [];
public function addFilter(ReflectionClass $filter, $args)
{
if (!$filter->isSubclassOf('RecursiveFilterIterator')) {
throw new InvalidArgumentException(
sprintf(
'Class "%s" does not extend RecursiveFilterIterator',
$filter->name
)
);
}
$this->filters[] = [$filter, $args];
}
public function factory(Iterator $iterator, PHPUnit_Framework_TestSuite $suite)
{
foreach ($this->filters as $filter) {
list($class, $args) = $filter;
$iterator = $class->newInstance($iterator, $args, $suite);
}
return $iterator;
}
}
<?php
abstract class PHPUnit_Runner_Filter_GroupFilterIterator extends RecursiveFilterIterator
{
protected $groupTests = [];
public function __construct(RecursiveIterator $iterator, array $groups, PHPUnit_Framework_TestSuite $suite)
{
parent::__construct($iterator);
foreach ($suite->getGroupDetails() as $group => $tests) {
if (in_array($group, $groups)) {
$testHashes = array_map(
function ($test) {
return spl_object_hash($test);
},
$tests
);
$this->groupTests = array_merge($this->groupTests, $testHashes);
}
}
}
public function accept()
{
$test = $this->getInnerIterator()->current();
if ($test instanceof PHPUnit_Framework_TestSuite) {
return true;
}
return $this->doAccept(spl_object_hash($test));
}
abstract protected function doAccept($hash);
}
<?php
class PHPUnit_Runner_Filter_Group_Exclude extends PHPUnit_Runner_Filter_GroupFilterIterator
{
protected function doAccept($hash)
{
return !in_array($hash, $this->groupTests);
}
}
<?php
class PHPUnit_Runner_Filter_Group_Include extends PHPUnit_Runner_Filter_GroupFilterIterator
{
protected function doAccept($hash)
{
return in_array($hash, $this->groupTests);
}
}
<?php
class PHPUnit_Runner_Filter_Test extends RecursiveFilterIterator
{
protected $filter = null;
protected $filterMin;
protected $filterMax;
public function __construct(RecursiveIterator $iterator, $filter)
{
parent::__construct($iterator);
$this->setFilter($filter);
}
protected function setFilter($filter)
{
if (PHPUnit_Util_Regex::pregMatchSafe($filter, '') === false) {
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 = $matches[2];
$this->filterMax = $matches[3];
} else {
$filter = sprintf(
'%s.*with data set #%s$',
$matches[1],
$matches[2]
);
}
}
elseif (preg_match('/^(.*?)@(.+)$/', $filter, $matches)) {
$filter = sprintf(
'%s.*with data set "%s"$',
$matches[1],
$matches[2]
);
}
$filter = sprintf('/%s/', str_replace(
'/',
'\\/',
$filter
));
}
$this->filter = $filter;
}
public function accept()
{
$test = $this->getInnerIterator()->current();
if ($test instanceof PHPUnit_Framework_TestSuite) {
return true;
}
$tmp = PHPUnit_Util_Test::describe($test, false);
if ($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 $accepted;
}
}
<?php
class PHPUnit_Runner_StandardTestSuiteLoader implements PHPUnit_Runner_TestSuiteLoader
{
public function load($suiteClassName, $suiteClassFile = '')
{
$suiteClassName = str_replace('.php', '', $suiteClassName);
if (empty($suiteClassFile)) {
$suiteClassFile = PHPUnit_Util_Filesystem::classNameToFilename(
$suiteClassName
);
}
if (!class_exists($suiteClassName, false)) {
$loadedClasses = get_declared_classes();
$filename = PHPUnit_Util_Fileloader::checkAndLoad($suiteClassFile);
$loadedClasses = array_values(
array_diff(get_declared_classes(), $loadedClasses)
);
}
if (!class_exists($suiteClassName, false) && !empty($loadedClasses)) {
$offset = 0 - strlen($suiteClassName);
foreach ($loadedClasses as $loadedClass) {
$class = new ReflectionClass($loadedClass);
if (substr($loadedClass, $offset) === $suiteClassName &&
$class->getFileName() == $filename) {
$suiteClassName = $loadedClass;
break;
}
}
}
if (!class_exists($suiteClassName, false) && !empty($loadedClasses)) {
$testCaseClass = 'PHPUnit_Framework_TestCase';
foreach ($loadedClasses as $loadedClass) {
$class = new ReflectionClass($loadedClass);
$classFile = $class->getFileName();
if ($class->isSubclassOf($testCaseClass) &&
!$class->isAbstract()) {
$suiteClassName = $loadedClass;
$testCaseClass = $loadedClass;
if ($classFile == realpath($suiteClassFile)) {
break;
}
}
if ($class->hasMethod('suite')) {
$method = $class->getMethod('suite');
if (!$method->isAbstract() &&
$method->isPublic() &&
$method->isStatic()) {
$suiteClassName = $loadedClass;
if ($classFile == realpath($suiteClassFile)) {
break;
}
}
}
}
}
if (class_exists($suiteClassName, false)) {
$class = new ReflectionClass($suiteClassName);
if ($class->getFileName() == realpath($suiteClassFile)) {
return $class;
}
}
throw new PHPUnit_Framework_Exception(
sprintf(
"Class '%s' could not be found in '%s'.",
$suiteClassName,
$suiteClassFile
)
);
}
public function reload(ReflectionClass $aClass)
{
return $aClass;
}
}
<?php
interface PHPUnit_Runner_TestSuiteLoader
{
public function load($suiteClassName, $suiteClassFile = '');
public function reload(ReflectionClass $aClass);
}
<?php
class PHPUnit_Runner_Version
{
private static $pharVersion;
private static $version;
public static function id()
{
if (self::$pharVersion !== null) {
return self::$pharVersion;
}
if (self::$version === null) {
$version = new SebastianBergmann\Version('5.5.5', dirname(dirname(__DIR__)));
self::$version = $version->getVersion();
}
return self::$version;
}
public static function series()
{
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()
{
return 'PHPUnit ' . self::id() . ' by Sebastian Bergmann and contributors.';
}
public static function getReleaseChannel()
{
if (strpos(self::$pharVersion, '-') !== false) {
return '-nightly';
}
return '';
}
}
<?php
class PHPUnit_TextUI_Command
{
protected $arguments = [
'listGroups' => false,
'listSuites' => false,
'loader' => null,
'useDefaultConfiguration' => true
];
protected $options = [];
protected $longOptions = [
'atleast-version=' => null,
'bootstrap=' => 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,
'enforce-time-limit' => null,
'exclude-group=' => null,
'filter=' => null,
'generate-configuration' => null,
'group=' => null,
'help' => null,
'include-path=' => null,
'list-groups' => null,
'list-suites' => null,
'loader=' => null,
'log-json=' => null,
'log-junit=' => null,
'log-tap=' => null,
'log-teamcity=' => null,
'no-configuration' => null,
'no-coverage' => null,
'no-globals-backup' => null,
'printer=' => null,
'process-isolation' => null,
'repeat=' => null,
'report-useless-tests' => null,
'reverse-list' => null,
'static-backup' => null,
'stderr' => 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,
'tap' => 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
];
private $versionStringPrinted = false;
public static function main($exit = true)
{
$command = new static;
return $command->run($_SERVER['argv'], $exit);
}
public function run(array $argv, $exit = true)
{
$this->handleArguments($argv);
$runner = $this->createRunner();
if (is_object($this->arguments['test']) &&
$this->arguments['test'] instanceof PHPUnit_Framework_Test) {
$suite = $this->arguments['test'];
} else {
$suite = $runner->getTest(
$this->arguments['test'],
$this->arguments['testFile'],
$this->arguments['testSuffixes']
);
}
if ($this->arguments['listGroups']) {
$this->printVersionString();
print "Available test group(s):\n";
$groups = $suite->getGroups();
sort($groups);
foreach ($groups as $group) {
print " - $group\n";
}
if ($exit) {
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
} else {
return PHPUnit_TextUI_TestRunner::SUCCESS_EXIT;
}
}
if ($this->arguments['listSuites']) {
$this->printVersionString();
print "Available test suite(s):\n";
$configuration = PHPUnit_Util_Configuration::getInstance(
$this->arguments['configuration']
);
$suiteNames = $configuration->getTestSuiteNames();
foreach ($suiteNames as $suiteName) {
print " - $suiteName\n";
}
if ($exit) {
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
} else {
return PHPUnit_TextUI_TestRunner::SUCCESS_EXIT;
}
}
unset($this->arguments['test']);
unset($this->arguments['testFile']);
try {
$result = $runner->doRun($suite, $this->arguments, $exit);
} catch (PHPUnit_Framework_Exception $e) {
print $e->getMessage() . "\n";
}
$return = PHPUnit_TextUI_TestRunner::FAILURE_EXIT;
if (isset($result) && $result->wasSuccessful()) {
$return = PHPUnit_TextUI_TestRunner::SUCCESS_EXIT;
} elseif (!isset($result) || $result->errorCount() > 0) {
$return = PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT;
}
return $return;
}
protected function createRunner()
{
return new PHPUnit_TextUI_TestRunner($this->arguments['loader']);
}
protected function handleArguments(array $argv)
{
if (defined('__PHPUNIT_PHAR__')) {
$this->longOptions['check-version'] = null;
$this->longOptions['selfupdate'] = null;
$this->longOptions['self-update'] = null;
$this->longOptions['selfupgrade'] = null;
$this->longOptions['self-upgrade'] = null;
}
try {
$this->options = PHPUnit_Util_Getopt::getopt(
$argv,
'd:c:hv',
array_keys($this->longOptions)
);
} catch (PHPUnit_Framework_Exception $e) {
$this->showError($e->getMessage());
}
foreach ($this->options[0] as $option) {
switch ($option[0]) {
case '--colors':
$this->arguments['colors'] = $option[1] ?: PHPUnit_TextUI_ResultPrinter::COLOR_AUTO;
break;
case '--bootstrap':
$this->arguments['bootstrap'] = $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], true);
}
}
break;
case '--debug':
$this->arguments['debug'] = true;
break;
case 'h':
case '--help':
$this->showHelp();
exit(PHPUnit_TextUI_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();
printf(
"Generating phpunit.xml in %s\n\n",
getcwd()
);
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));
if ($bootstrapScript == '') {
$bootstrapScript = 'vendor/autoload.php';
}
if ($testsDirectory == '') {
$testsDirectory = 'tests';
}
if ($src == '') {
$src = 'src';
}
$generator = new PHPUnit_Util_ConfigurationGenerator;
file_put_contents(
'phpunit.xml',
$generator->generateDefaultConfiguration(
PHPUnit_Runner_Version::series(),
$bootstrapScript,
$testsDirectory,
$src
)
);
printf(
"\nGenerated phpunit.xml in %s\n",
getcwd()
);
exit(PHPUnit_TextUI_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 '--printer':
$this->arguments['printer'] = $option[1];
break;
case '--loader':
$this->arguments['loader'] = $option[1];
break;
case '--log-json':
$this->arguments['jsonLogfile'] = $option[1];
break;
case '--log-junit':
$this->arguments['junitLogfile'] = $option[1];
break;
case '--log-tap':
$this->arguments['tapLogfile'] = $option[1];
break;
case '--log-teamcity':
$this->arguments['teamcityLogfile'] = $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-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 '--tap':
$this->arguments['printer'] = 'PHPUnit_Util_Log_TAP';
break;
case '--teamcity':
$this->arguments['printer'] = 'PHPUnit_Util_Log_TeamCity';
break;
case '--testdox':
$this->arguments['printer'] = 'PHPUnit_Util_TestDox_ResultPrinter_Text';
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-coverage':
$this->arguments['noCoverage'] = true;
break;
case '--no-globals-backup':
$this->arguments['backupGlobals'] = false;
break;
case '--static-backup':
$this->arguments['backupStaticAttributes'] = true;
break;
case 'v':
case '--verbose':
$this->arguments['verbose'] = true;
break;
case '--atleast-version':
exit(version_compare(PHPUnit_Runner_Version::id(), $option[1], '>=')
? PHPUnit_TextUI_TestRunner::SUCCESS_EXIT
: PHPUnit_TextUI_TestRunner::FAILURE_EXIT
);
break;
case '--version':
$this->printVersionString();
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
break;
case '--report-useless-tests':
$this->arguments['reportUselessTests'] = true;
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 '--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 '--selfupdate':
case '--self-update':
$this->handleSelfUpdate();
break;
case '--selfupgrade':
case '--self-upgrade':
$this->handleSelfUpdate(true);
break;
case '--whitelist':
$this->arguments['whitelist'] = $option[1];
break;
default:
$optionName = str_replace('--', '', $option[0]);
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['test'])) {
if (isset($this->options[1][0])) {
$this->arguments['test'] = $this->options[1][0];
}
if (isset($this->options[1][1])) {
$this->arguments['testFile'] = realpath($this->options[1][1]);
} else {
$this->arguments['testFile'] = '';
}
if (isset($this->arguments['test']) &&
is_file($this->arguments['test']) &&
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['testSuffixes'])) {
$this->arguments['testSuffixes'] = ['Test.php', '.phpt'];
}
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 = PHPUnit_Util_Configuration::getInstance(
$this->arguments['configuration']
);
} catch (Throwable $e) {
print $e->getMessage() . "\n";
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
} catch (Exception $e) {
print $e->getMessage() . "\n";
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
}
$phpunitConfiguration = $configuration->getPHPUnitConfiguration();
$configuration->handlePHPConfiguration();
if (isset($this->arguments['bootstrap'])) {
$this->handleBootstrap($this->arguments['bootstrap']);
} elseif (isset($phpunitConfiguration['bootstrap'])) {
$this->handleBootstrap($phpunitConfiguration['bootstrap']);
}
if (isset($phpunitConfiguration['stderr']) && ! isset($this->arguments['stderr'])) {
$this->arguments['stderr'] = $phpunitConfiguration['stderr'];
}
if (isset($phpunitConfiguration['columns']) && ! isset($this->arguments['columns'])) {
$this->arguments['columns'] = $phpunitConfiguration['columns'];
}
if (!isset($this->arguments['printer']) && isset($phpunitConfiguration['printerClass'])) {
if (isset($phpunitConfiguration['printerFile'])) {
$file = $phpunitConfiguration['printerFile'];
} else {
$file = '';
}
$this->arguments['printer'] = $this->handlePrinter(
$phpunitConfiguration['printerClass'],
$file
);
}
if (isset($phpunitConfiguration['testSuiteLoaderClass'])) {
if (isset($phpunitConfiguration['testSuiteLoaderFile'])) {
$file = $phpunitConfiguration['testSuiteLoaderFile'];
} else {
$file = '';
}
$this->arguments['loader'] = $this->handleLoader(
$phpunitConfiguration['testSuiteLoaderClass'],
$file
);
}
if (!isset($this->arguments['test'])) {
$testSuite = $configuration->getTestSuiteConfiguration(isset($this->arguments['testsuite']) ? $this->arguments['testsuite'] : null);
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']) && is_string($this->arguments['test']) && substr($this->arguments['test'], -5, 5) == '.phpt') {
$test = new PHPUnit_Extensions_PhptTestCase($this->arguments['test']);
$this->arguments['test'] = new PHPUnit_Framework_TestSuite;
$this->arguments['test']->addTest($test);
}
if (!isset($this->arguments['test']) ||
(isset($this->arguments['testDatabaseLogRevision']) && !isset($this->arguments['testDatabaseDSN']))) {
$this->showHelp();
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
}
protected function handleLoader($loaderClass, $loaderFile = '')
{
if (!class_exists($loaderClass, false)) {
if ($loaderFile == '') {
$loaderFile = PHPUnit_Util_Filesystem::classNameToFilename(
$loaderClass
);
}
$loaderFile = stream_resolve_include_path($loaderFile);
if ($loaderFile) {
require $loaderFile;
}
}
if (class_exists($loaderClass, false)) {
$class = new ReflectionClass($loaderClass);
if ($class->implementsInterface('PHPUnit_Runner_TestSuiteLoader') &&
$class->isInstantiable()) {
return $class->newInstance();
}
}
if ($loaderClass == 'PHPUnit_Runner_StandardTestSuiteLoader') {
return;
}
$this->showError(
sprintf(
'Could not use "%s" as loader.',
$loaderClass
)
);
}
protected function handlePrinter($printerClass, $printerFile = '')
{
if (!class_exists($printerClass, false)) {
if ($printerFile == '') {
$printerFile = PHPUnit_Util_Filesystem::classNameToFilename(
$printerClass
);
}
$printerFile = stream_resolve_include_path($printerFile);
if ($printerFile) {
require $printerFile;
}
}
if (class_exists($printerClass)) {
$class = new ReflectionClass($printerClass);
if ($class->implementsInterface('PHPUnit_Framework_TestListener') &&
$class->isSubclassOf('PHPUnit_Util_Printer') &&
$class->isInstantiable()) {
if ($class->isSubclassOf('PHPUnit_TextUI_ResultPrinter')) {
return $printerClass;
}
$outputStream = isset($this->arguments['stderr']) ? 'php://stderr' : null;
return $class->newInstance($outputStream);
}
}
$this->showError(
sprintf(
'Could not use "%s" as printer.',
$printerClass
)
);
}
protected function handleBootstrap($filename)
{
try {
PHPUnit_Util_Fileloader::checkAndLoad($filename);
} catch (PHPUnit_Framework_Exception $e) {
$this->showError($e->getMessage());
}
}
protected function handleSelfUpdate($upgrade = false)
{
$this->printVersionString();
$localFilename = realpath($_SERVER['argv'][0]);
if (!is_writable($localFilename)) {
print 'No write permission to update ' . $localFilename . "\n";
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
if (!extension_loaded('openssl')) {
print "The OpenSSL extension is not loaded.\n";
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
if (!$upgrade) {
$remoteFilename = sprintf(
'https://phar.phpunit.de/phpunit-%s.phar',
file_get_contents(
sprintf(
'https://phar.phpunit.de/latest-version-of/phpunit-%s',
PHPUnit_Runner_Version::series()
)
)
);
} else {
$remoteFilename = sprintf(
'https://phar.phpunit.de/phpunit%s.phar',
PHPUnit_Runner_Version::getReleaseChannel()
);
}
$tempFilename = tempnam(sys_get_temp_dir(), 'phpunit') . '.phar';
$caFile = dirname($tempFilename) . '/ca.pem';
copy(__PHPUNIT_PHAR_ROOT__ . '/ca.pem', $caFile);
print 'Updating the PHPUnit PHAR ... ';
$options = [
'ssl' => [
'allow_self_signed' => false,
'cafile' => $caFile,
'verify_peer' => true
]
];
file_put_contents(
$tempFilename,
file_get_contents(
$remoteFilename,
false,
stream_context_create($options)
)
);
chmod($tempFilename, 0777 & ~umask());
try {
$phar = new Phar($tempFilename);
unset($phar);
rename($tempFilename, $localFilename);
unlink($caFile);
} catch (Throwable $_e) {
$e = $_e;
} catch (Exception $_e) {
$e = $_e;
}
if (isset($e)) {
unlink($caFile);
unlink($tempFilename);
print " done\n\n" . $e->getMessage() . "\n";
exit(2);
}
print " done\n";
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
}
protected function handleVersionCheck()
{
$this->printVersionString();
$latestVersion = file_get_contents('https://phar.phpunit.de/latest-version-of/phpunit');
$isOutdated = version_compare($latestVersion, PHPUnit_Runner_Version::id(), '>');
if ($isOutdated) {
print "You are not using the latest version of PHPUnit.\n";
print 'Use "phpunit --self-upgrade" to install PHPUnit ' . $latestVersion . "\n";
} else {
print "You are using the latest version of PHPUnit.\n";
}
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
}
protected function showHelp()
{
$this->printVersionString();
print <<<EOT
Usage: phpunit [options] UnitTest [UnitTest.php]
phpunit [options] <directory>
Code Coverage Options:
--coverage-clover <file> Generate code coverage report in Clover XML format.
--coverage-crap4j <file> Generate code coverage report in Crap4J XML format.
--coverage-html <dir> Generate code coverage report in HTML format.
--coverage-php <file> Export PHP_CodeCoverage object to file.
--coverage-text=<file> Generate code coverage report in text format.
Default: Standard output.
--coverage-xml <dir> Generate code coverage report in PHPUnit XML format.
--whitelist <dir> Whitelist <dir> for code coverage analysis.
--disable-coverage-ignore Disable annotations for ignoring code coverage.
Logging Options:
--log-junit <file> Log test execution in JUnit XML format to file.
--log-tap <file> Log test execution in TAP format to file.
--log-teamcity <file> Log test execution in TeamCity format to file.
--log-json <file> Log test execution in JSON format.
--testdox-html <file> Write agile documentation in HTML format to file.
--testdox-text <file> Write agile documentation in Text format to file.
--testdox-xml <file> Write agile documentation in XML format to file.
--reverse-list Print defects in reverse order
Test Selection Options:
--filter <pattern> Filter which tests to run.
--testsuite <pattern> Filter which testsuite to run.
--group ... Only runs tests from the specified group(s).
--exclude-group ... Exclude tests from the specified group(s).
--list-groups List available test groups.
--list-suites List available test suites.
--test-suffix ... Only search for test in files with specified
suffix(es). Default: Test.php,.phpt
Test Execution Options:
--report-useless-tests Be strict about tests that do not test anything.
--strict-coverage Be strict about @covers annotation usage.
--strict-global-state Be strict about changes to global state
--disallow-test-output Be strict about output during tests.
--disallow-resource-usage Be strict about resource usage during small tests.
--enforce-time-limit Enforce time limit based on test size.
--disallow-todo-tests Disallow @todo-annotated tests.
--process-isolation Run each test in a separate PHP process.
--no-globals-backup Do not backup and restore \$GLOBALS for each test.
--static-backup Backup and restore static attributes for each test.
--colors=<flag> Use colors in output ("never", "auto" or "always").
--columns <n> Number of columns to use for progress output.
--columns max Use maximum number of columns for progress output.
--stderr Write to STDERR instead of STDOUT.
--stop-on-error Stop execution upon first error.
--stop-on-failure Stop execution upon first error or failure.
--stop-on-warning Stop execution upon first warning.
--stop-on-risky Stop execution upon first risky test.
--stop-on-skipped Stop execution upon first skipped test.
--stop-on-incomplete Stop execution upon first incomplete test.
--fail-on-warning Treat tests with warnings as failures.
--fail-on-risky Treat risky tests as failures.
-v|--verbose Output more verbose information.
--debug Display debugging information during test execution.
--loader <loader> TestSuiteLoader implementation to use.
--repeat <times> Runs the test(s) repeatedly.
--tap Report test execution progress in TAP format.
--teamcity Report test execution progress in TeamCity format.
--testdox Report test execution progress in TestDox format.
--testdox-group Only include tests from the specified group(s).
--testdox-exclude-group Exclude tests from the specified group(s).
--printer <printer> TestListener implementation to use.
Configuration Options:
--bootstrap <file> A "bootstrap" PHP file that is run before the tests.
-c|--configuration <file> Read configuration from XML file.
--no-configuration Ignore default configuration file (phpunit.xml).
--no-coverage Ignore code coverage configuration.
--include-path <path(s)> Prepend PHP's include_path with given path(s).
-d key[=value] Sets a php.ini value.
--generate-configuration Generate configuration file with suggested settings.
Miscellaneous Options:
-h|--help Prints this usage information.
--version Prints the version and exits.
--atleast-version <min> Checks that version is greater than min and exits.
EOT;
if (defined('__PHPUNIT_PHAR__')) {
print "\n --check-version Check whether PHPUnit is the latest version.";
print "\n --self-update Update PHPUnit to the latest version within the same\n release series.\n";
print "\n --self-upgrade Upgrade PHPUnit to the latest version.\n";
}
}
protected function handleCustomTestSuite()
{
}
private function printVersionString()
{
if ($this->versionStringPrinted) {
return;
}
print PHPUnit_Runner_Version::getVersionString() . "\n\n";
$this->versionStringPrinted = true;
}
private function showError($message)
{
$this->printVersionString();
print $message . "\n";
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
}
}
<?php
use SebastianBergmann\Environment\Console;
class PHPUnit_TextUI_ResultPrinter extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
const EVENT_TEST_START = 0;
const EVENT_TEST_END = 1;
const EVENT_TESTSUITE_START = 2;
const EVENT_TESTSUITE_END = 3;
const COLOR_NEVER = 'never';
const COLOR_AUTO = 'auto';
const COLOR_ALWAYS = 'always';
const COLOR_DEFAULT = self::COLOR_NEVER;
private static $ansiCodes = [
'bold' => 1,
'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-black' => 40,
'bg-red' => 41,
'bg-green' => 42,
'bg-yellow' => 43,
'bg-blue' => 44,
'bg-magenta' => 45,
'bg-cyan' => 46,
'bg-white' => 47
];
protected $column = 0;
protected $maxColumn;
protected $lastTestFailed = false;
protected $numAssertions = 0;
protected $numTests = -1;
protected $numTestsRun = 0;
protected $numTestsWidth;
protected $colors = false;
protected $debug = false;
protected $verbose = false;
private $numberOfColumns;
private $reverse = false;
private $defectListPrinted = false;
public function __construct($out = null, $verbose = false, $colors = self::COLOR_DEFAULT, $debug = false, $numberOfColumns = 80, $reverse = false)
{
parent::__construct($out);
if (!is_bool($verbose)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'boolean');
}
$availableColors = [self::COLOR_NEVER, self::COLOR_AUTO, self::COLOR_ALWAYS];
if (!in_array($colors, $availableColors)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
3,
vsprintf('value from "%s", "%s" or "%s"', $availableColors)
);
}
if (!is_bool($debug)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(4, 'boolean');
}
if (!is_int($numberOfColumns) && $numberOfColumns != 'max') {
throw PHPUnit_Util_InvalidArgumentHelper::factory(5, 'integer or "max"');
}
if (!is_bool($reverse)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(6, 'boolean');
}
$console = new Console;
$maxNumberOfColumns = $console->getNumberOfColumns();
if ($numberOfColumns == 'max' || $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);
}
}
public function printResult(PHPUnit_Framework_TestResult $result)
{
$this->printHeader();
$this->printErrors($result);
$this->printWarnings($result);
$this->printFailures($result);
if ($this->verbose) {
$this->printRisky($result);
$this->printIncompletes($result);
$this->printSkipped($result);
}
$this->printFooter($result);
}
protected function printDefects(array $defects, $type)
{
$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(PHPUnit_Framework_TestFailure $defect, $count)
{
$this->printDefectHeader($defect, $count);
$this->printDefectTrace($defect);
}
protected function printDefectHeader(PHPUnit_Framework_TestFailure $defect, $count)
{
$this->write(
sprintf(
"\n%d) %s\n",
$count,
$defect->getTestName()
)
);
}
protected function printDefectTrace(PHPUnit_Framework_TestFailure $defect)
{
$e = $defect->thrownException();
$this->write((string) $e);
while ($e = $e->getPrevious()) {
$this->write("\nCaused by\n" . $e);
}
}
protected function printErrors(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->errors(), 'error');
}
protected function printFailures(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->failures(), 'failure');
}
protected function printWarnings(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->warnings(), 'warning');
}
protected function printIncompletes(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->notImplemented(), 'incomplete test');
}
protected function printRisky(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->risky(), 'risky test');
}
protected function printSkipped(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->skipped(), 'skipped test');
}
protected function printHeader()
{
$this->write("\n\n" . PHP_Timer::resourceUsage() . "\n\n");
}
protected function printFooter(PHPUnit_Framework_TestResult $result)
{
if (count($result) === 0) {
$this->writeWithColor(
'fg-black, bg-yellow',
'No tests executed!'
);
return;
}
if ($result->wasSuccessful() &&
$result->allHarmless() &&
$result->allCompletelyImplemented() &&
$result->noneSkipped()) {
$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'
)
);
} else {
if ($result->wasSuccessful()) {
$color = 'fg-black, bg-yellow';
if ($this->verbose) {
$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, '.', true);
}
}
public function printWaitPrompt()
{
$this->write("\n<RETURN> to continue\n");
}
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgressWithColor('fg-red, bold', 'E');
$this->lastTestFailed = true;
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$this->writeProgressWithColor('bg-red, fg-white', 'F');
$this->lastTestFailed = true;
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
$this->writeProgressWithColor('fg-yellow, bold', 'W');
$this->lastTestFailed = true;
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgressWithColor('fg-yellow, bold', 'I');
$this->lastTestFailed = true;
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgressWithColor('fg-yellow, bold', 'R');
$this->lastTestFailed = true;
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgressWithColor('fg-cyan, bold', 'S');
$this->lastTestFailed = true;
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
if ($this->numTests == -1) {
$this->numTests = count($suite);
$this->numTestsWidth = strlen((string) $this->numTests);
$this->maxColumn = $this->numberOfColumns - strlen(' / (XXX%)') - (2 * $this->numTestsWidth);
}
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function startTest(PHPUnit_Framework_Test $test)
{
if ($this->debug) {
$this->write(
sprintf(
"\nStarting test '%s'.\n",
PHPUnit_Util_Test::describe($test)
)
);
}
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if (!$this->lastTestFailed) {
$this->writeProgress('.');
}
if ($test instanceof PHPUnit_Framework_TestCase) {
$this->numAssertions += $test->getNumAssertions();
} elseif ($test instanceof PHPUnit_Extensions_PhptTestCase) {
$this->numAssertions++;
}
$this->lastTestFailed = false;
if ($test instanceof PHPUnit_Framework_TestCase) {
if (!$test->hasExpectationOnOutput()) {
$this->write($test->getActualOutput());
}
}
}
protected function writeProgress($progress)
{
$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()
{
$this->column = 0;
$this->write("\n");
}
protected function formatWithColor($color, $buffer)
{
if (!$this->colors) {
return $buffer;
}
$codes = array_map('trim', explode(',', $color));
$lines = explode("\n", $buffer);
$padding = max(array_map('strlen', $lines));
$styles = [];
foreach ($codes as $code) {
$styles[] = self::$ansiCodes[$code];
}
$style = sprintf("\x1b[%sm", implode(';', $styles));
$styledLines = [];
foreach ($lines as $line) {
$styledLines[] = $style . str_pad($line, $padding) . "\x1b[0m";
}
return implode("\n", $styledLines);
}
protected function writeWithColor($color, $buffer, $lf = true)
{
$this->write($this->formatWithColor($color, $buffer));
if ($lf) {
$this->write("\n");
}
}
protected function writeProgressWithColor($color, $buffer)
{
$buffer = $this->formatWithColor($color, $buffer);
$this->writeProgress($buffer);
}
private function writeCountString($count, $name, $color, $always = false)
{
static $first = true;
if ($always || $count > 0) {
$this->writeWithColor(
$color,
sprintf(
'%s%s: %d',
!$first ? ', ' : '',
$name,
$count
),
false
);
$first = false;
}
}
}
<?php
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\Environment\Runtime;
class PHPUnit_TextUI_TestRunner extends PHPUnit_Runner_BaseTestRunner
{
const SUCCESS_EXIT = 0;
const FAILURE_EXIT = 1;
const EXCEPTION_EXIT = 2;
protected $codeCoverageFilter;
protected $loader = null;
protected $printer = null;
protected static $versionStringPrinted = false;
private $runtime;
private $messagePrinted = false;
public function __construct(PHPUnit_Runner_TestSuiteLoader $loader = null, CodeCoverageFilter $filter = null)
{
if ($filter === null) {
$filter = new CodeCoverageFilter;
}
$this->codeCoverageFilter = $filter;
$this->loader = $loader;
$this->runtime = new Runtime;
}
public static function run($test, array $arguments = [])
{
if ($test instanceof ReflectionClass) {
$test = new PHPUnit_Framework_TestSuite($test);
}
if ($test instanceof PHPUnit_Framework_Test) {
$aTestRunner = new self;
return $aTestRunner->doRun(
$test,
$arguments
);
} else {
throw new PHPUnit_Framework_Exception(
'No test case or test suite found.'
);
}
}
protected function createTestResult()
{
return new PHPUnit_Framework_TestResult;
}
private function processSuiteFilters(PHPUnit_Framework_TestSuite $suite, array $arguments)
{
if (!$arguments['filter'] &&
empty($arguments['groups']) &&
empty($arguments['excludeGroups'])) {
return;
}
$filterFactory = new PHPUnit_Runner_Filter_Factory();
if (!empty($arguments['excludeGroups'])) {
$filterFactory->addFilter(
new ReflectionClass('PHPUnit_Runner_Filter_Group_Exclude'),
$arguments['excludeGroups']
);
}
if (!empty($arguments['groups'])) {
$filterFactory->addFilter(
new ReflectionClass('PHPUnit_Runner_Filter_Group_Include'),
$arguments['groups']
);
}
if ($arguments['filter']) {
$filterFactory->addFilter(
new ReflectionClass('PHPUnit_Runner_Filter_Test'),
$arguments['filter']
);
}
$suite->injectFilter($filterFactory);
}
public function doRun(PHPUnit_Framework_Test $suite, array $arguments = [], $exit = true)
{
if (isset($arguments['configuration'])) {
$GLOBALS['__PHPUNIT_CONFIGURATION_FILE'] = $arguments['configuration'];
}
$this->handleConfiguration($arguments);
$this->processSuiteFilters($suite, $arguments);
if (isset($arguments['bootstrap'])) {
$GLOBALS['__PHPUNIT_BOOTSTRAP'] = $arguments['bootstrap'];
}
if ($arguments['backupGlobals'] === false) {
$suite->setBackupGlobals(false);
}
if ($arguments['backupStaticAttributes'] === true) {
$suite->setBackupStaticAttributes(true);
}
if ($arguments['beStrictAboutChangesToGlobalState'] === true) {
$suite->setbeStrictAboutChangesToGlobalState(true);
}
if (is_integer($arguments['repeat'])) {
$test = new PHPUnit_Extensions_RepeatedTest(
$suite,
$arguments['repeat'],
$arguments['processIsolation']
);
$suite = new PHPUnit_Framework_TestSuite();
$suite->addTest($test);
}
$result = $this->createTestResult();
if (!$arguments['convertErrorsToExceptions']) {
$result->convertErrorsToExceptions(false);
}
if (!$arguments['convertNoticesToExceptions']) {
PHPUnit_Framework_Error_Notice::$enabled = false;
}
if (!$arguments['convertWarningsToExceptions']) {
PHPUnit_Framework_Error_Warning::$enabled = 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['registerMockObjectsFromTestArgumentsRecursively']) {
$result->setRegisterMockObjectsFromTestArgumentsRecursively(true);
}
if ($this->printer === null) {
if (isset($arguments['printer']) &&
$arguments['printer'] instanceof PHPUnit_Util_Printer) {
$this->printer = $arguments['printer'];
} else {
$printerClass = 'PHPUnit_TextUI_ResultPrinter';
if (isset($arguments['printer']) &&
is_string($arguments['printer']) &&
class_exists($arguments['printer'], false)) {
$class = new ReflectionClass($arguments['printer']);
if ($class->isSubclassOf('PHPUnit_TextUI_ResultPrinter')) {
$printerClass = $arguments['printer'];
}
}
$this->printer = new $printerClass(
isset($arguments['stderr']) ? 'php://stderr' : null,
$arguments['verbose'],
$arguments['colors'],
$arguments['debug'],
$arguments['columns'],
$arguments['reverseList']
);
}
}
if (!$this->printer instanceof PHPUnit_Util_Log_TAP) {
$this->printer->write(
PHPUnit_Runner_Version::getVersionString() . "\n"
);
self::$versionStringPrinted = true;
if ($arguments['verbose']) {
$runtime = $this->runtime->getNameWithVersion();
if ($this->runtime->hasXdebug()) {
$runtime .= sprintf(
' with Xdebug %s',
phpversion('xdebug')
);
}
$this->writeMessage('Runtime', $runtime);
if (isset($arguments['configuration'])) {
$this->writeMessage(
'Configuration',
$arguments['configuration']->getFilename()
);
}
}
if (isset($arguments['deprecatedCheckForUnintentionallyCoveredCodeSettingUsed'])) {
print "Warning: Deprecated configuration setting \"checkForUnintentionallyCoveredCode\" used\n";
}
}
foreach ($arguments['listeners'] as $listener) {
$result->addListener($listener);
}
$result->addListener($this->printer);
if (isset($arguments['testdoxHTMLFile'])) {
$result->addListener(
new PHPUnit_Util_TestDox_ResultPrinter_HTML(
$arguments['testdoxHTMLFile'],
$arguments['testdoxGroups'],
$arguments['testdoxExcludeGroups']
)
);
}
if (isset($arguments['testdoxTextFile'])) {
$result->addListener(
new PHPUnit_Util_TestDox_ResultPrinter_Text(
$arguments['testdoxTextFile'],
$arguments['testdoxGroups'],
$arguments['testdoxExcludeGroups']
)
);
}
if (isset($arguments['testdoxXMLFile'])) {
$result->addListener(
new PHPUnit_Util_TestDox_ResultPrinter_XML(
$arguments['testdoxXMLFile']
)
);
}
$codeCoverageReports = 0;
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) {
if (!$this->runtime->canCollectCodeCoverage()) {
$this->writeMessage('Error', 'No code coverage driver is available');
$codeCoverageReports = 0;
} elseif (!isset($arguments['whitelist']) && !$this->codeCoverageFilter->hasWhitelist()) {
$this->writeMessage('Error', 'No whitelist configured, no code coverage will be generated');
$codeCoverageReports = 0;
}
}
if (!$this->printer instanceof PHPUnit_Util_Log_TAP) {
$this->printer->write("\n");
}
if ($codeCoverageReports > 0) {
$codeCoverage = new CodeCoverage(
null,
$this->codeCoverageFilter
);
$codeCoverage->setUnintentionallyCoveredSubclassesWhitelist(
[SebastianBergmann\Comparator\Comparator::class]
);
$codeCoverage->setAddUncoveredFilesFromWhitelist(
$arguments['addUncoveredFilesFromWhitelist']
);
$codeCoverage->setCheckForUnintentionallyCoveredCode(
$arguments['strictCoverage']
);
$codeCoverage->setCheckForMissingCoversAnnotation(
$arguments['strictCoverage']
);
$codeCoverage->setProcessUncoveredFilesFromWhitelist(
$arguments['processUncoveredFilesFromWhitelist']
);
if (isset($arguments['forceCoversAnnotation'])) {
$codeCoverage->setForceCoversAnnotation(
$arguments['forceCoversAnnotation']
);
}
if (isset($arguments['disableCodeCoverageIgnore'])) {
$codeCoverage->setDisableIgnoredLines(true);
}
if (isset($arguments['whitelist'])) {
$this->codeCoverageFilter->addDirectoryToWhitelist($arguments['whitelist']);
}
$result->setCodeCoverage($codeCoverage);
}
if ($codeCoverageReports > 1) {
if (isset($arguments['cacheTokens'])) {
$codeCoverage->setCacheTokens($arguments['cacheTokens']);
}
}
if (isset($arguments['jsonLogfile'])) {
$result->addListener(
new PHPUnit_Util_Log_JSON($arguments['jsonLogfile'])
);
}
if (isset($arguments['tapLogfile'])) {
$result->addListener(
new PHPUnit_Util_Log_TAP($arguments['tapLogfile'])
);
}
if (isset($arguments['teamcityLogfile'])) {
$result->addListener(
new PHPUnit_Util_Log_TeamCity($arguments['teamcityLogfile'])
);
}
if (isset($arguments['junitLogfile'])) {
$result->addListener(
new PHPUnit_Util_Log_JUnit(
$arguments['junitLogfile'],
$arguments['logIncompleteSkipped']
)
);
}
$result->beStrictAboutTestsThatDoNotTestAnything($arguments['reportUselessTests']);
$result->beStrictAboutOutputDuringTests($arguments['disallowTestOutput']);
$result->beStrictAboutTodoAnnotatedTests($arguments['disallowTodoAnnotatedTests']);
$result->beStrictAboutResourceUsageDuringSmallTests($arguments['beStrictAboutResourceUsageDuringSmallTests']);
$result->enforceTimeLimit($arguments['enforceTimeLimit']);
$result->setTimeoutForSmallTests($arguments['timeoutForSmallTests']);
$result->setTimeoutForMediumTests($arguments['timeoutForMediumTests']);
$result->setTimeoutForLargeTests($arguments['timeoutForLargeTests']);
if ($suite instanceof PHPUnit_Framework_TestSuite) {
$suite->setRunTestInSeparateProcess($arguments['processIsolation']);
}
$suite->run($result);
unset($suite);
$result->flushListeners();
if ($this->printer instanceof PHPUnit_TextUI_ResultPrinter) {
$this->printer->printResult($result);
}
if (isset($codeCoverage)) {
if (isset($arguments['coverageClover'])) {
$this->printer->write(
"\nGenerating code coverage report in Clover XML format ..."
);
try {
$writer = new CloverReport();
$writer->process($codeCoverage, $arguments['coverageClover']);
$this->printer->write(" done\n");
unset($writer);
} catch (CodeCoverageException $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coverageCrap4J'])) {
$this->printer->write(
"\nGenerating Crap4J report XML file ..."
);
try {
$writer = new Crap4jReport($arguments['crap4jThreshold']);
$writer->process($codeCoverage, $arguments['coverageCrap4J']);
$this->printer->write(" done\n");
unset($writer);
} catch (CodeCoverageException $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coverageHtml'])) {
$this->printer->write(
"\nGenerating code coverage report in HTML format ..."
);
try {
$writer = new HtmlReport(
$arguments['reportLowUpperBound'],
$arguments['reportHighLowerBound'],
sprintf(
' and <a href="https://phpunit.de/">PHPUnit %s</a>',
PHPUnit_Runner_Version::id()
)
);
$writer->process($codeCoverage, $arguments['coverageHtml']);
$this->printer->write(" done\n");
unset($writer);
} catch (CodeCoverageException $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coveragePHP'])) {
$this->printer->write(
"\nGenerating code coverage report in PHP format ..."
);
try {
$writer = new PhpReport();
$writer->process($codeCoverage, $arguments['coveragePHP']);
$this->printer->write(" done\n");
unset($writer);
} catch (CodeCoverageException $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coverageText'])) {
if ($arguments['coverageText'] == 'php://stdout') {
$outputStream = $this->printer;
$colors = $arguments['colors'] && $arguments['colors'] != PHPUnit_TextUI_ResultPrinter::COLOR_NEVER;
} else {
$outputStream = new PHPUnit_Util_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->printer->write(
"\nGenerating code coverage report in PHPUnit XML format ..."
);
try {
$writer = new XmlReport;
$writer->process($codeCoverage, $arguments['coverageXml']);
$this->printer->write(" done\n");
unset($writer);
} catch (CodeCoverageException $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
}
if ($exit) {
if ($result->wasSuccessful()) {
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(PHPUnit_TextUI_ResultPrinter $resultPrinter)
{
$this->printer = $resultPrinter;
}
protected function runFailed($message)
{
$this->write($message . PHP_EOL);
exit(self::FAILURE_EXIT);
}
protected function write($buffer)
{
if (PHP_SAPI != 'cli' && PHP_SAPI != 'phpdbg') {
$buffer = htmlspecialchars($buffer);
}
if ($this->printer !== null) {
$this->printer->write($buffer);
} else {
print $buffer;
}
}
public function getLoader()
{
if ($this->loader === null) {
$this->loader = new PHPUnit_Runner_StandardTestSuiteLoader;
}
return $this->loader;
}
protected function handleConfiguration(array &$arguments)
{
if (isset($arguments['configuration']) &&
!$arguments['configuration'] instanceof PHPUnit_Util_Configuration) {
$arguments['configuration'] = PHPUnit_Util_Configuration::getInstance(
$arguments['configuration']
);
}
$arguments['debug'] = isset($arguments['debug']) ? $arguments['debug'] : false;
$arguments['filter'] = isset($arguments['filter']) ? $arguments['filter'] : false;
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : [];
if (isset($arguments['configuration'])) {
$arguments['configuration']->handlePHPConfiguration();
$phpunitConfiguration = $arguments['configuration']->getPHPUnitConfiguration();
if (isset($phpunitConfiguration['deprecatedCheckForUnintentionallyCoveredCodeSettingUsed'])) {
$arguments['deprecatedCheckForUnintentionallyCoveredCodeSettingUsed'] = true;
}
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['cacheTokens']) &&
!isset($arguments['cacheTokens'])) {
$arguments['cacheTokens'] = $phpunitConfiguration['cacheTokens'];
}
if (isset($phpunitConfiguration['colors']) &&
!isset($arguments['colors'])) {
$arguments['colors'] = $phpunitConfiguration['colors'];
}
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['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['disallowTestOutput']) &&
!isset($arguments['disallowTestOutput'])) {
$arguments['disallowTestOutput'] = $phpunitConfiguration['disallowTestOutput'];
}
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'];
}
$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']->getListenerConfiguration() as $listener) {
if (!class_exists($listener['class'], false) &&
$listener['file'] !== '') {
require_once $listener['file'];
}
if (class_exists($listener['class'])) {
if (count($listener['arguments']) == 0) {
$listener = new $listener['class'];
} else {
$listenerClass = new ReflectionClass(
$listener['class']
);
$listener = $listenerClass->newInstanceArgs(
$listener['arguments']
);
}
if ($listener instanceof PHPUnit_Framework_TestListener) {
$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'];
if (isset($loggingConfiguration['coverageTextShowUncoveredFiles'])) {
$arguments['coverageTextShowUncoveredFiles'] = $loggingConfiguration['coverageTextShowUncoveredFiles'];
} else {
$arguments['coverageTextShowUncoveredFiles'] = false;
}
if (isset($loggingConfiguration['coverageTextShowOnlySummary'])) {
$arguments['coverageTextShowOnlySummary'] = $loggingConfiguration['coverageTextShowOnlySummary'];
} else {
$arguments['coverageTextShowOnlySummary'] = false;
}
}
if (isset($loggingConfiguration['coverage-xml']) &&
!isset($arguments['coverageXml'])) {
$arguments['coverageXml'] = $loggingConfiguration['coverage-xml'];
}
if (isset($loggingConfiguration['json']) &&
!isset($arguments['jsonLogfile'])) {
$arguments['jsonLogfile'] = $loggingConfiguration['json'];
}
if (isset($loggingConfiguration['plain'])) {
$arguments['listeners'][] = new PHPUnit_TextUI_ResultPrinter(
$loggingConfiguration['plain'],
true
);
}
if (isset($loggingConfiguration['tap']) &&
!isset($arguments['tapLogfile'])) {
$arguments['tapLogfile'] = $loggingConfiguration['tap'];
}
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['logIncompleteSkipped']) &&
!isset($arguments['logIncompleteSkipped'])) {
$arguments['logIncompleteSkipped'] = $loggingConfiguration['logIncompleteSkipped'];
}
}
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'];
}
if ((isset($arguments['coverageClover']) ||
isset($arguments['coverageCrap4J']) ||
isset($arguments['coverageHtml']) ||
isset($arguments['coveragePHP']) ||
isset($arguments['coverageText']) ||
isset($arguments['coverageXml'])) &&
$this->runtime->canCollectCodeCoverage()) {
$filterConfiguration = $arguments['configuration']->getFilterConfiguration();
$arguments['addUncoveredFilesFromWhitelist'] = $filterConfiguration['whitelist']['addUncoveredFilesFromWhitelist'];
$arguments['processUncoveredFilesFromWhitelist'] = $filterConfiguration['whitelist']['processUncoveredFilesFromWhitelist'];
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);
}
}
}
$arguments['addUncoveredFilesFromWhitelist'] = isset($arguments['addUncoveredFilesFromWhitelist']) ? $arguments['addUncoveredFilesFromWhitelist'] : true;
$arguments['processUncoveredFilesFromWhitelist'] = isset($arguments['processUncoveredFilesFromWhitelist']) ? $arguments['processUncoveredFilesFromWhitelist'] : false;
$arguments['backupGlobals'] = isset($arguments['backupGlobals']) ? $arguments['backupGlobals'] : null;
$arguments['backupStaticAttributes'] = isset($arguments['backupStaticAttributes']) ? $arguments['backupStaticAttributes'] : null;
$arguments['beStrictAboutChangesToGlobalState'] = isset($arguments['beStrictAboutChangesToGlobalState']) ? $arguments['beStrictAboutChangesToGlobalState'] : null;
$arguments['cacheTokens'] = isset($arguments['cacheTokens']) ? $arguments['cacheTokens'] : false;
$arguments['columns'] = isset($arguments['columns']) ? $arguments['columns'] : 80;
$arguments['colors'] = isset($arguments['colors']) ? $arguments['colors'] : PHPUnit_TextUI_ResultPrinter::COLOR_DEFAULT;
$arguments['convertErrorsToExceptions'] = isset($arguments['convertErrorsToExceptions']) ? $arguments['convertErrorsToExceptions'] : true;
$arguments['convertNoticesToExceptions'] = isset($arguments['convertNoticesToExceptions']) ? $arguments['convertNoticesToExceptions'] : true;
$arguments['convertWarningsToExceptions'] = isset($arguments['convertWarningsToExceptions']) ? $arguments['convertWarningsToExceptions'] : true;
$arguments['excludeGroups'] = isset($arguments['excludeGroups']) ? $arguments['excludeGroups'] : [];
$arguments['groups'] = isset($arguments['groups']) ? $arguments['groups'] : [];
$arguments['logIncompleteSkipped'] = isset($arguments['logIncompleteSkipped']) ? $arguments['logIncompleteSkipped'] : false;
$arguments['processIsolation'] = isset($arguments['processIsolation']) ? $arguments['processIsolation'] : false;
$arguments['repeat'] = isset($arguments['repeat']) ? $arguments['repeat'] : false;
$arguments['reportHighLowerBound'] = isset($arguments['reportHighLowerBound']) ? $arguments['reportHighLowerBound'] : 90;
$arguments['reportLowUpperBound'] = isset($arguments['reportLowUpperBound']) ? $arguments['reportLowUpperBound'] : 50;
$arguments['crap4jThreshold'] = isset($arguments['crap4jThreshold']) ? $arguments['crap4jThreshold'] : 30;
$arguments['stopOnError'] = isset($arguments['stopOnError']) ? $arguments['stopOnError'] : false;
$arguments['stopOnFailure'] = isset($arguments['stopOnFailure']) ? $arguments['stopOnFailure'] : false;
$arguments['stopOnWarning'] = isset($arguments['stopOnWarning']) ? $arguments['stopOnWarning'] : false;
$arguments['stopOnIncomplete'] = isset($arguments['stopOnIncomplete']) ? $arguments['stopOnIncomplete'] : false;
$arguments['stopOnRisky'] = isset($arguments['stopOnRisky']) ? $arguments['stopOnRisky'] : false;
$arguments['stopOnSkipped'] = isset($arguments['stopOnSkipped']) ? $arguments['stopOnSkipped'] : false;
$arguments['failOnWarning'] = isset($arguments['failOnWarning']) ? $arguments['failOnWarning'] : false;
$arguments['failOnRisky'] = isset($arguments['failOnRisky']) ? $arguments['failOnRisky'] : false;
$arguments['timeoutForSmallTests'] = isset($arguments['timeoutForSmallTests']) ? $arguments['timeoutForSmallTests'] : 1;
$arguments['timeoutForMediumTests'] = isset($arguments['timeoutForMediumTests']) ? $arguments['timeoutForMediumTests'] : 10;
$arguments['timeoutForLargeTests'] = isset($arguments['timeoutForLargeTests']) ? $arguments['timeoutForLargeTests'] : 60;
$arguments['reportUselessTests'] = isset($arguments['reportUselessTests']) ? $arguments['reportUselessTests'] : false;
$arguments['strictCoverage'] = isset($arguments['strictCoverage']) ? $arguments['strictCoverage'] : false;
$arguments['disallowTestOutput'] = isset($arguments['disallowTestOutput']) ? $arguments['disallowTestOutput'] : false;
$arguments['enforceTimeLimit'] = isset($arguments['enforceTimeLimit']) ? $arguments['enforceTimeLimit'] : false;
$arguments['disallowTodoAnnotatedTests'] = isset($arguments['disallowTodoAnnotatedTests']) ? $arguments['disallowTodoAnnotatedTests'] : false;
$arguments['beStrictAboutResourceUsageDuringSmallTests'] = isset($arguments['beStrictAboutResourceUsageDuringSmallTests']) ? $arguments['beStrictAboutResourceUsageDuringSmallTests'] : false;
$arguments['reverseList'] = isset($arguments['reverseList']) ? $arguments['reverseList'] : false;
$arguments['registerMockObjectsFromTestArgumentsRecursively'] = isset($arguments['registerMockObjectsFromTestArgumentsRecursively']) ? $arguments['registerMockObjectsFromTestArgumentsRecursively'] : false;
$arguments['verbose'] = isset($arguments['verbose']) ? $arguments['verbose'] : false;
$arguments['testdoxExcludeGroups'] = isset($arguments['testdoxExcludeGroups']) ? $arguments['testdoxExcludeGroups'] : [];
$arguments['testdoxGroups'] = isset($arguments['testdoxGroups']) ? $arguments['testdoxGroups'] : [];
}
private function writeMessage($type, $message)
{
if (!$this->messagePrinted) {
$this->write("\n");
}
$this->write(
sprintf(
"%-15s%s\n",
$type . ':',
$message
)
);
$this->messagePrinted = true;
}
}
<?php
class PHPUnit_Util_Blacklist
{
public static $blacklistedClassNames = [
'File_Iterator' => 1,
'PHP_Invoker' => 1,
'PHP_Timer' => 1,
'PHP_Token' => 1,
'PHPUnit_Framework_TestCase' => 2,
'PHPUnit_Extensions_Database_TestCase' => 2,
'PHPUnit_Framework_MockObject_Generator' => 2,
'Text_Template' => 1,
'Symfony\Component\Yaml\Yaml' => 1,
'SebastianBergmann\CodeCoverage\CodeCoverage' => 1,
'SebastianBergmann\Diff\Diff' => 1,
'SebastianBergmann\Environment\Runtime' => 1,
'SebastianBergmann\Comparator\Comparator' => 1,
'SebastianBergmann\Exporter\Exporter' => 1,
'SebastianBergmann\GlobalState\Snapshot' => 1,
'SebastianBergmann\RecursionContext\Context' => 1,
'SebastianBergmann\Version' => 1,
'Composer\Autoload\ClassLoader' => 1,
'Doctrine\Instantiator\Instantiator' => 1,
'phpDocumentor\Reflection\DocBlock' => 1,
'Prophecy\Prophet' => 1,
'DeepCopy\DeepCopy' => 1
];
private static $directories;
public function getBlacklistedDirectories()
{
$this->initialize();
return self::$directories;
}
public function isBlacklisted($file)
{
if (defined('PHPUNIT_TESTSUITE')) {
return false;
}
$this->initialize();
foreach (self::$directories as $directory) {
if (strpos($file, $directory) === 0) {
return true;
}
}
return false;
}
private function initialize()
{
if (self::$directories === null) {
self::$directories = [];
foreach (self::$blacklistedClassNames as $className => $parent) {
if (!class_exists($className)) {
continue;
}
$reflector = new ReflectionClass($className);
$directory = $reflector->getFileName();
for ($i = 0; $i < $parent; $i++) {
$directory = dirname($directory);
}
self::$directories[] = $directory;
}
if (DIRECTORY_SEPARATOR === '\\') {
self::$directories[] = sys_get_temp_dir() . '\\PHP';
}
}
}
}
<?php
class PHPUnit_Util_Configuration
{
private static $instances = [];
protected $document;
protected $xpath;
protected $filename;
protected function __construct($filename)
{
$this->filename = $filename;
$this->document = PHPUnit_Util_XML::loadFile($filename, false, true, true);
$this->xpath = new DOMXPath($this->document);
}
final private function __clone()
{
}
public static function getInstance($filename)
{
$realpath = realpath($filename);
if ($realpath === false) {
throw new PHPUnit_Framework_Exception(
sprintf(
'Could not read "%s".',
$filename
)
);
}
if (!isset(self::$instances[$realpath])) {
self::$instances[$realpath] = new self($realpath);
}
return self::$instances[$realpath];
}
public function getFilename()
{
return $this->filename;
}
public function getFilterConfiguration()
{
$addUncoveredFilesFromWhitelist = true;
$processUncoveredFilesFromWhitelist = false;
$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
);
}
}
return [
'whitelist' => [
'addUncoveredFilesFromWhitelist' => $addUncoveredFilesFromWhitelist,
'processUncoveredFilesFromWhitelist' => $processUncoveredFilesFromWhitelist,
'include' => [
'directory' => $this->readFilterDirectories(
'filter/whitelist/directory'
),
'file' => $this->readFilterFiles(
'filter/whitelist/file'
)
],
'exclude' => [
'directory' => $this->readFilterDirectories(
'filter/whitelist/exclude/directory'
),
'file' => $this->readFilterFiles(
'filter/whitelist/exclude/file'
)
]
]
];
}
public function getGroupConfiguration()
{
return $this->parseGroupConfiguration('groups');
}
public function getTestdoxGroupConfiguration()
{
return $this->parseGroupConfiguration('testdoxGroups');
}
private function parseGroupConfiguration($root)
{
$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;
}
public function getListenerConfiguration()
{
$result = [];
foreach ($this->xpath->query('listeners/listener') as $listener) {
$class = (string) $listener->getAttribute('class');
$file = '';
$arguments = [];
if ($listener->getAttribute('file')) {
$file = $this->toAbsolutePath(
(string) $listener->getAttribute('file'),
true
);
}
foreach ($listener->childNodes as $node) {
if ($node instanceof DOMElement && $node->tagName == 'arguments') {
foreach ($node->childNodes as $argument) {
if ($argument instanceof DOMElement) {
if ($argument->tagName == 'file' ||
$argument->tagName == 'directory') {
$arguments[] = $this->toAbsolutePath((string) $argument->textContent);
} else {
$arguments[] = PHPUnit_Util_XML::xmlToVariable($argument);
}
}
}
}
}
$result[] = [
'class' => $class,
'file' => $file,
'arguments' => $arguments
];
}
return $result;
}
public function getLoggingConfiguration()
{
$result = [];
foreach ($this->xpath->query('logging/log') as $log) {
$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 == 'junit') {
if ($log->hasAttribute('logIncompleteSkipped')) {
$result['logIncompleteSkipped'] = $this->getBoolean(
(string) $log->getAttribute('logIncompleteSkipped'),
false
);
}
} 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;
}
public function getPHPConfiguration()
{
$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) {
$name = (string) $ini->getAttribute('name');
$value = (string) $ini->getAttribute('value');
$result['ini'][$name] = $value;
}
foreach ($this->xpath->query('php/const') as $const) {
$name = (string) $const->getAttribute('name');
$value = (string) $const->getAttribute('value');
$result['const'][$name] = $this->getBoolean($value, $value);
}
foreach (['var', 'env', 'post', 'get', 'cookie', 'server', 'files', 'request'] as $array) {
foreach ($this->xpath->query('php/' . $array) as $var) {
$name = (string) $var->getAttribute('name');
$value = (string) $var->getAttribute('value');
$result[$array][$name] = $this->getBoolean($value, $value);
}
}
return $result;
}
public function handlePHPConfiguration()
{
$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 => $value) {
if (defined($value)) {
$value = constant($value);
}
ini_set($name, $value);
}
foreach ($configuration['const'] as $name => $value) {
if (!defined($name)) {
define($name, $value);
}
}
foreach (['var', 'post', 'get', 'cookie', 'server', 'files', 'request'] as $array) {
switch ($array) {
case 'var':
$target = &$GLOBALS;
break;
case 'server':
$target = &$_SERVER;
break;
default:
$target = &$GLOBALS['_' . strtoupper($array)];
break;
}
foreach ($configuration[$array] as $name => $value) {
$target[$name] = $value;
}
}
foreach ($configuration['env'] as $name => $value) {
if (false === getenv($name)) {
putenv("{$name}={$value}");
}
if (!isset($_ENV[$name])) {
$_ENV[$name] = $value;
}
}
}
public function getPHPUnitConfiguration()
{
$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')) {
if ($this->getBoolean($root->getAttribute('colors'), false)) {
$result['colors'] = PHPUnit_TextUI_ResultPrinter::COLOR_AUTO;
} else {
$result['colors'] = PHPUnit_TextUI_ResultPrinter::COLOR_NEVER;
}
}
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'),
true
);
}
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('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('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->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'),
false
);
}
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
);
} elseif ($root->hasAttribute('checkForUnintentionallyCoveredCode')) {
$result['strictCoverage'] = $this->getBoolean(
(string) $root->getAttribute('checkForUnintentionallyCoveredCode'),
false
);
$result['deprecatedCheckForUnintentionallyCoveredCodeSettingUsed'] = true;
}
if ($root->hasAttribute('enforceTimeLimit')) {
$result['enforceTimeLimit'] = $this->getBoolean(
(string) $root->getAttribute('enforceTimeLimit'),
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('registerMockObjectsFromTestArgumentsRecursively')) {
$result['registerMockObjectsFromTestArgumentsRecursively'] = $this->getBoolean(
(string) $root->getAttribute('registerMockObjectsFromTestArgumentsRecursively'),
false
);
}
return $result;
}
public function getTestSuiteConfiguration($testSuiteFilter = null)
{
$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);
}
if ($testSuiteNodes->length > 1) {
$suite = new PHPUnit_Framework_TestSuite;
foreach ($testSuiteNodes as $testSuiteNode) {
$suite->addTestSuite(
$this->getTestSuite($testSuiteNode, $testSuiteFilter)
);
}
return $suite;
}
}
public function getTestSuiteNames()
{
$names = [];
$nodes = $this->xpath->query('*/testsuite');
foreach ($nodes as $node) {
$names[] = $node->getAttribute('name');
}
return $names;
}
protected function getTestSuite(DOMElement $testSuiteNode, $testSuiteFilter = null)
{
if ($testSuiteNode->hasAttribute('name')) {
$suite = new PHPUnit_Framework_TestSuite(
(string) $testSuiteNode->getAttribute('name')
);
} else {
$suite = new PHPUnit_Framework_TestSuite;
}
$exclude = [];
foreach ($testSuiteNode->getElementsByTagName('exclude') as $excludeNode) {
$excludeFile = (string) $excludeNode->textContent;
if ($excludeFile) {
$exclude[] = $this->toAbsolutePath($excludeFile);
}
}
$fileIteratorFacade = new File_Iterator_Facade;
foreach ($testSuiteNode->getElementsByTagName('directory') as $directoryNode) {
if ($testSuiteFilter && $directoryNode->parentNode->getAttribute('name') != $testSuiteFilter) {
continue;
}
$directory = (string) $directoryNode->textContent;
if (empty($directory)) {
continue;
}
if ($directoryNode->hasAttribute('phpVersion')) {
$phpVersion = (string) $directoryNode->getAttribute('phpVersion');
} else {
$phpVersion = PHP_VERSION;
}
if ($directoryNode->hasAttribute('phpVersionOperator')) {
$phpVersionOperator = (string) $directoryNode->getAttribute('phpVersionOperator');
} else {
$phpVersionOperator = '>=';
}
if (!version_compare(PHP_VERSION, $phpVersion, $phpVersionOperator)) {
continue;
}
if ($directoryNode->hasAttribute('prefix')) {
$prefix = (string) $directoryNode->getAttribute('prefix');
} else {
$prefix = '';
}
if ($directoryNode->hasAttribute('suffix')) {
$suffix = (string) $directoryNode->getAttribute('suffix');
} else {
$suffix = 'Test.php';
}
$files = $fileIteratorFacade->getFilesAsArray(
$this->toAbsolutePath($directory),
$suffix,
$prefix,
$exclude
);
$suite->addTestFiles($files);
}
foreach ($testSuiteNode->getElementsByTagName('file') as $fileNode) {
if ($testSuiteFilter && $fileNode->parentNode->getAttribute('name') != $testSuiteFilter) {
continue;
}
$file = (string) $fileNode->textContent;
if (empty($file)) {
continue;
}
$file = $fileIteratorFacade->getFilesAsArray(
$this->toAbsolutePath($file)
);
if (!isset($file[0])) {
continue;
}
$file = $file[0];
if ($fileNode->hasAttribute('phpVersion')) {
$phpVersion = (string) $fileNode->getAttribute('phpVersion');
} else {
$phpVersion = PHP_VERSION;
}
if ($fileNode->hasAttribute('phpVersionOperator')) {
$phpVersionOperator = (string) $fileNode->getAttribute('phpVersionOperator');
} else {
$phpVersionOperator = '>=';
}
if (!version_compare(PHP_VERSION, $phpVersion, $phpVersionOperator)) {
continue;
}
$suite->addTestFile($file);
}
return $suite;
}
protected function getBoolean($value, $default)
{
if (strtolower($value) == 'false') {
return false;
} elseif (strtolower($value) == 'true') {
return true;
}
return $default;
}
protected function getInteger($value, $default)
{
if (is_numeric($value)) {
return (int) $value;
}
return $default;
}
protected function readFilterDirectories($query)
{
$directories = [];
foreach ($this->xpath->query($query) as $directory) {
$directoryPath = (string) $directory->textContent;
if (!$directoryPath) {
continue;
}
if ($directory->hasAttribute('prefix')) {
$prefix = (string) $directory->getAttribute('prefix');
} else {
$prefix = '';
}
if ($directory->hasAttribute('suffix')) {
$suffix = (string) $directory->getAttribute('suffix');
} else {
$suffix = '.php';
}
if ($directory->hasAttribute('group')) {
$group = (string) $directory->getAttribute('group');
} else {
$group = 'DEFAULT';
}
$directories[] = [
'path' => $this->toAbsolutePath($directoryPath),
'prefix' => $prefix,
'suffix' => $suffix,
'group' => $group
];
}
return $directories;
}
protected function readFilterFiles($query)
{
$files = [];
foreach ($this->xpath->query($query) as $file) {
$filePath = (string) $file->textContent;
if ($filePath) {
$files[] = $this->toAbsolutePath($filePath);
}
}
return $files;
}
protected function toAbsolutePath($path, $useIncludePath = false)
{
$path = trim($path);
if ($path[0] === '/') {
return $path;
}
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;
}
}
<?php
class PHPUnit_Util_ConfigurationGenerator
{
private $defaultTemplate = <<<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}"
backupGlobals="false"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
verbose="true">
<testsuite>
<directory suffix="Test.php">{tests_directory}</directory>
</testsuite>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">{src_directory}</directory>
</whitelist>
</filter>
</phpunit>
EOT;
public function generateDefaultConfiguration($phpunitVersion, $bootstrapScript, $testsDirectory, $srcDirectory)
{
return str_replace(
[
'{phpunit_version}',
'{bootstrap_script}',
'{tests_directory}',
'{src_directory}'
],
[
$phpunitVersion,
$bootstrapScript,
$testsDirectory,
$srcDirectory
],
$this->defaultTemplate
);
}
}
<?php
require_once dirname(__DIR__) . '/Framework/Error.php';
require_once dirname(__DIR__) . '/Framework/Error/Notice.php';
require_once dirname(__DIR__) . '/Framework/Error/Warning.php';
require_once dirname(__DIR__) . '/Framework/Error/Deprecated.php';
class PHPUnit_Util_ErrorHandler
{
protected static $errorStack = [];
public static function getErrorStack()
{
return self::$errorStack;
}
public static function handleError($errno, $errstr, $errfile, $errline)
{
if (!($errno & error_reporting())) {
return false;
}
self::$errorStack[] = [$errno, $errstr, $errfile, $errline];
$trace = debug_backtrace(false);
array_shift($trace);
foreach ($trace as $frame) {
if ($frame['function'] == '__toString') {
return false;
}
}
if ($errno == E_NOTICE || $errno == E_USER_NOTICE || $errno == E_STRICT) {
if (PHPUnit_Framework_Error_Notice::$enabled !== true) {
return false;
}
$exception = 'PHPUnit_Framework_Error_Notice';
} elseif ($errno == E_WARNING || $errno == E_USER_WARNING) {
if (PHPUnit_Framework_Error_Warning::$enabled !== true) {
return false;
}
$exception = 'PHPUnit_Framework_Error_Warning';
} elseif ($errno == E_DEPRECATED || $errno == E_USER_DEPRECATED) {
if (PHPUnit_Framework_Error_Deprecated::$enabled !== true) {
return false;
}
$exception = 'PHPUnit_Framework_Error_Deprecated';
} else {
$exception = 'PHPUnit_Framework_Error';
}
throw new $exception($errstr, $errno, $errfile, $errline);
}
public static function handleErrorOnce($severity = E_WARNING)
{
$terminator = function () {
static $expired = false;
if (!$expired) {
$expired = true;
return restore_error_handler();
}
};
set_error_handler(function ($errno, $errstr) use ($severity) {
if ($errno === $severity) {
return;
}
return false;
});
return $terminator;
}
}
<?php
class PHPUnit_Util_Fileloader
{
public static function checkAndLoad($filename)
{
$includePathFilename = stream_resolve_include_path($filename);
if (!$includePathFilename || !is_readable($includePathFilename)) {
throw new PHPUnit_Framework_Exception(
sprintf('Cannot open file "%s".' . "\n", $filename)
);
}
self::load($includePathFilename);
return $includePathFilename;
}
public static function load($filename)
{
$oldVariableNames = array_keys(get_defined_vars());
include_once $filename;
$newVariables = get_defined_vars();
$newVariableNames = array_diff(
array_keys($newVariables),
$oldVariableNames
);
foreach ($newVariableNames as $variableName) {
if ($variableName != 'oldVariableNames') {
$GLOBALS[$variableName] = $newVariables[$variableName];
}
}
return $filename;
}
}
<?php
class PHPUnit_Util_Filesystem
{
protected static $buffer = [];
public static function classNameToFilename($className)
{
return str_replace(
['_', '\\'],
DIRECTORY_SEPARATOR,
$className
) . '.php';
}
}
<?php
class PHPUnit_Util_Filter
{
public static function getFilteredStacktrace($e, $asString = true)
{
$prefix = false;
$script = realpath($GLOBALS['_SERVER']['SCRIPT_NAME']);
if (defined('__PHPUNIT_PHAR_ROOT__')) {
$prefix = __PHPUNIT_PHAR_ROOT__;
}
if ($asString === true) {
$filteredStacktrace = '';
} else {
$filteredStacktrace = [];
}
if ($e instanceof PHPUnit_Framework_SyntheticError) {
$eTrace = $e->getSyntheticTrace();
$eFile = $e->getSyntheticFile();
$eLine = $e->getSyntheticLine();
} elseif ($e instanceof PHPUnit_Framework_Exception) {
$eTrace = $e->getSerializableTrace();
$eFile = $e->getFile();
$eLine = $e->getLine();
} else {
if ($e->getPrevious()) {
$e = $e->getPrevious();
}
$eTrace = $e->getTrace();
$eFile = $e->getFile();
$eLine = $e->getLine();
}
if (!self::frameExists($eTrace, $eFile, $eLine)) {
array_unshift(
$eTrace,
['file' => $eFile, 'line' => $eLine]
);
}
$blacklist = new PHPUnit_Util_Blacklist;
foreach ($eTrace as $frame) {
if (isset($frame['file']) && is_file($frame['file']) &&
!$blacklist->isBlacklisted($frame['file']) &&
($prefix === false || strpos($frame['file'], $prefix) !== 0) &&
$frame['file'] !== $script) {
if ($asString === true) {
$filteredStacktrace .= sprintf(
"%s:%s\n",
$frame['file'],
isset($frame['line']) ? $frame['line'] : '?'
);
} else {
$filteredStacktrace[] = $frame;
}
}
}
return $filteredStacktrace;
}
private static function frameExists(array $trace, $file, $line)
{
foreach ($trace as $frame) {
if (isset($frame['file']) && $frame['file'] == $file &&
isset($frame['line']) && $frame['line'] == $line) {
return true;
}
}
return false;
}
}
<?php
class PHPUnit_Util_Getopt
{
public static function getopt(array $args, $short_options, $long_options = null)
{
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);
array_map('trim', $args);
while (list($i, $arg) = each($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;
} elseif (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];
}
protected static function parseShortOption($arg, $short_options, &$opts, &$args)
{
$argLen = strlen($arg);
for ($i = 0; $i < $argLen; $i++) {
$opt = $arg[$i];
$opt_arg = null;
if (($spec = strstr($short_options, $opt)) === false ||
$arg[$i] == ':') {
throw new PHPUnit_Framework_Exception(
"unrecognized option -- $opt"
);
}
if (strlen($spec) > 1 && $spec[1] == ':') {
if (strlen($spec) > 2 && $spec[2] == ':') {
if ($i + 1 < $argLen) {
$opts[] = [$opt, substr($arg, $i + 1)];
break;
}
} else {
if ($i + 1 < $argLen) {
$opts[] = [$opt, substr($arg, $i + 1)];
break;
} elseif (list(, $opt_arg) = each($args)) {
} else {
throw new PHPUnit_Framework_Exception(
"option requires an argument -- $opt"
);
}
}
}
$opts[] = [$opt, $opt_arg];
}
}
protected static function parseLongOption($arg, $long_options, &$opts, &$args)
{
$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);
for ($i = 0; $i < $count; $i++) {
$long_opt = $long_options[$i];
$opt_start = substr($long_opt, 0, $opt_len);
if ($opt_start != $opt) {
continue;
}
$opt_rest = substr($long_opt, $opt_len);
if ($opt_rest != '' && $opt[0] != '=' && $i + 1 < $count &&
$opt == substr($long_options[$i+1], 0, $opt_len)) {
throw new PHPUnit_Framework_Exception(
"option --$opt is ambiguous"
);
}
if (substr($long_opt, -1) == '=') {
if (substr($long_opt, -2) != '==') {
if (!strlen($opt_arg) &&
!(list(, $opt_arg) = each($args))) {
throw new PHPUnit_Framework_Exception(
"option --$opt requires an argument"
);
}
}
} elseif ($opt_arg) {
throw new PHPUnit_Framework_Exception(
"option --$opt doesn't allow an argument"
);
}
$full_option = '--' . preg_replace('/={1,2}$/', '', $long_opt);
$opts[] = [$full_option, $opt_arg];
return;
}
throw new PHPUnit_Framework_Exception("unrecognized option --$opt");
}
}
<?php
class PHPUnit_Util_GlobalState
{
protected static $superGlobalArrays = [
'_ENV',
'_POST',
'_GET',
'_COOKIE',
'_SERVER',
'_FILES',
'_REQUEST'
];
protected static $superGlobalArraysLong = [
'HTTP_ENV_VARS',
'HTTP_POST_VARS',
'HTTP_GET_VARS',
'HTTP_COOKIE_VARS',
'HTTP_SERVER_VARS',
'HTTP_POST_FILES'
];
public static function getIncludedFilesAsString()
{
return static::processIncludedFilesAsString(get_included_files());
}
public static function processIncludedFilesAsString(array $files)
{
$blacklist = new PHPUnit_Util_Blacklist;
$prefix = false;
$result = '';
if (defined('__PHPUNIT_PHAR__')) {
$prefix = 'phar://' . __PHPUNIT_PHAR__ . '/';
}
for ($i = count($files) - 1; $i > 0; $i--) {
$file = $files[$i];
if ($prefix !== false && strpos($file, $prefix) === 0) {
continue;
}
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()
{
$result = '';
$iniSettings = ini_get_all(null, false);
foreach ($iniSettings as $key => $value) {
$result .= sprintf(
'@ini_set(%s, %s);' . "\n",
self::exportVariable($key),
self::exportVariable($value)
);
}
return $result;
}
public static function getConstantsAsString()
{
$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()
{
$result = '';
$superGlobalArrays = self::getSuperGlobalArrays();
foreach ($superGlobalArrays 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 = $superGlobalArrays;
$blacklist[] = 'GLOBALS';
foreach (array_keys($GLOBALS) as $key) {
if (!in_array($key, $blacklist) && !$GLOBALS[$key] instanceof Closure) {
$result .= sprintf(
'$GLOBALS[\'%s\'] = %s;' . "\n",
$key,
self::exportVariable($GLOBALS[$key])
);
}
}
return $result;
}
protected static function getSuperGlobalArrays()
{
if (ini_get('register_long_arrays') == '1') {
return array_merge(
self::$superGlobalArrays,
self::$superGlobalArraysLong
);
} else {
return self::$superGlobalArrays;
}
}
protected static function exportVariable($variable)
{
if (is_scalar($variable) || is_null($variable) ||
(is_array($variable) && self::arrayOnlyContainsScalars($variable))) {
return var_export($variable, true);
}
return 'unserialize(' .
var_export(serialize($variable), true) .
')';
}
protected static function arrayOnlyContainsScalars(array $array)
{
$result = true;
foreach ($array as $element) {
if (is_array($element)) {
$result = self::arrayOnlyContainsScalars($element);
} elseif (!is_scalar($element) && !is_null($element)) {
$result = false;
}
if ($result === false) {
break;
}
}
return $result;
}
}
<?php
class PHPUnit_Util_InvalidArgumentHelper
{
public static function factory($argument, $type, $value = null)
{
$stack = debug_backtrace(false);
return new PHPUnit_Framework_Exception(
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
class PHPUnit_Util_Log_JSON extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
protected $currentTestSuiteName = '';
protected $currentTestName = '';
protected $currentTestPass = true;
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeCase(
'error',
$time,
PHPUnit_Util_Filter::getFilteredStacktrace($e, false),
PHPUnit_Framework_TestFailure::exceptionToString($e),
$test
);
$this->currentTestPass = false;
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
$this->writeCase(
'warning',
$time,
PHPUnit_Util_Filter::getFilteredStacktrace($e, false),
PHPUnit_Framework_TestFailure::exceptionToString($e),
$test
);
$this->currentTestPass = false;
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$this->writeCase(
'fail',
$time,
PHPUnit_Util_Filter::getFilteredStacktrace($e, false),
PHPUnit_Framework_TestFailure::exceptionToString($e),
$test
);
$this->currentTestPass = false;
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeCase(
'error',
$time,
PHPUnit_Util_Filter::getFilteredStacktrace($e, false),
'Incomplete Test: ' . $e->getMessage(),
$test
);
$this->currentTestPass = false;
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeCase(
'error',
$time,
PHPUnit_Util_Filter::getFilteredStacktrace($e, false),
'Risky Test: ' . $e->getMessage(),
$test
);
$this->currentTestPass = false;
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeCase(
'error',
$time,
PHPUnit_Util_Filter::getFilteredStacktrace($e, false),
'Skipped Test: ' . $e->getMessage(),
$test
);
$this->currentTestPass = false;
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$this->currentTestSuiteName = $suite->getName();
$this->currentTestName = '';
$this->write(
[
'event' => 'suiteStart',
'suite' => $this->currentTestSuiteName,
'tests' => count($suite)
]
);
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$this->currentTestSuiteName = '';
$this->currentTestName = '';
}
public function startTest(PHPUnit_Framework_Test $test)
{
$this->currentTestName = PHPUnit_Util_Test::describe($test);
$this->currentTestPass = true;
$this->write(
[
'event' => 'testStart',
'suite' => $this->currentTestSuiteName,
'test' => $this->currentTestName
]
);
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if ($this->currentTestPass) {
$this->writeCase('pass', $time, [], '', $test);
}
}
protected function writeCase($status, $time, array $trace = [], $message = '', $test = null)
{
$output = '';
if ($test !== null && method_exists($test, 'hasOutput') && $test->hasOutput()) {
$output = $test->getActualOutput();
}
$this->write(
[
'event' => 'test',
'suite' => $this->currentTestSuiteName,
'test' => $this->currentTestName,
'status' => $status,
'time' => $time,
'trace' => $trace,
'message' => PHPUnit_Util_String::convertToUtf8($message),
'output' => $output,
]
);
}
public function write($buffer)
{
array_walk_recursive($buffer, function (&$input) {
if (is_string($input)) {
$input = PHPUnit_Util_String::convertToUtf8($input);
}
});
parent::write(json_encode($buffer, JSON_PRETTY_PRINT));
}
}
<?php
class PHPUnit_Util_Log_JUnit extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
protected $document;
protected $root;
protected $logIncompleteSkipped = false;
protected $writeDocument = true;
protected $testSuites = [];
protected $testSuiteTests = [0];
protected $testSuiteAssertions = [0];
protected $testSuiteErrors = [0];
protected $testSuiteFailures = [0];
protected $testSuiteTimes = [0];
protected $testSuiteLevel = 0;
protected $currentTestCase = null;
protected $attachCurrentTestCase = true;
public function __construct($out = null, $logIncompleteSkipped = 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->logIncompleteSkipped = $logIncompleteSkipped;
}
public function flush()
{
if ($this->writeDocument === true) {
$this->write($this->getXML());
}
parent::flush();
}
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->doAddFault($test, $e, $time, 'error');
$this->testSuiteErrors[$this->testSuiteLevel]++;
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
if (!$this->logIncompleteSkipped) {
return;
}
$this->doAddFault($test, $e, $time, 'warning');
$this->testSuiteFailures[$this->testSuiteLevel]++;
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$this->doAddFault($test, $e, $time, 'failure');
$this->testSuiteFailures[$this->testSuiteLevel]++;
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if ($this->logIncompleteSkipped && $this->currentTestCase !== null) {
$error = $this->document->createElement(
'error',
PHPUnit_Util_XML::prepareString(
"Incomplete Test\n" .
PHPUnit_Util_Filter::getFilteredStacktrace($e)
)
);
$error->setAttribute('type', get_class($e));
$this->currentTestCase->appendChild($error);
$this->testSuiteErrors[$this->testSuiteLevel]++;
} else {
$this->attachCurrentTestCase = false;
}
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if ($this->logIncompleteSkipped && $this->currentTestCase !== null) {
$error = $this->document->createElement(
'error',
PHPUnit_Util_XML::prepareString(
"Risky Test\n" .
PHPUnit_Util_Filter::getFilteredStacktrace($e)
)
);
$error->setAttribute('type', get_class($e));
$this->currentTestCase->appendChild($error);
$this->testSuiteErrors[$this->testSuiteLevel]++;
} else {
$this->attachCurrentTestCase = false;
}
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if ($this->logIncompleteSkipped && $this->currentTestCase !== null) {
$error = $this->document->createElement(
'error',
PHPUnit_Util_XML::prepareString(
"Skipped Test\n" .
PHPUnit_Util_Filter::getFilteredStacktrace($e)
)
);
$error->setAttribute('type', get_class($e));
$this->currentTestCase->appendChild($error);
$this->testSuiteErrors[$this->testSuiteLevel]++;
} else {
$this->attachCurrentTestCase = false;
}
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$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->testSuiteFailures[$this->testSuiteLevel] = 0;
$this->testSuiteTimes[$this->testSuiteLevel] = 0;
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'tests',
$this->testSuiteTests[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'assertions',
$this->testSuiteAssertions[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'failures',
$this->testSuiteFailures[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'errors',
$this->testSuiteErrors[$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->testSuiteFailures[$this->testSuiteLevel - 1] += $this->testSuiteFailures[$this->testSuiteLevel];
$this->testSuiteTimes[$this->testSuiteLevel - 1] += $this->testSuiteTimes[$this->testSuiteLevel];
}
$this->testSuiteLevel--;
}
public function startTest(PHPUnit_Framework_Test $test)
{
$testCase = $this->document->createElement('testcase');
$testCase->setAttribute('name', $test->getName());
if ($test instanceof PHPUnit_Framework_TestCase) {
$class = new ReflectionClass($test);
$methodName = $test->getName();
if ($class->hasMethod($methodName)) {
$method = $class->getMethod($test->getName());
$testCase->setAttribute('class', $class->getName());
$testCase->setAttribute('file', $class->getFileName());
$testCase->setAttribute('line', $method->getStartLine());
}
}
$this->currentTestCase = $testCase;
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if ($this->attachCurrentTestCase) {
if ($test instanceof PHPUnit_Framework_TestCase) {
$numAssertions = $test->getNumAssertions();
$this->testSuiteAssertions[$this->testSuiteLevel] += $numAssertions;
$this->currentTestCase->setAttribute(
'assertions',
$numAssertions
);
}
$this->currentTestCase->setAttribute(
'time',
sprintf('%F', $time)
);
$this->testSuites[$this->testSuiteLevel]->appendChild(
$this->currentTestCase
);
$this->testSuiteTests[$this->testSuiteLevel]++;
$this->testSuiteTimes[$this->testSuiteLevel] += $time;
if (method_exists($test, 'hasOutput') && $test->hasOutput()) {
$systemOut = $this->document->createElement('system-out');
$systemOut->appendChild(
$this->document->createTextNode($test->getActualOutput())
);
$this->currentTestCase->appendChild($systemOut);
}
}
$this->attachCurrentTestCase = true;
$this->currentTestCase = null;
}
public function getXML()
{
return $this->document->saveXML();
}
public function setWriteDocument($flag)
{
if (is_bool($flag)) {
$this->writeDocument = $flag;
}
}
private function doAddFault(PHPUnit_Framework_Test $test, Exception $e, $time, $type)
{
if ($this->currentTestCase === null) {
return;
}
if ($test instanceof PHPUnit_Framework_SelfDescribing) {
$buffer = $test->toString() . "\n";
} else {
$buffer = '';
}
$buffer .= PHPUnit_Framework_TestFailure::exceptionToString($e) .
"\n" .
PHPUnit_Util_Filter::getFilteredStacktrace($e);
$fault = $this->document->createElement(
$type,
PHPUnit_Util_XML::prepareString($buffer)
);
$fault->setAttribute('type', get_class($e));
$this->currentTestCase->appendChild($fault);
}
}
<?php
class PHPUnit_Util_Log_TAP extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
protected $testNumber = 0;
protected $testSuiteLevel = 0;
protected $testSuccessful = true;
public function __construct($out = null)
{
parent::__construct($out);
$this->write("TAP version 13\n");
}
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeNotOk($test, 'Error');
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
$this->writeNotOk($test, 'Warning');
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$this->writeNotOk($test, 'Failure');
$message = explode(
"\n",
PHPUnit_Framework_TestFailure::exceptionToString($e)
);
$diagnostic = [
'message' => $message[0],
'severity' => 'fail'
];
if ($e instanceof PHPUnit_Framework_ExpectationFailedException) {
$cf = $e->getComparisonFailure();
if ($cf !== null) {
$diagnostic['data'] = [
'got' => $cf->getActual(),
'expected' => $cf->getExpected()
];
}
}
$yaml = new Symfony\Component\Yaml\Dumper;
$this->write(
sprintf(
" ---\n%s ...\n",
$yaml->dump($diagnostic, 2, 2)
)
);
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeNotOk($test, '', 'TODO Incomplete Test');
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->write(
sprintf(
"ok %d - # RISKY%s\n",
$this->testNumber,
$e->getMessage() != '' ? ' ' . $e->getMessage() : ''
)
);
$this->testSuccessful = false;
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->write(
sprintf(
"ok %d - # SKIP%s\n",
$this->testNumber,
$e->getMessage() != '' ? ' ' . $e->getMessage() : ''
)
);
$this->testSuccessful = false;
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$this->testSuiteLevel++;
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$this->testSuiteLevel--;
if ($this->testSuiteLevel == 0) {
$this->write(sprintf("1..%d\n", $this->testNumber));
}
}
public function startTest(PHPUnit_Framework_Test $test)
{
$this->testNumber++;
$this->testSuccessful = true;
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if ($this->testSuccessful === true) {
$this->write(
sprintf(
"ok %d - %s\n",
$this->testNumber,
PHPUnit_Util_Test::describe($test)
)
);
}
$this->writeDiagnostics($test);
}
protected function writeNotOk(PHPUnit_Framework_Test $test, $prefix = '', $directive = '')
{
$this->write(
sprintf(
"not ok %d - %s%s%s\n",
$this->testNumber,
$prefix != '' ? $prefix . ': ' : '',
PHPUnit_Util_Test::describe($test),
$directive != '' ? ' # ' . $directive : ''
)
);
$this->testSuccessful = false;
}
private function writeDiagnostics(PHPUnit_Framework_Test $test)
{
if (!$test instanceof PHPUnit_Framework_TestCase) {
return;
}
if (!$test->hasOutput()) {
return;
}
foreach (explode("\n", trim($test->getActualOutput())) as $line) {
$this->write(
sprintf(
"# %s\n",
$line
)
);
}
}
}
<?php
use SebastianBergmann\Comparator\ComparisonFailure;
class PHPUnit_Util_Log_TeamCity extends PHPUnit_TextUI_ResultPrinter
{
private $isSummaryTestCountPrinted = false;
private $startedTestName;
private $flowId;
protected function writeProgress($progress)
{
}
public function printResult(PHPUnit_Framework_TestResult $result)
{
$this->printHeader();
$this->printFooter($result);
}
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->printEvent(
'testFailed',
[
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
]
);
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
$this->printEvent(
'testFailed',
[
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e)
]
);
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$parameters = [
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
];
if ($e instanceof PHPUnit_Framework_ExpectationFailedException) {
$comparisonFailure = $e->getComparisonFailure();
if ($comparisonFailure instanceof ComparisonFailure) {
$expectedString = $comparisonFailure->getExpectedAsString();
if (is_null($expectedString) || empty($expectedString)) {
$expectedString = self::getPrimitiveValueAsString($comparisonFailure->getExpected());
}
$actualString = $comparisonFailure->getActualAsString();
if (is_null($actualString) || empty($actualString)) {
$actualString = self::getPrimitiveValueAsString($comparisonFailure->getActual());
}
if (!is_null($actualString) && !is_null($expectedString)) {
$parameters['type'] = 'comparisonFailure';
$parameters['actual'] = $actualString;
$parameters['expected'] = $expectedString;
}
}
}
$this->printEvent('testFailed', $parameters);
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->printIgnoredTest($test->getName(), $e);
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->addError($test, $e, $time);
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$testName = $test->getName();
if ($this->startedTestName != $testName) {
$this->startTest($test);
$this->printIgnoredTest($testName, $e);
$this->endTest($test, $time);
} else {
$this->printIgnoredTest($testName, $e);
}
}
public function printIgnoredTest($testName, Exception $e)
{
$this->printEvent(
'testIgnored',
[
'name' => $testName,
'message' => self::getMessage($e),
'details' => self::getDetails($e),
]
);
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
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 = preg_split('/::/', $suiteName);
if (count($split) == 2 && 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);
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$suiteName = $suite->getName();
if (empty($suiteName)) {
return;
}
$parameters = ['name' => $suiteName];
if (!class_exists($suiteName, false)) {
$split = preg_split('/::/', $suiteName);
if (count($split) == 2 && method_exists($split[0], $split[1])) {
$parameters['name'] = $split[1];
}
}
$this->printEvent('testSuiteFinished', $parameters);
}
public function startTest(PHPUnit_Framework_Test $test)
{
$testName = $test->getName();
$this->startedTestName = $testName;
$params = ['name' => $testName];
if ($test instanceof PHPUnit_Framework_TestCase) {
$className = get_class($test);
$fileName = self::getFileName($className);
$params['locationHint'] = "php_qn://$fileName::\\$className::$testName";
}
$this->printEvent('testStarted', $params);
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
parent::endTest($test, $time);
$this->printEvent(
'testFinished',
[
'name' => $test->getName(),
'duration' => (int) (round($time, 2) * 1000)
]
);
}
private function printEvent($eventName, $params = [])
{
$this->write("\n##teamcity[$eventName");
if ($this->flowId) {
$params['flowId'] = $this->flowId;
}
foreach ($params as $key => $value) {
$escapedValue = self::escapeValue($value);
$this->write(" $key='$escapedValue'");
}
$this->write("]\n");
}
private static function getMessage(Exception $e)
{
$message = '';
if (!$e instanceof PHPUnit_Framework_Exception) {
if (strlen(get_class($e)) != 0) {
$message = $message . get_class($e);
}
if (strlen($message) != 0 && strlen($e->getMessage()) != 0) {
$message = $message . ' : ';
}
}
return $message . $e->getMessage();
}
private static function getDetails(Exception $e)
{
$stackTrace = PHPUnit_Util_Filter::getFilteredStacktrace($e);
$previous = $e->getPrevious();
while ($previous) {
$stackTrace .= "\nCaused by\n" .
PHPUnit_Framework_TestFailure::exceptionToString($previous) . "\n" .
PHPUnit_Util_Filter::getFilteredStacktrace($previous);
$previous = $previous->getPrevious();
}
return ' ' . str_replace("\n", "\n ", $stackTrace);
}
private static function getPrimitiveValueAsString($value)
{
if (is_null($value)) {
return 'null';
} elseif (is_bool($value)) {
return $value == true ? 'true' : 'false';
} elseif (is_scalar($value)) {
return print_r($value, true);
}
return;
}
private static function escapeValue($text)
{
$text = str_replace('|', '||', $text);
$text = str_replace("'", "|'", $text);
$text = str_replace("\n", '|n', $text);
$text = str_replace("\r", '|r', $text);
$text = str_replace(']', '|]', $text);
$text = str_replace('[', '|[', $text);
return $text;
}
private static function getFileName($className)
{
$reflectionClass = new ReflectionClass($className);
$fileName = $reflectionClass->getFileName();
return $fileName;
}
}
<?php
use SebastianBergmann\Environment\Runtime;
abstract class PHPUnit_Util_PHP
{
protected $runtime;
protected $stderrRedirection = false;
protected $stdin = '';
protected $args = '';
protected $env = [];
protected $timeout = 0;
public function __construct()
{
$this->runtime = new Runtime();
}
public function setUseStderrRedirection($stderrRedirection)
{
if (!is_bool($stderrRedirection)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
$this->stderrRedirection = $stderrRedirection;
}
public function useStderrRedirection()
{
return $this->stderrRedirection;
}
public function setStdin($stdin)
{
$this->stdin = (string) $stdin;
}
public function getStdin()
{
return $this->stdin;
}
public function setArgs($args)
{
$this->args = (string) $args;
}
public function getArgs()
{
return $this->args;
}
public function setEnv(array $env)
{
$this->env = $env;
}
public function getEnv()
{
return $this->env;
}
public function setTimeout($timeout)
{
$this->timeout = (int) $timeout;
}
public function getTimeout()
{
return $this->timeout;
}
public static function factory()
{
if (DIRECTORY_SEPARATOR == '\\') {
return new PHPUnit_Util_PHP_Windows;
}
return new PHPUnit_Util_PHP_Default;
}
public function runTestJob($job, PHPUnit_Framework_Test $test, PHPUnit_Framework_TestResult $result)
{
$result->startTest($test);
$_result = $this->runJob($job);
$this->processChildResult(
$test,
$result,
$_result['stdout'],
$_result['stderr']
);
}
public function getCommand(array $settings, $file = null)
{
$command = $this->runtime->getBinary();
$command .= $this->settingsToParameters($settings);
if ('phpdbg' === PHP_SAPI) {
$command .= ' -qrr ';
if ($file) {
$command .= '-e ' . escapeshellarg($file);
} else {
$command .= escapeshellarg(__DIR__ . '/PHP/eval-stdin.php');
}
} elseif ($file) {
$command .= ' -f ' . escapeshellarg($file);
}
if ($this->args) {
$command .= ' -- ' . $this->args;
}
if (true === $this->stderrRedirection) {
$command .= ' 2>&1';
}
return $command;
}
abstract public function runJob($job, array $settings = []);
protected function settingsToParameters(array $settings)
{
$buffer = '';
foreach ($settings as $setting) {
$buffer .= ' -d ' . $setting;
}
return $buffer;
}
private function processChildResult(PHPUnit_Framework_Test $test, PHPUnit_Framework_TestResult $result, $stdout, $stderr)
{
$time = 0;
if (!empty($stderr)) {
$result->addError(
$test,
new PHPUnit_Framework_Exception(trim($stderr)),
$time
);
} else {
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
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();
} catch (ErrorException $e) {
restore_error_handler();
$childResult = false;
$result->addError(
$test,
new PHPUnit_Framework_Exception(trim($stdout), 0, $e),
$time
);
}
if ($childResult !== false) {
if (!empty($childResult['output'])) {
$output = $childResult['output'];
}
$test->setResult($childResult['testResult']);
$test->addToAssertionCount($childResult['numAssertions']);
$childResult = $childResult['result'];
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;
}
}
private function getException(PHPUnit_Framework_TestFailure $error)
{
$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 PHPUnit_Framework_SyntheticError(
sprintf(
'%s: %s',
$exceptionArray['_PHP_Incomplete_Class_Name'],
$exceptionArray['message']
),
$exceptionArray['code'],
$exceptionArray['file'],
$exceptionArray['line'],
$exceptionArray['trace']
);
}
return $exception;
}
}
<?php
class PHPUnit_Util_PHP_Default extends PHPUnit_Util_PHP
{
protected $tempFile;
protected $useTempFile = false;
public function runJob($job, array $settings = [])
{
if ($this->useTempFile || $this->stdin) {
if (!($this->tempFile = tempnam(sys_get_temp_dir(), 'PHPUnit')) ||
file_put_contents($this->tempFile, $job) === false) {
throw new PHPUnit_Framework_Exception(
'Unable to write temporary file'
);
}
$job = $this->stdin;
}
return $this->runProcess($job, $settings);
}
protected function getHandles()
{
return [];
}
protected function runProcess($job, $settings)
{
$handles = $this->getHandles();
$env = null;
if ($this->env) {
$env = isset($_SERVER) ? $_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 => isset($handles[0]) ? $handles[0] : ['pipe', 'r'],
1 => isset($handles[1]) ? $handles[1] : ['pipe', 'w'],
2 => isset($handles[2]) ? $handles[2] : ['pipe', 'w'],
];
$process = proc_open(
$this->getCommand($settings, $this->tempFile),
$pipeSpec,
$pipes,
null,
$env
);
if (!is_resource($process)) {
throw new PHPUnit_Framework_Exception(
'Unable to spawn worker process'
);
}
if ($job) {
$this->process($pipes[0], $job);
}
fclose($pipes[0]);
if ($this->timeout) {
$stderr = $stdout = '';
unset($pipes[0]);
while (true) {
$r = $pipes;
$w = null;
$e = null;
$n = @stream_select($r, $w, $e, $this->timeout);
if ($n === false) {
break;
} elseif ($n === 0) {
proc_terminate($process, 9);
throw new PHPUnit_Framework_Exception(sprintf('Job execution aborted after %d seconds', $this->timeout));
} elseif ($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 (strlen($line) == 0) {
fclose($pipes[$pipeOffset]);
unset($pipes[$pipeOffset]);
} else {
if ($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, $job)
{
fwrite($pipe, $job);
}
protected function cleanup()
{
if ($this->tempFile) {
unlink($this->tempFile);
}
}
}
<?php
class PHPUnit_Util_PHP_Windows extends PHPUnit_Util_PHP_Default
{
protected $useTempFile = true;
protected function getHandles()
{
if (false === $stdout_handle = tmpfile()) {
throw new PHPUnit_Framework_Exception(
'A temporary file could not be created; verify that your TEMP environment variable is writable'
);
}
return [
1 => $stdout_handle
];
}
public function getCommand(array $settings, $file = null)
{
return '"' . parent::getCommand($settings, $file) . '"';
}
}
<?php
eval('?>' . file_get_contents('php://input'));
<?php
class PHPUnit_Util_Printer
{
protected $autoFlush = false;
protected $out;
protected $outTarget;
protected $printsHTML = false;
public function __construct($out = null)
{
if ($out !== null) {
if (is_string($out)) {
if (strpos($out, 'socket://') === 0) {
$out = explode(':', str_replace('socket://', '', $out));
if (sizeof($out) != 2) {
throw new PHPUnit_Framework_Exception;
}
$this->out = fsockopen($out[0], $out[1]);
} else {
if (strpos($out, 'php://') === false &&
!is_dir(dirname($out))) {
mkdir(dirname($out), 0777, true);
}
$this->out = fopen($out, 'wt');
}
$this->outTarget = $out;
} else {
$this->out = $out;
}
}
}
public function flush()
{
if ($this->out && strncmp($this->outTarget, 'php://', 6) !== 0) {
fclose($this->out);
}
if ($this->printsHTML === true &&
$this->outTarget !== null &&
strpos($this->outTarget, 'php://') !== 0 &&
strpos($this->outTarget, 'socket://') !== 0 &&
extension_loaded('tidy')) {
file_put_contents(
$this->outTarget,
tidy_repair_file(
$this->outTarget,
['indent' => true, 'wrap' => 0],
'utf8'
)
);
}
}
public function incrementalFlush()
{
if ($this->out) {
fflush($this->out);
} else {
flush();
}
}
public function write($buffer)
{
if ($this->out) {
fwrite($this->out, $buffer);
if ($this->autoFlush) {
$this->incrementalFlush();
}
} else {
if (PHP_SAPI != 'cli' && PHP_SAPI != 'phpdbg') {
$buffer = htmlspecialchars($buffer);
}
print $buffer;
if ($this->autoFlush) {
$this->incrementalFlush();
}
}
}
public function getAutoFlush()
{
return $this->autoFlush;
}
public function setAutoFlush($autoFlush)
{
if (is_bool($autoFlush)) {
$this->autoFlush = $autoFlush;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'boolean');
}
}
}
<?php
class PHPUnit_Util_Regex
{
public static function pregMatchSafe($pattern, $subject, $matches = null, $flags = 0, $offset = 0)
{
$handler_terminator = PHPUnit_Util_ErrorHandler::handleErrorOnce(E_WARNING);
$match = preg_match($pattern, $subject, $matches, $flags, $offset);
$handler_terminator();
return $match;
}
}
<?php
class PHPUnit_Util_String
{
public static function convertToUtf8($string)
{
if (!self::isUtf8($string)) {
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, 'UTF-8');
} else {
$string = utf8_encode($string);
}
}
return $string;
}
protected static function isUtf8($string)
{
$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
class PHPUnit_Util_Test
{
const REGEX_DATA_PROVIDER = '/@dataProvider\s+([a-zA-Z0-9._:-\\\\x7f-\xff]+)/';
const REGEX_TEST_WITH = '/@testWith\s+/';
const REGEX_EXPECTED_EXCEPTION = '(@expectedException\s+([:.\w\\\\x7f-\xff]+)(?:[\t ]+(\S*))?(?:[\t ]+(\S*))?\s*$)m';
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';
const REGEX_REQUIRES_OS = '/@requires\s+OS\s+(?P<value>.+?)[ \t]*\r?$/m';
const REGEX_REQUIRES = '/@requires\s+(?P<name>function|extension)\s+(?P<value>([^ ]+?))\s*(?P<operator>[<>=!]{0,2})\s*(?P<version>[\d\.-]+[\d\.]?)?[ \t]*\r?$/m';
const UNKNOWN = -1;
const SMALL = 0;
const MEDIUM = 1;
const LARGE = 2;
private static $annotationCache = [];
private static $hookMethods = [];
public static function describe(PHPUnit_Framework_Test $test, $asString = true)
{
if ($asString) {
if ($test instanceof PHPUnit_Framework_SelfDescribing) {
return $test->toString();
} else {
return get_class($test);
}
} else {
if ($test instanceof PHPUnit_Framework_TestCase) {
return [
get_class($test), $test->getName()
];
} elseif ($test instanceof PHPUnit_Framework_SelfDescribing) {
return ['', $test->toString()];
} else {
return ['', get_class($test)];
}
}
}
public static function getLinesToBeCovered($className, $methodName)
{
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
if (isset($annotations['class']['coversNothing']) || isset($annotations['method']['coversNothing'])) {
return false;
}
return self::getLinesToBeCoveredOrUsed($className, $methodName, 'covers');
}
public static function getLinesToBeUsed($className, $methodName)
{
return self::getLinesToBeCoveredOrUsed($className, $methodName, 'uses');
}
private static function getLinesToBeCoveredOrUsed($className, $methodName, $mode)
{
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
$classShortcut = null;
if (!empty($annotations['class'][$mode . 'DefaultClass'])) {
if (count($annotations['class'][$mode . 'DefaultClass']) > 1) {
throw new PHPUnit_Framework_CodeCoverageException(
sprintf(
'More than one @%sClass annotation in class or interface "%s".',
$mode,
$className
)
);
}
$classShortcut = $annotations['class'][$mode . 'DefaultClass'][0];
}
$list = [];
if (isset($annotations['class'][$mode])) {
$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];
$codeList = array_merge(
$codeList,
self::resolveElementToReflectionObjects($element)
);
}
return self::resolveReflectionObjectsToLines($codeList);
}
public static function getRequirements($className, $methodName)
{
$reflector = new ReflectionClass($className);
$docComment = $reflector->getDocComment();
$reflector = new ReflectionMethod($className, $methodName);
$docComment .= "\n" . $reflector->getDocComment();
$requires = [];
if ($count = preg_match_all(self::REGEX_REQUIRES_OS, $docComment, $matches)) {
$requires['OS'] = sprintf(
'/%s/i',
addcslashes($matches['value'][$count - 1], '/')
);
}
if ($count = preg_match_all(self::REGEX_REQUIRES_VERSION, $docComment, $matches)) {
for ($i = 0; $i < $count; $i++) {
$requires[$matches['name'][$i]] = [
'version' => $matches['version'][$i],
'operator' => $matches['operator'][$i]
];
}
}
$matches = [];
if ($count = preg_match_all(self::REGEX_REQUIRES, $docComment, $matches)) {
for ($i = 0; $i < $count; $i++) {
$name = $matches['name'][$i] . 's';
if (!isset($requires[$name])) {
$requires[$name] = [];
}
$requires[$name][] = $matches['value'][$i];
if (empty($matches['version'][$i]) || $name != 'extensions') {
continue;
}
$requires['extension_versions'][$matches['value'][$i]] = [
'version' => $matches['version'][$i],
'operator' => $matches['operator'][$i]
];
}
}
return $requires;
}
public static function getMissingRequirements($className, $methodName)
{
$required = static::getRequirements($className, $methodName);
$missing = [];
$operator = empty($required['PHP']['operator']) ? '>=' : $required['PHP']['operator'];
if (!empty($required['PHP']) && !version_compare(PHP_VERSION, $required['PHP']['version'], $operator)) {
$missing[] = sprintf('PHP %s %s is required.', $operator, $required['PHP']['version']);
}
if (!empty($required['PHPUnit'])) {
$phpunitVersion = PHPUnit_Runner_Version::id();
$operator = empty($required['PHPUnit']['operator']) ? '>=' : $required['PHPUnit']['operator'];
if (!version_compare($phpunitVersion, $required['PHPUnit']['version'], $operator)) {
$missing[] = sprintf('PHPUnit %s %s is required.', $operator, $required['PHPUnit']['version']);
}
}
if (!empty($required['OS']) && !preg_match($required['OS'], PHP_OS)) {
$missing[] = sprintf('Operating system matching %s is required.', $required['OS']);
}
if (!empty($required['functions'])) {
foreach ($required['functions'] as $function) {
$pieces = explode('::', $function);
if (2 === count($pieces) && method_exists($pieces[0], $pieces[1])) {
continue;
}
if (function_exists($function)) {
continue;
}
$missing[] = sprintf('Function %s is required.', $function);
}
}
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);
}
}
}
if (!empty($required['extension_versions'])) {
foreach ($required['extension_versions'] as $extension => $required) {
$actualVersion = phpversion($extension);
$operator = empty($required['operator']) ? '>=' : $required['operator'];
if (false === $actualVersion || !version_compare($actualVersion, $required['version'], $operator)) {
$missing[] = sprintf('Extension %s %s %s is required.', $extension, $operator, $required['version']);
}
}
}
return $missing;
}
public static function getExpectedException($className, $methodName)
{
$reflector = new ReflectionMethod($className, $methodName);
$docComment = $reflector->getDocComment();
$docComment = substr($docComment, 3, -2);
if (preg_match(self::REGEX_EXPECTED_EXCEPTION, $docComment, $matches)) {
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
$class = $matches[1];
$code = null;
$message = '';
$messageRegExp = '';
if (isset($matches[2])) {
$message = trim($matches[2]);
} elseif (isset($annotations['method']['expectedExceptionMessage'])) {
$message = self::parseAnnotationContent(
$annotations['method']['expectedExceptionMessage'][0]
);
}
if (isset($annotations['method']['expectedExceptionMessageRegExp'])) {
$messageRegExp = self::parseAnnotationContent(
$annotations['method']['expectedExceptionMessageRegExp'][0]
);
}
if (isset($matches[3])) {
$code = $matches[3];
} elseif (isset($annotations['method']['expectedExceptionCode'])) {
$code = self::parseAnnotationContent(
$annotations['method']['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
];
}
return false;
}
private static function parseAnnotationContent($message)
{
if (strpos($message, '::') !== false && count(explode('::', $message) == 2)) {
if (defined($message)) {
$message = constant($message);
}
}
return $message;
}
public static function getProvidedData($className, $methodName)
{
$reflector = new ReflectionMethod($className, $methodName);
$docComment = $reflector->getDocComment();
$data = null;
if ($dataProviderData = self::getDataFromDataProviderAnnotation($docComment, $className, $methodName)) {
$data = $dataProviderData;
}
if ($testWithData = self::getDataFromTestWithAnnotation($docComment)) {
$data = $testWithData;
}
if ($data !== null) {
if (is_object($data)) {
$data = iterator_to_array($data);
}
foreach ($data as $key => $value) {
if (!is_array($value)) {
throw new PHPUnit_Framework_Exception(
sprintf(
'Data set %s is invalid.',
is_int($key) ? '#' . $key : '"' . $key . '"'
)
);
}
}
}
return $data;
}
private static function getDataFromDataProviderAnnotation($docComment, $className, $methodName)
{
if (preg_match(self::REGEX_DATA_PROVIDER, $docComment, $matches)) {
$dataProviderMethodNameNamespace = explode('\\', $matches[1]);
$leaf = explode('::', array_pop($dataProviderMethodNameNamespace));
$dataProviderMethodName = array_pop($leaf);
if (!empty($dataProviderMethodNameNamespace)) {
$dataProviderMethodNameNamespace = implode('\\', $dataProviderMethodNameNamespace) . '\\';
} else {
$dataProviderMethodNameNamespace = '';
}
if (!empty($leaf)) {
$dataProviderClassName = $dataProviderMethodNameNamespace . array_pop($leaf);
} else {
$dataProviderClassName = $className;
}
$dataProviderClass = new ReflectionClass($dataProviderClassName);
$dataProviderMethod = $dataProviderClass->getMethod(
$dataProviderMethodName
);
if ($dataProviderMethod->isStatic()) {
$object = null;
} else {
$object = $dataProviderClass->newInstance();
}
if ($dataProviderMethod->getNumberOfParameters() == 0) {
$data = $dataProviderMethod->invoke($object);
} else {
$data = $dataProviderMethod->invoke($object, $methodName);
}
return $data;
}
}
public static function getDataFromTestWithAnnotation($docComment)
{
$docComment = self::cleanUpMultiLineAnnotation($docComment);
if (preg_match(self::REGEX_TEST_WITH, $docComment, $matches, PREG_OFFSET_CAPTURE)) {
$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 PHPUnit_Framework_Exception(
'The dataset for the @testWith annotation cannot be parsed: ' . json_last_error_msg()
);
}
$data[] = $dataSet;
}
if (!$data) {
throw new PHPUnit_Framework_Exception('The dataset for the @testWith annotation cannot be parsed.');
}
return $data;
}
}
private static function cleanUpMultiLineAnnotation($docComment)
{
$docComment = preg_replace('/' . '\n' . '\s*' . '\*' . '\s?' . '/', "\n", $docComment);
$docComment = substr($docComment, 0, -1);
$docComment = rtrim($docComment, "\n");
return $docComment;
}
public static function parseTestMethodAnnotations($className, $methodName = '')
{
if (!isset(self::$annotationCache[$className])) {
$class = new ReflectionClass($className);
self::$annotationCache[$className] = self::parseAnnotations($class->getDocComment());
}
if (!empty($methodName) && !isset(self::$annotationCache[$className . '::' . $methodName])) {
try {
$method = new ReflectionMethod($className, $methodName);
$annotations = self::parseAnnotations($method->getDocComment());
} catch (ReflectionException $e) {
$annotations = [];
}
self::$annotationCache[$className . '::' . $methodName] = $annotations;
}
return [
'class' => self::$annotationCache[$className],
'method' => !empty($methodName) ? self::$annotationCache[$className . '::' . $methodName] : []
];
}
public static function getInlineAnnotations($className, $methodName)
{
$method = new ReflectionMethod($className, $methodName);
$code = file($method->getFileName());
$lineNumber = $method->getStartLine();
$startLine = $method->getStartLine() - 1;
$endLine = $method->getEndLine() - 1;
$methodLines = array_slice($code, $startLine, $endLine - $startLine + 1);
$annotations = [];
foreach ($methodLines 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;
}
private static function parseAnnotations($docblock)
{
$annotations = [];
$docblock = substr($docblock, 3, -2);
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]][] = $matches['value'][$i];
}
}
return $annotations;
}
public static function getBackupSettings($className, $methodName)
{
return [
'backupGlobals' => self::getBooleanAnnotationSetting(
$className,
$methodName,
'backupGlobals'
),
'backupStaticAttributes' => self::getBooleanAnnotationSetting(
$className,
$methodName,
'backupStaticAttributes'
)
];
}
public static function getDependencies($className, $methodName)
{
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
$dependencies = [];
if (isset($annotations['class']['depends'])) {
$dependencies = $annotations['class']['depends'];
}
if (isset($annotations['method']['depends'])) {
$dependencies = array_merge(
$dependencies,
$annotations['method']['depends']
);
}
return array_unique($dependencies);
}
public static function getErrorHandlerSettings($className, $methodName)
{
return self::getBooleanAnnotationSetting(
$className,
$methodName,
'errorHandler'
);
}
public static function getGroups($className, $methodName = '')
{
$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 = array_merge($groups, $annotations['class']['group']);
}
if (isset($annotations['method']['group'])) {
$groups = array_merge($groups, $annotations['method']['group']);
}
if (isset($annotations['class']['ticket'])) {
$groups = array_merge($groups, $annotations['class']['ticket']);
}
if (isset($annotations['method']['ticket'])) {
$groups = array_merge($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($groups);
}
public static function getSize($className, $methodName)
{
$groups = array_flip(self::getGroups($className, $methodName));
$size = self::UNKNOWN;
$class = new ReflectionClass($className);
if (isset($groups['large']) ||
(class_exists('PHPUnit_Extensions_Database_TestCase', false) &&
$class->isSubclassOf('PHPUnit_Extensions_Database_TestCase'))) {
$size = self::LARGE;
} elseif (isset($groups['medium'])) {
$size = self::MEDIUM;
} elseif (isset($groups['small'])) {
$size = self::SMALL;
}
return $size;
}
public static function getTickets($className, $methodName)
{
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
$tickets = [];
if (isset($annotations['class']['ticket'])) {
$tickets = $annotations['class']['ticket'];
}
if (isset($annotations['method']['ticket'])) {
$tickets = array_merge($tickets, $annotations['method']['ticket']);
}
return array_unique($tickets);
}
public static function getProcessIsolationSettings($className, $methodName)
{
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
if (isset($annotations['class']['runTestsInSeparateProcesses']) ||
isset($annotations['method']['runInSeparateProcess'])) {
return true;
} else {
return false;
}
}
public static function getPreserveGlobalStateSettings($className, $methodName)
{
return self::getBooleanAnnotationSetting(
$className,
$methodName,
'preserveGlobalState'
);
}
public static function getHookMethods($className)
{
if (!class_exists($className, false)) {
return self::emptyHookMethodsArray();
}
if (!isset(self::$hookMethods[$className])) {
self::$hookMethods[$className] = self::emptyHookMethodsArray();
try {
$class = new ReflectionClass($className);
foreach ($class->getMethods() as $method) {
if (self::isBeforeClassMethod($method)) {
self::$hookMethods[$className]['beforeClass'][] = $method->getName();
}
if (self::isBeforeMethod($method)) {
self::$hookMethods[$className]['before'][] = $method->getName();
}
if (self::isAfterMethod($method)) {
self::$hookMethods[$className]['after'][] = $method->getName();
}
if (self::isAfterClassMethod($method)) {
self::$hookMethods[$className]['afterClass'][] = $method->getName();
}
}
} catch (ReflectionException $e) {
}
}
return self::$hookMethods[$className];
}
private static function emptyHookMethodsArray()
{
return [
'beforeClass' => ['setUpBeforeClass'],
'before' => ['setUp'],
'after' => ['tearDown'],
'afterClass' => ['tearDownAfterClass']
];
}
private static function getBooleanAnnotationSetting($className, $methodName, $settingName)
{
$annotations = self::parseTestMethodAnnotations(
$className,
$methodName
);
$result = null;
if (isset($annotations['class'][$settingName])) {
if ($annotations['class'][$settingName][0] == 'enabled') {
$result = true;
} elseif ($annotations['class'][$settingName][0] == 'disabled') {
$result = false;
}
}
if (isset($annotations['method'][$settingName])) {
if ($annotations['method'][$settingName][0] == 'enabled') {
$result = true;
} elseif ($annotations['method'][$settingName][0] == 'disabled') {
$result = false;
}
}
return $result;
}
private static function resolveElementToReflectionObjects($element)
{
$codeToCoverList = [];
if (strpos($element, '\\') !== false && function_exists($element)) {
$codeToCoverList[] = new ReflectionFunction($element);
} elseif (strpos($element, '::') !== false) {
list($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 PHPUnit_Framework_InvalidCoversTargetException(
sprintf(
'Trying to @cover or @use not existing class or ' .
'interface "%s".',
$className
)
);
}
$class = new ReflectionClass($className);
$methods = $class->getMethods();
$inverse = isset($methodName[1]) && $methodName[1] == '!';
if (strpos($methodName, 'protected')) {
$visibility = 'isProtected';
} elseif (strpos($methodName, 'private')) {
$visibility = 'isPrivate';
} elseif (strpos($methodName, 'public')) {
$visibility = 'isPublic';
}
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)) {
$codeToCoverList[] = new ReflectionFunction(
$methodName
);
} else {
if (!((class_exists($className) ||
interface_exists($className) ||
trait_exists($className)) &&
method_exists($className, $methodName))) {
throw new PHPUnit_Framework_InvalidCoversTargetException(
sprintf(
'Trying to @cover or @use not existing method "%s::%s".',
$className,
$methodName
)
);
}
$codeToCoverList[] = new ReflectionMethod(
$className,
$methodName
);
}
}
}
} 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 PHPUnit_Framework_InvalidCoversTargetException(
sprintf(
'Trying to @cover or @use not existing class or ' .
'interface "%s".',
$className
)
);
}
$codeToCoverList[] = new ReflectionClass($className);
}
}
return $codeToCoverList;
}
private static function resolveReflectionObjectsToLines(array $reflectors)
{
$result = [];
foreach ($reflectors as $reflector) {
$filename = $reflector->getFileName();
if (!isset($result[$filename])) {
$result[$filename] = [];
}
$result[$filename] = array_unique(
array_merge(
$result[$filename],
range($reflector->getStartLine(), $reflector->getEndLine())
)
);
}
return $result;
}
private static function isBeforeClassMethod(ReflectionMethod $method)
{
return $method->isStatic() && strpos($method->getDocComment(), '@beforeClass') !== false;
}
private static function isBeforeMethod(ReflectionMethod $method)
{
return preg_match('/@before\b/', $method->getDocComment());
}
private static function isAfterClassMethod(ReflectionMethod $method)
{
return $method->isStatic() && strpos($method->getDocComment(), '@afterClass') !== false;
}
private static function isAfterMethod(ReflectionMethod $method)
{
return preg_match('/@after\b/', $method->getDocComment());
}
}
<?php
class PHPUnit_Util_TestDox_NamePrettifier
{
protected $prefix = 'Test';
protected $suffix = 'Test';
protected $strings = [];
public function prettifyTestClass($name)
{
$title = $name;
if ($this->suffix !== null &&
$this->suffix == substr($name, -1 * strlen($this->suffix))) {
$title = substr($title, 0, strripos($title, $this->suffix));
}
if ($this->prefix !== null &&
$this->prefix == substr($name, 0, strlen($this->prefix))) {
$title = substr($title, strlen($this->prefix));
}
if (substr($title, 0, 1) == '\\') {
$title = substr($title, 1);
}
return $title;
}
public function prettifyTestMethod($name)
{
$buffer = '';
if (!is_string($name) || strlen($name) == 0) {
return $buffer;
}
$string = preg_replace('#\d+$#', '', $name, -1, $count);
if (in_array($string, $this->strings)) {
$name = $string;
} elseif ($count == 0) {
$this->strings[] = $string;
}
if (substr($name, 0, 4) == 'test') {
$name = substr($name, 4);
}
if (strlen($name) == 0) {
return $buffer;
}
$name[0] = strtoupper($name[0]);
if (strpos($name, '_') !== false) {
return trim(str_replace('_', ' ', $name));
}
$max = strlen($name);
$wasNumeric = false;
for ($i = 0; $i < $max; $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;
}
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
public function setSuffix($suffix)
{
$this->suffix = $suffix;
}
}
<?php
abstract class PHPUnit_Util_TestDox_ResultPrinter extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
protected $prettifier;
protected $testClass = '';
protected $testStatus = false;
protected $tests = [];
protected $successful = 0;
protected $warned = 0;
protected $failed = 0;
protected $risky = 0;
protected $skipped = 0;
protected $incomplete = 0;
protected $currentTestClassPrettified;
protected $currentTestMethodPrettified;
private $groups;
private $excludeGroups;
public function __construct($out = null, array $groups = [], array $excludeGroups = [])
{
parent::__construct($out);
$this->groups = $groups;
$this->excludeGroups = $excludeGroups;
$this->prettifier = new PHPUnit_Util_TestDox_NamePrettifier;
$this->startRun();
}
public function flush()
{
$this->doEndClass();
$this->endRun();
parent::flush();
}
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_ERROR;
$this->failed++;
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_WARNING;
$this->warned++;
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE;
$this->failed++;
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE;
$this->incomplete++;
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_RISKY;
$this->risky++;
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED;
$this->skipped++;
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function startTest(PHPUnit_Framework_Test $test)
{
if (!$this->isOfInterest($test)) {
return;
}
$class = get_class($test);
if ($this->testClass != $class) {
if ($this->testClass != '') {
$this->doEndClass();
}
$classAnnotations = PHPUnit_Util_Test::parseTestMethodAnnotations($class);
if (isset($classAnnotations['class']['testdox'][0])) {
$this->currentTestClassPrettified = $classAnnotations['class']['testdox'][0];
} else {
$this->currentTestClassPrettified = $this->prettifier->prettifyTestClass($class);
}
$this->startClass($class);
$this->testClass = $class;
$this->tests = [];
}
$annotations = $test->getAnnotations();
if (isset($annotations['method']['testdox'][0])) {
$this->currentTestMethodPrettified = $annotations['method']['testdox'][0];
} else {
$this->currentTestMethodPrettified = $this->prettifier->prettifyTestMethod($test->getName(false));
}
if ($test instanceof PHPUnit_Framework_TestCase && $test->usesDataProvider()) {
$this->currentTestMethodPrettified .= ' ' . $test->dataDescription();
}
$this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_PASSED;
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if (!$this->isOfInterest($test)) {
return;
}
if (!isset($this->tests[$this->currentTestMethodPrettified])) {
if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) {
$this->tests[$this->currentTestMethodPrettified]['success'] = 1;
$this->tests[$this->currentTestMethodPrettified]['failure'] = 0;
} else {
$this->tests[$this->currentTestMethodPrettified]['success'] = 0;
$this->tests[$this->currentTestMethodPrettified]['failure'] = 1;
}
} else {
if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) {
$this->tests[$this->currentTestMethodPrettified]['success']++;
} else {
$this->tests[$this->currentTestMethodPrettified]['failure']++;
}
}
$this->currentTestClassPrettified = null;
$this->currentTestMethodPrettified = null;
}
protected function doEndClass()
{
foreach ($this->tests as $name => $data) {
$this->onTest($name, $data['failure'] == 0);
}
$this->endClass($this->testClass);
}
protected function startRun()
{
}
protected function startClass($name)
{
}
protected function onTest($name, $success = true)
{
}
protected function endClass($name)
{
}
protected function endRun()
{
}
private function isOfInterest(PHPUnit_Framework_Test $test)
{
if (!$test instanceof PHPUnit_Framework_TestCase) {
return false;
}
if ($test instanceof PHPUnit_Framework_WarningTestCase) {
return false;
}
if (!empty($this->groups)) {
foreach ($test->getGroups() as $group) {
if (in_array($group, $this->groups)) {
return true;
}
}
return false;
}
if (!empty($this->excludeGroups)) {
foreach ($test->getGroups() as $group) {
if (in_array($group, $this->excludeGroups)) {
return false;
}
}
return true;
}
return true;
}
}
<?php
class PHPUnit_Util_TestDox_ResultPrinter_HTML extends PHPUnit_Util_TestDox_ResultPrinter
{
protected $printsHTML = true;
private $pageHeader = <<<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;
}
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;
private $classHeader = <<<EOT
<h2 id="%s">%s</h2>
<ul>
EOT;
private $classFooter = <<<EOT
</ul>
EOT;
private $pageFooter = <<<EOT
</body>
</html>
EOT;
protected function startRun()
{
$this->write($this->pageHeader);
}
protected function startClass($name)
{
$this->write(
sprintf(
$this->classHeader,
$name,
$this->currentTestClassPrettified
)
);
}
protected function onTest($name, $success = true)
{
$this->write(
sprintf(
" <li style=\"color: %s;\">%s %s</li>\n",
$success ? '#555753' : '#ef2929',
$success ? '✓' : 'â<>Œ',
$name
)
);
}
protected function endClass($name)
{
$this->write($this->classFooter);
}
protected function endRun()
{
$this->write($this->pageFooter);
}
}
<?php
class PHPUnit_Util_TestDox_ResultPrinter_Text extends PHPUnit_Util_TestDox_ResultPrinter
{
protected function startClass($name)
{
$this->write($this->currentTestClassPrettified . "\n");
}
protected function onTest($name, $success = true)
{
if ($success) {
$this->write(' [x] ');
} else {
$this->write(' [ ] ');
}
$this->write($name . "\n");
}
protected function endClass($name)
{
$this->write("\n");
}
}
<?php
class PHPUnit_Util_TestDox_ResultPrinter_XML extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
private $document;
private $root;
private $prettifier;
private $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 PHPUnit_Util_TestDox_NamePrettifier;
parent::__construct($out);
}
public function flush()
{
$this->write($this->document->saveXML());
parent::flush();
}
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->exception = $e;
}
public function addWarning(PHPUnit_Framework_Test $test, PHPUnit_Framework_Warning $e, $time)
{
}
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$this->exception = $e;
}
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
public function startTest(PHPUnit_Framework_Test $test)
{
$this->exception = null;
}
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if (!$test instanceof PHPUnit_Framework_TestCase) {
return;
}
$groups = array_filter(
$test->getGroups(),
function ($group) {
if ($group == 'small' || $group == 'medium' || $group == 'large') {
return false;
}
return true;
}
);
$node = $this->document->createElement('test');
$node->setAttribute('className', get_class($test));
$node->setAttribute('methodName', $test->getName());
$node->setAttribute('prettifiedClassName', $this->prettifier->prettifyTestClass(get_class($test)));
$node->setAttribute('prettifiedMethodName', $this->prettifier->prettifyTestMethod($test->getName()));
$node->setAttribute('status', $test->getStatus());
$node->setAttribute('time', $time);
$node->setAttribute('size', $test->getSize());
$node->setAttribute('groups', implode(',', $groups));
$inlineAnnotations = PHPUnit_Util_Test::getInlineAnnotations(get_class($test), $test->getName());
if (isset($inlineAnnotations['given']) && isset($inlineAnnotations['when']) && isset($inlineAnnotations['then'])) {
$node->setAttribute('given', $inlineAnnotations['given']['value']);
$node->setAttribute('givenStartLine', $inlineAnnotations['given']['line']);
$node->setAttribute('when', $inlineAnnotations['when']['value']);
$node->setAttribute('whenStartLine', $inlineAnnotations['when']['line']);
$node->setAttribute('then', $inlineAnnotations['then']['value']);
$node->setAttribute('thenStartLine', $inlineAnnotations['then']['line']);
}
if ($this->exception !== null) {
if ($this->exception instanceof PHPUnit_Framework_Exception) {
$steps = $this->exception->getSerializableTrace();
} else {
$steps = $this->exception->getTrace();
}
$class = new ReflectionClass($test);
$file = $class->getFileName();
foreach ($steps as $step) {
if (isset($step['file']) && $step['file'] == $file) {
$node->setAttribute('exceptionLine', $step['line']);
break;
}
}
$node->setAttribute('exceptionMessage', $this->exception->getMessage());
}
$this->root->appendChild($node);
}
}
<?php
class PHPUnit_Util_TestSuiteIterator implements RecursiveIterator
{
protected $position;
protected $tests;
public function __construct(PHPUnit_Framework_TestSuite $testSuite)
{
$this->tests = $testSuite->tests();
}
public function rewind()
{
$this->position = 0;
}
public function valid()
{
return $this->position < count($this->tests);
}
public function key()
{
return $this->position;
}
public function current()
{
return $this->valid() ? $this->tests[$this->position] : null;
}
public function next()
{
$this->position++;
}
public function getChildren()
{
return new self(
$this->tests[$this->position]
);
}
public function hasChildren()
{
return $this->tests[$this->position] instanceof PHPUnit_Framework_TestSuite;
}
}
<?php
class PHPUnit_Util_Type
{
public static function isType($type)
{
return in_array(
$type,
[
'numeric',
'integer',
'int',
'float',
'string',
'boolean',
'bool',
'null',
'array',
'object',
'resource',
'scalar'
]
);
}
}
<?php
class PHPUnit_Util_XML
{
public static function load($actual, $isHtml = false, $filename = '', $xinclude = false, $strict = false)
{
if ($actual instanceof DOMDocument) {
return $actual;
}
if (!is_string($actual)) {
throw new PHPUnit_Framework_Exception('Could not load XML from ' . gettype($actual));
}
if ($actual === '') {
throw new PHPUnit_Framework_Exception('Could not load XML from empty string');
}
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) {
$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 ($xinclude) {
@chdir($cwd);
}
if ($loaded === false || ($strict && $message !== '')) {
if ($filename !== '') {
throw new PHPUnit_Framework_Exception(
sprintf(
'Could not load "%s".%s',
$filename,
$message != '' ? "\n" . $message : ''
)
);
} else {
if ($message === '') {
$message = 'Could not load XML for unknown reason';
}
throw new PHPUnit_Framework_Exception($message);
}
}
return $document;
}
public static function loadFile($filename, $isHtml = false, $xinclude = false, $strict = false)
{
$reporting = error_reporting(0);
$contents = file_get_contents($filename);
error_reporting($reporting);
if ($contents === false) {
throw new PHPUnit_Framework_Exception(
sprintf(
'Could not read "%s".',
$filename
)
);
}
return self::load($contents, $isHtml, $filename, $xinclude, $strict);
}
public static function removeCharacterDataNodes(DOMNode $node)
{
if ($node->hasChildNodes()) {
for ($i = $node->childNodes->length - 1; $i >= 0; $i--) {
if (($child = $node->childNodes->item($i)) instanceof DOMCharacterData) {
$node->removeChild($child);
}
}
}
}
public static function prepareString($string)
{
return preg_replace(
'/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/',
'',
htmlspecialchars(
PHPUnit_Util_String::convertToUtf8($string),
ENT_QUOTES,
'UTF-8'
)
);
}
public static function xmlToVariable(DOMElement $element)
{
$variable = null;
switch ($element->tagName) {
case 'array':
$variable = [];
foreach ($element->getElementsByTagName('element') as $element) {
$item = $element->childNodes->item(0);
if ($item instanceof DOMText) {
$item = $element->childNodes->item(1);
}
$value = self::xmlToVariable($item);
if ($element->hasAttribute('key')) {
$variable[(string) $element->getAttribute('key')] = $value;
} else {
$variable[] = $value;
}
}
break;
case 'object':
$className = $element->getAttribute('class');
if ($element->hasChildNodes()) {
$arguments = $element->childNodes->item(1)->childNodes;
$constructorArgs = [];
foreach ($arguments as $argument) {
if ($argument instanceof DOMElement) {
$constructorArgs[] = self::xmlToVariable($argument);
}
}
$class = new ReflectionClass($className);
$variable = $class->newInstanceArgs($constructorArgs);
} else {
$variable = new $className;
}
break;
case 'boolean':
$variable = $element->textContent == 'true' ? true : false;
break;
case 'integer':
case 'double':
case 'string':
$variable = $element->textContent;
settype($variable, $element->tagName);
break;
}
return $variable;
}
}
<?php
namespace Webmozart\Assert;
use BadMethodCallException;
use InvalidArgumentException;
use Traversable;
class Assert
{
public static function string($value, $message = '')
{
if (!is_string($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a string. Got: %s',
self::typeToString($value)
));
}
}
public static function stringNotEmpty($value, $message = '')
{
self::string($value, $message);
self::notEmpty($value, $message);
}
public static function integer($value, $message = '')
{
if (!is_int($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an integer. Got: %s',
self::typeToString($value)
));
}
}
public static function integerish($value, $message = '')
{
if (!is_numeric($value) || $value != (int) $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an integerish value. Got: %s',
self::typeToString($value)
));
}
}
public static function float($value, $message = '')
{
if (!is_float($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a float. Got: %s',
self::typeToString($value)
));
}
}
public static function numeric($value, $message = '')
{
if (!is_numeric($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a numeric. Got: %s',
self::typeToString($value)
));
}
}
public static function boolean($value, $message = '')
{
if (!is_bool($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a boolean. Got: %s',
self::typeToString($value)
));
}
}
public static function scalar($value, $message = '')
{
if (!is_scalar($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a scalar. Got: %s',
self::typeToString($value)
));
}
}
public static function object($value, $message = '')
{
if (!is_object($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an object. Got: %s',
self::typeToString($value)
));
}
}
public static function resource($value, $type = null, $message = '')
{
if (!is_resource($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a resource. Got: %s',
self::typeToString($value)
));
}
if ($type && $type !== get_resource_type($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a resource of type %2$s. Got: %s',
self::typeToString($value),
$type
));
}
}
public static function isCallable($value, $message = '')
{
if (!is_callable($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a callable. Got: %s',
self::typeToString($value)
));
}
}
public static function isArray($value, $message = '')
{
if (!is_array($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an array. Got: %s',
self::typeToString($value)
));
}
}
public static function isTraversable($value, $message = '')
{
if (!is_array($value) && !($value instanceof Traversable)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a traversable. Got: %s',
self::typeToString($value)
));
}
}
public static function isInstanceOf($value, $class, $message = '')
{
if (!($value instanceof $class)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an instance of %2$s. Got: %s',
self::typeToString($value),
$class
));
}
}
public static function notInstanceOf($value, $class, $message = '')
{
if ($value instanceof $class) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an instance other than %2$s. Got: %s',
self::typeToString($value),
$class
));
}
}
public static function isEmpty($value, $message = '')
{
if (!empty($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an empty value. Got: %s',
self::valueToString($value)
));
}
}
public static function notEmpty($value, $message = '')
{
if (empty($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a non-empty value. Got: %s',
self::valueToString($value)
));
}
}
public static function null($value, $message = '')
{
if (null !== $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected null. Got: %s',
self::valueToString($value)
));
}
}
public static function notNull($value, $message = '')
{
if (null === $value) {
throw new InvalidArgumentException(
$message ?: 'Expected a value other than null.'
);
}
}
public static function true($value, $message = '')
{
if (true !== $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to be true. Got: %s',
self::valueToString($value)
));
}
}
public static function false($value, $message = '')
{
if (false !== $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to be false. Got: %s',
self::valueToString($value)
));
}
}
public static function eq($value, $value2, $message = '')
{
if ($value2 != $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value equal to %2$s. Got: %s',
self::valueToString($value),
self::valueToString($value2)
));
}
}
public static function notEq($value, $value2, $message = '')
{
if ($value2 == $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a different value than %s.',
self::valueToString($value2)
));
}
}
public static function same($value, $value2, $message = '')
{
if ($value2 !== $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value identical to %2$s. Got: %s',
self::valueToString($value),
self::valueToString($value2)
));
}
}
public static function notSame($value, $value2, $message = '')
{
if ($value2 === $value) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value not identical to %s.',
self::valueToString($value2)
));
}
}
public static function greaterThan($value, $limit, $message = '')
{
if ($value <= $limit) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value greater than %2$s. Got: %s',
self::valueToString($value),
self::valueToString($limit)
));
}
}
public static function greaterThanEq($value, $limit, $message = '')
{
if ($value < $limit) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value greater than or equal to %2$s. Got: %s',
self::valueToString($value),
self::valueToString($limit)
));
}
}
public static function lessThan($value, $limit, $message = '')
{
if ($value >= $limit) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value less than %2$s. Got: %s',
self::valueToString($value),
self::valueToString($limit)
));
}
}
public static function lessThanEq($value, $limit, $message = '')
{
if ($value > $limit) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value less than or equal to %2$s. Got: %s',
self::valueToString($value),
self::valueToString($limit)
));
}
}
public static function range($value, $min, $max, $message = '')
{
if ($value < $min || $value > $max) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value between %2$s and %3$s. Got: %s',
self::valueToString($value),
self::valueToString($min),
self::valueToString($max)
));
}
}
public static function oneOf($value, array $values, $message = '')
{
if (!in_array($value, $values, true)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected one of: %2$s. Got: %s',
self::valueToString($value),
implode(', ', array_map(array(__CLASS__, 'valueToString'), $values))
));
}
}
public static function contains($value, $subString, $message = '')
{
if (false === strpos($value, $subString)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain %2$s. Got: %s',
self::valueToString($value),
self::valueToString($subString)
));
}
}
public static function startsWith($value, $prefix, $message = '')
{
if (0 !== strpos($value, $prefix)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to start with %2$s. Got: %s',
self::valueToString($value),
self::valueToString($prefix)
));
}
}
public static function startsWithLetter($value, $message = '')
{
$valid = isset($value[0]);
if ($valid) {
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
$valid = ctype_alpha($value[0]);
setlocale(LC_CTYPE, $locale);
}
if (!$valid) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to start with a letter. Got: %s',
self::valueToString($value)
));
}
}
public static function endsWith($value, $suffix, $message = '')
{
if ($suffix !== substr($value, -self::strlen($suffix))) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to end with %2$s. Got: %s',
self::valueToString($value),
self::valueToString($suffix)
));
}
}
public static function regex($value, $pattern, $message = '')
{
if (!preg_match($pattern, $value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'The value %s does not match the expected pattern.',
self::valueToString($value)
));
}
}
public static function alpha($value, $message = '')
{
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
$valid = !ctype_alpha($value);
setlocale(LC_CTYPE, $locale);
if ($valid) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain only letters. Got: %s',
self::valueToString($value)
));
}
}
public static function digits($value, $message = '')
{
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
$valid = !ctype_digit($value);
setlocale(LC_CTYPE, $locale);
if ($valid) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain digits only. Got: %s',
self::valueToString($value)
));
}
}
public static function alnum($value, $message = '')
{
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
$valid = !ctype_alnum($value);
setlocale(LC_CTYPE, $locale);
if ($valid) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain letters and digits only. Got: %s',
self::valueToString($value)
));
}
}
public static function lower($value, $message = '')
{
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
$valid = !ctype_lower($value);
setlocale(LC_CTYPE, $locale);
if ($valid) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain lowercase characters only. Got: %s',
self::valueToString($value)
));
}
}
public static function upper($value, $message = '')
{
$locale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'C');
$valid = !ctype_upper($value);
setlocale(LC_CTYPE, $locale);
if ($valid) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain uppercase characters only. Got: %s',
self::valueToString($value)
));
}
}
public static function length($value, $length, $message = '')
{
if ($length !== self::strlen($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain %2$s characters. Got: %s',
self::valueToString($value),
$length
));
}
}
public static function minLength($value, $min, $message = '')
{
if (self::strlen($value) < $min) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain at least %2$s characters. Got: %s',
self::valueToString($value),
$min
));
}
}
public static function maxLength($value, $max, $message = '')
{
if (self::strlen($value) > $max) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain at most %2$s characters. Got: %s',
self::valueToString($value),
$max
));
}
}
public static function lengthBetween($value, $min, $max, $message = '')
{
$length = self::strlen($value);
if ($length < $min || $length > $max) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a value to contain between %2$s and %3$s characters. Got: %s',
self::valueToString($value),
$min,
$max
));
}
}
public static function fileExists($value, $message = '')
{
self::string($value);
if (!file_exists($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'The file %s does not exist.',
self::valueToString($value)
));
}
}
public static function file($value, $message = '')
{
self::fileExists($value, $message);
if (!is_file($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'The path %s is not a file.',
self::valueToString($value)
));
}
}
public static function directory($value, $message = '')
{
self::fileExists($value, $message);
if (!is_dir($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'The path %s is no directory.',
self::valueToString($value)
));
}
}
public static function readable($value, $message = '')
{
if (!is_readable($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'The path %s is not readable.',
self::valueToString($value)
));
}
}
public static function writable($value, $message = '')
{
if (!is_writable($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'The path %s is not writable.',
self::valueToString($value)
));
}
}
public static function classExists($value, $message = '')
{
if (!class_exists($value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an existing class name. Got: %s',
self::valueToString($value)
));
}
}
public static function subclassOf($value, $class, $message = '')
{
if (!is_subclass_of($value, $class)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected a sub-class of %2$s. Got: %s',
self::valueToString($value),
self::valueToString($class)
));
}
}
public static function implementsInterface($value, $interface, $message = '')
{
if (!in_array($interface, class_implements($value))) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected an implementation of %2$s. Got: %s',
self::valueToString($value),
self::valueToString($interface)
));
}
}
public static function propertyExists($classOrObject, $property, $message = '')
{
if (!property_exists($classOrObject, $property)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected the property %s to exist.',
self::valueToString($property)
));
}
}
public static function propertyNotExists($classOrObject, $property, $message = '')
{
if (property_exists($classOrObject, $property)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected the property %s to not exist.',
self::valueToString($property)
));
}
}
public static function methodExists($classOrObject, $method, $message = '')
{
if (!method_exists($classOrObject, $method)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected the method %s to exist.',
self::valueToString($method)
));
}
}
public static function methodNotExists($classOrObject, $method, $message = '')
{
if (method_exists($classOrObject, $method)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected the method %s to not exist.',
self::valueToString($method)
));
}
}
public static function keyExists($array, $key, $message = '')
{
if (!array_key_exists($key, $array)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected the key %s to exist.',
self::valueToString($key)
));
}
}
public static function keyNotExists($array, $key, $message = '')
{
if (array_key_exists($key, $array)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Expected the key %s to not exist.',
self::valueToString($key)
));
}
}
public static function uuid($value, $message = '')
{
$value = str_replace(array('urn:', 'uuid:', '{', '}'), '', $value);
if ('00000000-0000-0000-0000-000000000000' === $value) {
return;
}
if (!preg_match('/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/', $value)) {
throw new InvalidArgumentException(sprintf(
$message ?: 'Value "%s" is not a valid UUID.',
self::valueToString($value)
));
}
}
public static function __callStatic($name, $arguments)
{
if ('nullOr' === substr($name, 0, 6)) {
if (null !== $arguments[0]) {
$method = lcfirst(substr($name, 6));
call_user_func_array(array('static', $method), $arguments);
}
return;
}
if ('all' === substr($name, 0, 3)) {
self::isTraversable($arguments[0]);
$method = lcfirst(substr($name, 3));
$args = $arguments;
foreach ($arguments[0] as $entry) {
$args[0] = $entry;
call_user_func_array(array('static', $method), $args);
}
return;
}
throw new BadMethodCallException('No such method: '.$name);
}
protected static function valueToString($value)
{
if (null === $value) {
return 'null';
}
if (true === $value) {
return 'true';
}
if (false === $value) {
return 'false';
}
if (is_array($value)) {
return 'array';
}
if (is_object($value)) {
return get_class($value);
}
if (is_resource($value)) {
return 'resource';
}
if (is_string($value)) {
return '"'.$value.'"';
}
return (string) $value;
}
protected static function typeToString($value)
{
return is_object($value) ? get_class($value) : gettype($value);
}
protected static function strlen($value)
{
if (!function_exists('mb_detect_encoding')) {
return strlen($value);
}
if (false === $encoding = mb_detect_encoding($value)) {
return strlen($value);
}
return mb_strwidth($value, $encoding);
}
private function __construct()
{
}
}
<?php
namespace phpDocumentor\Reflection;
interface Element
{
public function getFqsen();
public function getName();
}<?php
namespace phpDocumentor\Reflection;
interface File
{
public function getContents();
public function md5();
public function path();
}
<?php
namespace phpDocumentor\Reflection;
final class Fqsen
{
private $fqsen;
private $name;
public function __construct($fqsen)
{
$matches = array();
$result = preg_match('/^\\\\([\\w_\\\\]*)(?:[:]{2}\\$?([\\w_]+))?(?:\\(\\))?$/', $fqsen, $matches);
if ($result === 0) {
throw new \InvalidArgumentException(
sprintf('"%s" is not a valid Fqsen.', $fqsen)
);
}
$this->fqsen = $fqsen;
if (isset($matches[2])) {
$this->name = $matches[2];
} else {
$matches = explode('\\', $fqsen);
$this->name = trim(end($matches), '()');
}
}
public function __toString()
{
return $this->fqsen;
}
public function getName()
{
return $this->name;
}
}
<?php
namespace phpDocumentor\Reflection;
final class Location
{
private $lineNumber = 0;
private $columnNumber = 0;
public function __construct($lineNumber, $columnNumber = 0)
{
$this->lineNumber = $lineNumber;
$this->columnNumber = $columnNumber;
}
public function getLineNumber()
{
return $this->lineNumber;
}
public function getColumnNumber()
{
return $this->columnNumber;
}
}
<?php
namespace phpDocumentor\Reflection;
interface Project
{
public function getName();
}
<?php
namespace phpDocumentor\Reflection;
interface ProjectFactory
{
public function create($name, array $files);
}
<?php
use phpDocumentor\Reflection\TypeResolver;
require '../vendor/autoload.php';
$typeResolver = new TypeResolver();
var_export($typeResolver->resolve('string|integer'));
var_dump((string)$typeResolver->resolve('string|integer'));
<?php
use phpDocumentor\Reflection\Types\Context;
use phpDocumentor\Reflection\TypeResolver;
require '../vendor/autoload.php';
$typeResolver = new TypeResolver();
$context = new Context('\phpDocumentor', [ 'm' => 'Mockery' ]);
var_dump((string)$typeResolver->resolve('Types\Resolver|m\MockInterface', $context));
<?php
use phpDocumentor\Reflection\Types\Context;
use phpDocumentor\Reflection\FqsenResolver;
require '../vendor/autoload.php';
$fqsenResolver = new FqsenResolver();
$context = new Context('\phpDocumentor\Types');
var_dump((string)$fqsenResolver->resolve('Types\Resolver::resolveFqsen()', $context));
var_dump((string)$fqsenResolver->resolve('Types\Resolver::$keyWords', $context));
<?php
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\ContextFactory;
require '../vendor/autoload.php';
require 'Classy.php';
$typeResolver = new TypeResolver();
$fqsenResolver = new FqsenResolver();
$contextFactory = new ContextFactory();
$context = $contextFactory->createFromReflector(new ReflectionClass('My\\Example\\Classy'));
var_dump((string)$typeResolver->resolve('Types\Resolver', $context));
var_dump((string)$typeResolver->resolve('string', $context));
var_dump((string)$fqsenResolver->resolve('Types\Resolver::$keyWords', $context));
var_dump((string)$fqsenResolver->resolve('string', $context));
<?php
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\ContextFactory;
require '../vendor/autoload.php';
require 'Classy.php';
$typeResolver = new TypeResolver();
$fqsenResolver = new FqsenResolver();
$contextFactory = new ContextFactory();
$context = $contextFactory->createFromReflector(new ReflectionMethod('My\\Example\\Classy', '__construct'));
var_dump((string)$typeResolver->resolve('Types\Resolver', $context));
var_dump((string)$typeResolver->resolve('string', $context));
var_dump((string)$fqsenResolver->resolve('Types\Resolver::$keyWords', $context));
var_dump((string)$fqsenResolver->resolve('string', $context));
<?php
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\ContextFactory;
require '../vendor/autoload.php';
$typeResolver = new TypeResolver();
$fqsenResolver = new FqsenResolver();
$contextFactory = new ContextFactory();
$context = $contextFactory->createForNamespace('My\Example', file_get_contents('Classy.php'));
var_dump((string)$typeResolver->resolve('Types\Resolver', $context));
var_dump((string)$typeResolver->resolve('string', $context));
var_dump((string)$fqsenResolver->resolve('Types\Resolver::$keyWords', $context));
<?php
namespace My\Example;
use Mockery as m;
use phpDocumentor\Reflection\Types;
class Classy
{
public function __construct($context)
{
}
}
<?php
namespace phpDocumentor\Reflection;
use phpDocumentor\Reflection\Types\Context;
class FqsenResolver
{
const OPERATOR_NAMESPACE = '\\';
public function resolve($fqsen, Context $context = null)
{
if ($context === null) {
$context = new Context('');
}
if ($this->isFqsen($fqsen)) {
return new Fqsen($fqsen);
}
return $this->resolvePartialStructuralElementName($fqsen, $context);
}
private function isFqsen($type)
{
return strpos($type, self::OPERATOR_NAMESPACE) === 0;
}
private function resolvePartialStructuralElementName($type, Context $context)
{
$typeParts = explode(self::OPERATOR_NAMESPACE, $type, 2);
$namespaceAliases = $context->getNamespaceAliases();
if (!isset($namespaceAliases[$typeParts[0]])) {
$namespace = $context->getNamespace();
if ('' !== $namespace) {
$namespace .= self::OPERATOR_NAMESPACE;
}
return new Fqsen(self::OPERATOR_NAMESPACE . $namespace . $type);
}
$typeParts[0] = $namespaceAliases[$typeParts[0]];
return new Fqsen(self::OPERATOR_NAMESPACE . implode(self::OPERATOR_NAMESPACE, $typeParts));
}
}
<?php
namespace phpDocumentor\Reflection;
interface Type
{
public function __toString();
}
<?php
namespace phpDocumentor\Reflection;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\Compound;
use phpDocumentor\Reflection\Types\Context;
use phpDocumentor\Reflection\Types\Object_;
final class TypeResolver
{
const OPERATOR_ARRAY = '[]';
const OPERATOR_NAMESPACE = '\\';
private $keywords = array(
'string' => 'phpDocumentor\Reflection\Types\String_',
'int' => 'phpDocumentor\Reflection\Types\Integer',
'integer' => 'phpDocumentor\Reflection\Types\Integer',
'bool' => 'phpDocumentor\Reflection\Types\Boolean',
'boolean' => 'phpDocumentor\Reflection\Types\Boolean',
'float' => 'phpDocumentor\Reflection\Types\Float_',
'double' => 'phpDocumentor\Reflection\Types\Float_',
'object' => 'phpDocumentor\Reflection\Types\Object_',
'mixed' => 'phpDocumentor\Reflection\Types\Mixed',
'array' => 'phpDocumentor\Reflection\Types\Array_',
'resource' => 'phpDocumentor\Reflection\Types\Resource',
'void' => 'phpDocumentor\Reflection\Types\Void_',
'null' => 'phpDocumentor\Reflection\Types\Null_',
'scalar' => 'phpDocumentor\Reflection\Types\Scalar',
'callback' => 'phpDocumentor\Reflection\Types\Callable_',
'callable' => 'phpDocumentor\Reflection\Types\Callable_',
'false' => 'phpDocumentor\Reflection\Types\Boolean',
'true' => 'phpDocumentor\Reflection\Types\Boolean',
'self' => 'phpDocumentor\Reflection\Types\Self_',
'$this' => 'phpDocumentor\Reflection\Types\This',
'static' => 'phpDocumentor\Reflection\Types\Static_'
);
private $fqsenResolver;
public function __construct(FqsenResolver $fqsenResolver = null)
{
$this->fqsenResolver = $fqsenResolver ?: new FqsenResolver();
}
public function resolve($type, Context $context = null)
{
if (!is_string($type)) {
throw new \InvalidArgumentException(
'Attempted to resolve type but it appeared not to be a string, received: ' . var_export($type, true)
);
}
$type = trim($type);
if (!$type) {
throw new \InvalidArgumentException('Attempted to resolve "' . $type . '" but it appears to be empty');
}
if ($context === null) {
$context = new Context('');
}
switch (true) {
case $this->isKeyword($type):
return $this->resolveKeyword($type);
case ($this->isCompoundType($type)):
return $this->resolveCompoundType($type, $context);
case $this->isTypedArray($type):
return $this->resolveTypedArray($type, $context);
case $this->isFqsen($type):
return $this->resolveTypedObject($type);
case $this->isPartialStructuralElementName($type):
return $this->resolveTypedObject($type, $context);
default:
throw new \RuntimeException(
'Unable to resolve type "' . $type . '", there is no known method to resolve it'
);
}
}
public function addKeyword($keyword, $typeClassName)
{
if (!class_exists($typeClassName)) {
throw new \InvalidArgumentException(
'The Value Object that needs to be created with a keyword "' . $keyword . '" must be an existing class'
. ' but we could not find the class ' . $typeClassName
);
}
if (!in_array(Type::class, class_implements($typeClassName))) {
throw new \InvalidArgumentException(
'The class "' . $typeClassName . '" must implement the interface "phpDocumentor\Reflection\Type"'
);
}
$this->keywords[$keyword] = $typeClassName;
}
private function isTypedArray($type)
{
return substr($type, -2) === self::OPERATOR_ARRAY;
}
private function isKeyword($type)
{
return in_array(strtolower($type), array_keys($this->keywords), true);
}
private function isPartialStructuralElementName($type)
{
return ($type[0] !== self::OPERATOR_NAMESPACE) && !$this->isKeyword($type);
}
private function isFqsen($type)
{
return strpos($type, self::OPERATOR_NAMESPACE) === 0;
}
private function isCompoundType($type)
{
return strpos($type, '|') !== false;
}
private function resolveTypedArray($type, Context $context)
{
return new Array_($this->resolve(substr($type, 0, -2), $context));
}
private function resolveKeyword($type)
{
$className = $this->keywords[strtolower($type)];
return new $className();
}
private function resolveTypedObject($type, Context $context = null)
{
return new Object_($this->fqsenResolver->resolve($type, $context));
}
private function resolveCompoundType($type, Context $context)
{
$types = [];
foreach (explode('|', $type) as $part) {
$types[] = $this->resolve($part, $context);
}
return new Compound($types);
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\Type;
final class Array_ implements Type
{
private $valueType;
private $keyType;
public function __construct(Type $valueType = null, Type $keyType = null)
{
if ($keyType === null) {
$keyType = new Compound([ new String_(), new Integer() ]);
}
if ($valueType === null) {
$valueType = new Mixed();
}
$this->valueType = $valueType;
$this->keyType = $keyType;
}
public function getKeyType()
{
return $this->keyType;
}
public function getValueType()
{
return $this->valueType;
}
public function __toString()
{
if ($this->valueType instanceof Mixed) {
return 'array';
}
return $this->valueType . '[]';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Boolean implements Type
{
public function __toString()
{
return 'bool';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Callable_ implements Type
{
public function __toString()
{
return 'callable';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Compound implements Type
{
private $types = [];
public function __construct(array $types)
{
foreach ($types as $type) {
if (!$type instanceof Type) {
throw new \InvalidArgumentException('A compound type can only have other types as elements');
}
}
$this->types = $types;
}
public function get($index)
{
if (!$this->has($index)) {
return null;
}
return $this->types[$index];
}
public function has($index)
{
return isset($this->types[$index]);
}
public function __toString()
{
return implode('|', $this->types);
}
}
<?php
namespace phpDocumentor\Reflection\Types;
final class Context
{
private $namespace = '';
private $namespaceAliases = [];
public function __construct($namespace, array $namespaceAliases = [])
{
$this->namespace = ('global' !== $namespace && 'default' !== $namespace)
? trim((string)$namespace, '\\')
: '';
foreach ($namespaceAliases as $alias => $fqnn) {
if ($fqnn[0] === '\\') {
$fqnn = substr($fqnn, 1);
}
if ($fqnn[count($fqnn)-1] === '\\') {
$fqnn = substr($fqnn, 0, -1);
}
$namespaceAliases[$alias] = $fqnn;
}
$this->namespaceAliases = $namespaceAliases;
}
public function getNamespace()
{
return $this->namespace;
}
public function getNamespaceAliases()
{
return $this->namespaceAliases;
}
}
<?php
namespace phpDocumentor\Reflection\Types;
final class ContextFactory
{
const T_LITERAL_END_OF_USE = ';';
const T_LITERAL_USE_SEPARATOR = ',';
public function createFromReflector(\Reflector $reflector)
{
if (method_exists($reflector, 'getDeclaringClass')) {
$reflector = $reflector->getDeclaringClass();
}
$fileName = $reflector->getFileName();
$namespace = $reflector->getNamespaceName();
if (file_exists($fileName)) {
return $this->createForNamespace($namespace, file_get_contents($fileName));
}
return new Context($namespace, []);
}
public function createForNamespace($namespace, $fileContents)
{
$namespace = trim($namespace, '\\');
$useStatements = [];
$currentNamespace = '';
$tokens = new \ArrayIterator(token_get_all($fileContents));
while ($tokens->valid()) {
switch ($tokens->current()[0]) {
case T_NAMESPACE:
$currentNamespace = $this->parseNamespace($tokens);
break;
case T_CLASS:
$braceLevel = 0;
$firstBraceFound = false;
while ($tokens->valid() && ($braceLevel > 0 || !$firstBraceFound)) {
if ($tokens->current() === '{'
|| $tokens->current()[0] === T_CURLY_OPEN
|| $tokens->current()[0] === T_DOLLAR_OPEN_CURLY_BRACES) {
if (!$firstBraceFound) {
$firstBraceFound = true;
}
$braceLevel++;
}
if ($tokens->current() === '}') {
$braceLevel--;
}
$tokens->next();
}
break;
case T_USE:
if ($currentNamespace === $namespace) {
$useStatements = array_merge($useStatements, $this->parseUseStatement($tokens));
}
break;
}
$tokens->next();
}
return new Context($namespace, $useStatements);
}
private function parseNamespace(\ArrayIterator $tokens)
{
$this->skipToNextStringOrNamespaceSeparator($tokens);
$name = '';
while ($tokens->valid() && ($tokens->current()[0] === T_STRING || $tokens->current()[0] === T_NS_SEPARATOR)
) {
$name .= $tokens->current()[1];
$tokens->next();
}
return $name;
}
private function parseUseStatement(\ArrayIterator $tokens)
{
$uses = [];
$continue = true;
while ($continue) {
$this->skipToNextStringOrNamespaceSeparator($tokens);
list($alias, $fqnn) = $this->extractUseStatement($tokens);
$uses[$alias] = $fqnn;
if ($tokens->current()[0] === self::T_LITERAL_END_OF_USE) {
$continue = false;
}
}
return $uses;
}
private function skipToNextStringOrNamespaceSeparator(\ArrayIterator $tokens)
{
while ($tokens->valid() && ($tokens->current()[0] !== T_STRING) && ($tokens->current()[0] !== T_NS_SEPARATOR)) {
$tokens->next();
}
}
private function extractUseStatement(\ArrayIterator $tokens)
{
$result = [''];
while ($tokens->valid()
&& ($tokens->current()[0] !== self::T_LITERAL_USE_SEPARATOR)
&& ($tokens->current()[0] !== self::T_LITERAL_END_OF_USE)
) {
if ($tokens->current()[0] === T_AS) {
$result[] = '';
}
if ($tokens->current()[0] === T_STRING || $tokens->current()[0] === T_NS_SEPARATOR) {
$result[count($result) - 1] .= $tokens->current()[1];
}
$tokens->next();
}
if (count($result) == 1) {
$backslashPos = strrpos($result[0], '\\');
if (false !== $backslashPos) {
$result[] = substr($result[0], $backslashPos + 1);
} else {
$result[] = $result[0];
}
}
return array_reverse($result);
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Float_ implements Type
{
public function __toString()
{
return 'float';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Integer implements Type
{
public function __toString()
{
return 'int';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Mixed implements Type
{
public function __toString()
{
return 'mixed';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Null_ implements Type
{
public function __toString()
{
return 'null';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\Type;
final class Object_ implements Type
{
private $fqsen;
public function __construct(Fqsen $fqsen = null)
{
if (strpos((string)$fqsen, '::') !== false || strpos((string)$fqsen, '()') !== false) {
throw new \InvalidArgumentException(
'Object types can only refer to a class, interface or trait but a method, function, constant or '
. 'property was received: ' . (string)$fqsen
);
}
$this->fqsen = $fqsen;
}
public function getFqsen()
{
return $this->fqsen;
}
public function __toString()
{
if ($this->fqsen) {
return (string)$this->fqsen;
}
return 'object';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Resource implements Type
{
public function __toString()
{
return 'resource';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Scalar implements Type
{
public function __toString()
{
return 'scalar';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Self_ implements Type
{
public function __toString()
{
return 'self';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Static_ implements Type
{
public function __toString()
{
return 'static';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class String_ implements Type
{
public function __toString()
{
return 'string';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class This implements Type
{
public function __toString()
{
return '$this';
}
}
<?php
namespace phpDocumentor\Reflection\Types;
use phpDocumentor\Reflection\Type;
final class Void_ implements Type
{
public function __toString()
{
return 'void';
}
}
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
use phpDocumentor\Reflection\DocBlockFactory;
$docComment = <<<DOCCOMMENT
/**
* This is an example of a summary.
*
* This is a Description. A Summary and Description are separated by either
* two subsequent newlines (thus a whiteline in between as can be seen in this
* example), or when the Summary ends with a dot (`.`) and some form of
* whitespace.
*/
DOCCOMMENT;
$factory = DocBlockFactory::createInstance();
$docblock = $factory->create($docComment);
$summary = $docblock->getSummary();
$description = $docblock->getDescription();
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
use phpDocumentor\Reflection\DocBlockFactory;
$docComment = <<<DOCCOMMENT
/**
* This is an example of a summary.
*
* @see \phpDocumentor\Reflection\DocBlock\StandardTagFactory
*/
DOCCOMMENT;
$factory = DocBlockFactory::createInstance();
$docblock = $factory->create($docComment);
$hasSeeTag = $docblock->hasTag('see');
$tags = $docblock->getTags();
$seeTags = $docblock->getTagsByName('see');
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
use phpDocumentor\Reflection\DocBlock\Serializer;
use phpDocumentor\Reflection\DocBlockFactory;
$docComment = <<<DOCCOMMENT
/**
* This is an example of a summary.
*
* And here is an example of the description
* of a DocBlock that can span multiple lines.
*
* @see \phpDocumentor\Reflection\DocBlock\StandardTagFactory
*/
DOCCOMMENT;
$factory = DocBlockFactory::createInstance();
$docblock = $factory->create($docComment);
$serializer = new Serializer();
$reconstitutedDocComment = $serializer->getDocComment($docblock);
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
use phpDocumentor\Reflection\DocBlock\Serializer;
use phpDocumentor\Reflection\DocBlock\Tags\Factory\StaticMethod;
use phpDocumentor\Reflection\DocBlockFactory;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\DocBlock\Tags\BaseTag;
use phpDocumentor\Reflection\Types\Context;
use Webmozart\Assert\Assert;
final class MyTag extends BaseTag implements StaticMethod
{
protected $name = 'my-tag';
public function __construct(Description $description = null)
{
$this->description = $description;
}
public static function create($body, DescriptionFactory $descriptionFactory = null, Context $context = null)
{
Assert::string($body);
Assert::notNull($descriptionFactory);
return new static($descriptionFactory->create($body, $context));
}
public function __toString()
{
return (string)$this->description;
}
}
$docComment = <<<DOCCOMMENT
/**
* This is an example of a summary.
*
* @my-tag I have a description
*/
DOCCOMMENT;
$customTags = ['my-tag' => MyTag::class];
$factory = DocBlockFactory::createInstance($customTags);
$docblock = $factory->create($docComment);
$customTagObjects = $docblock->getTagsByName('my-tag');
$serializer = new Serializer();
$reconstitutedDocComment = $serializer->getDocComment($docblock);
<?php
require_once(__DIR__ . '/../../vendor/autoload.php');
use phpDocumentor\Reflection\DocBlockFactory;
$docComment = <<<DOCCOMMENT
/**
* This is an example of a summary.
*
* You can escape the @-sign by surrounding it with braces, for example: {@}. And escape a closing brace within an
* inline tag by adding an opening brace in front of it like this: {}.
*
* Here are example texts where you can see how they could be used in a real life situation:
*
* This is a text with an {@internal inline tag where a closing brace ({}) is shown}.
* Or an {@internal inline tag with a literal {{@}link{} in it}.
*
* Do note that an {@internal inline tag that has an opening brace ({) does not break out}.
*/
DOCCOMMENT;
$factory = DocBlockFactory::createInstance();
$docblock = $factory->create($docComment);
$description = $docblock->getDescription();
$receivedDocComment = <<<DOCCOMMENT
/**
* This is an example of a summary.
*
* You can escape the @-sign by surrounding it with braces, for example: {@}. And escape a closing brace within an
* inline tag by adding an opening brace in front of it like this: {}.
*
* Here are example texts where you can see how they could be used in a real life situation:
*
* This is a text with an {@internal inline tag where a closing brace ({}) is shown}.
* Or an {@internal inline tag with a literal {{@}link{} in it}.
*
* Do note that an {@internal inline tag that has an opening brace ({) does not break out}.
*/
DOCCOMMENT;
$foundDescription = $description->render();
<?php
namespace phpDocumentor\Reflection;
use phpDocumentor\Reflection\DocBlock\Tag;
use Webmozart\Assert\Assert;
final class DocBlock
{
private $summary = '';
private $description = null;
private $tags = array();
private $context = null;
private $location = null;
private $isTemplateStart = false;
private $isTemplateEnd = false;
public function __construct(
$summary = '',
DocBlock\Description $description = null,
array $tags = [],
Types\Context $context = null,
Location $location = null,
$isTemplateStart = false,
$isTemplateEnd = false
)
{
Assert::string($summary);
Assert::boolean($isTemplateStart);
Assert::boolean($isTemplateEnd);
Assert::allIsInstanceOf($tags, Tag::class);
$this->summary = $summary;
$this->description = $description ?: new DocBlock\Description('');
foreach ($tags as $tag) {
$this->addTag($tag);
}
$this->context = $context;
$this->location = $location;
$this->isTemplateEnd = $isTemplateEnd;
$this->isTemplateStart = $isTemplateStart;
}
public function getSummary()
{
return $this->summary;
}
public function getDescription()
{
return $this->description;
}
public function getContext()
{
return $this->context;
}
public function getLocation()
{
return $this->location;
}
public function isTemplateStart()
{
return $this->isTemplateStart;
}
public function isTemplateEnd()
{
return $this->isTemplateEnd;
}
public function getTags()
{
return $this->tags;
}
public function getTagsByName($name)
{
Assert::string($name);
$result = array();
foreach ($this->getTags() as $tag) {
if ($tag->getName() != $name) {
continue;
}
$result[] = $tag;
}
return $result;
}
public function hasTag($name)
{
Assert::string($name);
foreach ($this->getTags() as $tag) {
if ($tag->getName() == $name) {
return true;
}
}
return false;
}
private function addTag(Tag $tag)
{
$this->tags[] = $tag;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tags\Formatter;
use phpDocumentor\Reflection\DocBlock\Tags\Formatter\PassthroughFormatter;
use Webmozart\Assert\Assert;
class Description
{
private $bodyTemplate;
private $tags;
public function __construct($bodyTemplate, array $tags = [])
{
Assert::string($bodyTemplate);
$this->bodyTemplate = $bodyTemplate;
$this->tags = $tags;
}
public function render(Formatter $formatter = null)
{
if ($formatter === null) {
$formatter = new PassthroughFormatter();
}
$tags = [];
foreach ($this->tags as $tag) {
$tags[] = '{' . $formatter->format($tag) . '}';
}
return vsprintf($this->bodyTemplate, $tags);
}
public function __toString()
{
return $this->render();
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\Types\Context as TypeContext;
class DescriptionFactory
{
private $tagFactory;
public function __construct(TagFactory $tagFactory)
{
$this->tagFactory = $tagFactory;
}
public function create($contents, TypeContext $context = null)
{
list($text, $tags) = $this->parse($this->lex($contents), $context);
return new Description($text, $tags);
}
private function lex($contents)
{
$contents = $this->removeSuperfluousStartingWhitespace($contents);
if (strpos($contents, '{@') === false) {
return [$contents];
}
return preg_split(
'/\{
# "{@}" is not a valid inline tag. This ensures that we do not treat it as one, but treat it literally.
(?!@\})
# We want to capture the whole tag line, but without the inline tag delimiters.
(\@
# Match everything up to the next delimiter.
[^{}]*
# Nested inline tag content should not be captured, or it will appear in the result separately.
(?:
# Match nested inline tags.
(?:
# Because we did not catch the tag delimiters earlier, we must be explicit with them here.
# Notice that this also matches "{}", as a way to later introduce it as an escape sequence.
\{(?1)?\}
|
# Make sure we match hanging "{".
\{
)
# Match content after the nested inline tag.
[^{}]*
)* # If there are more inline tags, match them as well. We use "*" since there may not be any
# nested inline tags.
)
\}/Sux',
$contents,
null,
PREG_SPLIT_DELIM_CAPTURE
);
}
private function parse($tokens, TypeContext $context)
{
$count = count($tokens);
$tagCount = 0;
$tags = [];
for ($i = 1; $i < $count; $i += 2) {
$tags[] = $this->tagFactory->create($tokens[$i], $context);
$tokens[$i] = '%' . ++$tagCount . '$s';
}
for ($i = 0; $i < $count; $i += 2) {
$tokens[$i] = str_replace(['{@}', '{}'], ['@', '}'], $tokens[$i]);
}
return [implode('', $tokens), $tags];
}
private function removeSuperfluousStartingWhitespace($contents)
{
$lines = explode("\n", $contents);
if (count($lines) <= 1) {
return $contents;
}
$startingSpaceCount = 9999999;
for ($i = 1; $i < count($lines); $i++) {
if (strlen(trim($lines[$i])) === 0) {
continue;
}
$startingSpaceCount = min($startingSpaceCount, strlen($lines[$i]) - strlen(ltrim($lines[$i])));
}
if ($startingSpaceCount > 0) {
for ($i = 1; $i < count($lines); $i++) {
$lines[$i] = substr($lines[$i], $startingSpaceCount);
}
}
return implode("\n", $lines);
}
}
<?php
namespace phpDocumentor\Reflection;
use phpDocumentor\Reflection\DocBlock\Tags\Example;
class ExampleFinder
{
private $sourceDirectory = '';
private $exampleDirectories = array();
public function find(Example $example)
{
$filename = $example->getFilePath();
$file = $this->getExampleFileContents($filename);
if (!$file) {
return "** File not found : {$filename} **";
}
return implode('', array_slice($file, $example->getStartingLine() - 1, $example->getLineCount()));
}
public function setSourceDirectory($directory = '')
{
$this->sourceDirectory = $directory;
}
public function getSourceDirectory()
{
return $this->sourceDirectory;
}
public function setExampleDirectories(array $directories)
{
$this->exampleDirectories = $directories;
}
public function getExampleDirectories()
{
return $this->exampleDirectories;
}
private function getExampleFileContents($filename)
{
$normalizedPath = null;
foreach ($this->exampleDirectories as $directory) {
$exampleFileFromConfig = $this->constructExamplePath($directory, $filename);
if (is_readable($exampleFileFromConfig)) {
$normalizedPath = $exampleFileFromConfig;
break;
}
}
if (!$normalizedPath) {
if (is_readable($this->getExamplePathFromSource($filename))) {
$normalizedPath = $this->getExamplePathFromSource($filename);
} elseif (is_readable($this->getExamplePathFromExampleDirectory($filename))) {
$normalizedPath = $this->getExamplePathFromExampleDirectory($filename);
} elseif (is_readable($filename)) {
$normalizedPath = $filename;
}
}
return $normalizedPath && is_readable($normalizedPath) ? file($normalizedPath) : null;
}
private function getExamplePathFromExampleDirectory($file)
{
return getcwd() . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . $file;
}
private function constructExamplePath($directory, $file)
{
return rtrim($directory, '\\/') . DIRECTORY_SEPARATOR . $file;
}
private function getExamplePathFromSource($file)
{
return sprintf(
'%s%s%s',
trim($this->getSourceDirectory(), '\\/'),
DIRECTORY_SEPARATOR,
trim($file, '"')
);
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock;
use Webmozart\Assert\Assert;
class Serializer
{
protected $indentString = ' ';
protected $indent = 0;
protected $isFirstLineIndented = true;
protected $lineLength = null;
public function __construct($indent = 0, $indentString = ' ', $indentFirstLine = true, $lineLength = null)
{
Assert::integer($indent);
Assert::string($indentString);
Assert::boolean($indentFirstLine);
Assert::nullOrInteger($lineLength);
$this->indent = $indent;
$this->indentString = $indentString;
$this->isFirstLineIndented = $indentFirstLine;
$this->lineLength = $lineLength;
}
public function getDocComment(DocBlock $docblock)
{
$indent = str_repeat($this->indentString, $this->indent);
$firstIndent = $this->isFirstLineIndented ? $indent : '';
$wrapLength = $this->lineLength ? $this->lineLength - strlen($indent) - 3 : null;
$text = $this->removeTrailingSpaces(
$indent,
$this->addAsterisksForEachLine(
$indent,
$this->getSummaryAndDescriptionTextBlock($docblock, $wrapLength)
)
);
$comment = "{$firstIndent}/**\n{$indent} * {$text}\n{$indent} *\n";
$comment = $this->addTagBlock($docblock, $wrapLength, $indent, $comment);
$comment .= $indent . ' */';
return $comment;
}
private function removeTrailingSpaces($indent, $text)
{
return str_replace("\n{$indent} * \n", "\n{$indent} *\n", $text);
}
private function addAsterisksForEachLine($indent, $text)
{
return str_replace("\n", "\n{$indent} * ", $text);
}
private function getSummaryAndDescriptionTextBlock(DocBlock $docblock, $wrapLength)
{
$text = $docblock->getSummary() . ((string)$docblock->getDescription() ? "\n\n" . $docblock->getDescription()
: '');
if ($wrapLength !== null) {
$text = wordwrap($text, $wrapLength);
return $text;
}
return $text;
}
private function addTagBlock(DocBlock $docblock, $wrapLength, $indent, $comment)
{
foreach ($docblock->getTags() as $tag) {
$formatter = new DocBlock\Tags\Formatter\PassthroughFormatter();
$tagText = $formatter->format($tag);
if ($wrapLength !== null) {
$tagText = wordwrap($tagText, $wrapLength);
}
$tagText = str_replace("\n", "\n{$indent} * ", $tagText);
$comment .= "{$indent} * {$tagText}\n";
}
return $comment;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tags\Factory\StaticMethod;
use phpDocumentor\Reflection\DocBlock\Tags\Generic;
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class StandardTagFactory implements TagFactory
{
const REGEX_TAGNAME = '[\w\-\_\\\\]+';
private $tagHandlerMappings = [
'author' => '\phpDocumentor\Reflection\DocBlock\Tags\Author',
'covers' => '\phpDocumentor\Reflection\DocBlock\Tags\Covers',
'deprecated' => '\phpDocumentor\Reflection\DocBlock\Tags\Deprecated',
'link' => '\phpDocumentor\Reflection\DocBlock\Tags\Link',
'method' => '\phpDocumentor\Reflection\DocBlock\Tags\Method',
'param' => '\phpDocumentor\Reflection\DocBlock\Tags\Param',
'property-read' => '\phpDocumentor\Reflection\DocBlock\Tags\PropertyRead',
'property' => '\phpDocumentor\Reflection\DocBlock\Tags\Property',
'property-write' => '\phpDocumentor\Reflection\DocBlock\Tags\PropertyWrite',
'return' => '\phpDocumentor\Reflection\DocBlock\Tags\Return_',
'see' => '\phpDocumentor\Reflection\DocBlock\Tags\See',
'since' => '\phpDocumentor\Reflection\DocBlock\Tags\Since',
'source' => '\phpDocumentor\Reflection\DocBlock\Tags\Source',
'throw' => '\phpDocumentor\Reflection\DocBlock\Tags\Throws',
'throws' => '\phpDocumentor\Reflection\DocBlock\Tags\Throws',
'uses' => '\phpDocumentor\Reflection\DocBlock\Tags\Uses',
'var' => '\phpDocumentor\Reflection\DocBlock\Tags\Var_',
'version' => '\phpDocumentor\Reflection\DocBlock\Tags\Version'
];
private $tagHandlerParameterCache = [];
private $fqsenResolver;
private $serviceLocator = [];
public function __construct(FqsenResolver $fqsenResolver, array $tagHandlers = null)
{
$this->fqsenResolver = $fqsenResolver;
if ($tagHandlers !== null) {
$this->tagHandlerMappings = $tagHandlers;
}
$this->addService($fqsenResolver, FqsenResolver::class);
}
public function create($tagLine, TypeContext $context = null)
{
if (! $context) {
$context = new TypeContext('');
}
list($tagName, $tagBody) = $this->extractTagParts($tagLine);
return $this->createTag($tagBody, $tagName, $context);
}
public function addParameter($name, $value)
{
$this->serviceLocator[$name] = $value;
}
public function addService($service, $alias = null)
{
$this->serviceLocator[$alias ?: get_class($service)] = $service;
}
public function registerTagHandler($tagName, $handler)
{
Assert::stringNotEmpty($tagName);
Assert::stringNotEmpty($handler);
Assert::classExists($handler);
Assert::implementsInterface($handler, StaticMethod::class);
if (strpos($tagName, '\\') && $tagName[0] !== '\\') {
throw new \InvalidArgumentException(
'A namespaced tag must have a leading backslash as it must be fully qualified'
);
}
$this->tagHandlerMappings[$tagName] = $handler;
}
private function extractTagParts($tagLine)
{
$matches = array();
if (! preg_match('/^@(' . self::REGEX_TAGNAME . ')(?:\s*([^\s].*)|$)?/us', $tagLine, $matches)) {
throw new \InvalidArgumentException(
'The tag "' . $tagLine . '" does not seem to be wellformed, please check it for errors'
);
}
if (count($matches) < 3) {
$matches[] = '';
}
return array_slice($matches, 1);
}
private function createTag($body, $name, TypeContext $context)
{
$handlerClassName = $this->findHandlerClassName($name, $context);
$arguments = $this->getArgumentsForParametersFromWiring(
$this->fetchParametersForHandlerFactoryMethod($handlerClassName),
$this->getServiceLocatorWithDynamicParameters($context, $name, $body)
)
;
return call_user_func_array([$handlerClassName, 'create'], $arguments);
}
private function findHandlerClassName($tagName, TypeContext $context)
{
$handlerClassName = Generic::class;
if (isset($this->tagHandlerMappings[$tagName])) {
$handlerClassName = $this->tagHandlerMappings[$tagName];
} elseif ($this->isAnnotation($tagName)) {
}
return $handlerClassName;
}
private function getArgumentsForParametersFromWiring($parameters, $locator)
{
$arguments = [];
foreach ($parameters as $index => $parameter) {
$typeHint = $parameter->getClass() ? $parameter->getClass()->getName() : null;
if (isset($locator[$typeHint])) {
$arguments[] = $locator[$typeHint];
continue;
}
$parameterName = $parameter->getName();
if (isset($locator[$parameterName])) {
$arguments[] = $locator[$parameterName];
continue;
}
$arguments[] = null;
}
return $arguments;
}
private function fetchParametersForHandlerFactoryMethod($handlerClassName)
{
if (! isset($this->tagHandlerParameterCache[$handlerClassName])) {
$methodReflection = new \ReflectionMethod($handlerClassName, 'create');
$this->tagHandlerParameterCache[$handlerClassName] = $methodReflection->getParameters();
}
return $this->tagHandlerParameterCache[$handlerClassName];
}
private function getServiceLocatorWithDynamicParameters(TypeContext $context, $tagName, $tagBody)
{
$locator = array_merge(
$this->serviceLocator,
[
'name' => $tagName,
'body' => $tagBody,
TypeContext::class => $context
]
);
return $locator;
}
private function isAnnotation($tagContent)
{
return false;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tags\Formatter;
interface Tag
{
public function getName();
public static function create($body);
public function render(Formatter $formatter = null);
public function __toString();
}
<?php
namespace phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\Types\Context as TypeContext;
interface TagFactory
{
public function addParameter($name, $value);
public function addService($service);
public function create($tagLine, TypeContext $context = null);
public function registerTagHandler($tagName, $handler);
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use Webmozart\Assert\Assert;
final class Author extends BaseTag implements Factory\StaticMethod
{
protected $name = 'author';
private $authorName = '';
private $authorEmail = '';
public function __construct($authorName, $authorEmail)
{
Assert::string($authorName);
Assert::string($authorEmail);
if ($authorEmail && !filter_var($authorEmail, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('The author tag does not have a valid e-mail address');
}
$this->authorName = $authorName;
$this->authorEmail = $authorEmail;
}
public function getAuthorName()
{
return $this->authorName;
}
public function getEmail()
{
return $this->authorEmail;
}
public function __toString()
{
return $this->authorName . '<' . $this->authorEmail . '>';
}
public static function create($body)
{
Assert::string($body);
$splitTagContent = preg_match('/^([^\<]*)(?:\<([^\>]*)\>)?$/u', $body, $matches);
if (!$splitTagContent) {
return null;
}
$authorName = trim($matches[1]);
$email = isset($matches[2]) ? trim($matches[2]) : '';
return new static($authorName, $email);
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Description;
abstract class BaseTag implements DocBlock\Tag
{
protected $name = '';
protected $description;
public function getName()
{
return $this->name;
}
public function getDescription()
{
return $this->description;
}
public function render(Formatter $formatter = null)
{
if ($formatter === null) {
$formatter = new Formatter\PassthroughFormatter();
}
return $formatter->format($this);
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use phpDocumentor\Reflection\FqsenResolver;
use Webmozart\Assert\Assert;
final class Covers extends BaseTag implements Factory\StaticMethod
{
protected $name = 'covers';
private $refers = null;
public function __construct(Fqsen $refers, Description $description = null)
{
$this->refers = $refers;
$this->description = $description;
}
public static function create(
$body,
DescriptionFactory $descriptionFactory = null,
FqsenResolver $resolver = null,
TypeContext $context = null
)
{
Assert::string($body);
Assert::notEmpty($body);
$parts = preg_split('/\s+/Su', $body, 2);
return new static(
$resolver->resolve($parts[0], $context),
$descriptionFactory->create(isset($parts[1]) ? $parts[1] : '', $context)
);
}
public function getReference()
{
return $this->refers;
}
public function __toString()
{
return $this->refers . ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use Webmozart\Assert\Assert;
final class Deprecated extends BaseTag implements Factory\StaticMethod
{
protected $name = 'deprecated';
const REGEX_VECTOR = '(?:
# Normal release vectors.
\d\S*
|
# VCS version vectors. Per PHPCS, they are expected to
# follow the form of the VCS name, followed by ":", followed
# by the version vector itself.
# By convention, popular VCSes like CVS, SVN and GIT use "$"
# around the actual version vector.
[^\s\:]+\:\s*\$[^\$]+\$
)';
private $version = '';
public function __construct($version = null, Description $description = null)
{
Assert::nullOrStringNotEmpty($version);
$this->version = $version;
$this->description = $description;
}
public static function create($body, DescriptionFactory $descriptionFactory = null, TypeContext $context = null)
{
Assert::nullOrString($body);
if (empty($body)) {
return new static();
}
$matches = [];
if (!preg_match('/^(' . self::REGEX_VECTOR . ')\s*(.+)?$/sux', $body, $matches)) {
return null;
}
return new static(
$matches[1],
$descriptionFactory->create(isset($matches[2]) ? $matches[2] : '', $context)
);
}
public function getVersion()
{
return $this->version;
}
public function __toString()
{
return $this->version . ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Tag;
final class Example extends BaseTag
{
private $filePath = '';
private $isURI = false;
public function getContent()
{
if (null === $this->description) {
$filePath = '"' . $this->filePath . '"';
if ($this->isURI) {
$filePath = $this->isUriRelative($this->filePath)
? str_replace('%2F', '/', rawurlencode($this->filePath))
:$this->filePath;
}
$this->description = $filePath . ' ' . parent::getContent();
}
return $this->description;
}
public static function create($body)
{
if (! preg_match('/^(?:\"([^\"]+)\"|(\S+))(?:\s+(.*))?$/sux', $body, $matches)) {
return null;
}
$filePath = null;
$fileUri = null;
if ('' !== $matches[1]) {
$filePath = $matches[1];
} else {
$fileUri = $matches[2];
}
$startingLine = 1;
$lineCount = null;
$description = null;
if (preg_match('/^([1-9]\d*)\s*(?:((?1))\s+)?(.*)$/sux', $matches[3], $matches)) {
$startingLine = (int)$matches[1];
if (isset($matches[2]) && $matches[2] !== '') {
$lineCount = (int)$matches[2];
}
$description = $matches[3];
}
return new static($filePath, $fileUri, $startingLine, $lineCount, $description);
}
public function getFilePath()
{
return $this->filePath;
}
public function setFilePath($filePath)
{
$this->isURI = false;
$this->filePath = trim($filePath);
$this->description = null;
return $this;
}
public function setFileURI($uri)
{
$this->isURI = true;
$this->description = null;
$this->filePath = $this->isUriRelative($uri)
? rawurldecode(str_replace(array('/', '\\'), '%2F', $uri))
: $this->filePath = $uri;
return $this;
}
public function __toString()
{
return $this->filePath . ($this->description ? ' ' . $this->description->render() : '');
}
private function isUriRelative($uri)
{
return false === strpos($uri, ':');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags\Factory;
interface StaticMethod
{
public static function create($body);
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags\Factory;
interface Strategy
{
public function create($body);
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Tag;
interface Formatter
{
public function format(Tag $tag);
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags\Formatter;
use phpDocumentor\Reflection\DocBlock\Tag;
use phpDocumentor\Reflection\DocBlock\Tags\Formatter;
class PassthroughFormatter implements Formatter
{
public function format(Tag $tag)
{
return '@' . $tag->getName() . ' ' . (string)$tag;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\DocBlock\StandardTagFactory;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
class Generic extends BaseTag implements Factory\StaticMethod
{
public function __construct($name, Description $description = null)
{
$this->validateTagName($name);
$this->name = $name;
$this->description = $description;
}
public static function create(
$body,
$name = '',
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::string($body);
Assert::stringNotEmpty($name);
Assert::notNull($descriptionFactory);
$description = $descriptionFactory && $body ? $descriptionFactory->create($body, $context) : null;
return new static($name, $description);
}
public function __toString()
{
return ($this->description ? $this->description->render() : '');
}
private function validateTagName($name)
{
if (! preg_match('/^' . StandardTagFactory::REGEX_TAGNAME . '$/u', $name)) {
throw new \InvalidArgumentException(
'The tag name "' . $name . '" is not wellformed. Tags may only consist of letters, underscores, '
. 'hyphens and backslashes.'
);
}
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class Link extends BaseTag implements Factory\StaticMethod
{
protected $name = 'link';
private $link = '';
public function __construct($link, Description $description = null)
{
Assert::string($link);
$this->link = $link;
$this->description = $description;
}
public static function create($body, DescriptionFactory $descriptionFactory = null, TypeContext $context = null)
{
Assert::string($body);
Assert::notNull($descriptionFactory);
$parts = preg_split('/\s+/Su', $body, 2);
$description = isset($parts[1]) ? $descriptionFactory->create($parts[1], $context) : null;
return new static($parts[0], $description);
}
public function getLink()
{
return $this->link;
}
public function __toString()
{
return $this->link . ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use phpDocumentor\Reflection\Types\Void_;
use Webmozart\Assert\Assert;
final class Method extends BaseTag implements Factory\StaticMethod
{
protected $name = 'method';
private $methodName = '';
private $arguments = [];
private $isStatic = false;
private $returnType;
public function __construct(
$methodName,
array $arguments = [],
Type $returnType = null,
$static = false,
Description $description = null
) {
Assert::stringNotEmpty($methodName);
Assert::boolean($static);
if ($returnType === null) {
$returnType = new Void_();
}
$this->methodName = $methodName;
$this->arguments = $this->filterArguments($arguments);
$this->returnType = $returnType;
$this->isStatic = $static;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::stringNotEmpty($body);
Assert::allNotNull([ $typeResolver, $descriptionFactory ]);
if (!preg_match(
'/^
# Static keyword
# Declares a static method ONLY if type is also present
(?:
(static)
\s+
)?
# Return type
(?:
(
(?:[\w\|_\\\\]+)
# array notation
(?:\[\])*
)?
\s+
)?
# Legacy method name (not captured)
(?:
[\w_]+\(\)\s+
)?
# Method name
([\w\|_\\\\]+)
# Arguments
(?:
\(([^\)]*)\)
)?
\s*
# Description
(.*)
$/sux',
$body,
$matches
)) {
return null;
}
list(, $static, $returnType, $methodName, $arguments, $description) = $matches;
$static = $static === 'static';
$returnType = $typeResolver->resolve($returnType, $context);
$description = $descriptionFactory->create($description, $context);
if ('' !== $arguments) {
$arguments = explode(',', $arguments);
foreach($arguments as &$argument) {
$argument = explode(' ', trim($argument));
if ($argument[0][0] === '$') {
$argumentName = substr($argument[0], 1);
$argumentType = new Void_();
} else {
$argumentType = $typeResolver->resolve($argument[0], $context);
$argumentName = '';
if (isset($argument[1])) {
$argumentName = substr($argument[1], 1);
}
}
$argument = [ 'name' => $argumentName, 'type' => $argumentType];
}
} else {
$arguments = [];
}
return new static($methodName, $arguments, $returnType, $static, $description);
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
public function isStatic()
{
return $this->isStatic;
}
public function getReturnType()
{
return $this->returnType;
}
public function __toString()
{
$arguments = [];
foreach ($this->arguments as $argument) {
$arguments[] = $argument['type'] . ' $' . $argument['name'];
}
return ($this->isStatic() ? 'static ' : '')
. (string)$this->returnType . ' '
. $this->methodName
. '(' . implode(', ', $arguments) . ')'
. ($this->description ? ' ' . $this->description->render() : '');
}
private function filterArguments($arguments)
{
foreach ($arguments as &$argument) {
if (is_string($argument)) {
$argument = [ 'name' => $argument ];
}
if (! isset($argument['type'])) {
$argument['type'] = new Void_();
}
$keys = array_keys($argument);
if ($keys !== [ 'name', 'type' ]) {
throw new \InvalidArgumentException(
'Arguments can only have the "name" and "type" fields, found: ' . var_export($keys, true)
);
}
}
return $arguments;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class Param extends BaseTag implements Factory\StaticMethod
{
protected $name = 'param';
private $type;
private $variableName = '';
private $isVariadic = false;
public function __construct($variableName, Type $type = null, $isVariadic = false, Description $description = null)
{
Assert::string($variableName);
Assert::boolean($isVariadic);
$this->variableName = $variableName;
$this->type = $type;
$this->isVariadic = $isVariadic;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::stringNotEmpty($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/(\s+)/Su', $body, 3, PREG_SPLIT_DELIM_CAPTURE);
$type = null;
$variableName = '';
$isVariadic = false;
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] !== '$')) {
$type = $typeResolver->resolve(array_shift($parts), $context);
array_shift($parts);
}
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] == '$' || substr($parts[0], 0, 4) === '...$')) {
$variableName = array_shift($parts);
array_shift($parts);
if (substr($variableName, 0, 3) === '...') {
$isVariadic = true;
$variableName = substr($variableName, 3);
}
if (substr($variableName, 0, 1) === '$') {
$variableName = substr($variableName, 1);
}
}
$description = $descriptionFactory->create(implode('', $parts), $context);
return new static($variableName, $type, $isVariadic, $description);
}
public function getVariableName()
{
return $this->variableName;
}
public function getType()
{
return $this->type;
}
public function isVariadic()
{
return $this->isVariadic;
}
public function __toString()
{
return ($this->type ? $this->type . ' ' : '')
. ($this->isVariadic() ? '...' : '')
. '$' . $this->variableName
. ($this->description ? ' ' . $this->description : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
class Property extends BaseTag implements Factory\StaticMethod
{
protected $name = 'property';
private $type;
protected $variableName = '';
public function __construct($variableName, Type $type = null, Description $description = null)
{
Assert::string($variableName);
$this->variableName = $variableName;
$this->type = $type;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::stringNotEmpty($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/(\s+)/Su', $body, 3, PREG_SPLIT_DELIM_CAPTURE);
$type = null;
$variableName = '';
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] !== '$')) {
$type = $typeResolver->resolve(array_shift($parts), $context);
array_shift($parts);
}
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] == '$')) {
$variableName = array_shift($parts);
array_shift($parts);
if (substr($variableName, 0, 1) === '$') {
$variableName = substr($variableName, 1);
}
}
$description = $descriptionFactory->create(implode('', $parts), $context);
return new static($variableName, $type, $description);
}
public function getVariableName()
{
return $this->variableName;
}
public function getType()
{
return $this->type;
}
public function __toString()
{
return ($this->type ? $this->type . ' ' : '')
. '$' . $this->variableName
. ($this->description ? ' ' . $this->description : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
class PropertyRead extends BaseTag implements Factory\StaticMethod
{
protected $name = 'property-read';
private $type;
protected $variableName = '';
public function __construct($variableName, Type $type = null, Description $description = null)
{
Assert::string($variableName);
$this->variableName = $variableName;
$this->type = $type;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::stringNotEmpty($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/(\s+)/Su', $body, 3, PREG_SPLIT_DELIM_CAPTURE);
$type = null;
$variableName = '';
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] !== '$')) {
$type = $typeResolver->resolve(array_shift($parts), $context);
array_shift($parts);
}
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] == '$')) {
$variableName = array_shift($parts);
array_shift($parts);
if (substr($variableName, 0, 1) === '$') {
$variableName = substr($variableName, 1);
}
}
$description = $descriptionFactory->create(implode('', $parts), $context);
return new static($variableName, $type, $description);
}
public function getVariableName()
{
return $this->variableName;
}
public function getType()
{
return $this->type;
}
public function __toString()
{
return ($this->type ? $this->type . ' ' : '')
. '$' . $this->variableName
. ($this->description ? ' ' . $this->description : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
class PropertyWrite extends BaseTag implements Factory\StaticMethod
{
protected $name = 'property-write';
private $type;
protected $variableName = '';
public function __construct($variableName, Type $type = null, Description $description = null)
{
Assert::string($variableName);
$this->variableName = $variableName;
$this->type = $type;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::stringNotEmpty($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/(\s+)/Su', $body, 3, PREG_SPLIT_DELIM_CAPTURE);
$type = null;
$variableName = '';
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] !== '$')) {
$type = $typeResolver->resolve(array_shift($parts), $context);
array_shift($parts);
}
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] == '$')) {
$variableName = array_shift($parts);
array_shift($parts);
if (substr($variableName, 0, 1) === '$') {
$variableName = substr($variableName, 1);
}
}
$description = $descriptionFactory->create(implode('', $parts), $context);
return new static($variableName, $type, $description);
}
public function getVariableName()
{
return $this->variableName;
}
public function getType()
{
return $this->type;
}
public function __toString()
{
return ($this->type ? $this->type . ' ' : '')
. '$' . $this->variableName
. ($this->description ? ' ' . $this->description : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class Return_ extends BaseTag implements Factory\StaticMethod
{
protected $name = 'return';
private $type;
public function __construct(Type $type, Description $description = null)
{
$this->type = $type;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
)
{
Assert::string($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/\s+/Su', $body, 2);
$type = $typeResolver->resolve(isset($parts[0]) ? $parts[0] : '', $context);
$description = $descriptionFactory->create(isset($parts[1]) ? $parts[1] : '', $context);
return new static($type, $description);
}
public function getType()
{
return $this->type;
}
public function __toString()
{
return $this->type . ' ' . $this->description;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use phpDocumentor\Reflection\DocBlock\Description;
use Webmozart\Assert\Assert;
class See extends BaseTag implements Factory\StaticMethod
{
protected $name = 'see';
protected $refers = null;
public function __construct(Fqsen $refers, Description $description = null)
{
$this->refers = $refers;
$this->description = $description;
}
public static function create(
$body,
FqsenResolver $resolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::string($body);
Assert::allNotNull([$resolver, $descriptionFactory]);
$parts = preg_split('/\s+/Su', $body, 2);
$description = isset($parts[1]) ? $descriptionFactory->create($parts[1], $context) : null;
return new static($resolver->resolve($parts[0], $context), $description);
}
public function getReference()
{
return $this->refers;
}
public function __toString()
{
return $this->refers . ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use Webmozart\Assert\Assert;
final class Since extends BaseTag implements Factory\StaticMethod
{
protected $name = 'since';
const REGEX_VECTOR = '(?:
# Normal release vectors.
\d\S*
|
# VCS version vectors. Per PHPCS, they are expected to
# follow the form of the VCS name, followed by ":", followed
# by the version vector itself.
# By convention, popular VCSes like CVS, SVN and GIT use "$"
# around the actual version vector.
[^\s\:]+\:\s*\$[^\$]+\$
)';
private $version = '';
public function __construct($version = null, Description $description = null)
{
Assert::nullOrStringNotEmpty($version);
$this->version = $version;
$this->description = $description;
}
public static function create($body, DescriptionFactory $descriptionFactory = null, TypeContext $context = null)
{
Assert::nullOrString($body);
if (empty($body)) {
return new static();
}
$matches = [];
if (! preg_match('/^(' . self::REGEX_VECTOR . ')\s*(.+)?$/sux', $body, $matches)) {
return null;
}
return new static(
$matches[1],
$descriptionFactory->create(isset($matches[2]) ? $matches[2] : '', $context)
);
}
public function getVersion()
{
return $this->version;
}
public function __toString()
{
return $this->version . ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class Source extends BaseTag implements Factory\StaticMethod
{
protected $name = 'source';
private $startingLine = 1;
private $lineCount = null;
public function __construct($startingLine, $lineCount = null, Description $description = null)
{
Assert::integerish($startingLine);
Assert::nullOrIntegerish($lineCount);
$this->startingLine = (int)$startingLine;
$this->lineCount = $lineCount !== null ? (int)$lineCount : null;
$this->description = $description;
}
public static function create($body, DescriptionFactory $descriptionFactory = null, TypeContext $context = null)
{
Assert::stringNotEmpty($body);
Assert::notNull($descriptionFactory);
$startingLine = 1;
$lineCount = null;
$description = null;
if (preg_match('/^([1-9]\d*)\s*(?:((?1))\s+)?(.*)$/sux', $body, $matches)) {
$startingLine = (int)$matches[1];
if (isset($matches[2]) && $matches[2] !== '') {
$lineCount = (int)$matches[2];
}
$description = $matches[3];
}
return new static($startingLine, $lineCount, $descriptionFactory->create($description, $context));
}
public function getStartingLine()
{
return $this->startingLine;
}
public function getLineCount()
{
return $this->lineCount;
}
public function __toString()
{
return $this->startingLine
. ($this->lineCount !== null ? ' ' . $this->lineCount : '')
. ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class Throws extends BaseTag implements Factory\StaticMethod
{
protected $name = 'throws';
private $type;
public function __construct(Type $type, Description $description = null)
{
$this->type = $type;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::string($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/\s+/Su', $body, 2);
$type = $typeResolver->resolve(isset($parts[0]) ? $parts[0] : '', $context);
$description = $descriptionFactory->create(isset($parts[1]) ? $parts[1] : '', $context);
return new static($type, $description);
}
public function getType()
{
return $this->type;
}
public function __toString()
{
return $this->type . ' ' . $this->description;
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
final class Uses extends BaseTag implements Factory\StaticMethod
{
protected $name = 'uses';
protected $refers = null;
public function __construct(Fqsen $refers, Description $description = null)
{
$this->refers = $refers;
$this->description = $description;
}
public static function create(
$body,
FqsenResolver $resolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::string($body);
Assert::allNotNull([$resolver, $descriptionFactory]);
$parts = preg_split('/\s+/Su', $body, 2);
return new static(
$resolver->resolve($parts[0], $context),
$descriptionFactory->create(isset($parts[1]) ? $parts[1] : '', $context)
);
}
public function getReference()
{
return $this->refers;
}
public function __toString()
{
return $this->refers . ' ' . $this->description->render();
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use Webmozart\Assert\Assert;
class Var_ extends BaseTag implements Factory\StaticMethod
{
protected $name = 'var';
private $type;
protected $variableName = '';
public function __construct($variableName, Type $type = null, Description $description = null)
{
Assert::string($variableName);
$this->variableName = $variableName;
$this->type = $type;
$this->description = $description;
}
public static function create(
$body,
TypeResolver $typeResolver = null,
DescriptionFactory $descriptionFactory = null,
TypeContext $context = null
) {
Assert::stringNotEmpty($body);
Assert::allNotNull([$typeResolver, $descriptionFactory]);
$parts = preg_split('/(\s+)/Su', $body, 3, PREG_SPLIT_DELIM_CAPTURE);
$type = null;
$variableName = '';
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] !== '$')) {
$type = $typeResolver->resolve(array_shift($parts), $context);
array_shift($parts);
}
if (isset($parts[0]) && (strlen($parts[0]) > 0) && ($parts[0][0] == '$')) {
$variableName = array_shift($parts);
array_shift($parts);
if (substr($variableName, 0, 1) === '$') {
$variableName = substr($variableName, 1);
}
}
$description = $descriptionFactory->create(implode('', $parts), $context);
return new static($variableName, $type, $description);
}
public function getVariableName()
{
return $this->variableName;
}
public function getType()
{
return $this->type;
}
public function __toString()
{
return ($this->type ? $this->type . ' ' : '')
. '$' . $this->variableName
. ($this->description ? ' ' . $this->description : '');
}
}
<?php
namespace phpDocumentor\Reflection\DocBlock\Tags;
use phpDocumentor\Reflection\Types\Context as TypeContext;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use Webmozart\Assert\Assert;
final class Version extends BaseTag implements Factory\StaticMethod
{
protected $name = 'version';
const REGEX_VECTOR = '(?:
# Normal release vectors.
\d\S*
|
# VCS version vectors. Per PHPCS, they are expected to
# follow the form of the VCS name, followed by ":", followed
# by the version vector itself.
# By convention, popular VCSes like CVS, SVN and GIT use "$"
# around the actual version vector.
[^\s\:]+\:\s*\$[^\$]+\$
)';
private $version = '';
public function __construct($version = null, Description $description = null)
{
Assert::nullOrStringNotEmpty($version);
$this->version = $version;
$this->description = $description;
}
public static function create($body, DescriptionFactory $descriptionFactory = null, TypeContext $context = null)
{
Assert::nullOrString($body);
if (empty($body)) {
return new static();
}
$matches = [];
if (!preg_match('/^(' . self::REGEX_VECTOR . ')\s*(.+)?$/sux', $body, $matches)) {
return null;
}
return new static(
$matches[1],
$descriptionFactory->create(isset($matches[2]) ? $matches[2] : '', $context)
);
}
public function getVersion()
{
return $this->version;
}
public function __toString()
{
return $this->version . ($this->description ? ' ' . $this->description->render() : '');
}
}
<?php
namespace phpDocumentor\Reflection;
use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\DocBlock\StandardTagFactory;
use phpDocumentor\Reflection\DocBlock\Tag;
use phpDocumentor\Reflection\DocBlock\TagFactory;
use Webmozart\Assert\Assert;
final class DocBlockFactory implements DocBlockFactoryInterface
{
private $descriptionFactory;
private $tagFactory;
public function __construct(DescriptionFactory $descriptionFactory, TagFactory $tagFactory)
{
$this->descriptionFactory = $descriptionFactory;
$this->tagFactory = $tagFactory;
}
public static function createInstance(array $additionalTags = [])
{
$fqsenResolver = new FqsenResolver();
$tagFactory = new StandardTagFactory($fqsenResolver);
$descriptionFactory = new DescriptionFactory($tagFactory);
$tagFactory->addService($descriptionFactory);
$tagFactory->addService(new TypeResolver($fqsenResolver));
$docBlockFactory = new self($descriptionFactory, $tagFactory);
foreach ($additionalTags as $tagName => $tagHandler) {
$docBlockFactory->registerTagHandler($tagName, $tagHandler);
}
return $docBlockFactory;
}
public function create($docblock, Types\Context $context = null, Location $location = null)
{
if (is_object($docblock)) {
if (!method_exists($docblock, 'getDocComment')) {
$exceptionMessage = 'Invalid object passed; the given object must support the getDocComment method';
throw new \InvalidArgumentException($exceptionMessage);
}
$docblock = $docblock->getDocComment();
}
Assert::stringNotEmpty($docblock);
if ($context === null) {
$context = new Types\Context('');
}
$parts = $this->splitDocBlock($this->stripDocComment($docblock));
list($templateMarker, $summary, $description, $tags) = $parts;
return new DocBlock(
$summary,
$description ? $this->descriptionFactory->create($description, $context) : null,
array_filter($this->parseTagBlock($tags, $context), function($tag) {
return $tag instanceof Tag;
}),
$context,
$location,
$templateMarker === '#@+',
$templateMarker === '#@-'
);
}
public function registerTagHandler($tagName, $handler)
{
$this->tagFactory->registerTagHandler($tagName, $handler);
}
private function stripDocComment($comment)
{
$comment = trim(preg_replace('#[ \t]*(?:\/\*\*|\*\/|\*)?[ \t]{0,1}(.*)?#u', '$1', $comment));
if (substr($comment, -2) == '*/') {
$comment = trim(substr($comment, 0, -2));
}
return str_replace(array("\r\n", "\r"), "\n", $comment);
}
private function splitDocBlock($comment)
{
if (strpos($comment, '@') === 0) {
return array('', '', '', $comment);
}
$comment = preg_replace('/\h*$/Sum', '', $comment);
preg_match(
'/
\A
# 1. Extract the template marker
(?:(\#\@\+|\#\@\-)\n?)?
# 2. Extract the summary
(?:
(?! @\pL ) # The summary may not start with an @
(
[^\n.]+
(?:
(?! \. \n | \n{2} ) # End summary upon a dot followed by newline or two newlines
[\n.] (?! [ \t]* @\pL ) # End summary when an @ is found as first character on a new line
[^\n.]+ # Include anything else
)*
\.?
)?
)
# 3. Extract the description
(?:
\s* # Some form of whitespace _must_ precede a description because a summary must be there
(?! @\pL ) # The description may not start with an @
(
[^\n]+
(?: \n+
(?! [ \t]* @\pL ) # End description when an @ is found as first character on a new line
[^\n]+ # Include anything else
)*
)
)?
# 4. Extract the tags (anything that follows)
(\s+ [\s\S]*)? # everything that follows
/ux',
$comment,
$matches
);
array_shift($matches);
while (count($matches) < 4) {
$matches[] = '';
}
return $matches;
}
private function parseTagBlock($tags, Types\Context $context)
{
$tags = $this->filterTagBlock($tags);
if (!$tags) {
return [];
}
$result = $this->splitTagBlockIntoTagLines($tags);
foreach ($result as $key => $tagLine) {
$result[$key] = $this->tagFactory->create(trim($tagLine), $context);
}
return $result;
}
private function splitTagBlockIntoTagLines($tags)
{
$result = array();
foreach (explode("\n", $tags) as $tag_line) {
if (isset($tag_line[0]) && ($tag_line[0] === '@')) {
$result[] = $tag_line;
} else {
$result[count($result) - 1] .= "\n" . $tag_line;
}
}
return $result;
}
private function filterTagBlock($tags)
{
$tags = trim($tags);
if (!$tags) {
return null;
}
if ('@' !== $tags[0]) {
throw new \LogicException('A tag block started with text instead of an at-sign(@): ' . $tags);
}
return $tags;
}
}
<?php
namespace phpDocumentor\Reflection;
interface DocBlockFactoryInterface
{
public static function createInstance(array $additionalTags = []);
public function create($docblock, Types\Context $context = null, Location $location = null);
}
<?php
namespace spec\Prophecy\Argument;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument\Token\TokenInterface;
class ArgumentsWildcardSpec extends ObjectBehavior
{
function it_wraps_non_token_arguments_into_ExactValueToken($object)
{
$this->beConstructedWith(array(42, 'zet', $object));
$class = get_class($object->getWrappedObject());
$hash = spl_object_hash($object->getWrappedObject());
$this->__toString()->shouldReturn("exact(42), exact(\"zet\"), exact($class:$hash Object (\n 'objectProphecy' => Prophecy\Prophecy\ObjectProphecy Object (*Prophecy*)\n))");
}
function it_generates_string_representation_from_all_tokens_imploded($token1, $token2, $token3)
{
$token1->__toString()->willReturn('token_1');
$token2->__toString()->willReturn('token_2');
$token3->__toString()->willReturn('token_3');
$this->beConstructedWith(array($token1, $token2, $token3));
$this->__toString()->shouldReturn('token_1, token_2, token_3');
}
function it_exposes_list_of_tokens($token)
{
$this->beConstructedWith(array($token));
$this->getTokens()->shouldReturn(array($token));
}
function it_returns_score_of_1_if_there_are_no_tokens_and_arguments()
{
$this->beConstructedWith(array());
$this->scoreArguments(array())->shouldReturn(1);
}
function it_should_return_match_score_based_on_all_tokens_score($token1, $token2, $token3)
{
$token1->scoreArgument('one')->willReturn(3);
$token1->isLast()->willReturn(false);
$token2->scoreArgument(2)->willReturn(5);
$token2->isLast()->willReturn(false);
$token3->scoreArgument($obj = new \stdClass())->willReturn(10);
$token3->isLast()->willReturn(false);
$this->beConstructedWith(array($token1, $token2, $token3));
$this->scoreArguments(array('one', 2, $obj))->shouldReturn(18);
}
function it_returns_false_if_there_is_less_arguments_than_tokens($token1, $token2, $token3)
{
$token1->scoreArgument('one')->willReturn(3);
$token1->isLast()->willReturn(false);
$token2->scoreArgument(2)->willReturn(5);
$token2->isLast()->willReturn(false);
$token3->scoreArgument(null)->willReturn(false);
$token3->isLast()->willReturn(false);
$this->beConstructedWith(array($token1, $token2, $token3));
$this->scoreArguments(array('one', 2))->shouldReturn(false);
}
function it_returns_false_if_there_is_less_tokens_than_arguments($token1, $token2, $token3)
{
$token1->scoreArgument('one')->willReturn(3);
$token1->isLast()->willReturn(false);
$token2->scoreArgument(2)->willReturn(5);
$token2->isLast()->willReturn(false);
$token3->scoreArgument($obj = new \stdClass())->willReturn(10);
$token3->isLast()->willReturn(false);
$this->beConstructedWith(array($token1, $token2, $token3));
$this->scoreArguments(array('one', 2, $obj, 4))->shouldReturn(false);
}
function it_should_return_false_if_one_of_the_tokens_returns_false($token1, $token2, $token3)
{
$token1->scoreArgument('one')->willReturn(3);
$token1->isLast()->willReturn(false);
$token2->scoreArgument(2)->willReturn(false);
$token2->isLast()->willReturn(false);
$token3->scoreArgument($obj = new \stdClass())->willReturn(10);
$token3->isLast()->willReturn(false);
$this->beConstructedWith(array($token1, $token2, $token3));
$this->scoreArguments(array('one', 2, $obj))->shouldReturn(false);
}
function it_should_calculate_score_until_last_token($token1, $token2, $token3)
{
$token1->scoreArgument('one')->willReturn(3);
$token1->isLast()->willReturn(false);
$token2->scoreArgument(2)->willReturn(7);
$token2->isLast()->willReturn(true);
$token3->scoreArgument($obj = new \stdClass())->willReturn(10);
$token3->isLast()->willReturn(false);
$this->beConstructedWith(array($token1, $token2, $token3));
$this->scoreArguments(array('one', 2, $obj))->shouldReturn(10);
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class AnyValueTokenSpec extends ObjectBehavior
{
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function its_string_representation_is_star()
{
$this->__toString()->shouldReturn('*');
}
function it_scores_any_argument_as_3()
{
$this->scoreArgument(42)->shouldReturn(3);
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class AnyValuesTokenSpec extends ObjectBehavior
{
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_last()
{
$this->shouldBeLast();
}
function its_string_representation_is_star_with_followup()
{
$this->__toString()->shouldReturn('* [, ...]');
}
function it_scores_any_argument_as_2()
{
$this->scoreArgument(42)->shouldReturn(2);
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ApproximateValueTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(10.12345678, 4);
}
function it_is_initializable()
{
$this->shouldHaveType('Prophecy\Argument\Token\ApproximateValueToken');
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_scores_10_if_rounded_argument_matches_rounded_value()
{
$this->scoreArgument(10.12345)->shouldReturn(10);
}
function it_does_not_score_if_rounded_argument_does_not_match_rounded_value()
{
$this->scoreArgument(10.1234)->shouldReturn(false);
}
function it_uses_a_default_precision_of_zero()
{
$this->beConstructedWith(10.7);
$this->scoreArgument(11.4)->shouldReturn(10);
}
function it_does_not_score_if_rounded_argument_is_not_numeric()
{
$this->scoreArgument('hello')->shouldReturn(false);
}
function it_has_simple_string_representation()
{
$this->__toString()->shouldBe('≅10.1235');
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class ArrayCountTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(2);
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_scores_6_if_argument_array_has_proper_count()
{
$this->scoreArgument(array(1,2))->shouldReturn(6);
}
function it_scores_6_if_argument_countable_object_has_proper_count($countable)
{
$countable->count()->willReturn(2);
$this->scoreArgument($countable)->shouldReturn(6);
}
function it_does_not_score_if_argument_is_neither_array_nor_countable_object()
{
$this->scoreArgument('string')->shouldBe(false);
$this->scoreArgument(5)->shouldBe(false);
$this->scoreArgument(new \stdClass)->shouldBe(false);
}
function it_does_not_score_if_argument_array_has_wrong_count()
{
$this->scoreArgument(array(1))->shouldReturn(false);
}
function it_does_not_score_if_argument_countable_object_has_wrong_count($countable)
{
$countable->count()->willReturn(3);
$this->scoreArgument($countable)->shouldReturn(false);
}
function it_has_simple_string_representation()
{
$this->__toString()->shouldBe('count(2)');
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Prophecy\Exception\InvalidArgumentException;
class ArrayEntryTokenSpec extends ObjectBehavior
{
function let($key, $value)
{
$this->beConstructedWith($key, $value);
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_holds_key_and_value($key, $value)
{
$this->getKey()->shouldBe($key);
$this->getValue()->shouldBe($value);
}
function its_string_representation_tells_that_its_an_array_containing_the_key_value_pair($key, $value)
{
$key->__toString()->willReturn('key');
$value->__toString()->willReturn('value');
$this->__toString()->shouldBe('[..., key => value, ...]');
}
function it_wraps_non_token_value_into_ExactValueToken($key, $object)
{
$this->beConstructedWith($key, $object);
$this->getValue()->shouldHaveType('\Prophecy\Argument\Token\ExactValueToken');
}
function it_wraps_non_token_key_into_ExactValueToken($object, $value)
{
$this->beConstructedWith($object, $value);
$this->getKey()->shouldHaveType('\Prophecy\Argument\Token\ExactValueToken');
}
function it_scores_array_half_of_combined_scores_from_key_and_value_tokens($key, $value)
{
$key->scoreArgument('key')->willReturn(4);
$value->scoreArgument('value')->willReturn(6);
$this->scoreArgument(array('key'=>'value'))->shouldBe(5);
}
function it_scores_traversable_object_half_of_combined_scores_from_key_and_value_tokens($key, $value, $object)
{
$object->current()->will(function () use ($object) {
$object->valid()->willReturn(false);
return 'value';
});
$object->key()->willReturn('key');
$object->rewind()->willReturn(null);
$object->next()->willReturn(null);
$object->valid()->willReturn(true);
$key->scoreArgument('key')->willReturn(6);
$value->scoreArgument('value')->willReturn(2);
$this->scoreArgument($object)->shouldBe(4);
}
function it_throws_exception_during_scoring_of_array_accessible_object_if_key_is_not_ExactValueToken($key, $value, $object)
{
$key->__toString()->willReturn('any_token');
$this->beConstructedWith($key,$value);
$errorMessage = 'You can only use exact value tokens to match key of ArrayAccess object'.PHP_EOL.
'But you used `any_token`.';
$this->shouldThrow(new InvalidArgumentException($errorMessage))->duringScoreArgument($object);
}
function it_scores_array_accessible_object_half_of_combined_scores_from_key_and_value_tokens($key, $value, $object)
{
$object->offsetExists('key')->willReturn(true);
$object->offsetGet('key')->willReturn('value');
$key->getValue()->willReturn('key');
$key->scoreArgument('key')->willReturn(3);
$value->scoreArgument('value')->willReturn(1);
$this->scoreArgument($object)->shouldBe(2);
}
function it_accepts_any_key_token_type_to_score_object_that_is_both_traversable_and_array_accessible($key, $value, $object)
{
$this->beConstructedWith($key, $value);
$object->current()->will(function () use ($object) {
$object->valid()->willReturn(false);
return 'value';
});
$object->key()->willReturn('key');
$object->rewind()->willReturn(null);
$object->next()->willReturn(null);
$object->valid()->willReturn(true);
$this->shouldNotThrow(new InvalidArgumentException)->duringScoreArgument($object);
}
function it_does_not_score_if_argument_is_neither_array_nor_traversable_nor_array_accessible()
{
$this->scoreArgument('string')->shouldBe(false);
$this->scoreArgument(new \stdClass)->shouldBe(false);
}
function it_does_not_score_empty_array()
{
$this->scoreArgument(array())->shouldBe(false);
}
function it_does_not_score_array_if_key_and_value_tokens_do_not_score_same_entry($key, $value)
{
$argument = array(1 => 'foo', 2 => 'bar');
$key->scoreArgument(1)->willReturn(true);
$key->scoreArgument(2)->willReturn(false);
$value->scoreArgument('foo')->willReturn(false);
$value->scoreArgument('bar')->willReturn(true);
$this->scoreArgument($argument)->shouldBe(false);
}
function it_does_not_score_traversable_object_without_entries($object)
{
$object->rewind()->willReturn(null);
$object->next()->willReturn(null);
$object->valid()->willReturn(false);
$this->scoreArgument($object)->shouldBe(false);
}
function it_does_not_score_traversable_object_if_key_and_value_tokens_do_not_score_same_entry($key, $value, $object)
{
$object->current()->willReturn('foo');
$object->current()->will(function () use ($object) {
$object->valid()->willReturn(false);
return 'bar';
});
$object->key()->willReturn(1);
$object->key()->willReturn(2);
$object->rewind()->willReturn(null);
$object->next()->willReturn(null);
$object->valid()->willReturn(true);
$key->scoreArgument(1)->willReturn(true);
$key->scoreArgument(2)->willReturn(false);
$value->scoreArgument('foo')->willReturn(false);
$value->scoreArgument('bar')->willReturn(true);
$this->scoreArgument($object)->shouldBe(false);
}
function it_does_not_score_array_accessible_object_if_it_has_no_offset_with_key_token_value($key, $object)
{
$object->offsetExists('key')->willReturn(false);
$key->getValue()->willReturn('key');
$this->scoreArgument($object)->shouldBe(false);
}
function it_does_not_score_array_accessible_object_if_key_and_value_tokens_do_not_score_same_entry($key, $value, $object)
{
$object->offsetExists('key')->willReturn(true);
$object->offsetGet('key')->willReturn('value');
$key->getValue()->willReturn('key');
$value->scoreArgument('value')->willReturn(false);
$key->scoreArgument('key')->willReturn(true);
$this->scoreArgument($object)->shouldBe(false);
}
function its_score_is_capped_at_8($key, $value)
{
$key->scoreArgument('key')->willReturn(10);
$value->scoreArgument('value')->willReturn(10);
$this->scoreArgument(array('key'=>'value'))->shouldBe(8);
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ArrayEveryEntryTokenSpec extends ObjectBehavior
{
function let($value)
{
$this->beConstructedWith($value);
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_holds_value($value)
{
$this->getValue()->shouldBe($value);
}
function its_string_representation_tells_that_its_an_array_containing_only_value($value)
{
$value->__toString()->willReturn('value');
$this->__toString()->shouldBe('[value, ..., value]');
}
function it_wraps_non_token_value_into_ExactValueToken($stdClass)
{
$this->beConstructedWith($stdClass);
$this->getValue()->shouldHaveType('Prophecy\Argument\Token\ExactValueToken');
}
function it_does_not_score_if_argument_is_neither_array_nor_traversable()
{
$this->scoreArgument('string')->shouldBe(false);
$this->scoreArgument(new \stdClass)->shouldBe(false);
}
function it_does_not_score_empty_array()
{
$this->scoreArgument(array())->shouldBe(false);
}
function it_does_not_score_traversable_object_without_entries($object)
{
$object->rewind()->willReturn(null);
$object->next()->willReturn(null);
$object->valid()->willReturn(false);
$this->scoreArgument($object)->shouldBe(false);
}
function it_scores_avg_of_scores_from_value_tokens($value)
{
$value->scoreArgument('value1')->willReturn(6);
$value->scoreArgument('value2')->willReturn(3);
$this->scoreArgument(array('value1', 'value2'))->shouldBe(4.5);
}
function it_scores_false_if_entry_scores_false($value)
{
$value->scoreArgument('value1')->willReturn(6);
$value->scoreArgument('value2')->willReturn(false);
$this->scoreArgument(array('value1', 'value2'))->shouldBe(false);
}
function it_does_not_score_array_keys($value)
{
$value->scoreArgument('value')->willReturn(6);
$value->scoreArgument('key')->shouldNotBeCalled(0);
$this->scoreArgument(array('key' => 'value'))->shouldBe(6);
}
function it_scores_traversable_object_from_value_token($value, $object)
{
$object->current()->will(function ($args, $object) {
$object->valid()->willReturn(false);
return 'value';
});
$object->key()->willReturn('key');
$object->rewind()->willReturn(null);
$object->next()->willReturn(null);
$object->valid()->willReturn(true);
$value->scoreArgument('value')->willReturn(2);
$this->scoreArgument($object)->shouldBe(2);
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class CallbackTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('get_class');
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_scores_7_if_argument_matches_callback()
{
$this->beConstructedWith(function ($argument) { return 2 === $argument; });
$this->scoreArgument(2)->shouldReturn(7);
}
function it_does_not_scores_if_argument_does_not_match_callback()
{
$this->beConstructedWith(function ($argument) { return 2 === $argument; });
$this->scoreArgument(5)->shouldReturn(false);
}
function its_string_representation_should_tell_that_its_callback()
{
$this->__toString()->shouldReturn('callback()');
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class ExactValueTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(42);
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_holds_value()
{
$this->getValue()->shouldReturn(42);
}
function it_scores_10_if_value_is_equal_to_argument()
{
$this->scoreArgument(42)->shouldReturn(10);
$this->scoreArgument('42')->shouldReturn(10);
}
function it_scores_10_if_value_is_an_object_and_equal_to_argument()
{
$value = new \DateTime();
$value2 = clone $value;
$this->beConstructedWith($value);
$this->scoreArgument($value2)->shouldReturn(10);
}
function it_does_not_scores_if_value_is_not_equal_to_argument()
{
$this->scoreArgument(50)->shouldReturn(false);
$this->scoreArgument(new \stdClass())->shouldReturn(false);
}
function it_does_not_scores_if_value_an_object_and_is_not_equal_to_argument()
{
$value = new ExactValueTokenFixtureB('ABC');
$value2 = new ExactValueTokenFixtureB('CBA');
$this->beConstructedWith($value);
$this->scoreArgument($value2)->shouldReturn(false);
}
function it_does_not_scores_if_value_type_and_is_not_equal_to_argument()
{
$this->beConstructedWith(false);
$this->scoreArgument(0)->shouldReturn(false);
}
function it_generates_proper_string_representation_for_integer()
{
$this->beConstructedWith(42);
$this->__toString()->shouldReturn('exact(42)');
}
function it_generates_proper_string_representation_for_string()
{
$this->beConstructedWith('some string');
$this->__toString()->shouldReturn('exact("some string")');
}
function it_generates_single_line_representation_for_multiline_string()
{
$this->beConstructedWith("some\nstring");
$this->__toString()->shouldReturn('exact("some\\nstring")');
}
function it_generates_proper_string_representation_for_double()
{
$this->beConstructedWith(42.3);
$this->__toString()->shouldReturn('exact(42.3)');
}
function it_generates_proper_string_representation_for_boolean_true()
{
$this->beConstructedWith(true);
$this->__toString()->shouldReturn('exact(true)');
}
function it_generates_proper_string_representation_for_boolean_false()
{
$this->beConstructedWith(false);
$this->__toString()->shouldReturn('exact(false)');
}
function it_generates_proper_string_representation_for_null()
{
$this->beConstructedWith(null);
$this->__toString()->shouldReturn('exact(null)');
}
function it_generates_proper_string_representation_for_empty_array()
{
$this->beConstructedWith(array());
$this->__toString()->shouldReturn('exact([])');
}
function it_generates_proper_string_representation_for_array()
{
$this->beConstructedWith(array('zet', 42));
$this->__toString()->shouldReturn('exact(["zet", 42])');
}
function it_generates_proper_string_representation_for_resource()
{
$resource = fopen(__FILE__, 'r');
$this->beConstructedWith($resource);
$this->__toString()->shouldReturn('exact(stream:'.$resource.')');
}
function it_generates_proper_string_representation_for_object($object)
{
$objHash = sprintf('%s:%s',
get_class($object->getWrappedObject()),
spl_object_hash($object->getWrappedObject())
);
$this->beConstructedWith($object);
$this->__toString()->shouldReturn("exact($objHash Object (\n 'objectProphecy' => Prophecy\Prophecy\ObjectProphecy Object (*Prophecy*)\n))");
}
}
class ExactValueTokenFixtureA
{
public $errors;
}
class ExactValueTokenFixtureB extends ExactValueTokenFixtureA
{
public $errors;
public $value = null;
public function __construct($value)
{
$this->value = $value;
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class IdenticalValueTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(42);
}
function it_is_initializable()
{
$this->shouldHaveType('Prophecy\Argument\Token\IdenticalValueToken');
}
function it_scores_11_if_string_value_is_identical_to_argument()
{
$this->beConstructedWith('foo');
$this->scoreArgument('foo')->shouldReturn(11);
}
function it_scores_11_if_boolean_value_is_identical_to_argument()
{
$this->beConstructedWith(false);
$this->scoreArgument(false)->shouldReturn(11);
}
function it_scores_11_if_integer_value_is_identical_to_argument()
{
$this->beConstructedWith(31);
$this->scoreArgument(31)->shouldReturn(11);
}
function it_scores_11_if_float_value_is_identical_to_argument()
{
$this->beConstructedWith(31.12);
$this->scoreArgument(31.12)->shouldReturn(11);
}
function it_scores_11_if_array_value_is_identical_to_argument()
{
$this->beConstructedWith(array('foo' => 'bar'));
$this->scoreArgument(array('foo' => 'bar'))->shouldReturn(11);
}
function it_scores_11_if_object_value_is_identical_to_argument()
{
$object = new \stdClass();
$this->beConstructedWith($object);
$this->scoreArgument($object)->shouldReturn(11);
}
function it_scores_false_if_value_is_not_identical_to_argument()
{
$this->beConstructedWith(new \stdClass());
$this->scoreArgument('foo')->shouldReturn(false);
}
function it_scores_false_if_object_value_is_not_the_same_instance_than_argument()
{
$this->beConstructedWith(new \stdClass());
$this->scoreArgument(new \stdClass())->shouldReturn(false);
}
function it_scores_false_if_integer_value_is_not_identical_to_boolean_argument()
{
$this->beConstructedWith(1);
$this->scoreArgument(true)->shouldReturn(false);
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_generates_proper_string_representation_for_integer()
{
$this->beConstructedWith(42);
$this->__toString()->shouldReturn('identical(42)');
}
function it_generates_proper_string_representation_for_string()
{
$this->beConstructedWith('some string');
$this->__toString()->shouldReturn('identical("some string")');
}
function it_generates_single_line_representation_for_multiline_string()
{
$this->beConstructedWith("some\nstring");
$this->__toString()->shouldReturn('identical("some\\nstring")');
}
function it_generates_proper_string_representation_for_double()
{
$this->beConstructedWith(42.3);
$this->__toString()->shouldReturn('identical(42.3)');
}
function it_generates_proper_string_representation_for_boolean_true()
{
$this->beConstructedWith(true);
$this->__toString()->shouldReturn('identical(true)');
}
function it_generates_proper_string_representation_for_boolean_false()
{
$this->beConstructedWith(false);
$this->__toString()->shouldReturn('identical(false)');
}
function it_generates_proper_string_representation_for_null()
{
$this->beConstructedWith(null);
$this->__toString()->shouldReturn('identical(null)');
}
function it_generates_proper_string_representation_for_empty_array()
{
$this->beConstructedWith(array());
$this->__toString()->shouldReturn('identical([])');
}
function it_generates_proper_string_representation_for_array()
{
$this->beConstructedWith(array('zet', 42));
$this->__toString()->shouldReturn('identical(["zet", 42])');
}
function it_generates_proper_string_representation_for_resource()
{
$resource = fopen(__FILE__, 'r');
$this->beConstructedWith($resource);
$this->__toString()->shouldReturn('identical(stream:'.$resource.')');
}
function it_generates_proper_string_representation_for_object($object)
{
$objHash = sprintf('%s:%s',
get_class($object->getWrappedObject()),
spl_object_hash($object->getWrappedObject())
);
$this->beConstructedWith($object);
$this->__toString()->shouldReturn("identical($objHash Object (\n 'objectProphecy' => Prophecy\Prophecy\ObjectProphecy Object (*Prophecy*)\n))");
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class LogicalAndTokenSpec extends ObjectBehavior
{
function it_implements_TokenInterface()
{
$this->beConstructedWith(array());
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->beConstructedWith(array());
$this->shouldNotBeLast();
}
function it_generates_string_representation_from_all_tokens_imploded($token1, $token2, $token3)
{
$token1->__toString()->willReturn('token_1');
$token2->__toString()->willReturn('token_2');
$token3->__toString()->willReturn('token_3');
$this->beConstructedWith(array($token1, $token2, $token3));
$this->__toString()->shouldReturn('bool(token_1 AND token_2 AND token_3)');
}
function it_wraps_non_token_arguments_into_ExactValueToken()
{
$this->beConstructedWith(array(15, '1985'));
$this->__toString()->shouldReturn("bool(exact(15) AND exact(\"1985\"))");
}
function it_scores_the_maximum_score_from_all_scores_returned_by_tokens($token1, $token2)
{
$token1->scoreArgument(1)->willReturn(10);
$token2->scoreArgument(1)->willReturn(5);
$this->beConstructedWith(array($token1, $token2));
$this->scoreArgument(1)->shouldReturn(10);
}
function it_does_not_score_if_there_are_no_arguments_or_tokens()
{
$this->beConstructedWith(array());
$this->scoreArgument('any')->shouldReturn(false);
}
function it_does_not_score_if_either_of_tokens_does_not_score($token1, $token2)
{
$token1->scoreArgument(1)->willReturn(10);
$token1->scoreArgument(2)->willReturn(false);
$token2->scoreArgument(1)->willReturn(false);
$token2->scoreArgument(2)->willReturn(10);
$this->beConstructedWith(array($token1, $token2));
$this->scoreArgument(1)->shouldReturn(false);
$this->scoreArgument(2)->shouldReturn(false);
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument\Token\TokenInterface;
class LogicalNotTokenSpec extends ObjectBehavior
{
function let($token)
{
$this->beConstructedWith($token);
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_holds_originating_token($token)
{
$this->getOriginatingToken()->shouldReturn($token);
}
function it_has_simple_string_representation($token)
{
$token->__toString()->willReturn('value');
$this->__toString()->shouldBe('not(value)');
}
function it_wraps_non_token_argument_into_ExactValueToken()
{
$this->beConstructedWith(5);
$token = $this->getOriginatingToken();
$token->shouldhaveType('Prophecy\Argument\Token\ExactValueToken');
$token->getValue()->shouldBe(5);
}
function it_scores_4_if_preset_token_does_not_match_the_argument($token)
{
$token->scoreArgument('argument')->willReturn(false);
$this->scoreArgument('argument')->shouldBe(4);
}
function it_does_not_score_if_preset_token_matches_argument($token)
{
$token->scoreArgument('argument')->willReturn(5);
$this->scoreArgument('argument')->shouldBe(false);
}
function it_is_last_if_preset_token_is_last($token)
{
$token->isLast()->willReturn(true);
$this->shouldBeLast();
}
function it_is_not_last_if_preset_token_is_not_last($token)
{
$token->isLast()->willReturn(false);
$this->shouldNotBeLast();
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class ObjectStateTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('getName', 'stdClass');
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_scores_8_if_argument_object_has_specific_method_state($reflection)
{
$reflection->getName()->willReturn('stdClass');
$this->scoreArgument($reflection)->shouldReturn(8);
}
function it_scores_8_if_argument_object_has_specific_property_state($class)
{
$class->getName = 'stdClass';
$this->scoreArgument($class)->shouldReturn(8);
}
function it_does_not_score_if_argument_method_state_does_not_match()
{
$value = new ObjectStateTokenFixtureB('ABC');
$value2 = new ObjectStateTokenFixtureB('CBA');
$this->beConstructedWith('getSelf', $value);
$this->scoreArgument($value2)->shouldReturn(false);
}
function it_does_not_score_if_argument_property_state_does_not_match($class)
{
$class->getName = 'SplFileInfo';
$this->scoreArgument($class)->shouldReturn(false);
}
function it_does_not_score_if_argument_object_does_not_have_method_or_property($class)
{
$this->scoreArgument($class)->shouldReturn(false);
}
function it_does_not_score_if_argument_is_not_object()
{
$this->scoreArgument(42)->shouldReturn(false);
}
function it_has_simple_string_representation()
{
$this->__toString()->shouldReturn('state(getName(), "stdClass")');
}
}
class ObjectStateTokenFixtureA
{
public $errors;
}
class ObjectStateTokenFixtureB extends ObjectStateTokenFixtureA
{
public $errors;
public $value = null;
public function __construct($value)
{
$this->value = $value;
}
public function getSelf()
{
return $this;
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class StringContainsTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('a substring');
}
function it_is_initializable()
{
$this->shouldHaveType('Prophecy\Argument\Token\StringContainsToken');
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_holds_value()
{
$this->getValue()->shouldReturn('a substring');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_scores_6_if_the_argument_contains_the_value()
{
$this->scoreArgument('Argument containing a substring')->shouldReturn(6);
}
function it_does_not_score_if_the_argument_does_not_contain_the_value()
{
$this->scoreArgument('Argument will not match')->shouldReturn(false);
}
function its_string_representation_shows_substring()
{
$this->__toString()->shouldReturn('contains("a substring")');
}
}
<?php
namespace spec\Prophecy\Argument\Token;
use PhpSpec\ObjectBehavior;
class TypeTokenSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('integer');
}
function it_implements_TokenInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
}
function it_is_not_last()
{
$this->shouldNotBeLast();
}
function it_scores_5_if_argument_matches_simple_type()
{
$this->beConstructedWith('integer');
$this->scoreArgument(42)->shouldReturn(5);
}
function it_does_not_scores_if_argument_does_not_match_simple_type()
{
$this->beConstructedWith('integer');
$this->scoreArgument(42.0)->shouldReturn(false);
}
function it_scores_5_if_argument_is_an_instance_of_specified_class($object)
{
$this->beConstructedWith('ReflectionClass');
$this->scoreArgument($object)->shouldReturn(5);
}
function it_has_simple_string_representation()
{
$this->__toString()->shouldReturn('type(integer)');
}
function it_scores_5_if_argument_is_an_instance_of_specified_interface($interface)
{
$this->beConstructedWith('Prophecy\Argument\Token\TokenInterface');
$this->scoreArgument($interface)->shouldReturn(5);
}
}
<?php
namespace spec\Prophecy;
use PhpSpec\ObjectBehavior;
class ArgumentSpec extends ObjectBehavior
{
function it_has_a_shortcut_for_exact_argument_token()
{
$token = $this->exact(42);
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ExactValueToken');
$token->getValue()->shouldReturn(42);
}
function it_has_a_shortcut_for_any_argument_token()
{
$token = $this->any();
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\AnyValueToken');
}
function it_has_a_shortcut_for_multiple_arguments_token()
{
$token = $this->cetera();
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\AnyValuesToken');
}
function it_has_a_shortcut_for_type_token()
{
$token = $this->type('integer');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\TypeToken');
}
function it_has_a_shortcut_for_callback_token()
{
$token = $this->that('get_class');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\CallbackToken');
}
function it_has_a_shortcut_for_object_state_token()
{
$token = $this->which('getName', 'everzet');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ObjectStateToken');
}
function it_has_a_shortcut_for_logical_and_token()
{
$token = $this->allOf('integer', 5);
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\LogicalAndToken');
}
function it_has_a_shortcut_for_array_count_token()
{
$token = $this->size(5);
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayCountToken');
}
function it_has_a_shortcut_for_array_entry_token()
{
$token = $this->withEntry('key', 'value');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEntryToken');
}
function it_has_a_shortcut_for_array_every_entry_token()
{
$token = $this->withEveryEntry('value');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEveryEntryToken');
}
function it_has_a_shortcut_for_identical_value_token()
{
$token = $this->is('value');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\IdenticalValueToken');
}
function it_has_a_shortcut_for_array_entry_token_matching_any_key()
{
$token = $this->containing('value');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEntryToken');
$token->getKey()->shouldHaveType('Prophecy\Argument\Token\AnyValueToken');
}
function it_has_a_shortcut_for_array_entry_token_matching_any_value()
{
$token = $this->withKey('key');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEntryToken');
$token->getValue()->shouldHaveType('Prophecy\Argument\Token\AnyValueToken');
}
function it_has_a_shortcut_for_logical_not_token()
{
$token = $this->not('kagux');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\LogicalNotToken');
}
function it_has_a_shortcut_for_string_contains_token()
{
$token = $this->containingString('string');
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\StringContainsToken');
}
function it_has_a_shortcut_for_approximate_token()
{
$token = $this->approximate(10);
$token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ApproximateValueToken');
}
}
<?php
namespace spec\Prophecy\Call;
use PhpSpec\ObjectBehavior;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Argument\ArgumentsWildcard;
class CallCenterSpec extends ObjectBehavior
{
function let($objectProphecy)
{
}
function it_records_calls_made_through_makeCall_method($objectProphecy, $wildcard)
{
$wildcard->scoreArguments(array(5, 2, 3))->willReturn(10);
$objectProphecy->getMethodProphecies()->willReturn(array());
$this->makeCall($objectProphecy, 'setValues', array(5, 2, 3));
$calls = $this->findCalls('setValues', $wildcard);
$calls->shouldHaveCount(1);
$calls[0]->shouldBeAnInstanceOf('Prophecy\Call\Call');
$calls[0]->getMethodName()->shouldReturn('setValues');
$calls[0]->getArguments()->shouldReturn(array(5, 2, 3));
$calls[0]->getReturnValue()->shouldReturn(null);
}
function it_returns_null_for_any_call_through_makeCall_if_no_method_prophecies_added(
$objectProphecy
)
{
$objectProphecy->getMethodProphecies()->willReturn(array());
$this->makeCall($objectProphecy, 'setValues', array(5, 2, 3))->shouldReturn(null);
}
function it_executes_promise_of_method_prophecy_that_matches_signature_passed_to_makeCall(
$objectProphecy, $method1, $method2, $method3, $arguments1, $arguments2, $arguments3,
$promise
)
{
$method1->getMethodName()->willReturn('getName');
$method1->getArgumentsWildcard()->willReturn($arguments1);
$arguments1->scoreArguments(array('world', 'everything'))->willReturn(false);
$method2->getMethodName()->willReturn('setTitle');
$method2->getArgumentsWildcard()->willReturn($arguments2);
$arguments2->scoreArguments(array('world', 'everything'))->willReturn(false);
$method3->getMethodName()->willReturn('getName');
$method3->getArgumentsWildcard()->willReturn($arguments3);
$method3->getPromise()->willReturn($promise);
$arguments3->scoreArguments(array('world', 'everything'))->willReturn(200);
$objectProphecy->getMethodProphecies()->willReturn(array(
'method1' => array($method1),
'method2' => array($method2, $method3)
));
$objectProphecy->getMethodProphecies('getName')->willReturn(array($method1, $method3));
$objectProphecy->reveal()->willReturn(new \stdClass());
$promise->execute(array('world', 'everything'), $objectProphecy->getWrappedObject(), $method3)->willReturn(42);
$this->makeCall($objectProphecy, 'getName', array('world', 'everything'))->shouldReturn(42);
$calls = $this->findCalls('getName', $arguments3);
$calls->shouldHaveCount(1);
$calls[0]->getReturnValue()->shouldReturn(42);
}
function it_executes_promise_of_method_prophecy_that_matches_with_highest_score_to_makeCall(
$objectProphecy, $method1, $method2, $method3, $arguments1, $arguments2, $arguments3,
$promise
)
{
$method1->getMethodName()->willReturn('getName');
$method1->getArgumentsWildcard()->willReturn($arguments1);
$arguments1->scoreArguments(array('world', 'everything'))->willReturn(50);
$method2->getMethodName()->willReturn('getName');
$method2->getArgumentsWildcard()->willReturn($arguments2);
$method2->getPromise()->willReturn($promise);
$arguments2->scoreArguments(array('world', 'everything'))->willReturn(300);
$method3->getMethodName()->willReturn('getName');
$method3->getArgumentsWildcard()->willReturn($arguments3);
$arguments3->scoreArguments(array('world', 'everything'))->willReturn(200);
$objectProphecy->getMethodProphecies()->willReturn(array(
'method1' => array($method1),
'method2' => array($method2, $method3)
));
$objectProphecy->getMethodProphecies('getName')->willReturn(array(
$method1, $method2, $method3
));
$objectProphecy->reveal()->willReturn(new \stdClass());
$promise->execute(array('world', 'everything'), $objectProphecy->getWrappedObject(), $method2)
->willReturn('second');
$this->makeCall($objectProphecy, 'getName', array('world', 'everything'))
->shouldReturn('second');
}
function it_throws_exception_if_call_does_not_match_any_of_defined_method_prophecies(
$objectProphecy, $method, $arguments
)
{
$method->getMethodName()->willReturn('getName');
$method->getArgumentsWildcard()->willReturn($arguments);
$arguments->scoreArguments(array('world', 'everything'))->willReturn(false);
$arguments->__toString()->willReturn('arg1, arg2');
$objectProphecy->getMethodProphecies()->willReturn(array('method1' => array($method)));
$objectProphecy->getMethodProphecies('getName')->willReturn(array($method));
$this->shouldThrow('Prophecy\Exception\Call\UnexpectedCallException')
->duringMakeCall($objectProphecy, 'getName', array('world', 'everything'));
}
function it_returns_null_if_method_prophecy_that_matches_makeCall_arguments_has_no_promise(
$objectProphecy, $method, $arguments
)
{
$method->getMethodName()->willReturn('getName');
$method->getArgumentsWildcard()->willReturn($arguments);
$method->getPromise()->willReturn(null);
$arguments->scoreArguments(array('world', 'everything'))->willReturn(100);
$objectProphecy->getMethodProphecies()->willReturn(array($method));
$objectProphecy->getMethodProphecies('getName')->willReturn(array($method));
$this->makeCall($objectProphecy, 'getName', array('world', 'everything'))
->shouldReturn(null);
}
function it_finds_recorded_calls_by_a_method_name_and_arguments_wildcard(
$objectProphecy, $wildcard
)
{
$objectProphecy->getMethodProphecies()->willReturn(array());
$this->makeCall($objectProphecy, 'getName', array('world'));
$this->makeCall($objectProphecy, 'getName', array('everything'));
$this->makeCall($objectProphecy, 'setName', array(42));
$wildcard->scoreArguments(array('world'))->willReturn(false);
$wildcard->scoreArguments(array('everything'))->willReturn(10);
$calls = $this->findCalls('getName', $wildcard);
$calls->shouldHaveCount(1);
$calls[0]->getMethodName()->shouldReturn('getName');
$calls[0]->getArguments()->shouldReturn(array('everything'));
}
}
<?php
namespace spec\Prophecy\Call;
use PhpSpec\ObjectBehavior;
class CallSpec extends ObjectBehavior
{
function let($exception)
{
$this->beConstructedWith('setValues', array(5, 2), 42, $exception, 'some_file.php', 23);
}
function it_exposes_method_name_through_getter()
{
$this->getMethodName()->shouldReturn('setValues');
}
function it_exposes_arguments_through_getter()
{
$this->getArguments()->shouldReturn(array(5, 2));
}
function it_exposes_return_value_through_getter()
{
$this->getReturnValue()->shouldReturn(42);
}
function it_exposes_exception_through_getter($exception)
{
$this->getException()->shouldReturn($exception);
}
function it_exposes_file_and_line_through_getter()
{
$this->getFile()->shouldReturn('some_file.php');
$this->getLine()->shouldReturn(23);
}
function it_returns_shortpath_to_callPlace()
{
$this->getCallPlace()->shouldReturn('some_file.php:23');
}
function it_returns_unknown_as_callPlace_if_no_file_or_line_provided()
{
$this->beConstructedWith('setValues', array(), 0, null, null, null);
$this->getCallPlace()->shouldReturn('unknown');
}
}
<?php
namespace spec\Prophecy\Comparator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ClosureComparatorSpec extends ObjectBehavior
{
function it_is_comparator()
{
$this->shouldHaveType('SebastianBergmann\Comparator\Comparator');
}
function it_accepts_only_closures()
{
$this->accepts(123, 321)->shouldReturn(false);
$this->accepts('string', 'string')->shouldReturn(false);
$this->accepts(false, true)->shouldReturn(false);
$this->accepts(true, false)->shouldReturn(false);
$this->accepts((object)array(), (object)array())->shouldReturn(false);
$this->accepts(function(){}, (object)array())->shouldReturn(false);
$this->accepts(function(){}, (object)array())->shouldReturn(false);
$this->accepts(function(){}, function(){})->shouldReturn(true);
}
function it_asserts_that_all_closures_are_different()
{
$this->shouldThrow()->duringAssertEquals(function(){}, function(){});
}
function it_asserts_that_all_closures_are_different_even_if_its_the_same_closure()
{
$closure = function(){};
$this->shouldThrow()->duringAssertEquals($closure, $closure);
}
}
<?php
namespace spec\Prophecy\Comparator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class FactorySpec extends ObjectBehavior
{
function it_extends_Sebastian_Comparator_Factory()
{
$this->shouldHaveType('SebastianBergmann\Comparator\Factory');
}
function it_should_have_ClosureComparator_registered()
{
$comparator = $this->getInstance()->getComparatorFor(function(){}, function(){});
$comparator->shouldHaveType('Prophecy\Comparator\ClosureComparator');
}
}
<?php
namespace spec\Prophecy\Comparator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Prophecy\Prophet;
class ProphecyComparatorSpec extends ObjectBehavior
{
function it_is_a_comparator()
{
$this->shouldHaveType('SebastianBergmann\Comparator\ObjectComparator');
}
function it_accepts_only_prophecy_objects()
{
$this->accepts(123, 321)->shouldReturn(false);
$this->accepts('string', 'string')->shouldReturn(false);
$this->accepts(false, true)->shouldReturn(false);
$this->accepts(true, false)->shouldReturn(false);
$this->accepts((object)array(), (object)array())->shouldReturn(false);
$this->accepts(function(){}, (object)array())->shouldReturn(false);
$this->accepts(function(){}, function(){})->shouldReturn(false);
$prophet = new Prophet();
$prophecy = $prophet->prophesize('Prophecy\Prophecy\ObjectProphecy');
$this->accepts($prophecy, $prophecy)->shouldReturn(true);
}
function it_asserts_that_an_object_is_equal_to_its_revealed_prophecy()
{
$prophet = new Prophet();
$prophecy = $prophet->prophesize('Prophecy\Prophecy\ObjectProphecy');
$this->shouldNotThrow()->duringAssertEquals($prophecy->reveal(), $prophecy);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DisableConstructorPatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function its_priority_is_100()
{
$this->getPriority()->shouldReturn(100);
}
function it_supports_anything($node)
{
$this->supports($node)->shouldReturn(true);
}
function it_makes_all_constructor_arguments_optional($class, $method, $arg1, $arg2)
{
$class->hasMethod('__construct')->willReturn(true);
$class->getMethod('__construct')->willReturn($method);
$method->getArguments()->willReturn(array($arg1, $arg2));
$arg1->setDefault(null)->shouldBeCalled();
$arg2->setDefault(null)->shouldBeCalled();
$method->setCode(Argument::type('string'))->shouldBeCalled();
$this->apply($class);
}
function it_creates_new_constructor_if_object_has_none($class)
{
$class->hasMethod('__construct')->willReturn(false);
$class->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))
->shouldBeCalled();
$this->apply($class);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class HhvmExceptionPatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function its_priority_is_minus_50()
{
$this->getPriority()->shouldReturn(-50);
}
function it_uses_parent_code_for_setTraceOptions($node, $method, $getterMethod)
{
$node->hasMethod('setTraceOptions')->willReturn(true);
$node->getMethod('setTraceOptions')->willReturn($method);
$node->hasMethod('getTraceOptions')->willReturn(true);
$node->getMethod('getTraceOptions')->willReturn($getterMethod);
$method->useParentCode()->shouldBeCalled();
$getterMethod->useParentCode()->shouldBeCalled();
$this->apply($node);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Prophecy\Doubler\Generator\Node\MethodNode;
class KeywordPatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function its_priority_is_49()
{
$this->getPriority()->shouldReturn(49);
}
function it_will_remove_echo_and_eval_methods($node, $method1, $method2, $method3)
{
$node->removeMethod('eval')->shouldBeCalled();
$node->removeMethod('echo')->shouldBeCalled();
$method1->getName()->willReturn('echo');
$method2->getName()->willReturn('eval');
$method3->getName()->willReturn('notKeyword');
$node->getMethods()->willReturn(array(
'echo' => $method1,
'eval' => $method2,
'notKeyword' => $method3,
));
$this->apply($node);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Prophecy\Doubler\Generator\Node\MethodNode;
class MagicCallPatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function it_supports_anything($node)
{
$this->supports($node)->shouldReturn(true);
}
function it_discovers_api_using_phpdoc($node)
{
$node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApi');
$node->addMethod(new MethodNode('undefinedMethod'))->shouldBeCalled();
$this->apply($node);
}
function it_ignores_existing_methods($node)
{
$node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiExtended');
$node->addMethod(new MethodNode('undefinedMethod'))->shouldBeCalled();
$node->addMethod(new MethodNode('definedMethod'))->shouldNotBeCalled();
$this->apply($node);
}
function it_ignores_empty_methods_from_phpdoc($node)
{
$node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiInvalidMethodDefinition');
$node->addMethod(new MethodNode(''))->shouldNotBeCalled();
$this->apply($node);
}
function it_discovers_api_using_phpdoc_from_interface($node)
{
$node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiImplemented');
$node->addMethod(new MethodNode('implementedMethod'))->shouldBeCalled();
$this->apply($node);
}
function it_has_50_priority()
{
$this->getPriority()->shouldReturn(50);
}
}
class MagicalApi
{
public function definedMethod()
{
}
}
class MagicalApiInvalidMethodDefinition
{
}
class MagicalApiExtended extends MagicalApi
{
}
class MagicalApiImplemented implements MagicalApiInterface
{
}
interface MagicalApiInterface
{
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ProphecySubjectPatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function it_has_priority_of_0()
{
$this->getPriority()->shouldReturn(0);
}
function it_supports_any_class($node)
{
$this->supports($node)->shouldReturn(true);
}
function it_forces_class_to_implement_ProphecySubjectInterface($node)
{
$node->addInterface('Prophecy\Prophecy\ProphecySubjectInterface')->shouldBeCalled();
$node->addProperty('objectProphecy', 'private')->willReturn(null);
$node->getMethods()->willReturn(array());
$node->hasMethod(Argument::any())->willReturn(false);
$node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))->willReturn(null);
$node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))->willReturn(null);
$this->apply($node);
}
function it_forces_all_class_methods_except_constructor_to_proxy_calls_into_prophecy_makeCall(
$node, $constructor, $method1, $method2, $method3
)
{
$node->addInterface('Prophecy\Prophecy\ProphecySubjectInterface')->willReturn(null);
$node->addProperty('objectProphecy', 'private')->willReturn(null);
$node->hasMethod(Argument::any())->willReturn(false);
$node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))->willReturn(null);
$node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))->willReturn(null);
$constructor->getName()->willReturn('__construct');
$method1->getName()->willReturn('method1');
$method2->getName()->willReturn('method2');
$method3->getName()->willReturn('method3');
$node->getMethods()->willReturn(array(
'method1' => $method1,
'method2' => $method2,
'method3' => $method3,
));
$constructor->setCode(Argument::any())->shouldNotBeCalled();
$method1->setCode('return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());')
->shouldBeCalled();
$method2->setCode('return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());')
->shouldBeCalled();
$method3->setCode('return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());')
->shouldBeCalled();
$this->apply($node);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ReflectionClassNewInstancePatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function its_priority_is_50()
{
$this->getPriority()->shouldReturn(50);
}
function it_supports_ReflectionClass_only($reflectionClassNode, $anotherClassNode)
{
$reflectionClassNode->getParentClass()->willReturn('ReflectionClass');
$anotherClassNode->getParentClass()->willReturn('stdClass');
$this->supports($reflectionClassNode)->shouldReturn(true);
$this->supports($anotherClassNode)->shouldReturn(false);
}
function it_makes_all_newInstance_arguments_optional($class, $method, $arg1, $arg2)
{
$class->getMethod('newInstance')->willReturn($method);
$method->getArguments()->willReturn(array($arg1));
$arg1->setDefault(null)->shouldBeCalled();
$this->apply($class);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class SplFileInfoPatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function its_priority_is_50()
{
$this->getPriority()->shouldReturn(50);
}
function it_does_not_support_nodes_without_parent_class($node)
{
$node->getParentClass()->willReturn('stdClass');
$this->supports($node)->shouldReturn(false);
}
function it_supports_nodes_with_SplFileInfo_as_parent_class($node)
{
$node->getParentClass()->willReturn('SplFileInfo');
$this->supports($node)->shouldReturn(true);
}
function it_supports_nodes_with_derivative_of_SplFileInfo_as_parent_class($node)
{
$node->getParentClass()->willReturn('SplFileInfo');
$this->supports($node)->shouldReturn(true);
}
function it_adds_a_method_to_node_if_not_exists($node)
{
$node->hasMethod('__construct')->willReturn(false);
$node->addMethod(Argument::any())->shouldBeCalled();
$node->getParentClass()->shouldBeCalled();
$this->apply($node);
}
function it_updates_existing_method_if_found($node, $method)
{
$node->hasMethod('__construct')->willReturn(true);
$node->getMethod('__construct')->willReturn($method);
$node->getParentClass()->shouldBeCalled();
$method->useParentCode()->shouldBeCalled();
$this->apply($node);
}
function it_should_not_supply_a_file_for_a_directory_iterator($node, $method)
{
$node->hasMethod('__construct')->willReturn(true);
$node->getMethod('__construct')->willReturn($method);
$node->getParentClass()->willReturn('DirectoryIterator');
$method->setCode(Argument::that(function($value) {
return strpos($value, '.php') === false;
}))->shouldBeCalled();
$this->apply($node);
}
function it_should_supply_a_file_for_a_spl_file_object($node, $method)
{
$node->hasMethod('__construct')->willReturn(true);
$node->getMethod('__construct')->willReturn($method);
$node->getParentClass()->willReturn('SplFileObject');
$method->setCode(Argument::that(function($value) {
return strpos($value, '.php') !== false;
}))->shouldBeCalled();
$this->apply($node);
}
}
<?php
namespace spec\Prophecy\Doubler\ClassPatch;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class TraversablePatchSpec extends ObjectBehavior
{
function it_is_a_patch()
{
$this->shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface');
}
function it_supports_class_that_implements_only_Traversable($node)
{
$node->getInterfaces()->willReturn(array('Traversable'));
$this->supports($node)->shouldReturn(true);
}
function it_does_not_support_class_that_implements_Iterator($node)
{
$node->getInterfaces()->willReturn(array('Traversable', 'Iterator'));
$this->supports($node)->shouldReturn(false);
}
function it_does_not_support_class_that_implements_IteratorAggregate($node)
{
$node->getInterfaces()->willReturn(array('Traversable', 'IteratorAggregate'));
$this->supports($node)->shouldReturn(false);
}
function it_has_100_priority()
{
$this->getPriority()->shouldReturn(100);
}
function it_forces_node_to_implement_IteratorAggregate($node)
{
$node->addInterface('Iterator')->shouldBeCalled();
$node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))->willReturn(null);
$this->apply($node);
}
}
<?php
namespace spec\Prophecy\Doubler;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DoublerSpec extends ObjectBehavior
{
function let($mirror, $creator, $namer)
{
$this->beConstructedWith($mirror, $creator, $namer);
}
function it_does_not_have_patches_by_default()
{
$this->getClassPatches()->shouldHaveCount(0);
}
function its_registerClassPatch_adds_a_patch_to_the_doubler($patch)
{
$this->registerClassPatch($patch);
$this->getClassPatches()->shouldReturn(array($patch));
}
function its_getClassPatches_sorts_patches_by_priority($alt1, $alt2, $alt3, $alt4)
{
$alt1->getPriority()->willReturn(2);
$alt2->getPriority()->willReturn(50);
$alt3->getPriority()->willReturn(10);
$alt4->getPriority()->willReturn(0);
$this->registerClassPatch($alt1);
$this->registerClassPatch($alt2);
$this->registerClassPatch($alt3);
$this->registerClassPatch($alt4);
$this->getClassPatches()->shouldReturn(array($alt2, $alt3, $alt1, $alt4));
}
function its_double_mirrors_alterates_and_instantiates_provided_class(
$mirror, $creator, $namer, $alt1, $alt2, $class, $interface1, $interface2, $node
)
{
$mirror->reflect($class, array($interface1, $interface2))->willReturn($node);
$alt1->supports($node)->willReturn(true);
$alt2->supports($node)->willReturn(false);
$alt1->getPriority()->willReturn(1);
$alt2->getPriority()->willReturn(2);
$namer->name($class, array($interface1, $interface2))->willReturn('SplStack');
$class->getName()->willReturn('stdClass');
$interface1->getName()->willReturn('ArrayAccess');
$interface2->getName()->willReturn('Iterator');
$alt1->apply($node)->shouldBeCalled();
$alt2->apply($node)->shouldNotBeCalled();
$creator->create('SplStack', $node)->shouldBeCalled();
$this->registerClassPatch($alt1);
$this->registerClassPatch($alt2);
$this->double($class, array($interface1, $interface2))
->shouldReturnAnInstanceOf('SplStack');
}
function it_double_instantiates_a_class_with_constructor_argument($mirror, $class, $node, $namer)
{
$class->getName()->willReturn('ReflectionClass');
$mirror->reflect($class, array())->willReturn($node);
$namer->name($class, array())->willReturn('ReflectionClass');
$double = $this->double($class, array(), array('stdClass'));
$double->shouldBeAnInstanceOf('ReflectionClass');
$double->getName()->shouldReturn('stdClass');
}
function it_can_instantiate_class_with_final_constructor($mirror, $class, $node, $namer)
{
$class->getName()->willReturn('spec\Prophecy\Doubler\WithFinalConstructor');
$mirror->reflect($class, array())->willReturn($node);
$namer->name($class, array())->willReturn('spec\Prophecy\Doubler\WithFinalConstructor');
$double = $this->double($class, array());
$double->shouldBeAnInstanceOf('spec\Prophecy\Doubler\WithFinalConstructor');
}
}
class WithFinalConstructor
{
final public function __construct() {}
}
<?php
namespace spec\Prophecy\Doubler\Generator;
use PhpSpec\ObjectBehavior;
class ClassCodeGeneratorSpec extends ObjectBehavior
{
function it_generates_proper_php_code_for_specific_ClassNode(
$class, $method1, $method2, $method3, $argument11, $argument12, $argument21, $argument31
)
{
$class->getParentClass()->willReturn('RuntimeException');
$class->getInterfaces()->willReturn(array(
'Prophecy\Doubler\Generator\MirroredInterface', 'ArrayAccess', 'ArrayIterator'
));
$class->getProperties()->willReturn(array('name' => 'public', 'email' => 'private'));
$class->getMethods()->willReturn(array($method1, $method2, $method3));
$method1->getName()->willReturn('getName');
$method1->getVisibility()->willReturn('public');
$method1->returnsReference()->willReturn(false);
$method1->isStatic()->willReturn(true);
$method1->getArguments()->willReturn(array($argument11, $argument12));
$method1->hasReturnType()->willReturn(true);
$method1->getReturnType()->willReturn('string');
$method1->getCode()->willReturn('return $this->name;');
$method2->getName()->willReturn('getEmail');
$method2->getVisibility()->willReturn('protected');
$method2->returnsReference()->willReturn(false);
$method2->isStatic()->willReturn(false);
$method2->getArguments()->willReturn(array($argument21));
$method2->hasReturnType()->willReturn(false);
$method2->getCode()->willReturn('return $this->email;');
$method3->getName()->willReturn('getRefValue');
$method3->getVisibility()->willReturn('public');
$method3->returnsReference()->willReturn(true);
$method3->isStatic()->willReturn(false);
$method3->getArguments()->willReturn(array($argument31));
$method3->hasReturnType()->willReturn(false);
$method3->getCode()->willReturn('return $this->refValue;');
$argument11->getName()->willReturn('fullname');
$argument11->getTypeHint()->willReturn('array');
$argument11->isOptional()->willReturn(true);
$argument11->getDefault()->willReturn(null);
$argument11->isPassedByReference()->willReturn(false);
$argument11->isVariadic()->willReturn(false);
$argument12->getName()->willReturn('class');
$argument12->getTypeHint()->willReturn('ReflectionClass');
$argument12->isOptional()->willReturn(false);
$argument12->isPassedByReference()->willReturn(false);
$argument12->isVariadic()->willReturn(false);
$argument21->getName()->willReturn('default');
$argument21->getTypeHint()->willReturn('string');
$argument21->isOptional()->willReturn(true);
$argument21->getDefault()->willReturn('ever.zet@gmail.com');
$argument21->isPassedByReference()->willReturn(false);
$argument21->isVariadic()->willReturn(false);
$argument31->getName()->willReturn('refValue');
$argument31->getTypeHint()->willReturn(null);
$argument31->isOptional()->willReturn(false);
$argument31->getDefault()->willReturn();
$argument31->isPassedByReference()->willReturn(false);
$argument31->isVariadic()->willReturn(false);
$code = $this->generate('CustomClass', $class);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$expected = <<<'PHP'
namespace {
class CustomClass extends \RuntimeException implements \Prophecy\Doubler\Generator\MirroredInterface, \ArrayAccess, \ArrayIterator {
public $name;
private $email;
public static function getName(array $fullname = NULL, \ReflectionClass $class): string {
return $this->name;
}
protected function getEmail(string $default = 'ever.zet@gmail.com') {
return $this->email;
}
public function &getRefValue( $refValue) {
return $this->refValue;
}
}
}
PHP;
} else {
$expected = <<<'PHP'
namespace {
class CustomClass extends \RuntimeException implements \Prophecy\Doubler\Generator\MirroredInterface, \ArrayAccess, \ArrayIterator {
public $name;
private $email;
public static function getName(array $fullname = NULL, \ReflectionClass $class) {
return $this->name;
}
protected function getEmail(\string $default = 'ever.zet@gmail.com') {
return $this->email;
}
public function &getRefValue( $refValue) {
return $this->refValue;
}
}
}
PHP;
}
$expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n"));
$code->shouldBe($expected);
}
function it_generates_proper_php_code_for_variadics(
$class, $method1, $method2, $method3, $method4, $argument1, $argument2,
$argument3, $argument4
)
{
$class->getParentClass()->willReturn('stdClass');
$class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface'));
$class->getProperties()->willReturn(array());
$class->getMethods()->willReturn(array(
$method1, $method2, $method3, $method4
));
$method1->getName()->willReturn('variadic');
$method1->getVisibility()->willReturn('public');
$method1->returnsReference()->willReturn(false);
$method1->isStatic()->willReturn(false);
$method1->getArguments()->willReturn(array($argument1));
$method1->hasReturnType()->willReturn(false);
$method1->getCode()->willReturn('');
$method2->getName()->willReturn('variadicByRef');
$method2->getVisibility()->willReturn('public');
$method2->returnsReference()->willReturn(false);
$method2->isStatic()->willReturn(false);
$method2->getArguments()->willReturn(array($argument2));
$method2->hasReturnType()->willReturn(false);
$method2->getCode()->willReturn('');
$method3->getName()->willReturn('variadicWithType');
$method3->getVisibility()->willReturn('public');
$method3->returnsReference()->willReturn(false);
$method3->isStatic()->willReturn(false);
$method3->getArguments()->willReturn(array($argument3));
$method3->hasReturnType()->willReturn(false);
$method3->getCode()->willReturn('');
$method4->getName()->willReturn('variadicWithTypeByRef');
$method4->getVisibility()->willReturn('public');
$method4->returnsReference()->willReturn(false);
$method4->isStatic()->willReturn(false);
$method4->getArguments()->willReturn(array($argument4));
$method4->hasReturnType()->willReturn(false);
$method4->getCode()->willReturn('');
$argument1->getName()->willReturn('args');
$argument1->getTypeHint()->willReturn(null);
$argument1->isOptional()->willReturn(false);
$argument1->isPassedByReference()->willReturn(false);
$argument1->isVariadic()->willReturn(true);
$argument2->getName()->willReturn('args');
$argument2->getTypeHint()->willReturn(null);
$argument2->isOptional()->willReturn(false);
$argument2->isPassedByReference()->willReturn(true);
$argument2->isVariadic()->willReturn(true);
$argument3->getName()->willReturn('args');
$argument3->getTypeHint()->willReturn('\ReflectionClass');
$argument3->isOptional()->willReturn(false);
$argument3->isPassedByReference()->willReturn(false);
$argument3->isVariadic()->willReturn(true);
$argument4->getName()->willReturn('args');
$argument4->getTypeHint()->willReturn('\ReflectionClass');
$argument4->isOptional()->willReturn(false);
$argument4->isPassedByReference()->willReturn(true);
$argument4->isVariadic()->willReturn(true);
$code = $this->generate('CustomClass', $class);
$expected = <<<'PHP'
namespace {
class CustomClass extends \stdClass implements \Prophecy\Doubler\Generator\MirroredInterface {
public function variadic( ...$args) {
}
public function variadicByRef( &...$args) {
}
public function variadicWithType(\\ReflectionClass ...$args) {
}
public function variadicWithTypeByRef(\\ReflectionClass &...$args) {
}
}
}
PHP;
$expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n"));
$code->shouldBe($expected);
}
function it_overrides_properly_methods_with_args_passed_by_reference(
$class, $method, $argument
)
{
$class->getParentClass()->willReturn('RuntimeException');
$class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface'));
$class->getProperties()->willReturn(array());
$class->getMethods()->willReturn(array($method));
$method->getName()->willReturn('getName');
$method->getVisibility()->willReturn('public');
$method->isStatic()->willReturn(false);
$method->getArguments()->willReturn(array($argument));
$method->hasReturnType()->willReturn(false);
$method->returnsReference()->willReturn(false);
$method->getCode()->willReturn('return $this->name;');
$argument->getName()->willReturn('fullname');
$argument->getTypeHint()->willReturn('array');
$argument->isOptional()->willReturn(true);
$argument->getDefault()->willReturn(null);
$argument->isPassedByReference()->willReturn(true);
$argument->isVariadic()->willReturn(false);
$code = $this->generate('CustomClass', $class);
$expected =<<<'PHP'
namespace {
class CustomClass extends \RuntimeException implements \Prophecy\Doubler\Generator\MirroredInterface {
public function getName(array &$fullname = NULL) {
return $this->name;
}
}
}
PHP;
$expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n"));
$code->shouldBe($expected);
}
function it_generates_empty_class_for_empty_ClassNode($class)
{
$class->getParentClass()->willReturn('stdClass');
$class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface'));
$class->getProperties()->willReturn(array());
$class->getMethods()->willReturn(array());
$code = $this->generate('CustomClass', $class);
$expected =<<<'PHP'
namespace {
class CustomClass extends \stdClass implements \Prophecy\Doubler\Generator\MirroredInterface {
}
}
PHP;
$expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n"));
$code->shouldBe($expected);
}
function it_wraps_class_in_namespace_if_it_is_namespaced($class)
{
$class->getParentClass()->willReturn('stdClass');
$class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface'));
$class->getProperties()->willReturn(array());
$class->getMethods()->willReturn(array());
$code = $this->generate('My\Awesome\CustomClass', $class);
$expected =<<<'PHP'
namespace My\Awesome {
class CustomClass extends \stdClass implements \Prophecy\Doubler\Generator\MirroredInterface {
}
}
PHP;
$expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n"));
$code->shouldBe($expected);
}
}
<?php
namespace spec\Prophecy\Doubler\Generator;
use PhpSpec\ObjectBehavior;
class ClassCreatorSpec extends ObjectBehavior
{
function let($generator)
{
$this->beConstructedWith($generator);
}
function it_evaluates_code_generated_by_ClassCodeGenerator($generator, $class)
{
$generator->generate('stdClass', $class)->shouldBeCalled()->willReturn(
'return 42;'
);
$this->create('stdClass', $class)->shouldReturn(42);
}
function it_throws_an_exception_if_class_does_not_exist_after_evaluation($generator, $class)
{
$generator->generate('CustomClass', $class)->shouldBeCalled()->willReturn(
'return 42;'
);
$class->getParentClass()->willReturn('stdClass');
$class->getInterfaces()->willReturn(array('Interface1', 'Interface2'));
$this->shouldThrow('Prophecy\Exception\Doubler\ClassCreatorException')
->duringCreate('CustomClass', $class);
}
}
<?php
namespace spec\Prophecy\Doubler\Generator;
use I\Simply;
use PhpSpec\ObjectBehavior;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
class ClassMirrorSpec extends ObjectBehavior
{
function it_reflects_a_class_by_mirroring_all_its_public_methods(
$class, $parent, $method1, $method2, $method3
)
{
$class->getName()->willReturn('Custom\ClassName');
$class->getParentClass()->willReturn($parent);
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array(
$method1, $method2, $method3
));
$parent->getName()->willReturn('Custom\ParentClassName');
$method1->getDeclaringClass()->willReturn($class);
$method2->getDeclaringClass()->willReturn($class);
$method3->getDeclaringClass()->willReturn($class);
$method1->getName()->willReturn('getName');
$method2->getName()->willReturn('getSelf');
$method3->getName()->willReturn('getParent');
$method1->isFinal()->willReturn(false);
$method2->isFinal()->willReturn(false);
$method3->isFinal()->willReturn(false);
$method1->isProtected()->willReturn(false);
$method2->isProtected()->willReturn(false);
$method3->isProtected()->willReturn(false);
$method1->isStatic()->willReturn(false);
$method2->isStatic()->willReturn(false);
$method3->isStatic()->willReturn(false);
$method1->returnsReference()->willReturn(false);
$method2->returnsReference()->willReturn(false);
$method3->returnsReference()->willReturn(false);
$method1->getParameters()->willReturn(array());
$method2->getParameters()->willReturn(array());
$method3->getParameters()->willReturn(array());
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method1->hasReturnType()->willReturn(true);
$method1->getReturnType()->willReturn('string');
$method2->hasReturnType()->willReturn(true);
$method2->getReturnType()->willReturn('self');
$method3->hasReturnType()->willReturn(true);
$method3->getReturnType()->willReturn('parent');
}
$classNode = $this->reflect($class, array());
$classNode->shouldBeAnInstanceOf('Prophecy\Doubler\Generator\Node\ClassNode');
$classNode->getParentClass()->shouldReturn('Custom\ClassName');
$methodNodes = $classNode->getMethods();
$methodNodes->shouldHaveCount(3);
$classNode->hasMethod('getName')->shouldReturn(true);
$classNode->hasMethod('getSelf')->shouldReturn(true);
$classNode->hasMethod('getParent')->shouldReturn(true);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$classNode->getMethod('getName')->getReturnType()->shouldReturn('string');
$classNode->getMethod('getSelf')->getReturnType()->shouldReturn('\Custom\ClassName');
$classNode->getMethod('getParent')->getReturnType()->shouldReturn('\Custom\ParentClassName');
}
}
function it_changes_argument_names_if_they_are_varying($class, $method, $parameter)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$method->getParameters()->willReturn(array($parameter));
$method->getName()->willReturn('methodName');
$method->isFinal()->willReturn(false);
$method->isProtected()->willReturn(false);
$method->isStatic()->willReturn(false);
$method->returnsReference()->willReturn(false);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method->hasReturnType()->willReturn(false);
}
$parameter->getName()->willReturn('...');
$parameter->isDefaultValueAvailable()->willReturn(true);
$parameter->getDefaultValue()->willReturn(null);
$parameter->isPassedByReference()->willReturn(false);
$parameter->getClass()->willReturn($class);
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$parameter->isVariadic()->willReturn(false);
}
$classNode = $this->reflect($class, array());
$methodNodes = $classNode->getMethods();
$argumentNodes = $methodNodes['methodName']->getArguments();
$argumentNode = $argumentNodes[0];
$argumentNode->getName()->shouldReturn('__dot_dot_dot__');
}
function it_reflects_protected_abstract_methods($class, $method)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array($method));
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array());
$method->isProtected()->willReturn(true);
$method->isStatic()->willReturn(false);
$method->getParameters()->willReturn(array());
$method->getName()->willReturn('innerDetail');
$method->returnsReference()->willReturn(false);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method->hasReturnType()->willReturn(false);
}
$classNode = $this->reflect($class, array());
$classNode->shouldBeAnInstanceOf('Prophecy\Doubler\Generator\Node\ClassNode');
$classNode->getParentClass()->shouldReturn('Custom\ClassName');
$methodNodes = $classNode->getMethods();
$methodNodes->shouldHaveCount(1);
$methodNodes['innerDetail']->getVisibility()->shouldReturn('protected');
}
function it_reflects_public_static_methods($class, $method)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array($method));
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array());
$method->isProtected()->willReturn(true);
$method->isStatic()->willReturn(true);
$method->getParameters()->willReturn(array());
$method->getName()->willReturn('innerDetail');
$method->returnsReference()->willReturn(false);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method->hasReturnType()->willReturn(false);
}
$classNode = $this->reflect($class, array());
$classNode->shouldBeAnInstanceOf('Prophecy\Doubler\Generator\Node\ClassNode');
$classNode->getParentClass()->shouldReturn('Custom\ClassName');
$methodNodes = $classNode->getMethods();
$methodNodes->shouldHaveCount(1);
$methodNodes['innerDetail']->getVisibility()->shouldReturn('protected');
$methodNodes['innerDetail']->isStatic()->shouldReturn(true);
}
function it_reflects_allowed_magic_methods($class, $constructMethod, $destructMethod, $sleepMethod, $wakeupMethod, $toStringMethod, $callMethod, $invokeMethod)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array(
$constructMethod, $destructMethod, $sleepMethod, $wakeupMethod, $toStringMethod, $callMethod, $invokeMethod
));
$constructMethod->getName()->willReturn('__construct');
$destructMethod->getName()->willReturn('__destruct');
$sleepMethod->getName()->willReturn('__sleep');
$wakeupMethod->getName()->willReturn('__wakeup');
$toStringMethod->getName()->willReturn('__toString');
$callMethod->getName()->willReturn('__call');
$invokeMethod->getName()->willReturn('__invoke');
$constructMethod->isFinal()->willReturn(false);
$destructMethod->isFinal()->willReturn(false);
$sleepMethod->isFinal()->willReturn(false);
$wakeupMethod->isFinal()->willReturn(false);
$toStringMethod->isFinal()->willReturn(false);
$callMethod->isFinal()->willReturn(false);
$invokeMethod->isFinal()->willReturn(false);
$constructMethod->isProtected()->willReturn(false);
$destructMethod->isProtected()->willReturn(false);
$sleepMethod->isProtected()->willReturn(false);
$wakeupMethod->isProtected()->willReturn(false);
$toStringMethod->isProtected()->willReturn(false);
$callMethod->isProtected()->willReturn(false);
$invokeMethod->isProtected()->willReturn(false);
$constructMethod->isStatic()->willReturn(false);
$destructMethod->isStatic()->willReturn(false);
$sleepMethod->isStatic()->willReturn(false);
$wakeupMethod->isStatic()->willReturn(false);
$toStringMethod->isStatic()->willReturn(false);
$callMethod->isStatic()->willReturn(false);
$invokeMethod->isStatic()->willReturn(false);
$constructMethod->returnsReference()->willReturn(false);
$destructMethod->returnsReference()->willReturn(false);
$sleepMethod->returnsReference()->willReturn(false);
$wakeupMethod->returnsReference()->willReturn(false);
$toStringMethod->returnsReference()->willReturn(false);
$callMethod->returnsReference()->willReturn(false);
$invokeMethod->returnsReference()->willReturn(false);
$constructMethod->getParameters()->willReturn(array());
$destructMethod->getParameters()->willReturn(array());
$sleepMethod->getParameters()->willReturn(array());
$wakeupMethod->getParameters()->willReturn(array());
$toStringMethod->getParameters()->willReturn(array());
$callMethod->getParameters()->willReturn(array());
$invokeMethod->getParameters()->willReturn(array());
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$constructMethod->hasReturnType()->willReturn(false);
$destructMethod->hasReturnType()->willReturn(false);
$sleepMethod->hasReturnType()->willReturn(false);
$wakeupMethod->hasReturnType()->willReturn(false);
$toStringMethod->hasReturnType()->willReturn(false);
$callMethod->hasReturnType()->willReturn(false);
$invokeMethod->hasReturnType()->willReturn(false);
}
$classNode = $this->reflect($class, array());
$classNode->shouldBeAnInstanceOf('Prophecy\Doubler\Generator\Node\ClassNode');
$classNode->getParentClass()->shouldReturn('Custom\ClassName');
$methodNodes = $classNode->getMethods();
$methodNodes->shouldHaveCount(7);
}
function it_properly_reads_methods_arguments_with_types(
$class, $method, $param1, $param2, $typeHint, $param3, $param4
)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$method->getName()->willReturn('methodWithArgs');
$method->isFinal()->willReturn(false);
$method->isProtected()->willReturn(true);
$method->isStatic()->willReturn(false);
$method->returnsReference()->willReturn(false);
$method->getParameters()->willReturn(array($param1, $param2, $param3, $param4));
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method->hasReturnType()->willReturn(false);
}
$param1->getName()->willReturn('arg_1');
$param1->isArray()->willReturn(true);
$param1->getClass()->willReturn(null);
$param1->isDefaultValueAvailable()->willReturn(true);
$param1->isPassedByReference()->willReturn(false);
$param1->allowsNull()->willReturn(false);
$param1->getDefaultValue()->willReturn(array());
$param2->getName()->willReturn('arg2');
$param2->isArray()->willReturn(false);
$param2->getClass()->willReturn($typeHint);
$param2->isDefaultValueAvailable()->willReturn(false);
$param2->isOptional()->willReturn(false);
$param2->isPassedByReference()->willReturn(false);
$param2->allowsNull()->willReturn(false);
$typeHint->getName()->willReturn('ArrayAccess');
$param3->getName()->willReturn('arg_3');
$param3->isArray()->willReturn(false);
if (version_compare(PHP_VERSION, '5.4', '>=')) {
$param3->isCallable()->willReturn(true);
}
$param3->getClass()->willReturn(null);
$param3->isOptional()->willReturn(false);
$param3->isDefaultValueAvailable()->willReturn(false);
$param3->isPassedByReference()->willReturn(false);
$param3->allowsNull()->willReturn(true);
$param4->getName()->willReturn('arg_4');
$param4->isArray()->willReturn(false);
$param4->getClass()->willReturn($typeHint);
$param4->isPassedByReference()->willReturn(false);
$param4->allowsNull()->willReturn(true);
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$param1->isVariadic()->willReturn(false);
$param2->isVariadic()->willReturn(false);
$param3->isVariadic()->willReturn(false);
$param4->isVariadic()->willReturn(true);
} else {
$param4->isOptional()->willReturn(true);
$param4->isDefaultValueAvailable()->willReturn(false);
}
$classNode = $this->reflect($class, array());
$methodNodes = $classNode->getMethods();
$argNodes = $methodNodes['methodWithArgs']->getArguments();
$argNodes[0]->getName()->shouldReturn('arg_1');
$argNodes[0]->getTypeHint()->shouldReturn('array');
$argNodes[0]->isOptional()->shouldReturn(true);
$argNodes[0]->getDefault()->shouldReturn(array());
$argNodes[1]->getName()->shouldReturn('arg2');
$argNodes[1]->getTypeHint()->shouldReturn('ArrayAccess');
$argNodes[1]->isOptional()->shouldReturn(false);
$argNodes[2]->getName()->shouldReturn('arg_3');
if (version_compare(PHP_VERSION, '5.4', '>=')) {
$argNodes[2]->getTypeHint()->shouldReturn('callable');
$argNodes[2]->isOptional()->shouldReturn(true);
$argNodes[2]->getDefault()->shouldReturn(null);
} else {
$argNodes[2]->isOptional()->shouldReturn(false);
}
$argNodes[3]->getName()->shouldReturn('arg_4');
$argNodes[3]->getTypeHint()->shouldReturn('ArrayAccess');
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$argNodes[3]->isVariadic()->shouldReturn(true);
} else {
$argNodes[3]->isOptional()->shouldReturn(true);
$argNodes[3]->getDefault()->shouldReturn(null);
}
}
function it_marks_required_args_without_types_as_not_optional(
$class, $method, $param1
)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$method->getName()->willReturn('methodWithArgs');
$method->isFinal()->willReturn(false);
$method->isProtected()->willReturn(false);
$method->isStatic()->willReturn(false);
$method->returnsReference()->willReturn(false);
$method->getParameters()->willReturn(array($param1));
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method->hasReturnType()->willReturn(false);
}
$param1->getName()->willReturn('arg_1');
$param1->isArray()->willReturn(false);
if (version_compare(PHP_VERSION, '5.4', '>=')) {
$param1->isCallable()->willReturn(false);
}
$param1->getClass()->willReturn(null);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$param1->hasType()->willReturn(false);
}
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$param1->isVariadic()->willReturn(false);
}
$param1->isDefaultValueAvailable()->willReturn(false);
$param1->isOptional()->willReturn(false);
$param1->isPassedByReference()->willReturn(false);
$param1->allowsNull()->willReturn(true);
if (defined('HHVM_VERSION')) {
$param1->getTypehintText()->willReturn(null);
}
$classNode = $this->reflect($class, array());
$methodNodes = $classNode->getMethods();
$argNodes = $methodNodes['methodWithArgs']->getArguments();
$argNodes[0]->isOptional()->shouldReturn(false);
}
function it_marks_passed_by_reference_args_as_passed_by_reference(
$class, $method, $param1, $param2, $param3, $typeHint
)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$method->getName()->willReturn('methodWithArgs');
$method->isFinal()->willReturn(false);
$method->isProtected()->willReturn(false);
$method->isStatic()->willReturn(false);
$method->returnsReference()->willReturn(false);
$method->getParameters()->willReturn(array($param1, $param2, $param3));
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method->hasReturnType()->willReturn(false);
}
$param1->getName()->willReturn('arg_1');
$param1->isArray()->willReturn(false);
if (version_compare(PHP_VERSION, '5.4', '>=')) {
$param1->isCallable()->willReturn(false);
}
$param1->getClass()->willReturn(null);
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$param1->isVariadic()->willReturn(false);
}
$param1->isDefaultValueAvailable()->willReturn(false);
$param1->isOptional()->willReturn(true);
$param1->isPassedByReference()->willReturn(true);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$param1->hasType()->willReturn(false);
}
$param1->allowsNull()->willReturn(false);
if (defined('HHVM_VERSION')) {
$param1->getTypehintText()->willReturn(null);
}
$param2->getName()->willReturn('arg2');
$param2->isArray()->willReturn(false);
$param2->getClass()->willReturn($typeHint);
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$param2->isVariadic()->willReturn(false);
}
$param2->isDefaultValueAvailable()->willReturn(false);
$param2->isOptional()->willReturn(false);
$param2->isPassedByReference()->willReturn(false);
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$param2->hasType()->willReturn(false);
}
$param2->allowsNull()->willReturn(false);
$typeHint->getName()->willReturn('ArrayAccess');
$param3->getName()->willReturn('arg2');
$param3->isArray()->willReturn(false);
$param3->getClass()->willReturn($typeHint);
if (version_compare(PHP_VERSION, '5.6', '>=')) {
$param3->isVariadic()->willReturn(true);
} else {
$param3->isOptional()->willReturn(true);
$param3->isDefaultValueAvailable()->willReturn(false);
}
$param3->isPassedByReference()->willReturn(true);
$param3->allowsNull()->willReturn(true);
$classNode = $this->reflect($class, array());
$methodNodes = $classNode->getMethods();
$argNodes = $methodNodes['methodWithArgs']->getArguments();
$argNodes[0]->isPassedByReference()->shouldReturn(true);
$argNodes[1]->isPassedByReference()->shouldReturn(false);
$argNodes[2]->isPassedByReference()->shouldReturn(true);
}
function it_throws_an_exception_if_class_is_final($class)
{
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(true);
$class->getName()->willReturn('Custom\ClassName');
$this->shouldThrow('Prophecy\Exception\Doubler\ClassMirrorException')
->duringReflect($class, array());
}
function it_ignores_final_methods($class, $method)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$method->isFinal()->willReturn(true);
$method->getName()->willReturn('finalImplementation');
$classNode = $this->reflect($class, array());
$classNode->getMethods()->shouldHaveCount(0);
}
function it_marks_final_methods_as_unextendable($class, $method)
{
$class->getName()->willReturn('Custom\ClassName');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$method->isFinal()->willReturn(true);
$method->getName()->willReturn('finalImplementation');
$classNode = $this->reflect($class, array());
$classNode->getUnextendableMethods()->shouldHaveCount(1);
$classNode->isExtendable('finalImplementation')->shouldReturn(false);
}
function it_throws_an_exception_if_interface_provided_instead_of_class($interface)
{
$interface->isInterface()->willReturn(true);
$interface->getName()->willReturn('Custom\ClassName');
$this->shouldThrow('Prophecy\Exception\InvalidArgumentException')
->duringReflect($interface, array());
}
function it_reflects_all_interfaces_methods(
$interface1, $interface2, $method1, $method2, $method3
)
{
$interface1->getName()->willReturn('MyInterface1');
$interface2->getName()->willReturn('MyInterface2');
$interface1->isInterface()->willReturn(true);
$interface2->isInterface()->willReturn(true);
$interface1->getMethods()->willReturn(array($method1));
$interface2->getMethods()->willReturn(array($method2, $method3));
$method1->getName()->willReturn('getName');
$method2->getName()->willReturn('isPublic');
$method3->getName()->willReturn('isAbstract');
$method1->isProtected()->willReturn(false);
$method2->isProtected()->willReturn(false);
$method3->isProtected()->willReturn(false);
$method1->returnsReference()->willReturn(false);
$method2->returnsReference()->willReturn(false);
$method3->returnsReference()->willReturn(false);
$method1->isStatic()->willReturn(false);
$method2->isStatic()->willReturn(false);
$method3->isStatic()->willReturn(false);
$method1->getParameters()->willReturn(array());
$method2->getParameters()->willReturn(array());
$method3->getParameters()->willReturn(array());
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method1->hasReturnType()->willReturn(false);
$method2->hasReturnType()->willReturn(false);
$method3->hasReturnType()->willReturn(false);
}
$classNode = $this->reflect(null, array($interface1, $interface2));
$classNode->shouldBeAnInstanceOf('Prophecy\Doubler\Generator\Node\ClassNode');
$classNode->getParentClass()->shouldReturn('stdClass');
$classNode->getInterfaces()->shouldReturn(array(
'Prophecy\Doubler\Generator\ReflectionInterface', 'MyInterface2', 'MyInterface1',
));
$methodNodes = $classNode->getMethods();
$methodNodes->shouldHaveCount(3);
$classNode->hasMethod('getName')->shouldReturn(true);
$classNode->hasMethod('isPublic')->shouldReturn(true);
$classNode->hasMethod('isAbstract')->shouldReturn(true);
}
function it_ignores_virtually_private_methods($class, $method1, $method2, $method3)
{
$class->getName()->willReturn('SomeClass');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method1, $method2, $method3));
$method1->getName()->willReturn('_getName');
$method2->getName()->willReturn('__toString');
$method3->getName()->willReturn('isAbstract');
$method1->isFinal()->willReturn(false);
$method2->isFinal()->willReturn(false);
$method3->isFinal()->willReturn(false);
$method1->isProtected()->willReturn(false);
$method2->isProtected()->willReturn(false);
$method3->isProtected()->willReturn(false);
$method1->isStatic()->willReturn(false);
$method2->isStatic()->willReturn(false);
$method3->isStatic()->willReturn(false);
$method1->returnsReference()->willReturn(false);
$method2->returnsReference()->willReturn(false);
$method3->returnsReference()->willReturn(false);
$method1->getParameters()->willReturn(array());
$method2->getParameters()->willReturn(array());
$method3->getParameters()->willReturn(array());
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$method1->hasReturnType()->willReturn(false);
$method2->hasReturnType()->willReturn(false);
$method3->hasReturnType()->willReturn(false);
}
$classNode = $this->reflect($class, array());
$methodNodes = $classNode->getMethods();
$methodNodes->shouldHaveCount(2);
$classNode->hasMethod('isAbstract')->shouldReturn(true);
}
function it_does_not_throw_exception_for_virtually_private_finals($class, $method)
{
$class->getName()->willReturn('SomeClass');
$class->isInterface()->willReturn(false);
$class->isFinal()->willReturn(false);
$class->getMethods(ReflectionMethod::IS_ABSTRACT)->willReturn(array());
$class->getMethods(ReflectionMethod::IS_PUBLIC)->willReturn(array($method));
$method->getName()->willReturn('__toString');
$method->isFinal()->willReturn(true);
$this->shouldNotThrow()->duringReflect($class, array());
}
function it_throws_an_exception_if_class_provided_in_interfaces_list($class)
{
$class->getName()->willReturn('MyClass');
$class->isInterface()->willReturn(false);
$this->shouldThrow('InvalidArgumentException')
->duringReflect(null, array($class));
}
function it_throws_an_exception_if_not_reflection_provided_as_interface()
{
$this->shouldThrow('InvalidArgumentException')
->duringReflect(null, array(null));
}
function it_doesnt_fail_to_typehint_nonexistent_FQCN()
{
$classNode = $this->reflect(new ReflectionClass('spec\Prophecy\Doubler\Generator\OptionalDepsClass'), array());
$method = $classNode->getMethod('iHaveAStrangeTypeHintedArg');
$arguments = $method->getArguments();
$arguments[0]->getTypeHint()->shouldBe('I\Simply\Am\Nonexistent');
}
function it_doesnt_fail_to_typehint_nonexistent_RQCN()
{
$classNode = $this->reflect(new ReflectionClass('spec\Prophecy\Doubler\Generator\OptionalDepsClass'), array());
$method = $classNode->getMethod('iHaveAnEvenStrangerTypeHintedArg');
$arguments = $method->getArguments();
$arguments[0]->getTypeHint()->shouldBe('I\Simply\Am\Not');
}
function it_doesnt_use_scalar_typehints()
{
$classNode = $this->reflect(new ReflectionClass('ReflectionMethod'), array());
$method = $classNode->getMethod('export');
$arguments = $method->getArguments();
$arguments[0]->getTypeHint()->shouldReturn(null);
$arguments[1]->getTypeHint()->shouldReturn(null);
$arguments[2]->getTypeHint()->shouldReturn(null);
}
}
class OptionalDepsClass
{
public function iHaveAStrangeTypeHintedArg(\I\Simply\Am\Nonexistent $class)
{
}
public function iHaveAnEvenStrangerTypeHintedArg(Simply\Am\Not $class)
{
}
}
<?php
namespace spec\Prophecy\Doubler\Generator\Node;
use PhpSpec\ObjectBehavior;
class ArgumentNodeSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('name');
}
function it_is_not_be_passed_by_reference_by_default()
{
$this->shouldNotBePassedByReference();
}
function it_is_passed_by_reference_if_marked()
{
$this->setAsPassedByReference();
$this->shouldBePassedByReference();
}
function it_is_not_variadic_by_default()
{
$this->shouldNotBeVariadic();
}
function it_is_variadic_if_marked()
{
$this->setAsVariadic();
$this->shouldBeVariadic();
}
function it_does_not_have_default_by_default()
{
$this->shouldNotHaveDefault();
}
function it_does_not_have_default_if_variadic()
{
$this->setDefault(null);
$this->setAsVariadic();
$this->shouldNotHaveDefault();
}
function it_does_have_default_if_not_variadic()
{
$this->setDefault(null);
$this->setAsVariadic(false);
$this->hasDefault()->shouldReturn(true);
}
function it_has_name_with_which_it_was_been_constructed()
{
$this->getName()->shouldReturn('name');
}
function it_has_no_typehint_by_default()
{
$this->getTypeHint()->shouldReturn(null);
}
function its_typeHint_is_mutable()
{
$this->setTypeHint('array');
$this->getTypeHint()->shouldReturn('array');
}
function it_does_not_have_default_value_by_default()
{
$this->getDefault()->shouldReturn(null);
}
function it_is_not_optional_by_default()
{
$this->isOptional()->shouldReturn(false);
}
function its_default_is_mutable()
{
$this->setDefault(array());
$this->getDefault()->shouldReturn(array());
}
function it_is_marked_as_optional_when_default_is_set()
{
$this->setDefault(null);
$this->isOptional()->shouldReturn(true);
}
}
<?php
namespace spec\Prophecy\Doubler\Generator\Node;
use PhpSpec\ObjectBehavior;
use Prophecy\Exception\Doubler\MethodNotExtendableException;
class ClassNodeSpec extends ObjectBehavior
{
function its_parentClass_is_a_stdClass_by_default()
{
$this->getParentClass()->shouldReturn('stdClass');
}
function its_parentClass_is_mutable()
{
$this->setParentClass('Exception');
$this->getParentClass()->shouldReturn('Exception');
}
function its_parentClass_is_set_to_stdClass_if_user_set_null()
{
$this->setParentClass(null);
$this->getParentClass()->shouldReturn('stdClass');
}
function it_does_not_implement_any_interface_by_default()
{
$this->getInterfaces()->shouldHaveCount(0);
}
function its_addInterface_adds_item_to_the_list_of_implemented_interfaces()
{
$this->addInterface('MyInterface');
$this->getInterfaces()->shouldHaveCount(1);
}
function its_hasInterface_returns_true_if_class_implements_interface()
{
$this->addInterface('MyInterface');
$this->hasInterface('MyInterface')->shouldReturn(true);
}
function its_hasInterface_returns_false_if_class_does_not_implements_interface()
{
$this->hasInterface('MyInterface')->shouldReturn(false);
}
function it_supports_implementation_of_multiple_interfaces()
{
$this->addInterface('MyInterface');
$this->addInterface('MySecondInterface');
$this->getInterfaces()->shouldHaveCount(2);
}
function it_ignores_same_interfaces_added_twice()
{
$this->addInterface('MyInterface');
$this->addInterface('MyInterface');
$this->getInterfaces()->shouldHaveCount(1);
$this->getInterfaces()->shouldReturn(array('MyInterface'));
}
function it_does_not_have_methods_by_default()
{
$this->getMethods()->shouldHaveCount(0);
}
function it_can_has_methods($method1, $method2)
{
$method1->getName()->willReturn('__construct');
$method2->getName()->willReturn('getName');
$this->addMethod($method1);
$this->addMethod($method2);
$this->getMethods()->shouldReturn(array(
'__construct' => $method1,
'getName' => $method2
));
}
function its_hasMethod_returns_true_if_method_exists($method)
{
$method->getName()->willReturn('getName');
$this->addMethod($method);
$this->hasMethod('getName')->shouldReturn(true);
}
function its_getMethod_returns_method_by_name($method)
{
$method->getName()->willReturn('getName');
$this->addMethod($method);
$this->getMethod('getName')->shouldReturn($method);
}
function its_hasMethod_returns_false_if_method_does_not_exists()
{
$this->hasMethod('getName')->shouldReturn(false);
}
function its_hasMethod_returns_false_if_method_has_been_removed($method)
{
$method->getName()->willReturn('getName');
$this->addMethod($method);
$this->removeMethod('getName');
$this->hasMethod('getName')->shouldReturn(false);
}
function it_does_not_have_properties_by_default()
{
$this->getProperties()->shouldHaveCount(0);
}
function it_is_able_to_have_properties()
{
$this->addProperty('title');
$this->addProperty('text', 'private');
$this->getProperties()->shouldReturn(array(
'title' => 'public',
'text' => 'private'
));
}
function its_addProperty_does_not_accept_unsupported_visibility()
{
$this->shouldThrow('InvalidArgumentException')->duringAddProperty('title', 'town');
}
function its_addProperty_lowercases_visibility_before_setting()
{
$this->addProperty('text', 'PRIVATE');
$this->getProperties()->shouldReturn(array('text' => 'private'));
}
function its_has_no_unextendable_methods_by_default()
{
$this->getUnextendableMethods()->shouldHaveCount(0);
}
function its_addUnextendableMethods_adds_an_unextendable_method()
{
$this->addUnextendableMethod('testMethod');
$this->getUnextendableMethods()->shouldHaveCount(1);
}
function its_methods_are_extendable_by_default()
{
$this->isExtendable('testMethod')->shouldReturn(true);
}
function its_unextendable_methods_are_not_extendable()
{
$this->addUnextendableMethod('testMethod');
$this->isExtendable('testMethod')->shouldReturn(false);
}
function its_addUnextendableMethods_doesnt_create_duplicates()
{
$this->addUnextendableMethod('testMethod');
$this->addUnextendableMethod('testMethod');
$this->getUnextendableMethods()->shouldHaveCount(1);
}
function it_throws_an_exception_when_adding_a_method_that_isnt_extendable($method)
{
$this->addUnextendableMethod('testMethod');
$method->getName()->willReturn('testMethod');
$expectedException = new MethodNotExtendableException(
"Method `testMethod` is not extendable, so can not be added.",
"stdClass",
"testMethod"
);
$this->shouldThrow($expectedException)->duringAddMethod($method);
}
}
<?php
namespace spec\Prophecy\Doubler\Generator\Node;
use PhpSpec\ObjectBehavior;
class MethodNodeSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('getTitle');
}
function it_has_a_name()
{
$this->getName()->shouldReturn('getTitle');
}
function it_has_public_visibility_by_default()
{
$this->getVisibility()->shouldReturn('public');
}
function its_visibility_is_mutable()
{
$this->setVisibility('private');
$this->getVisibility()->shouldReturn('private');
}
function it_is_not_static_by_default()
{
$this->shouldNotBeStatic();
}
function it_does_not_return_a_reference_by_default()
{
$this->returnsReference()->shouldReturn(false);
}
function it_should_be_settable_as_returning_a_reference_through_setter()
{
$this->setReturnsReference();
$this->returnsReference()->shouldReturn(true);
}
function it_should_be_settable_as_static_through_setter()
{
$this->setStatic();
$this->shouldBeStatic();
}
function it_accepts_only_supported_visibilities()
{
$this->shouldThrow('InvalidArgumentException')->duringSetVisibility('stealth');
}
function it_lowercases_visibility_before_setting_it()
{
$this->setVisibility('Public');
$this->getVisibility()->shouldReturn('public');
}
function its_useParentCode_causes_method_to_call_parent($argument1, $argument2)
{
$argument1->getName()->willReturn('objectName');
$argument2->getName()->willReturn('default');
$argument1->isVariadic()->willReturn(false);
$argument2->isVariadic()->willReturn(true);
$this->addArgument($argument1);
$this->addArgument($argument2);
$this->useParentCode();
$this->getCode()->shouldReturn(
'return parent::getTitle($objectName, ...$default);'
);
}
function its_code_is_mutable()
{
$this->setCode('echo "code";');
$this->getCode()->shouldReturn('echo "code";');
}
function its_reference_returning_methods_will_generate_exceptions()
{
$this->setCode('echo "code";');
$this->setReturnsReference();
$this->getCode()->shouldReturn("throw new \Prophecy\Exception\Doubler\ReturnByReferenceException('Returning by reference not supported', get_class(\$this), 'getTitle');");
}
function its_setCode_provided_with_null_cleans_method_body()
{
$this->setCode(null);
$this->getCode()->shouldReturn('');
}
function it_is_constructable_with_code()
{
$this->beConstructedWith('getTitle', 'die();');
$this->getCode()->shouldReturn('die();');
}
function it_does_not_have_arguments_by_default()
{
$this->getArguments()->shouldHaveCount(0);
}
function it_supports_adding_arguments($argument1, $argument2)
{
$this->addArgument($argument1);
$this->addArgument($argument2);
$this->getArguments()->shouldReturn(array($argument1, $argument2));
}
function it_does_not_have_return_type_by_default()
{
$this->hasReturnType()->shouldReturn(false);
}
function it_setReturnType_sets_return_type()
{
$returnType = 'string';
$this->setReturnType($returnType);
$this->hasReturnType()->shouldReturn(true);
$this->getReturnType()->shouldReturn($returnType);
}
}
<?php
namespace spec\Prophecy\Doubler;
use PhpSpec\ObjectBehavior;
class LazyDoubleSpec extends ObjectBehavior
{
function let($doubler)
{
$this->beConstructedWith($doubler);
}
function it_returns_anonymous_double_instance_by_default($doubler, $double)
{
$doubler->double(null, array())->willReturn($double);
$this->getInstance()->shouldReturn($double);
}
function it_returns_class_double_instance_if_set($doubler, $double, $class)
{
$doubler->double($class, array())->willReturn($double);
$this->setParentClass($class);
$this->getInstance()->shouldReturn($double);
}
function it_returns_same_double_instance_if_called_2_times(
$doubler, $double1, $double2
)
{
$doubler->double(null, array())->willReturn($double1);
$doubler->double(null, array())->willReturn($double2);
$this->getInstance()->shouldReturn($double2);
$this->getInstance()->shouldReturn($double2);
}
function its_setParentClass_throws_ClassNotFoundException_if_class_not_found()
{
$this->shouldThrow('Prophecy\Exception\Doubler\ClassNotFoundException')
->duringSetParentClass('SomeUnexistingClass');
}
function its_setParentClass_throws_exception_if_prophecy_is_already_created(
$doubler, $double
)
{
$doubler->double(null, array())->willReturn($double);
$this->getInstance();
$this->shouldThrow('Prophecy\Exception\Doubler\DoubleException')
->duringSetParentClass('stdClass');
}
function its_addInterface_throws_InterfaceNotFoundException_if_no_interface_found()
{
$this->shouldThrow('Prophecy\Exception\Doubler\InterfaceNotFoundException')
->duringAddInterface('SomeUnexistingInterface');
}
function its_addInterface_throws_exception_if_prophecy_is_already_created(
$doubler, $double
)
{
$doubler->double(null, array())->willReturn($double);
$this->getInstance();
$this->shouldThrow('Prophecy\Exception\Doubler\DoubleException')
->duringAddInterface('ArrayAccess');
}
}
<?php
namespace spec\Prophecy\Doubler;
use PhpSpec\ObjectBehavior;
class NameGeneratorSpec extends ObjectBehavior
{
function its_name_generates_name_based_on_simple_class_reflection($class)
{
$class->getName()->willReturn('stdClass');
$this->name($class, array())->shouldStartWith('Double\stdClass\\');
}
function its_name_generates_name_based_on_namespaced_class_reflection($class)
{
$class->getName()->willReturn('Some\Custom\Class');
$this->name($class, array())->shouldStartWith('Double\Some\Custom\Class\P');
}
function its_name_generates_name_based_on_interface_shortnames($interface1, $interface2)
{
$interface1->getShortName()->willReturn('HandlerInterface');
$interface2->getShortName()->willReturn('LoaderInterface');
$this->name(null, array($interface1, $interface2))->shouldStartWith(
'Double\HandlerInterface\LoaderInterface\P'
);
}
function it_generates_proper_name_for_no_class_and_interfaces_list()
{
$this->name(null, array())->shouldStartWith('Double\stdClass\P');
}
function its_name_generates_name_based_only_on_class_if_its_available(
$class, $interface1, $interface2
)
{
$class->getName()->willReturn('Some\Custom\Class');
$interface1->getShortName()->willReturn('HandlerInterface');
$interface2->getShortName()->willReturn('LoaderInterface');
$this->name($class, array($interface1, $interface2))->shouldStartWith(
'Double\Some\Custom\Class\P'
);
}
public function getMatchers()
{
return array(
'startWith' => function ($subject, $string) {
return 0 === strpos($subject, $string);
},
);
}
}
<?php
namespace spec\Prophecy\Exception\Call;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy\Prophecy;
class UnexpectedCallExceptionSpec extends ObjectBehavior
{
function let($objectProphecy)
{
$this->beConstructedWith('msg', $objectProphecy, 'getName', array('arg1', 'arg2'));
}
function it_is_prophecy_exception()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ObjectProphecyException');
}
function it_exposes_method_name_through_getter()
{
$this->getMethodName()->shouldReturn('getName');
}
function it_exposes_arguments_through_getter()
{
$this->getArguments()->shouldReturn(array('arg1', 'arg2'));
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class ClassCreatorExceptionSpec extends ObjectBehavior
{
function let($node)
{
$this->beConstructedWith('', $node);
}
function it_is_a_prophecy_exception()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Exception');
$this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoublerException');
}
function it_contains_a_reflected_node($node)
{
$this->getClassNode()->shouldReturn($node);
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
class ClassMirrorExceptionSpec extends ObjectBehavior
{
function let($class)
{
$this->beConstructedWith('', $class);
}
function it_is_a_prophecy_exception()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Exception');
$this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoublerException');
}
function it_contains_a_reflected_class_link($class)
{
$this->getReflectedClass()->shouldReturn($class);
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class ClassNotFoundExceptionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('msg', 'CustomClass');
}
function it_is_a_prophecy_exception()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Exception');
$this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoubleException');
}
function its_getClassname_returns_classname()
{
$this->getClassname()->shouldReturn('CustomClass');
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
class DoubleExceptionSpec extends ObjectBehavior
{
function it_is_a_double_exception()
{
$this->shouldBeAnInstanceOf('RuntimeException');
$this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoublerException');
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class InterfaceNotFoundExceptionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('msg', 'CustomInterface');
}
function it_extends_ClassNotFoundException()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\ClassNotFoundException');
}
function its_getClassname_returns_classname()
{
$this->getClassname()->shouldReturn('CustomInterface');
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class MethodNotExtendableExceptionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('', 'User', 'getName');
}
function it_is_DoubleException()
{
$this->shouldHaveType('Prophecy\Exception\Doubler\DoubleException');
}
function it_has_MethodName()
{
$this->getMethodName()->shouldReturn('getName');
}
function it_has_classname()
{
$this->getClassName()->shouldReturn('User');
}
}
<?php
namespace spec\Prophecy\Exception\Doubler;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class MethodNotFoundExceptionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('', 'User', 'getName', array(1, 2, 3));
}
function it_is_DoubleException()
{
$this->shouldHaveType('Prophecy\Exception\Doubler\DoubleException');
}
function it_has_MethodName()
{
$this->getMethodName()->shouldReturn('getName');
}
function it_has_classnamej()
{
$this->getClassname()->shouldReturn('User');
}
function it_has_an_arguments_list()
{
$this->getArguments()->shouldReturn(array(1, 2, 3));
}
function it_has_a_default_null_argument_list()
{
$this->beConstructedWith('', 'User', 'getName');
$this->getArguments()->shouldReturn(null);
}
}
<?php
namespace spec\Prophecy\Exception\Prediction;
use PhpSpec\ObjectBehavior;
class AggregateExceptionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(null);
}
function it_is_prediction_exception()
{
$this->shouldBeAnInstanceOf('RuntimeException');
$this->shouldBeAnInstanceOf('Prophecy\Exception\Prediction\PredictionException');
}
function it_can_store_objectProphecy_link($object)
{
$this->setObjectProphecy($object);
$this->getObjectProphecy()->shouldReturn($object);
}
function it_should_not_have_exceptions_at_the_beginning()
{
$this->getExceptions()->shouldHaveCount(0);
}
function it_should_append_exception_through_append_method($exception)
{
$exception->getMessage()->willReturn('Exception #1');
$this->append($exception);
$this->getExceptions()->shouldReturn(array($exception));
}
function it_should_update_message_during_append($exception)
{
$exception->getMessage()->willReturn('Exception #1');
$this->append($exception);
$this->getMessage()->shouldReturn(" Exception #1");
}
}
<?php
namespace spec\Prophecy\Exception\Prediction;
use PhpSpec\ObjectBehavior;
class NoCallsExceptionSpec extends ObjectBehavior
{
function let($objectProphecy, $methodProphecy)
{
$methodProphecy->getObjectProphecy()->willReturn($objectProphecy);
$this->beConstructedWith('message', $methodProphecy);
}
function it_is_PredictionException()
{
$this->shouldHaveType('Prophecy\Exception\Prediction\PredictionException');
}
function it_extends_MethodProphecyException()
{
$this->shouldHaveType('Prophecy\Exception\Prophecy\MethodProphecyException');
}
}
<?php
namespace spec\Prophecy\Exception\Prediction;
use PhpSpec\ObjectBehavior;
class UnexpectedCallsCountExceptionSpec extends ObjectBehavior
{
function let($objectProphecy, $methodProphecy, $call1, $call2)
{
$methodProphecy->getObjectProphecy()->willReturn($objectProphecy);
$this->beConstructedWith('message', $methodProphecy, 5, array($call1, $call2));
}
function it_extends_UnexpectedCallsException()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Prediction\UnexpectedCallsException');
}
function it_should_expose_expectedCount_through_getter()
{
$this->getExpectedCount()->shouldReturn(5);
}
}
<?php
namespace spec\Prophecy\Exception\Prediction;
use PhpSpec\ObjectBehavior;
class UnexpectedCallsExceptionSpec extends ObjectBehavior
{
function let($objectProphecy, $methodProphecy, $call1, $call2)
{
$methodProphecy->getObjectProphecy()->willReturn($objectProphecy);
$this->beConstructedWith('message', $methodProphecy, array($call1, $call2));
}
function it_is_PredictionException()
{
$this->shouldHaveType('Prophecy\Exception\Prediction\PredictionException');
}
function it_extends_MethodProphecyException()
{
$this->shouldHaveType('Prophecy\Exception\Prophecy\MethodProphecyException');
}
function it_should_expose_calls_list_through_getter($call1, $call2)
{
$this->getCalls()->shouldReturn(array($call1, $call2));
}
}
<?php
namespace spec\Prophecy\Exception\Prophecy;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class MethodProphecyExceptionSpec extends ObjectBehavior
{
function let($objectProphecy, $methodProphecy)
{
$methodProphecy->getObjectProphecy()->willReturn($objectProphecy);
$this->beConstructedWith('message', $methodProphecy);
}
function it_extends_DoubleException()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ObjectProphecyException');
}
function it_holds_a_stub_reference($methodProphecy)
{
$this->getMethodProphecy()->shouldReturn($methodProphecy);
}
}
<?php
namespace spec\Prophecy\Exception\Prophecy;
use PhpSpec\ObjectBehavior;
use spec\Prophecy\Exception\Prophecy;
class ObjectProphecyExceptionSpec extends ObjectBehavior
{
function let($objectProphecy)
{
$this->beConstructedWith('message', $objectProphecy);
}
function it_should_be_a_prophecy_exception()
{
$this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ProphecyException');
}
function it_holds_double_reference($objectProphecy)
{
$this->getObjectProphecy()->shouldReturn($objectProphecy);
}
}
<?php
namespace spec\Prophecy\Prediction;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class CallPredictionSpec extends ObjectBehavior
{
function it_is_prediction()
{
$this->shouldHaveType('Prophecy\Prediction\PredictionInterface');
}
function it_does_nothing_if_there_is_more_than_one_call_been_made($object, $method, $call)
{
$this->check(array($call), $object, $method)->shouldReturn(null);
}
function it_throws_NoCallsException_if_no_calls_found($object, $method, $arguments)
{
$method->getObjectProphecy()->willReturn($object);
$method->getMethodName()->willReturn('getName');
$method->getArgumentsWildcard()->willReturn($arguments);
$arguments->__toString()->willReturn('123');
$object->reveal()->willReturn(new \stdClass());
$object->findProphecyMethodCalls('getName', Argument::any())->willReturn(array());
$this->shouldThrow('Prophecy\Exception\Prediction\NoCallsException')
->duringCheck(array(), $object, $method);
}
}
<?php
namespace spec\Prophecy\Prediction;
use PhpSpec\ObjectBehavior;
class CallTimesPredictionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(2);
}
function it_is_prediction()
{
$this->shouldHaveType('Prophecy\Prediction\PredictionInterface');
}
function it_does_nothing_if_there_were_exact_amount_of_calls_being_made(
$object, $method, $call1, $call2
)
{
$this->check(array($call1, $call2), $object, $method)->shouldReturn(null);
}
function it_throws_UnexpectedCallsCountException_if_calls_found(
$object, $method, $call, $arguments
)
{
$method->getObjectProphecy()->willReturn($object);
$method->getMethodName()->willReturn('getName');
$method->getArgumentsWildcard()->willReturn($arguments);
$arguments->__toString()->willReturn('123');
$call->getMethodName()->willReturn('getName');
$call->getArguments()->willReturn(array(5, 4, 'three'));
$call->getCallPlace()->willReturn('unknown');
$this->shouldThrow('Prophecy\Exception\Prediction\UnexpectedCallsCountException')
->duringCheck(array($call), $object, $method);
}
}
<?php
namespace spec\Prophecy\Prediction;
use PhpSpec\ObjectBehavior;
use RuntimeException;
class CallbackPredictionSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('get_class');
}
function it_is_prediction()
{
$this->shouldHaveType('Prophecy\Prediction\PredictionInterface');
}
function it_proxies_call_to_callback($object, $method, $call)
{
$returnFirstCallCallback = function ($calls, $object, $method) {
throw new RuntimeException;
};
$this->beConstructedWith($returnFirstCallCallback);
$this->shouldThrow('RuntimeException')->duringCheck(array($call), $object, $method);
}
}
<?php
namespace spec\Prophecy\Prediction;
use PhpSpec\ObjectBehavior;
class NoCallsPredictionSpec extends ObjectBehavior
{
function it_is_prediction()
{
$this->shouldHaveType('Prophecy\Prediction\PredictionInterface');
}
function it_does_nothing_if_there_is_no_calls_made($object, $method)
{
$this->check(array(), $object, $method)->shouldReturn(null);
}
function it_throws_UnexpectedCallsException_if_calls_found($object, $method, $call, $arguments)
{
$method->getObjectProphecy()->willReturn($object);
$method->getMethodName()->willReturn('getName');
$method->getArgumentsWildcard()->willReturn($arguments);
$arguments->__toString()->willReturn('123');
$call->getMethodName()->willReturn('getName');
$call->getArguments()->willReturn(array(5, 4, 'three'));
$call->getCallPlace()->willReturn('unknown');
$this->shouldThrow('Prophecy\Exception\Prediction\UnexpectedCallsException')
->duringCheck(array($call), $object, $method);
}
}
<?php
namespace spec\Prophecy\Promise;
use PhpSpec\ObjectBehavior;
class CallbackPromiseSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('get_class');
}
function it_is_promise()
{
$this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface');
}
function it_should_execute_closure_callback($object, $method)
{
$firstArgumentCallback = function ($args) {
return $args[0];
};
$this->beConstructedWith($firstArgumentCallback);
$this->execute(array('one', 'two'), $object, $method)->shouldReturn('one');
}
function it_should_execute_static_array_callback($object, $method)
{
$firstArgumentCallback = array('spec\Prophecy\Promise\ClassCallback', 'staticCallbackMethod');
$this->beConstructedWith($firstArgumentCallback);
$this->execute(array('one', 'two'), $object, $method)->shouldReturn('one');
}
function it_should_execute_instance_array_callback($object, $method)
{
$class = new ClassCallback();
$firstArgumentCallback = array($class, 'callbackMethod');
$this->beConstructedWith($firstArgumentCallback);
$this->execute(array('one', 'two'), $object, $method)->shouldReturn('one');
}
function it_should_execute_string_function_callback($object, $method)
{
$firstArgumentCallback = 'spec\Prophecy\Promise\functionCallbackFirstArgument';
$this->beConstructedWith($firstArgumentCallback);
$this->execute(array('one', 'two'), $object, $method)->shouldReturn('one');
}
}
class ClassCallback
{
function callbackMethod($args)
{
return $args[0];
}
static function staticCallbackMethod($args)
{
return $args[0];
}
}
function functionCallbackFirstArgument($args)
{
return $args[0];
}
<?php
namespace spec\Prophecy\Promise;
use PhpSpec\ObjectBehavior;
class ReturnArgumentPromiseSpec extends ObjectBehavior
{
function it_is_promise()
{
$this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface');
}
function it_should_return_first_argument_if_provided($object, $method)
{
$this->execute(array('one', 'two'), $object, $method)->shouldReturn('one');
}
function it_should_return_null_if_no_arguments_provided($object, $method)
{
$this->execute(array(), $object, $method)->shouldReturn(null);
}
function it_should_return_nth_argument_if_provided($object, $method)
{
$this->beConstructedWith(1);
$this->execute(array('one', 'two'), $object, $method)->shouldReturn('two');
}
}
<?php
namespace spec\Prophecy\Promise;
use PhpSpec\ObjectBehavior;
class ReturnPromiseSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(array(42));
}
function it_is_promise()
{
$this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface');
}
function it_returns_value_it_was_constructed_with($object, $method)
{
$this->execute(array(), $object, $method)->shouldReturn(42);
}
function it_always_returns_last_value_left_in_the_return_values($object, $method)
{
$this->execute(array(), $object, $method)->shouldReturn(42);
$this->execute(array(), $object, $method)->shouldReturn(42);
}
function it_consequently_returns_multiple_values_it_was_constructed_with($object, $method)
{
$this->beConstructedWith(array(42, 24, 12));
$this->execute(array(), $object, $method)->shouldReturn(42);
$this->execute(array(), $object, $method)->shouldReturn(24);
$this->execute(array(), $object, $method)->shouldReturn(12);
}
function it_returns_null_if_constructed_with_empty_array($object, $method)
{
$this->beConstructedWith(array());
$this->execute(array(), $object, $method)->shouldReturn(null);
}
}
<?php
namespace spec\Prophecy\Promise;
use PhpSpec\ObjectBehavior;
class ThrowPromiseSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('RuntimeException');
}
function it_is_promise()
{
$this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface');
}
function it_instantiates_and_throws_exception_from_provided_classname($object, $method)
{
$this->beConstructedWith('InvalidArgumentException');
$this->shouldThrow('InvalidArgumentException')
->duringExecute(array(), $object, $method);
}
function it_instantiates_exceptions_with_required_arguments($object, $method)
{
$this->beConstructedWith('spec\Prophecy\Promise\RequiredArgumentException');
$this->shouldThrow('spec\Prophecy\Promise\RequiredArgumentException')
->duringExecute(array(), $object, $method);
}
function it_throws_provided_exception($object, $method)
{
$this->beConstructedWith($exc = new \RuntimeException('Some exception'));
$this->shouldThrow($exc)->duringExecute(array(), $object, $method);
}
}
class RequiredArgumentException extends \Exception
{
final public function __construct($message, $code) {}
}
<?php
namespace spec\Prophecy\Prophecy;
use PhpSpec\ObjectBehavior;
class ClassWithFinalMethod
{
final public function finalMethod() {}
}
class MethodProphecySpec extends ObjectBehavior
{
function let($objectProphecy, $reflection)
{
$objectProphecy->reveal()->willReturn($reflection);
$this->beConstructedWith($objectProphecy, 'getName', null);
}
function it_is_initializable()
{
$this->shouldHaveType('Prophecy\Prophecy\MethodProphecy');
}
function its_constructor_throws_MethodNotFoundException_for_unexisting_method($objectProphecy)
{
$this->shouldThrow('Prophecy\Exception\Doubler\MethodNotFoundException')->during(
'__construct', array($objectProphecy, 'getUnexisting', null)
);
}
function its_constructor_throws_MethodProphecyException_for_final_methods($objectProphecy, $subject)
{
$objectProphecy->reveal()->willReturn($subject);
$this->shouldThrow('Prophecy\Exception\Prophecy\MethodProphecyException')->during(
'__construct', array($objectProphecy, 'finalMethod', null)
);
}
function its_constructor_transforms_array_passed_as_3rd_argument_to_ArgumentsWildcard(
$objectProphecy
)
{
$this->beConstructedWith($objectProphecy, 'getName', array(42, 33));
$wildcard = $this->getArgumentsWildcard();
$wildcard->shouldNotBe(null);
$wildcard->__toString()->shouldReturn('exact(42), exact(33)');
}
function its_constructor_does_not_touch_third_argument_if_it_is_null($objectProphecy)
{
$this->beConstructedWith($objectProphecy, 'getName', null);
$wildcard = $this->getArgumentsWildcard();
$wildcard->shouldBe(null);
}
function it_records_promise_through_will_method($promise, $objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->will($promise);
$this->getPromise()->shouldReturn($promise);
}
function it_adds_itself_to_ObjectProphecy_during_call_to_will($objectProphecy, $promise)
{
$objectProphecy->addMethodProphecy($this)->shouldBeCalled();
$this->will($promise);
}
function it_adds_ReturnPromise_during_willReturn_call($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->willReturn(42);
$this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\ReturnPromise');
}
function it_adds_ThrowPromise_during_willThrow_call($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->willThrow('RuntimeException');
$this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\ThrowPromise');
}
function it_adds_ReturnArgumentPromise_during_willReturnArgument_call($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->willReturnArgument();
$this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\ReturnArgumentPromise');
}
function it_adds_ReturnArgumentPromise_during_willReturnArgument_call_with_index_argument($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->willReturnArgument(1);
$promise = $this->getPromise();
$promise->shouldBeAnInstanceOf('Prophecy\Promise\ReturnArgumentPromise');
$promise->execute(array('one', 'two'), $objectProphecy, $this)->shouldReturn('two');
}
function it_adds_CallbackPromise_during_will_call_with_callback_argument($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$callback = function () {};
$this->will($callback);
$this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\CallbackPromise');
}
function it_records_prediction_through_should_method($prediction, $objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->callOnWrappedObject('should', array($prediction));
$this->getPrediction()->shouldReturn($prediction);
}
function it_adds_CallbackPrediction_during_should_call_with_callback_argument($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$callback = function () {};
$this->callOnWrappedObject('should', array($callback));
$this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallbackPrediction');
}
function it_adds_itself_to_ObjectProphecy_during_call_to_should($objectProphecy, $prediction)
{
$objectProphecy->addMethodProphecy($this)->shouldBeCalled();
$this->callOnWrappedObject('should', array($prediction));
}
function it_adds_CallPrediction_during_shouldBeCalled_call($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->callOnWrappedObject('shouldBeCalled', array());
$this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallPrediction');
}
function it_adds_NoCallsPrediction_during_shouldNotBeCalled_call($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->callOnWrappedObject('shouldNotBeCalled', array());
$this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\NoCallsPrediction');
}
function it_adds_CallTimesPrediction_during_shouldBeCalledTimes_call($objectProphecy)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->callOnWrappedObject('shouldBeCalledTimes', array(5));
$this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallTimesPrediction');
}
function it_checks_prediction_via_shouldHave_method_call(
$objectProphecy, $arguments, $prediction, $call1, $call2
)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled();
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$this->withArguments($arguments);
$this->callOnWrappedObject('shouldHave', array($prediction));
}
function it_sets_return_promise_during_shouldHave_call_if_none_was_set_before(
$objectProphecy, $arguments, $prediction, $call1, $call2
)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled();
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$this->withArguments($arguments);
$this->callOnWrappedObject('shouldHave', array($prediction));
$this->getPromise()->shouldReturnAnInstanceOf('Prophecy\Promise\ReturnPromise');
}
function it_does_not_set_return_promise_during_shouldHave_call_if_it_was_set_before(
$objectProphecy, $arguments, $prediction, $call1, $call2, $promise
)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled();
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$this->will($promise);
$this->withArguments($arguments);
$this->callOnWrappedObject('shouldHave', array($prediction));
$this->getPromise()->shouldReturn($promise);
}
function it_records_checked_predictions(
$objectProphecy, $arguments, $prediction1, $prediction2, $call1, $call2, $promise
)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$prediction1->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->willReturn();
$prediction2->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->willReturn();
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$this->will($promise);
$this->withArguments($arguments);
$this->callOnWrappedObject('shouldHave', array($prediction1));
$this->callOnWrappedObject('shouldHave', array($prediction2));
$this->getCheckedPredictions()->shouldReturn(array($prediction1, $prediction2));
}
function it_records_even_failed_checked_predictions(
$objectProphecy, $arguments, $prediction, $call1, $call2, $promise
)
{
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->willThrow(new \RuntimeException());
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$this->will($promise);
$this->withArguments($arguments);
try {
$this->callOnWrappedObject('shouldHave', array($prediction));
} catch (\Exception $e) {}
$this->getCheckedPredictions()->shouldReturn(array($prediction));
}
function it_checks_prediction_via_shouldHave_method_call_with_callback(
$objectProphecy, $arguments, $prediction, $call1, $call2
)
{
$callback = function ($calls, $object, $method) {
throw new \RuntimeException;
};
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$this->withArguments($arguments);
$this->shouldThrow('RuntimeException')->duringShouldHave($callback);
}
function it_does_nothing_during_checkPrediction_if_no_prediction_set()
{
$this->checkPrediction()->shouldReturn(null);
}
function it_checks_set_prediction_during_checkPrediction(
$objectProphecy, $arguments, $prediction, $call1, $call2
)
{
$prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled();
$objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2));
$objectProphecy->addMethodProphecy($this)->willReturn(null);
$this->withArguments($arguments);
$this->callOnWrappedObject('should', array($prediction));
$this->checkPrediction();
}
function it_links_back_to_ObjectProphecy_through_getter($objectProphecy)
{
$this->getObjectProphecy()->shouldReturn($objectProphecy);
}
function it_has_MethodName()
{
$this->getMethodName()->shouldReturn('getName');
}
function it_contains_ArgumentsWildcard_it_was_constructed_with($objectProphecy, $wildcard)
{
$this->beConstructedWith($objectProphecy, 'getName', $wildcard);
$this->getArgumentsWildcard()->shouldReturn($wildcard);
}
function its_ArgumentWildcard_is_mutable_through_setter($wildcard)
{
$this->withArguments($wildcard);
$this->getArgumentsWildcard()->shouldReturn($wildcard);
}
function its_withArguments_transforms_passed_array_into_ArgumentsWildcard()
{
$this->withArguments(array(42, 33));
$wildcard = $this->getArgumentsWildcard();
$wildcard->shouldNotBe(null);
$wildcard->__toString()->shouldReturn('exact(42), exact(33)');
}
function its_withArguments_throws_exception_if_wrong_arguments_provided()
{
$this->shouldThrow('Prophecy\Exception\InvalidArgumentException')->duringWithArguments(42);
}
}
<?php
namespace spec\Prophecy\Prophecy;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ObjectProphecySpec extends ObjectBehavior
{
function let($lazyDouble, $double)
{
$this->beConstructedWith($lazyDouble);
$lazyDouble->getInstance()->willReturn($double);
}
function it_implements_ProphecyInterface()
{
$this->shouldBeAnInstanceOf('Prophecy\Prophecy\ProphecyInterface');
}
function it_sets_parentClass_during_willExtend_call($lazyDouble)
{
$lazyDouble->setParentClass('123')->shouldBeCalled();
$this->willExtend('123');
}
function it_adds_interface_during_willImplement_call($lazyDouble)
{
$lazyDouble->addInterface('222')->shouldBeCalled();
$this->willImplement('222');
}
function it_sets_constructor_arguments_during_willBeConstructedWith_call($lazyDouble)
{
$lazyDouble->setArguments(array(1, 2, 5))->shouldBeCalled();
$this->willBeConstructedWith(array(1, 2, 5));
}
function it_does_not_have_method_prophecies_by_default()
{
$this->getMethodProphecies()->shouldHaveCount(0);
}
function it_should_get_method_prophecies_by_method_name($method1, $method2, $arguments)
{
$method1->getMethodName()->willReturn('getName');
$method1->getArgumentsWildcard()->willReturn($arguments);
$method2->getMethodName()->willReturn('setName');
$method2->getArgumentsWildcard()->willReturn($arguments);
$this->addMethodProphecy($method1);
$this->addMethodProphecy($method2);
$methods = $this->getMethodProphecies('setName');
$methods->shouldHaveCount(1);
$methods[0]->getMethodName()->shouldReturn('setName');
}
function it_should_return_empty_array_if_no_method_prophecies_found()
{
$methods = $this->getMethodProphecies('setName');
$methods->shouldHaveCount(0);
}
function it_should_proxy_makeProphecyMethodCall_to_CallCenter($lazyDouble, $callCenter)
{
$this->beConstructedWith($lazyDouble, $callCenter);
$callCenter->makeCall($this->getWrappedObject(), 'setName', array('everzet'))->willReturn(42);
$this->makeProphecyMethodCall('setName', array('everzet'))->shouldReturn(42);
}
function it_should_reveal_arguments_and_return_values_from_callCenter(
$lazyDouble, $callCenter, $revealer
)
{
$this->beConstructedWith($lazyDouble, $callCenter, $revealer);
$revealer->reveal(array('question'))->willReturn(array('life'));
$revealer->reveal('answer')->willReturn(42);
$callCenter->makeCall($this->getWrappedObject(), 'setName', array('life'))->willReturn('answer');
$this->makeProphecyMethodCall('setName', array('question'))->shouldReturn(42);
}
function it_should_proxy_getProphecyMethodCalls_to_CallCenter(
$lazyDouble, $callCenter, $wildcard, $call
)
{
$this->beConstructedWith($lazyDouble, $callCenter);
$callCenter->findCalls('setName', $wildcard)->willReturn(array($call));
$this->findProphecyMethodCalls('setName', $wildcard)->shouldReturn(array($call));
}
function its_addMethodProphecy_adds_method_prophecy(
$methodProphecy, $argumentsWildcard
)
{
$methodProphecy->getArgumentsWildcard()->willReturn($argumentsWildcard);
$methodProphecy->getMethodName()->willReturn('getUsername');
$this->addMethodProphecy($methodProphecy);
$this->getMethodProphecies()->shouldReturn(array(
'getUsername' => array($methodProphecy)
));
}
function its_addMethodProphecy_handles_prophecies_with_different_arguments(
$methodProphecy1, $methodProphecy2, $argumentsWildcard1, $argumentsWildcard2
)
{
$methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1);
$methodProphecy1->getMethodName()->willReturn('getUsername');
$methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2);
$methodProphecy2->getMethodName()->willReturn('getUsername');
$this->addMethodProphecy($methodProphecy1);
$this->addMethodProphecy($methodProphecy2);
$this->getMethodProphecies()->shouldReturn(array(
'getUsername' => array(
$methodProphecy1,
$methodProphecy2,
)
));
}
function its_addMethodProphecy_handles_prophecies_for_different_methods(
$methodProphecy1, $methodProphecy2, $argumentsWildcard1, $argumentsWildcard2
)
{
$methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1);
$methodProphecy1->getMethodName()->willReturn('getUsername');
$methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2);
$methodProphecy2->getMethodName()->willReturn('isUsername');
$this->addMethodProphecy($methodProphecy1);
$this->addMethodProphecy($methodProphecy2);
$this->getMethodProphecies()->shouldReturn(array(
'getUsername' => array(
$methodProphecy1
),
'isUsername' => array(
$methodProphecy2
)
));
}
function its_addMethodProphecy_throws_exception_when_method_has_no_ArgumentsWildcard(
$methodProphecy
)
{
$methodProphecy->getArgumentsWildcard()->willReturn(null);
$methodProphecy->getObjectProphecy()->willReturn($this);
$methodProphecy->getMethodName()->willReturn('getTitle');
$this->shouldThrow('Prophecy\Exception\Prophecy\MethodProphecyException')->duringAddMethodProphecy(
$methodProphecy
);
}
function it_returns_null_after_checkPredictions_call_if_there_is_no_method_prophecies()
{
$this->checkProphecyMethodsPredictions()->shouldReturn(null);
}
function it_throws_AggregateException_during_checkPredictions_if_predictions_fail(
$methodProphecy1, $methodProphecy2, $argumentsWildcard1, $argumentsWildcard2
)
{
$methodProphecy1->getMethodName()->willReturn('getName');
$methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1);
$methodProphecy1->checkPrediction()
->willThrow('Prophecy\Exception\Prediction\AggregateException');
$methodProphecy2->getMethodName()->willReturn('setName');
$methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2);
$methodProphecy2->checkPrediction()
->willThrow('Prophecy\Exception\Prediction\AggregateException');
$this->addMethodProphecy($methodProphecy1);
$this->addMethodProphecy($methodProphecy2);
$this->shouldThrow('Prophecy\Exception\Prediction\AggregateException')
->duringCheckProphecyMethodsPredictions();
}
function it_returns_new_MethodProphecy_instance_for_arbitrary_call($doubler, $reflection)
{
$doubler->double(Argument::any())->willReturn($reflection);
$return = $this->getProphecy();
$return->shouldBeAnInstanceOf('Prophecy\Prophecy\MethodProphecy');
$return->getMethodName()->shouldReturn('getProphecy');
}
function it_returns_same_MethodProphecy_for_same_registered_signature($doubler, $reflection)
{
$doubler->double(Argument::any())->willReturn($reflection);
$this->addMethodProphecy($methodProphecy1 = $this->getProphecy(1, 2, 3));
$methodProphecy2 = $this->getProphecy(1, 2, 3);
$methodProphecy2->shouldBe($methodProphecy1);
}
function it_returns_new_MethodProphecy_for_different_signatures($doubler, $reflection)
{
$doubler->double(Argument::any())->willReturn($reflection);
$value = new ObjectProphecySpecFixtureB('ABC');
$value2 = new ObjectProphecySpecFixtureB('CBA');
$this->addMethodProphecy($methodProphecy1 = $this->getProphecy(1, 2, 3, $value));
$methodProphecy2 = $this->getProphecy(1, 2, 3, $value2);
$methodProphecy2->shouldNotBe($methodProphecy1);
}
function it_returns_new_MethodProphecy_for_all_callback_signatures($doubler, $reflection)
{
$doubler->double(Argument::any())->willReturn($reflection);
$this->addMethodProphecy($methodProphecy1 = $this->getProphecy(function(){}));
$methodProphecy2 = $this->getProphecy(function(){});
$methodProphecy2->shouldNotBe($methodProphecy1);
}
}
class ObjectProphecySpecFixtureA
{
public $errors;
}
class ObjectProphecySpecFixtureB extends ObjectProphecySpecFixtureA
{
public $errors;
public $value = null;
public function __construct($value)
{
$this->value = $value;
}
}
<?php
namespace spec\Prophecy\Prophecy;
use PhpSpec\ObjectBehavior;
class RevealerSpec extends ObjectBehavior
{
function it_is_revealer()
{
$this->shouldBeAnInstanceOf('Prophecy\Prophecy\RevealerInterface');
}
function it_reveals_single_instance_of_ProphecyInterface($prophecy, $object)
{
$prophecy->reveal()->willReturn($object);
$this->reveal($prophecy)->shouldReturn($object);
}
function it_reveals_instances_of_ProphecyInterface_inside_array(
$prophecy1, $prophecy2, $object1, $object2
)
{
$prophecy1->reveal()->willReturn($object1);
$prophecy2->reveal()->willReturn($object2);
$this->reveal(array(
array('item' => $prophecy2),
$prophecy1
))->shouldReturn(array(
array('item' => $object2),
$object1
));
}
function it_does_not_touch_non_prophecy_interface()
{
$this->reveal(42)->shouldReturn(42);
}
}
<?php
namespace spec\Prophecy;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class ProphetSpec extends ObjectBehavior
{
function let($doubler, $double)
{
$doubler->double(null, array())->willReturn($double);
$this->beConstructedWith($doubler);
}
function it_constructs_new_prophecy_on_prophesize_call()
{
$prophecy = $this->prophesize();
$prophecy->shouldBeAnInstanceOf('Prophecy\Prophecy\ObjectProphecy');
}
function it_constructs_new_prophecy_with_parent_class_if_specified($doubler, $newDouble)
{
$doubler->double(Argument::any(), array())->willReturn($newDouble);
$this->prophesize('Prophecy\Prophet')->reveal()->shouldReturn($newDouble);
}
function it_constructs_new_prophecy_with_interface_if_specified($doubler, $newDouble)
{
$doubler->double(null, Argument::any())->willReturn($newDouble);
$this->prophesize('ArrayAccess')->reveal()->shouldReturn($newDouble);
}
function it_exposes_all_created_prophecies_through_getter()
{
$prophecy1 = $this->prophesize();
$prophecy2 = $this->prophesize();
$this->getProphecies()->shouldReturn(array($prophecy1, $prophecy2));
}
function it_does_nothing_during_checkPredictions_call_if_no_predictions_defined()
{
$this->checkPredictions()->shouldReturn(null);
}
function it_throws_AggregateException_if_defined_predictions_fail(
$method1, $method2, $arguments1, $arguments2
)
{
$method1->getMethodName()->willReturn('getName');
$method1->getArgumentsWildcard()->willReturn($arguments1);
$method1->checkPrediction()->willReturn(null);
$method2->getMethodName()->willReturn('isSet');
$method2->getArgumentsWildcard()->willReturn($arguments2);
$method2->checkPrediction()->willThrow(
'Prophecy\Exception\Prediction\AggregateException'
);
$this->prophesize()->addMethodProphecy($method1);
$this->prophesize()->addMethodProphecy($method2);
$this->shouldThrow('Prophecy\Exception\Prediction\AggregateException')
->duringCheckPredictions();
}
function it_exposes_doubler_through_getter($doubler)
{
$this->getDoubler()->shouldReturn($doubler);
}
}
<?php
namespace spec\Prophecy\Util;
use PhpSpec\ObjectBehavior;
class StringUtilSpec extends ObjectBehavior
{
function it_generates_proper_string_representation_for_integer()
{
$this->stringify(42)->shouldReturn('42');
}
function it_generates_proper_string_representation_for_string()
{
$this->stringify('some string')->shouldReturn('"some string"');
}
function it_generates_single_line_representation_for_multiline_string()
{
$this->stringify("some\nstring")->shouldReturn('"some\\nstring"');
}
function it_generates_proper_string_representation_for_double()
{
$this->stringify(42.3)->shouldReturn('42.3');
}
function it_generates_proper_string_representation_for_boolean_true()
{
$this->stringify(true)->shouldReturn('true');
}
function it_generates_proper_string_representation_for_boolean_false()
{
$this->stringify(false)->shouldReturn('false');
}
function it_generates_proper_string_representation_for_null()
{
$this->stringify(null)->shouldReturn('null');
}
function it_generates_proper_string_representation_for_empty_array()
{
$this->stringify(array())->shouldReturn('[]');
}
function it_generates_proper_string_representation_for_array()
{
$this->stringify(array('zet', 42))->shouldReturn('["zet", 42]');
}
function it_generates_proper_string_representation_for_hash_containing_one_value()
{
$this->stringify(array('ever' => 'zet'))->shouldReturn('["ever" => "zet"]');
}
function it_generates_proper_string_representation_for_hash()
{
$this->stringify(array('ever' => 'zet', 52 => 'hey', 'num' => 42))->shouldReturn(
'["ever" => "zet", 52 => "hey", "num" => 42]'
);
}
function it_generates_proper_string_representation_for_resource()
{
$resource = fopen(__FILE__, 'r');
$this->stringify($resource)->shouldReturn('stream:'.$resource);
}
function it_generates_proper_string_representation_for_object($object)
{
$objHash = sprintf('%s:%s',
get_class($object->getWrappedObject()),
spl_object_hash($object->getWrappedObject())
) . " Object (\n 'objectProphecy' => Prophecy\Prophecy\ObjectProphecy Object (*Prophecy*)\n)";
$this->stringify($object)->shouldReturn("$objHash");
}
function it_generates_proper_string_representation_for_object_without_exporting($object)
{
$objHash = sprintf('%s:%s',
get_class($object->getWrappedObject()),
spl_object_hash($object->getWrappedObject())
);
$this->stringify($object, false)->shouldReturn("$objHash");
}
}
<?php
namespace Prophecy;
use Prophecy\Argument\Token;
class Argument
{
public static function exact($value)
{
return new Token\ExactValueToken($value);
}
public static function type($type)
{
return new Token\TypeToken($type);
}
public static function which($methodName, $value)
{
return new Token\ObjectStateToken($methodName, $value);
}
public static function that($callback)
{
return new Token\CallbackToken($callback);
}
public static function any()
{
return new Token\AnyValueToken;
}
public static function cetera()
{
return new Token\AnyValuesToken;
}
public static function allOf()
{
return new Token\LogicalAndToken(func_get_args());
}
public static function size($value)
{
return new Token\ArrayCountToken($value);
}
public static function withEntry($key, $value)
{
return new Token\ArrayEntryToken($key, $value);
}
public static function withEveryEntry($value)
{
return new Token\ArrayEveryEntryToken($value);
}
public static function containing($value)
{
return new Token\ArrayEntryToken(self::any(), $value);
}
public static function withKey($key)
{
return new Token\ArrayEntryToken($key, self::any());
}
public static function not($value)
{
return new Token\LogicalNotToken($value);
}
public static function containingString($value)
{
return new Token\StringContainsToken($value);
}
public static function is($value)
{
return new Token\IdenticalValueToken($value);
}
public static function approximate($value, $precision = 0)
{
return new Token\ApproximateValueToken($value, $precision);
}
}
<?php
namespace Prophecy\Argument;
class ArgumentsWildcard
{
private $tokens = array();
private $string;
public function __construct(array $arguments)
{
foreach ($arguments as $argument) {
if (!$argument instanceof Token\TokenInterface) {
$argument = new Token\ExactValueToken($argument);
}
$this->tokens[] = $argument;
}
}
public function scoreArguments(array $arguments)
{
if (0 == count($arguments) && 0 == count($this->tokens)) {
return 1;
}
$arguments = array_values($arguments);
$totalScore = 0;
foreach ($this->tokens as $i => $token) {
$argument = isset($arguments[$i]) ? $arguments[$i] : null;
if (1 >= $score = $token->scoreArgument($argument)) {
return false;
}
$totalScore += $score;
if (true === $token->isLast()) {
return $totalScore;
}
}
if (count($arguments) > count($this->tokens)) {
return false;
}
return $totalScore;
}
public function __toString()
{
if (null === $this->string) {
$this->string = implode(', ', array_map(function ($token) {
return (string) $token;
}, $this->tokens));
}
return $this->string;
}
public function getTokens()
{
return $this->tokens;
}
}
<?php
namespace Prophecy\Argument\Token;
class AnyValueToken implements TokenInterface
{
public function scoreArgument($argument)
{
return 3;
}
public function isLast()
{
return false;
}
public function __toString()
{
return '*';
}
}
<?php
namespace Prophecy\Argument\Token;
class AnyValuesToken implements TokenInterface
{
public function scoreArgument($argument)
{
return 2;
}
public function isLast()
{
return true;
}
public function __toString()
{
return '* [, ...]';
}
}
<?php
namespace Prophecy\Argument\Token;
class ApproximateValueToken implements TokenInterface
{
private $value;
private $precision;
public function __construct($value, $precision = 0)
{
$this->value = $value;
$this->precision = $precision;
}
public function scoreArgument($argument)
{
return round($argument, $this->precision) === round($this->value, $this->precision) ? 10 : false;
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('≅%s', round($this->value, $this->precision));
}
}
<?php
namespace Prophecy\Argument\Token;
class ArrayCountToken implements TokenInterface
{
private $count;
public function __construct($value)
{
$this->count = $value;
}
public function scoreArgument($argument)
{
return $this->isCountable($argument) && $this->hasProperCount($argument) ? 6 : false;
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('count(%s)', $this->count);
}
private function isCountable($argument)
{
return (is_array($argument) || $argument instanceof \Countable);
}
private function hasProperCount($argument)
{
return $this->count === count($argument);
}
}
<?php
namespace Prophecy\Argument\Token;
use Prophecy\Exception\InvalidArgumentException;
class ArrayEntryToken implements TokenInterface
{
private $key;
private $value;
public function __construct($key, $value)
{
$this->key = $this->wrapIntoExactValueToken($key);
$this->value = $this->wrapIntoExactValueToken($value);
}
public function scoreArgument($argument)
{
if ($argument instanceof \Traversable) {
$argument = iterator_to_array($argument);
}
if ($argument instanceof \ArrayAccess) {
$argument = $this->convertArrayAccessToEntry($argument);
}
if (!is_array($argument) || empty($argument)) {
return false;
}
$keyScores = array_map(array($this->key,'scoreArgument'), array_keys($argument));
$valueScores = array_map(array($this->value,'scoreArgument'), $argument);
$scoreEntry = function ($value, $key) {
return $value && $key ? min(8, ($key + $value) / 2) : false;
};
return max(array_map($scoreEntry, $valueScores, $keyScores));
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('[..., %s => %s, ...]', $this->key, $this->value);
}
public function getKey()
{
return $this->key;
}
public function getValue()
{
return $this->value;
}
private function wrapIntoExactValueToken($value)
{
return $value instanceof TokenInterface ? $value : new ExactValueToken($value);
}
private function convertArrayAccessToEntry(\ArrayAccess $object)
{
if (!$this->key instanceof ExactValueToken) {
throw new InvalidArgumentException(sprintf(
'You can only use exact value tokens to match key of ArrayAccess object'.PHP_EOL.
'But you used `%s`.',
$this->key
));
}
$key = $this->key->getValue();
return $object->offsetExists($key) ? array($key => $object[$key]) : array();
}
}
<?php
namespace Prophecy\Argument\Token;
class ArrayEveryEntryToken implements TokenInterface
{
private $value;
public function __construct($value)
{
if (!$value instanceof TokenInterface) {
$value = new ExactValueToken($value);
}
$this->value = $value;
}
public function scoreArgument($argument)
{
if (!$argument instanceof \Traversable && !is_array($argument)) {
return false;
}
$scores = array();
foreach ($argument as $key => $argumentEntry) {
$scores[] = $this->value->scoreArgument($argumentEntry);
}
if (empty($scores) || in_array(false, $scores, true)) {
return false;
}
return array_sum($scores) / count($scores);
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('[%s, ..., %s]', $this->value, $this->value);
}
public function getValue()
{
return $this->value;
}
}
<?php
namespace Prophecy\Argument\Token;
use Prophecy\Exception\InvalidArgumentException;
class CallbackToken implements TokenInterface
{
private $callback;
public function __construct($callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'Callable expected as an argument to CallbackToken, but got %s.',
gettype($callback)
));
}
$this->callback = $callback;
}
public function scoreArgument($argument)
{
return call_user_func($this->callback, $argument) ? 7 : false;
}
public function isLast()
{
return false;
}
public function __toString()
{
return 'callback()';
}
}
<?php
namespace Prophecy\Argument\Token;
use SebastianBergmann\Comparator\ComparisonFailure;
use Prophecy\Comparator\Factory as ComparatorFactory;
use Prophecy\Util\StringUtil;
class ExactValueToken implements TokenInterface
{
private $value;
private $string;
private $util;
private $comparatorFactory;
public function __construct($value, StringUtil $util = null, ComparatorFactory $comparatorFactory = null)
{
$this->value = $value;
$this->util = $util ?: new StringUtil();
$this->comparatorFactory = $comparatorFactory ?: ComparatorFactory::getInstance();
}
public function scoreArgument($argument)
{
if (is_object($argument) && is_object($this->value)) {
$comparator = $this->comparatorFactory->getComparatorFor(
$argument, $this->value
);
try {
$comparator->assertEquals($argument, $this->value);
return 10;
} catch (ComparisonFailure $failure) {}
}
if (is_object($argument) xor is_object($this->value)) {
if (is_object($argument) && !method_exists($argument, '__toString')) {
return false;
}
if (is_object($this->value) && !method_exists($this->value, '__toString')) {
return false;
}
} elseif (is_numeric($argument) && is_numeric($this->value)) {
} elseif (gettype($argument) !== gettype($this->value)) {
return false;
}
return $argument == $this->value ? 10 : false;
}
public function getValue()
{
return $this->value;
}
public function isLast()
{
return false;
}
public function __toString()
{
if (null === $this->string) {
$this->string = sprintf('exact(%s)', $this->util->stringify($this->value));
}
return $this->string;
}
}
<?php
namespace Prophecy\Argument\Token;
use Prophecy\Util\StringUtil;
class IdenticalValueToken implements TokenInterface
{
private $value;
private $string;
private $util;
public function __construct($value, StringUtil $util = null)
{
$this->value = $value;
$this->util = $util ?: new StringUtil();
}
public function scoreArgument($argument)
{
return $argument === $this->value ? 11 : false;
}
public function isLast()
{
return false;
}
public function __toString()
{
if (null === $this->string) {
$this->string = sprintf('identical(%s)', $this->util->stringify($this->value));
}
return $this->string;
}
}
<?php
namespace Prophecy\Argument\Token;
class LogicalAndToken implements TokenInterface
{
private $tokens = array();
public function __construct(array $arguments)
{
foreach ($arguments as $argument) {
if (!$argument instanceof TokenInterface) {
$argument = new ExactValueToken($argument);
}
$this->tokens[] = $argument;
}
}
public function scoreArgument($argument)
{
if (0 === count($this->tokens)) {
return false;
}
$maxScore = 0;
foreach ($this->tokens as $token) {
$score = $token->scoreArgument($argument);
if (false === $score) {
return false;
}
$maxScore = max($score, $maxScore);
}
return $maxScore;
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('bool(%s)', implode(' AND ', $this->tokens));
}
}
<?php
namespace Prophecy\Argument\Token;
class LogicalNotToken implements TokenInterface
{
private $token;
public function __construct($value)
{
$this->token = $value instanceof TokenInterface? $value : new ExactValueToken($value);
}
public function scoreArgument($argument)
{
return false === $this->token->scoreArgument($argument) ? 4 : false;
}
public function isLast()
{
return $this->token->isLast();
}
public function getOriginatingToken()
{
return $this->token;
}
public function __toString()
{
return sprintf('not(%s)', $this->token);
}
}
<?php
namespace Prophecy\Argument\Token;
use SebastianBergmann\Comparator\ComparisonFailure;
use Prophecy\Comparator\Factory as ComparatorFactory;
use Prophecy\Util\StringUtil;
class ObjectStateToken implements TokenInterface
{
private $name;
private $value;
private $util;
private $comparatorFactory;
public function __construct(
$methodName,
$value,
StringUtil $util = null,
ComparatorFactory $comparatorFactory = null
) {
$this->name = $methodName;
$this->value = $value;
$this->util = $util ?: new StringUtil;
$this->comparatorFactory = $comparatorFactory ?: ComparatorFactory::getInstance();
}
public function scoreArgument($argument)
{
if (is_object($argument) && method_exists($argument, $this->name)) {
$actual = call_user_func(array($argument, $this->name));
$comparator = $this->comparatorFactory->getComparatorFor(
$actual, $this->value
);
try {
$comparator->assertEquals($actual, $this->value);
return 8;
} catch (ComparisonFailure $failure) {
return false;
}
}
if (is_object($argument) && property_exists($argument, $this->name)) {
return $argument->{$this->name} === $this->value ? 8 : false;
}
return false;
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('state(%s(), %s)',
$this->name,
$this->util->stringify($this->value)
);
}
}
<?php
namespace Prophecy\Argument\Token;
class StringContainsToken implements TokenInterface
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function scoreArgument($argument)
{
return strpos($argument, $this->value) !== false ? 6 : false;
}
public function getValue()
{
return $this->value;
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('contains("%s")', $this->value);
}
}
<?php
namespace Prophecy\Argument\Token;
interface TokenInterface
{
public function scoreArgument($argument);
public function isLast();
public function __toString();
}
<?php
namespace Prophecy\Argument\Token;
use Prophecy\Exception\InvalidArgumentException;
class TypeToken implements TokenInterface
{
private $type;
public function __construct($type)
{
$checker = "is_{$type}";
if (!function_exists($checker) && !interface_exists($type) && !class_exists($type)) {
throw new InvalidArgumentException(sprintf(
'Type or class name expected as an argument to TypeToken, but got %s.', $type
));
}
$this->type = $type;
}
public function scoreArgument($argument)
{
$checker = "is_{$this->type}";
if (function_exists($checker)) {
return call_user_func($checker, $argument) ? 5 : false;
}
return $argument instanceof $this->type ? 5 : false;
}
public function isLast()
{
return false;
}
public function __toString()
{
return sprintf('type(%s)', $this->type);
}
}
<?php
namespace Prophecy\Call;
use Exception;
class Call
{
private $methodName;
private $arguments;
private $returnValue;
private $exception;
private $file;
private $line;
public function __construct($methodName, array $arguments, $returnValue,
Exception $exception = null, $file, $line)
{
$this->methodName = $methodName;
$this->arguments = $arguments;
$this->returnValue = $returnValue;
$this->exception = $exception;
if ($file) {
$this->file = $file;
$this->line = intval($line);
}
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
public function getReturnValue()
{
return $this->returnValue;
}
public function getException()
{
return $this->exception;
}
public function getFile()
{
return $this->file;
}
public function getLine()
{
return $this->line;
}
public function getCallPlace()
{
if (null === $this->file) {
return 'unknown';
}
return sprintf('%s:%d', $this->file, $this->line);
}
}
<?php
namespace Prophecy\Call;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Util\StringUtil;
use Prophecy\Exception\Call\UnexpectedCallException;
class CallCenter
{
private $util;
private $recordedCalls = array();
public function __construct(StringUtil $util = null)
{
$this->util = $util ?: new StringUtil;
}
public function makeCall(ObjectProphecy $prophecy, $methodName, array $arguments)
{
if (PHP_VERSION_ID >= 50400) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
} elseif (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
} else {
$backtrace = debug_backtrace();
}
$file = $line = null;
if (isset($backtrace[2]) && isset($backtrace[2]['file'])) {
$file = $backtrace[2]['file'];
$line = $backtrace[2]['line'];
}
if ('__destruct' === $methodName || 0 == count($prophecy->getMethodProphecies())) {
$this->recordedCalls[] = new Call($methodName, $arguments, null, null, $file, $line);
return null;
}
$matches = array();
foreach ($prophecy->getMethodProphecies($methodName) as $methodProphecy) {
if (0 < $score = $methodProphecy->getArgumentsWildcard()->scoreArguments($arguments)) {
$matches[] = array($score, $methodProphecy);
}
}
if (!count($matches)) {
throw $this->createUnexpectedCallException($prophecy, $methodName, $arguments);
}
@usort($matches, function ($match1, $match2) { return $match2[0] - $match1[0]; });
$returnValue = null;
$exception = null;
if ($promise = $matches[0][1]->getPromise()) {
try {
$returnValue = $promise->execute($arguments, $prophecy, $matches[0][1]);
} catch (\Exception $e) {
$exception = $e;
}
}
$this->recordedCalls[] = new Call(
$methodName, $arguments, $returnValue, $exception, $file, $line
);
if (null !== $exception) {
throw $exception;
}
return $returnValue;
}
public function findCalls($methodName, ArgumentsWildcard $wildcard)
{
return array_values(
array_filter($this->recordedCalls, function (Call $call) use ($methodName, $wildcard) {
return $methodName === $call->getMethodName()
&& 0 < $wildcard->scoreArguments($call->getArguments())
;
})
);
}
private function createUnexpectedCallException(ObjectProphecy $prophecy, $methodName,
array $arguments)
{
$classname = get_class($prophecy->reveal());
$argstring = implode(', ', array_map(array($this->util, 'stringify'), $arguments));
$expected = implode("\n", array_map(function (MethodProphecy $methodProphecy) {
return sprintf(' - %s(%s)',
$methodProphecy->getMethodName(),
$methodProphecy->getArgumentsWildcard()
);
}, call_user_func_array('array_merge', $prophecy->getMethodProphecies())));
return new UnexpectedCallException(
sprintf(
"Method call:\n".
" - %s(%s)\n".
"on %s was not expected, expected calls were:\n%s",
$methodName, $argstring, $classname, $expected
),
$prophecy, $methodName, $arguments
);
}
}
<?php
namespace Prophecy\Comparator;
use SebastianBergmann\Comparator\Comparator;
use SebastianBergmann\Comparator\ComparisonFailure;
final class ClosureComparator extends Comparator
{
public function accepts($expected, $actual)
{
return is_object($expected) && $expected instanceof \Closure
&& is_object($actual) && $actual instanceof \Closure;
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
{
throw new ComparisonFailure(
$expected,
$actual,
'',
'',
false,
'all closures are born different'
);
}
}
<?php
namespace Prophecy\Comparator;
use SebastianBergmann\Comparator\Factory as BaseFactory;
final class Factory extends BaseFactory
{
private static $instance;
public function __construct()
{
parent::__construct();
$this->register(new ClosureComparator());
$this->register(new ProphecyComparator());
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new Factory;
}
return self::$instance;
}
}
<?php
namespace Prophecy\Comparator;
use Prophecy\Prophecy\ProphecyInterface;
use SebastianBergmann\Comparator\ObjectComparator;
class ProphecyComparator extends ObjectComparator
{
public function accepts($expected, $actual)
{
return is_object($expected) && is_object($actual) && $actual instanceof ProphecyInterface;
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
{
parent::assertEquals($expected, $actual->reveal(), $delta, $canonicalize, $ignoreCase, $processed);
}
}
<?php
namespace Prophecy\Doubler;
use ReflectionClass;
class CachedDoubler extends Doubler
{
private $classes = array();
public function registerClassPatch(ClassPatch\ClassPatchInterface $patch)
{
$this->classes[] = array();
parent::registerClassPatch($patch);
}
protected function createDoubleClass(ReflectionClass $class = null, array $interfaces)
{
$classId = $this->generateClassId($class, $interfaces);
if (isset($this->classes[$classId])) {
return $this->classes[$classId];
}
return $this->classes[$classId] = parent::createDoubleClass($class, $interfaces);
}
private function generateClassId(ReflectionClass $class = null, array $interfaces)
{
$parts = array();
if (null !== $class) {
$parts[] = $class->getName();
}
foreach ($interfaces as $interface) {
$parts[] = $interface->getName();
}
sort($parts);
return md5(implode('', $parts));
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
interface ClassPatchInterface
{
public function supports(ClassNode $node);
public function apply(ClassNode $node);
public function getPriority();
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;
class DisableConstructorPatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
return true;
}
public function apply(ClassNode $node)
{
if (!$node->hasMethod('__construct')) {
$node->addMethod(new MethodNode('__construct', ''));
return;
}
$constructor = $node->getMethod('__construct');
foreach ($constructor->getArguments() as $argument) {
$argument->setDefault(null);
}
$constructor->setCode(<<<PHP
if (0 < func_num_args()) {
call_user_func_array(array('parent', '__construct'), func_get_args());
}
PHP
);
}
public function getPriority()
{
return 100;
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
class HhvmExceptionPatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
if (!defined('HHVM_VERSION')) {
return false;
}
return 'Exception' === $node->getParentClass() || is_subclass_of($node->getParentClass(), 'Exception');
}
public function apply(ClassNode $node)
{
if ($node->hasMethod('setTraceOptions')) {
$node->getMethod('setTraceOptions')->useParentCode();
}
if ($node->hasMethod('getTraceOptions')) {
$node->getMethod('getTraceOptions')->useParentCode();
}
}
public function getPriority()
{
return -50;
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
class KeywordPatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
return true;
}
public function apply(ClassNode $node)
{
$methodNames = array_keys($node->getMethods());
$methodsToRemove = array_intersect($methodNames, $this->getKeywords());
foreach ($methodsToRemove as $methodName) {
$node->removeMethod($methodName);
}
}
public function getPriority() {
return 49;
}
private function getKeywords() {
return array(
'__halt_compiler',
'abstract',
'and',
'array',
'as',
'break',
'callable',
'case',
'catch',
'class',
'clone',
'const',
'continue',
'declare',
'default',
'die',
'do',
'echo',
'else',
'elseif',
'empty',
'enddeclare',
'endfor',
'endforeach',
'endif',
'endswitch',
'endwhile',
'eval',
'exit',
'extends',
'final',
'finally',
'for',
'foreach',
'function',
'global',
'goto',
'if',
'implements',
'include',
'include_once',
'instanceof',
'insteadof',
'interface',
'isset',
'list',
'namespace',
'new',
'or',
'print',
'private',
'protected',
'public',
'require',
'require_once',
'return',
'static',
'switch',
'throw',
'trait',
'try',
'unset',
'use',
'var',
'while',
'xor',
'yield',
);
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;
use Prophecy\PhpDocumentor\ClassAndInterfaceTagRetriever;
use Prophecy\PhpDocumentor\MethodTagRetrieverInterface;
class MagicCallPatch implements ClassPatchInterface
{
private $tagRetriever;
public function __construct(MethodTagRetrieverInterface $tagRetriever = null)
{
$this->tagRetriever = null === $tagRetriever ? new ClassAndInterfaceTagRetriever() : $tagRetriever;
}
public function supports(ClassNode $node)
{
return true;
}
public function apply(ClassNode $node)
{
$parentClass = $node->getParentClass();
$reflectionClass = new \ReflectionClass($parentClass);
$tagList = $this->tagRetriever->getTagList($reflectionClass);
foreach($tagList as $tag) {
$methodName = $tag->getMethodName();
if (empty($methodName)) {
continue;
}
if (!$reflectionClass->hasMethod($methodName)) {
$methodNode = new MethodNode($methodName);
$methodNode->setStatic($tag->isStatic());
$node->addMethod($methodNode);
}
}
}
public function getPriority()
{
return 50;
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;
use Prophecy\Doubler\Generator\Node\ArgumentNode;
class ProphecySubjectPatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
return true;
}
public function apply(ClassNode $node)
{
$node->addInterface('Prophecy\Prophecy\ProphecySubjectInterface');
$node->addProperty('objectProphecy', 'private');
foreach ($node->getMethods() as $name => $method) {
if ('__construct' === strtolower($name)) {
continue;
}
$method->setCode(
'return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());'
);
}
$prophecySetter = new MethodNode('setProphecy');
$prophecyArgument = new ArgumentNode('prophecy');
$prophecyArgument->setTypeHint('Prophecy\Prophecy\ProphecyInterface');
$prophecySetter->addArgument($prophecyArgument);
$prophecySetter->setCode('$this->objectProphecy = $prophecy;');
$prophecyGetter = new MethodNode('getProphecy');
$prophecyGetter->setCode('return $this->objectProphecy;');
if ($node->hasMethod('__call')) {
$__call = $node->getMethod('__call');
} else {
$__call = new MethodNode('__call');
$__call->addArgument(new ArgumentNode('name'));
$__call->addArgument(new ArgumentNode('arguments'));
$node->addMethod($__call);
}
$__call->setCode(<<<PHP
throw new \Prophecy\Exception\Doubler\MethodNotFoundException(
sprintf('Method `%s::%s()` not found.', get_class(\$this), func_get_arg(0)),
\$this->getProphecy(), func_get_arg(0)
);
PHP
);
$node->addMethod($prophecySetter);
$node->addMethod($prophecyGetter);
}
public function getPriority()
{
return 0;
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
class ReflectionClassNewInstancePatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
return 'ReflectionClass' === $node->getParentClass();
}
public function apply(ClassNode $node)
{
foreach ($node->getMethod('newInstance')->getArguments() as $argument) {
$argument->setDefault(null);
}
}
public function getPriority()
{
return 50;
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;
class SplFileInfoPatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
if (null === $node->getParentClass()) {
return false;
}
return 'SplFileInfo' === $node->getParentClass()
|| is_subclass_of($node->getParentClass(), 'SplFileInfo')
;
}
public function apply(ClassNode $node)
{
if ($node->hasMethod('__construct')) {
$constructor = $node->getMethod('__construct');
} else {
$constructor = new MethodNode('__construct');
$node->addMethod($constructor);
}
if ($this->nodeIsDirectoryIterator($node)) {
$constructor->setCode('return parent::__construct("' . __DIR__ . '");');
return;
}
if ($this->nodeIsSplFileObject($node)) {
$constructor->setCode('return parent::__construct("' . __FILE__ .'");');
return;
}
$constructor->useParentCode();
}
public function getPriority()
{
return 50;
}
private function nodeIsDirectoryIterator(ClassNode $node)
{
$parent = $node->getParentClass();
return 'DirectoryIterator' === $parent
|| is_subclass_of($parent, 'DirectoryIterator');
}
private function nodeIsSplFileObject(ClassNode $node)
{
$parent = $node->getParentClass();
return 'SplFileObject' === $parent
|| is_subclass_of($parent, 'SplFileObject');
}
}
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;
class TraversablePatch implements ClassPatchInterface
{
public function supports(ClassNode $node)
{
if (in_array('Iterator', $node->getInterfaces())) {
return false;
}
if (in_array('IteratorAggregate', $node->getInterfaces())) {
return false;
}
foreach ($node->getInterfaces() as $interface) {
if ('Traversable' !== $interface && !is_subclass_of($interface, 'Traversable')) {
continue;
}
if ('Iterator' === $interface || is_subclass_of($interface, 'Iterator')) {
continue;
}
if ('IteratorAggregate' === $interface || is_subclass_of($interface, 'IteratorAggregate')) {
continue;
}
return true;
}
return false;
}
public function apply(ClassNode $node)
{
$node->addInterface('Iterator');
$node->addMethod(new MethodNode('current'));
$node->addMethod(new MethodNode('key'));
$node->addMethod(new MethodNode('next'));
$node->addMethod(new MethodNode('rewind'));
$node->addMethod(new MethodNode('valid'));
}
public function getPriority()
{
return 100;
}
}
<?php
namespace Prophecy\Doubler;
interface DoubleInterface
{
}
<?php
namespace Prophecy\Doubler;
use Doctrine\Instantiator\Instantiator;
use Prophecy\Doubler\ClassPatch\ClassPatchInterface;
use Prophecy\Doubler\Generator\ClassMirror;
use Prophecy\Doubler\Generator\ClassCreator;
use Prophecy\Exception\InvalidArgumentException;
use ReflectionClass;
class Doubler
{
private $mirror;
private $creator;
private $namer;
private $patches = array();
private $instantiator;
public function __construct(ClassMirror $mirror = null, ClassCreator $creator = null,
NameGenerator $namer = null)
{
$this->mirror = $mirror ?: new ClassMirror;
$this->creator = $creator ?: new ClassCreator;
$this->namer = $namer ?: new NameGenerator;
}
public function getClassPatches()
{
return $this->patches;
}
public function registerClassPatch(ClassPatchInterface $patch)
{
$this->patches[] = $patch;
@usort($this->patches, function (ClassPatchInterface $patch1, ClassPatchInterface $patch2) {
return $patch2->getPriority() - $patch1->getPriority();
});
}
public function double(ReflectionClass $class = null, array $interfaces, array $args = null)
{
foreach ($interfaces as $interface) {
if (!$interface instanceof ReflectionClass) {
throw new InvalidArgumentException(sprintf(
"[ReflectionClass \$interface1 [, ReflectionClass \$interface2]] array expected as\n".
"a second argument to `Doubler::double(...)`, but got %s.",
is_object($interface) ? get_class($interface).' class' : gettype($interface)
));
}
}
$classname = $this->createDoubleClass($class, $interfaces);
$reflection = new ReflectionClass($classname);
if (null !== $args) {
return $reflection->newInstanceArgs($args);
}
if ((null === $constructor = $reflection->getConstructor())
|| ($constructor->isPublic() && !$constructor->isFinal())) {
return $reflection->newInstance();
}
if (!$this->instantiator) {
$this->instantiator = new Instantiator();
}
return $this->instantiator->instantiate($classname);
}
protected function createDoubleClass(ReflectionClass $class = null, array $interfaces)
{
$name = $this->namer->name($class, $interfaces);
$node = $this->mirror->reflect($class, $interfaces);
foreach ($this->patches as $patch) {
if ($patch->supports($node)) {
$patch->apply($node);
}
}
$this->creator->create($name, $node);
return $name;
}
}
<?php
namespace Prophecy\Doubler\Generator;
class ClassCodeGenerator
{
public function generate($classname, Node\ClassNode $class)
{
$parts = explode('\\', $classname);
$classname = array_pop($parts);
$namespace = implode('\\', $parts);
$code = sprintf("class %s extends \%s implements %s {\n",
$classname, $class->getParentClass(), implode(', ',
array_map(function ($interface) {return '\\'.$interface;}, $class->getInterfaces())
)
);
foreach ($class->getProperties() as $name => $visibility) {
$code .= sprintf("%s \$%s;\n", $visibility, $name);
}
$code .= "\n";
foreach ($class->getMethods() as $method) {
$code .= $this->generateMethod($method)."\n";
}
$code .= "\n}";
return sprintf("namespace %s {\n%s\n}", $namespace, $code);
}
private function generateMethod(Node\MethodNode $method)
{
$php = sprintf("%s %s function %s%s(%s)%s {\n",
$method->getVisibility(),
$method->isStatic() ? 'static' : '',
$method->returnsReference() ? '&':'',
$method->getName(),
implode(', ', $this->generateArguments($method->getArguments())),
version_compare(PHP_VERSION, '7.0', '>=') && $method->hasReturnType()
? sprintf(': %s', $method->getReturnType())
: ''
);
$php .= $method->getCode()."\n";
return $php.'}';
}
private function generateArguments(array $arguments)
{
return array_map(function (Node\ArgumentNode $argument) {
$php = '';
if ($hint = $argument->getTypeHint()) {
switch ($hint) {
case 'array':
case 'callable':
$php .= $hint;
break;
case 'string':
case 'int':
case 'float':
case 'bool':
if (version_compare(PHP_VERSION, '7.0', '>=')) {
$php .= $hint;
break;
}
default:
$php .= '\\'.$hint;
}
}
$php .= ' '.($argument->isPassedByReference() ? '&' : '');
$php .= $argument->isVariadic() ? '...' : '';
$php .= '$'.$argument->getName();
if ($argument->isOptional() && !$argument->isVariadic()) {
$php .= ' = '.var_export($argument->getDefault(), true);
}
return $php;
}, $arguments);
}
}
<?php
namespace Prophecy\Doubler\Generator;
use Prophecy\Exception\Doubler\ClassCreatorException;
class ClassCreator
{
private $generator;
public function __construct(ClassCodeGenerator $generator = null)
{
$this->generator = $generator ?: new ClassCodeGenerator;
}
public function create($classname, Node\ClassNode $class)
{
$code = $this->generator->generate($classname, $class);
$return = eval($code);
if (!class_exists($classname, false)) {
if (count($class->getInterfaces())) {
throw new ClassCreatorException(sprintf(
'Could not double `%s` and implement interfaces: [%s].',
$class->getParentClass(), implode(', ', $class->getInterfaces())
), $class);
}
throw new ClassCreatorException(
sprintf('Could not double `%s`.', $class->getParentClass()),
$class
);
}
return $return;
}
}
<?php
namespace Prophecy\Doubler\Generator;
use Prophecy\Exception\InvalidArgumentException;
use Prophecy\Exception\Doubler\ClassMirrorException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
class ClassMirror
{
private static $reflectableMethods = array(
'__construct',
'__destruct',
'__sleep',
'__wakeup',
'__toString',
'__call',
'__invoke'
);
public function reflect(ReflectionClass $class = null, array $interfaces)
{
$node = new Node\ClassNode;
if (null !== $class) {
if (true === $class->isInterface()) {
throw new InvalidArgumentException(sprintf(
"Could not reflect %s as a class, because it\n".
"is interface - use the second argument instead.",
$class->getName()
));
}
$this->reflectClassToNode($class, $node);
}
foreach ($interfaces as $interface) {
if (!$interface instanceof ReflectionClass) {
throw new InvalidArgumentException(sprintf(
"[ReflectionClass \$interface1 [, ReflectionClass \$interface2]] array expected as\n".
"a second argument to `ClassMirror::reflect(...)`, but got %s.",
is_object($interface) ? get_class($interface).' class' : gettype($interface)
));
}
if (false === $interface->isInterface()) {
throw new InvalidArgumentException(sprintf(
"Could not reflect %s as an interface, because it\n".
"is class - use the first argument instead.",
$interface->getName()
));
}
$this->reflectInterfaceToNode($interface, $node);
}
$node->addInterface('Prophecy\Doubler\Generator\ReflectionInterface');
return $node;
}
private function reflectClassToNode(ReflectionClass $class, Node\ClassNode $node)
{
if (true === $class->isFinal()) {
throw new ClassMirrorException(sprintf(
'Could not reflect class %s as it is marked final.', $class->getName()
), $class);
}
$node->setParentClass($class->getName());
foreach ($class->getMethods(ReflectionMethod::IS_ABSTRACT) as $method) {
if (false === $method->isProtected()) {
continue;
}
$this->reflectMethodToNode($method, $node);
}
foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (0 === strpos($method->getName(), '_')
&& !in_array($method->getName(), self::$reflectableMethods)) {
continue;
}
if (true === $method->isFinal()) {
$node->addUnextendableMethod($method->getName());
continue;
}
$this->reflectMethodToNode($method, $node);
}
}
private function reflectInterfaceToNode(ReflectionClass $interface, Node\ClassNode $node)
{
$node->addInterface($interface->getName());
foreach ($interface->getMethods() as $method) {
$this->reflectMethodToNode($method, $node);
}
}
private function reflectMethodToNode(ReflectionMethod $method, Node\ClassNode $classNode)
{
$node = new Node\MethodNode($method->getName());
if (true === $method->isProtected()) {
$node->setVisibility('protected');
}
if (true === $method->isStatic()) {
$node->setStatic();
}
if (true === $method->returnsReference()) {
$node->setReturnsReference();
}
if (version_compare(PHP_VERSION, '7.0', '>=') && true === $method->hasReturnType()) {
$returnType = (string) $method->getReturnType();
$returnTypeLower = strtolower($returnType);
if ('self' === $returnTypeLower) {
$returnType = $method->getDeclaringClass()->getName();
}
if ('parent' === $returnTypeLower) {
$returnType = $method->getDeclaringClass()->getParentClass()->getName();
}
$node->setReturnType($returnType);
}
if (is_array($params = $method->getParameters()) && count($params)) {
foreach ($params as $param) {
$this->reflectArgumentToNode($param, $node);
}
}
$classNode->addMethod($node);
}
private function reflectArgumentToNode(ReflectionParameter $parameter, Node\MethodNode $methodNode)
{
$name = $parameter->getName() == '...' ? '__dot_dot_dot__' : $parameter->getName();
$node = new Node\ArgumentNode($name);
$node->setTypeHint($this->getTypeHint($parameter));
if ($this->isVariadic($parameter)) {
$node->setAsVariadic();
}
if ($this->hasDefaultValue($parameter)) {
$node->setDefault($this->getDefaultValue($parameter));
}
if ($parameter->isPassedByReference()) {
$node->setAsPassedByReference();
}
$methodNode->addArgument($node);
}
private function hasDefaultValue(ReflectionParameter $parameter)
{
if ($this->isVariadic($parameter)) {
return false;
}
if ($parameter->isDefaultValueAvailable()) {
return true;
}
return $parameter->isOptional() || $this->isNullable($parameter);
}
private function getDefaultValue(ReflectionParameter $parameter)
{
if (!$parameter->isDefaultValueAvailable()) {
return null;
}
return $parameter->getDefaultValue();
}
private function getTypeHint(ReflectionParameter $parameter)
{
if (null !== $className = $this->getParameterClassName($parameter)) {
return $className;
}
if (true === $parameter->isArray()) {
return 'array';
}
if (version_compare(PHP_VERSION, '5.4', '>=') && true === $parameter->isCallable()) {
return 'callable';
}
if (version_compare(PHP_VERSION, '7.0', '>=') && true === $parameter->hasType()) {
return (string) $parameter->getType();
}
return null;
}
private function isVariadic(ReflectionParameter $parameter)
{
return PHP_VERSION_ID >= 50600 && $parameter->isVariadic();
}
private function isNullable(ReflectionParameter $parameter)
{
return $parameter->allowsNull() && null !== $this->getTypeHint($parameter);
}
private function getParameterClassName(ReflectionParameter $parameter)
{
try {
return $parameter->getClass() ? $parameter->getClass()->getName() : null;
} catch (\ReflectionException $e) {
preg_match('/\[\s\<\w+?>\s([\w,\\\]+)/s', $parameter, $matches);
return isset($matches[1]) ? $matches[1] : null;
}
}
}
<?php
namespace Prophecy\Doubler\Generator\Node;
class ArgumentNode
{
private $name;
private $typeHint;
private $default;
private $optional = false;
private $byReference = false;
private $isVariadic = false;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function getTypeHint()
{
return $this->typeHint;
}
public function setTypeHint($typeHint = null)
{
$this->typeHint = $typeHint;
}
public function hasDefault()
{
return $this->isOptional() && !$this->isVariadic();
}
public function getDefault()
{
return $this->default;
}
public function setDefault($default = null)
{
$this->optional = true;
$this->default = $default;
}
public function isOptional()
{
return $this->optional;
}
public function setAsPassedByReference($byReference = true)
{
$this->byReference = $byReference;
}
public function isPassedByReference()
{
return $this->byReference;
}
public function setAsVariadic($isVariadic = true)
{
$this->isVariadic = $isVariadic;
}
public function isVariadic()
{
return $this->isVariadic;
}
}
<?php
namespace Prophecy\Doubler\Generator\Node;
use Prophecy\Exception\Doubler\MethodNotExtendableException;
use Prophecy\Exception\InvalidArgumentException;
class ClassNode
{
private $parentClass = 'stdClass';
private $interfaces = array();
private $properties = array();
private $unextendableMethods = array();
private $methods = array();
public function getParentClass()
{
return $this->parentClass;
}
public function setParentClass($class)
{
$this->parentClass = $class ?: 'stdClass';
}
public function getInterfaces()
{
return $this->interfaces;
}
public function addInterface($interface)
{
if ($this->hasInterface($interface)) {
return;
}
array_unshift($this->interfaces, $interface);
}
public function hasInterface($interface)
{
return in_array($interface, $this->interfaces);
}
public function getProperties()
{
return $this->properties;
}
public function addProperty($name, $visibility = 'public')
{
$visibility = strtolower($visibility);
if (!in_array($visibility, array('public', 'private', 'protected'))) {
throw new InvalidArgumentException(sprintf(
'`%s` property visibility is not supported.', $visibility
));
}
$this->properties[$name] = $visibility;
}
public function getMethods()
{
return $this->methods;
}
public function addMethod(MethodNode $method)
{
if (!$this->isExtendable($method->getName())){
$message = sprintf(
'Method `%s` is not extendable, so can not be added.', $method->getName()
);
throw new MethodNotExtendableException($message, $this->getParentClass(), $method->getName());
}
$this->methods[$method->getName()] = $method;
}
public function removeMethod($name)
{
unset($this->methods[$name]);
}
public function getMethod($name)
{
return $this->hasMethod($name) ? $this->methods[$name] : null;
}
public function hasMethod($name)
{
return isset($this->methods[$name]);
}
public function getUnextendableMethods()
{
return $this->unextendableMethods;
}
public function addUnextendableMethod($unextendableMethod)
{
if (!$this->isExtendable($unextendableMethod)){
return;
}
$this->unextendableMethods[] = $unextendableMethod;
}
public function isExtendable($method)
{
return !in_array($method, $this->unextendableMethods);
}
}
<?php
namespace Prophecy\Doubler\Generator\Node;
use Prophecy\Exception\InvalidArgumentException;
class MethodNode
{
private $name;
private $code;
private $visibility = 'public';
private $static = false;
private $returnsReference = false;
private $returnType;
private $arguments = array();
public function __construct($name, $code = null)
{
$this->name = $name;
$this->code = $code;
}
public function getVisibility()
{
return $this->visibility;
}
public function setVisibility($visibility)
{
$visibility = strtolower($visibility);
if (!in_array($visibility, array('public', 'private', 'protected'))) {
throw new InvalidArgumentException(sprintf(
'`%s` method visibility is not supported.', $visibility
));
}
$this->visibility = $visibility;
}
public function isStatic()
{
return $this->static;
}
public function setStatic($static = true)
{
$this->static = (bool) $static;
}
public function returnsReference()
{
return $this->returnsReference;
}
public function setReturnsReference()
{
$this->returnsReference = true;
}
public function getName()
{
return $this->name;
}
public function addArgument(ArgumentNode $argument)
{
$this->arguments[] = $argument;
}
public function getArguments()
{
return $this->arguments;
}
public function hasReturnType()
{
return null !== $this->returnType;
}
public function setReturnType($type = null)
{
switch ($type) {
case '':
$this->returnType = null;
break;
case 'string';
case 'float':
case 'int':
case 'bool':
case 'array':
case 'callable':
$this->returnType = $type;
break;
case 'double':
case 'real':
$this->returnType = 'float';
break;
case 'boolean':
$this->returnType = 'bool';
break;
case 'integer':
$this->returnType = 'int';
break;
default:
$this->returnType = '\\' . ltrim($type, '\\');
}
}
public function getReturnType()
{
return $this->returnType;
}
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
if ($this->returnsReference)
{
return "throw new \Prophecy\Exception\Doubler\ReturnByReferenceException('Returning by reference not supported', get_class(\$this), '{$this->name}');";
}
return (string) $this->code;
}
public function useParentCode()
{
$this->code = sprintf(
'return parent::%s(%s);', $this->getName(), implode(', ',
array_map(array($this, 'generateArgument'), $this->arguments)
)
);
}
private function generateArgument(ArgumentNode $arg)
{
$argument = '$'.$arg->getName();
if ($arg->isVariadic()) {
$argument = '...'.$argument;
}
return $argument;
}
}
<?php
namespace Prophecy\Doubler\Generator;
interface ReflectionInterface
{
}
<?php
namespace Prophecy\Doubler;
use Prophecy\Exception\Doubler\DoubleException;
use Prophecy\Exception\Doubler\ClassNotFoundException;
use Prophecy\Exception\Doubler\InterfaceNotFoundException;
use ReflectionClass;
class LazyDouble
{
private $doubler;
private $class;
private $interfaces = array();
private $arguments = null;
private $double;
public function __construct(Doubler $doubler)
{
$this->doubler = $doubler;
}
public function setParentClass($class)
{
if (null !== $this->double) {
throw new DoubleException('Can not extend class with already instantiated double.');
}
if (!$class instanceof ReflectionClass) {
if (!class_exists($class)) {
throw new ClassNotFoundException(sprintf('Class %s not found.', $class), $class);
}
$class = new ReflectionClass($class);
}
$this->class = $class;
}
public function addInterface($interface)
{
if (null !== $this->double) {
throw new DoubleException(
'Can not implement interface with already instantiated double.'
);
}
if (!$interface instanceof ReflectionClass) {
if (!interface_exists($interface)) {
throw new InterfaceNotFoundException(
sprintf('Interface %s not found.', $interface),
$interface
);
}
$interface = new ReflectionClass($interface);
}
$this->interfaces[] = $interface;
}
public function setArguments(array $arguments = null)
{
$this->arguments = $arguments;
}
public function getInstance()
{
if (null === $this->double) {
if (null !== $this->arguments) {
return $this->double = $this->doubler->double(
$this->class, $this->interfaces, $this->arguments
);
}
$this->double = $this->doubler->double($this->class, $this->interfaces);
}
return $this->double;
}
}
<?php
namespace Prophecy\Doubler;
use ReflectionClass;
class NameGenerator
{
private static $counter = 1;
public function name(ReflectionClass $class = null, array $interfaces)
{
$parts = array();
if (null !== $class) {
$parts[] = $class->getName();
} else {
foreach ($interfaces as $interface) {
$parts[] = $interface->getShortName();
}
}
if (!count($parts)) {
$parts[] = 'stdClass';
}
return sprintf('Double\%s\P%d', implode('\\', $parts), self::$counter++);
}
}
<?php
namespace Prophecy\Exception\Call;
use Prophecy\Exception\Prophecy\ObjectProphecyException;
use Prophecy\Prophecy\ObjectProphecy;
class UnexpectedCallException extends ObjectProphecyException
{
private $methodName;
private $arguments;
public function __construct($message, ObjectProphecy $objectProphecy,
$methodName, array $arguments)
{
parent::__construct($message, $objectProphecy);
$this->methodName = $methodName;
$this->arguments = $arguments;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
}
<?php
namespace Prophecy\Exception\Doubler;
use Prophecy\Doubler\Generator\Node\ClassNode;
class ClassCreatorException extends \RuntimeException implements DoublerException
{
private $node;
public function __construct($message, ClassNode $node)
{
parent::__construct($message);
$this->node = $node;
}
public function getClassNode()
{
return $this->node;
}
}
<?php
namespace Prophecy\Exception\Doubler;
use ReflectionClass;
class ClassMirrorException extends \RuntimeException implements DoublerException
{
private $class;
public function __construct($message, ReflectionClass $class)
{
parent::__construct($message);
$this->class = $class;
}
public function getReflectedClass()
{
return $this->class;
}
}
<?php
namespace Prophecy\Exception\Doubler;
class ClassNotFoundException extends DoubleException
{
private $classname;
public function __construct($message, $classname)
{
parent::__construct($message);
$this->classname = $classname;
}
public function getClassname()
{
return $this->classname;
}
}
<?php
namespace Prophecy\Exception\Doubler;
use RuntimeException;
class DoubleException extends RuntimeException implements DoublerException
{
}
<?php
namespace Prophecy\Exception\Doubler;
use Prophecy\Exception\Exception;
interface DoublerException extends Exception
{
}
<?php
namespace Prophecy\Exception\Doubler;
class InterfaceNotFoundException extends ClassNotFoundException
{
public function getInterfaceName()
{
return $this->getClassname();
}
}
<?php
namespace Prophecy\Exception\Doubler;
class MethodNotExtendableException extends DoubleException
{
private $methodName;
private $className;
public function __construct($message, $className, $methodName)
{
parent::__construct($message);
$this->methodName = $methodName;
$this->className = $className;
}
public function getMethodName()
{
return $this->methodName;
}
public function getClassName()
{
return $this->className;
}
}
<?php
namespace Prophecy\Exception\Doubler;
class MethodNotFoundException extends DoubleException
{
private $classname;
private $methodName;
private $arguments;
public function __construct($message, $classname, $methodName, $arguments = null)
{
parent::__construct($message);
$this->classname = $classname;
$this->methodName = $methodName;
$this->arguments = $arguments;
}
public function getClassname()
{
return $this->classname;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
}
<?php
namespace Prophecy\Exception\Doubler;
class ReturnByReferenceException extends DoubleException
{
private $classname;
private $methodName;
public function __construct($message, $classname, $methodName)
{
parent::__construct($message);
$this->classname = $classname;
$this->methodName = $methodName;
}
public function getClassname()
{
return $this->classname;
}
public function getMethodName()
{
return $this->methodName;
}
}
<?php
namespace Prophecy\Exception;
interface Exception
{
public function getMessage();
}
<?php
namespace Prophecy\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
namespace Prophecy\Exception\Prediction;
use Prophecy\Prophecy\ObjectProphecy;
class AggregateException extends \RuntimeException implements PredictionException
{
private $exceptions = array();
private $objectProphecy;
public function append(PredictionException $exception)
{
$message = $exception->getMessage();
$message = ' '.strtr($message, array("\n" => "\n "))."\n";
$this->message = rtrim($this->message.$message);
$this->exceptions[] = $exception;
}
public function getExceptions()
{
return $this->exceptions;
}
public function setObjectProphecy(ObjectProphecy $objectProphecy)
{
$this->objectProphecy = $objectProphecy;
}
public function getObjectProphecy()
{
return $this->objectProphecy;
}
}
<?php
namespace Prophecy\Exception\Prediction;
use RuntimeException;
class FailedPredictionException extends RuntimeException implements PredictionException
{
}
<?php
namespace Prophecy\Exception\Prediction;
use Prophecy\Exception\Prophecy\MethodProphecyException;
class NoCallsException extends MethodProphecyException implements PredictionException
{
}
<?php
namespace Prophecy\Exception\Prediction;
use Prophecy\Exception\Exception;
interface PredictionException extends Exception
{
}
<?php
namespace Prophecy\Exception\Prediction;
use Prophecy\Prophecy\MethodProphecy;
class UnexpectedCallsCountException extends UnexpectedCallsException
{
private $expectedCount;
public function __construct($message, MethodProphecy $methodProphecy, $count, array $calls)
{
parent::__construct($message, $methodProphecy, $calls);
$this->expectedCount = intval($count);
}
public function getExpectedCount()
{
return $this->expectedCount;
}
}
<?php
namespace Prophecy\Exception\Prediction;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Exception\Prophecy\MethodProphecyException;
class UnexpectedCallsException extends MethodProphecyException implements PredictionException
{
private $calls = array();
public function __construct($message, MethodProphecy $methodProphecy, array $calls)
{
parent::__construct($message, $methodProphecy);
$this->calls = $calls;
}
public function getCalls()
{
return $this->calls;
}
}
<?php
namespace Prophecy\Exception\Prophecy;
use Prophecy\Prophecy\MethodProphecy;
class MethodProphecyException extends ObjectProphecyException
{
private $methodProphecy;
public function __construct($message, MethodProphecy $methodProphecy)
{
parent::__construct($message, $methodProphecy->getObjectProphecy());
$this->methodProphecy = $methodProphecy;
}
public function getMethodProphecy()
{
return $this->methodProphecy;
}
}
<?php
namespace Prophecy\Exception\Prophecy;
use Prophecy\Prophecy\ObjectProphecy;
class ObjectProphecyException extends \RuntimeException implements ProphecyException
{
private $objectProphecy;
public function __construct($message, ObjectProphecy $objectProphecy)
{
parent::__construct($message);
$this->objectProphecy = $objectProphecy;
}
public function getObjectProphecy()
{
return $this->objectProphecy;
}
}
<?php
namespace Prophecy\Exception\Prophecy;
use Prophecy\Exception\Exception;
interface ProphecyException extends Exception
{
}
<?php
namespace Prophecy\PhpDocumentor;
use phpDocumentor\Reflection\DocBlock\Tag\MethodTag as LegacyMethodTag;
use phpDocumentor\Reflection\DocBlock\Tags\Method;
final class ClassAndInterfaceTagRetriever implements MethodTagRetrieverInterface
{
private $classRetriever;
public function __construct(MethodTagRetrieverInterface $classRetriever = null)
{
if (null !== $classRetriever) {
$this->classRetriever = $classRetriever;
return;
}
$this->classRetriever = class_exists('phpDocumentor\Reflection\DocBlockFactory') && class_exists('phpDocumentor\Reflection\Types\ContextFactory')
? new ClassTagRetriever()
: new LegacyClassTagRetriever()
;
}
public function getTagList(\ReflectionClass $reflectionClass)
{
return array_merge(
$this->classRetriever->getTagList($reflectionClass),
$this->getInterfacesTagList($reflectionClass)
);
}
private function getInterfacesTagList(\ReflectionClass $reflectionClass)
{
$interfaces = $reflectionClass->getInterfaces();
$tagList = array();
foreach($interfaces as $interface) {
$tagList = array_merge($tagList, $this->classRetriever->getTagList($interface));
}
return $tagList;
}
}
<?php
namespace Prophecy\PhpDocumentor;
use phpDocumentor\Reflection\DocBlock\Tags\Method;
use phpDocumentor\Reflection\DocBlockFactory;
use phpDocumentor\Reflection\Types\ContextFactory;
final class ClassTagRetriever implements MethodTagRetrieverInterface
{
private $docBlockFactory;
private $contextFactory;
public function __construct()
{
$this->docBlockFactory = DocBlockFactory::createInstance();
$this->contextFactory = new ContextFactory();
}
public function getTagList(\ReflectionClass $reflectionClass)
{
try {
$phpdoc = $this->docBlockFactory->create(
$reflectionClass,
$this->contextFactory->createFromReflector($reflectionClass)
);
return $phpdoc->getTagsByName('method');
} catch (\InvalidArgumentException $e) {
return array();
}
}
}
<?php
namespace Prophecy\PhpDocumentor;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tag\MethodTag as LegacyMethodTag;
final class LegacyClassTagRetriever implements MethodTagRetrieverInterface
{
public function getTagList(\ReflectionClass $reflectionClass)
{
$phpdoc = new DocBlock($reflectionClass->getDocComment());
return $phpdoc->getTagsByName('method');
}
}
<?php
namespace Prophecy\PhpDocumentor;
use phpDocumentor\Reflection\DocBlock\Tag\MethodTag as LegacyMethodTag;
use phpDocumentor\Reflection\DocBlock\Tags\Method;
interface MethodTagRetrieverInterface
{
public function getTagList(\ReflectionClass $reflectionClass);
}
<?php
namespace Prophecy\Prediction;
use Prophecy\Call\Call;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Argument\Token\AnyValuesToken;
use Prophecy\Util\StringUtil;
use Prophecy\Exception\Prediction\NoCallsException;
class CallPrediction implements PredictionInterface
{
private $util;
public function __construct(StringUtil $util = null)
{
$this->util = $util ?: new StringUtil;
}
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method)
{
if (count($calls)) {
return;
}
$methodCalls = $object->findProphecyMethodCalls(
$method->getMethodName(),
new ArgumentsWildcard(array(new AnyValuesToken))
);
if (count($methodCalls)) {
throw new NoCallsException(sprintf(
"No calls have been made that match:\n".
" %s->%s(%s)\n".
"but expected at least one.\n".
"Recorded `%s(...)` calls:\n%s",
get_class($object->reveal()),
$method->getMethodName(),
$method->getArgumentsWildcard(),
$method->getMethodName(),
$this->util->stringifyCalls($methodCalls)
), $method);
}
throw new NoCallsException(sprintf(
"No calls have been made that match:\n".
" %s->%s(%s)\n".
"but expected at least one.",
get_class($object->reveal()),
$method->getMethodName(),
$method->getArgumentsWildcard()
), $method);
}
}
<?php
namespace Prophecy\Prediction;
use Prophecy\Call\Call;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Argument\Token\AnyValuesToken;
use Prophecy\Util\StringUtil;
use Prophecy\Exception\Prediction\UnexpectedCallsCountException;
class CallTimesPrediction implements PredictionInterface
{
private $times;
private $util;
public function __construct($times, StringUtil $util = null)
{
$this->times = intval($times);
$this->util = $util ?: new StringUtil;
}
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method)
{
if ($this->times == count($calls)) {
return;
}
$methodCalls = $object->findProphecyMethodCalls(
$method->getMethodName(),
new ArgumentsWildcard(array(new AnyValuesToken))
);
if (count($calls)) {
$message = sprintf(
"Expected exactly %d calls that match:\n".
" %s->%s(%s)\n".
"but %d were made:\n%s",
$this->times,
get_class($object->reveal()),
$method->getMethodName(),
$method->getArgumentsWildcard(),
count($calls),
$this->util->stringifyCalls($calls)
);
} elseif (count($methodCalls)) {
$message = sprintf(
"Expected exactly %d calls that match:\n".
" %s->%s(%s)\n".
"but none were made.\n".
"Recorded `%s(...)` calls:\n%s",
$this->times,
get_class($object->reveal()),
$method->getMethodName(),
$method->getArgumentsWildcard(),
$method->getMethodName(),
$this->util->stringifyCalls($methodCalls)
);
} else {
$message = sprintf(
"Expected exactly %d calls that match:\n".
" %s->%s(%s)\n".
"but none were made.",
$this->times,
get_class($object->reveal()),
$method->getMethodName(),
$method->getArgumentsWildcard()
);
}
throw new UnexpectedCallsCountException($message, $method, $this->times, $calls);
}
}
<?php
namespace Prophecy\Prediction;
use Prophecy\Call\Call;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Exception\InvalidArgumentException;
use Closure;
class CallbackPrediction implements PredictionInterface
{
private $callback;
public function __construct($callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'Callable expected as an argument to CallbackPrediction, but got %s.',
gettype($callback)
));
}
$this->callback = $callback;
}
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method)
{
$callback = $this->callback;
if ($callback instanceof Closure && method_exists('Closure', 'bind')) {
$callback = Closure::bind($callback, $object);
}
call_user_func($callback, $calls, $object, $method);
}
}
<?php
namespace Prophecy\Prediction;
use Prophecy\Call\Call;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Util\StringUtil;
use Prophecy\Exception\Prediction\UnexpectedCallsException;
class NoCallsPrediction implements PredictionInterface
{
private $util;
public function __construct(StringUtil $util = null)
{
$this->util = $util ?: new StringUtil;
}
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method)
{
if (!count($calls)) {
return;
}
$verb = count($calls) === 1 ? 'was' : 'were';
throw new UnexpectedCallsException(sprintf(
"No calls expected that match:\n".
" %s->%s(%s)\n".
"but %d %s made:\n%s",
get_class($object->reveal()),
$method->getMethodName(),
$method->getArgumentsWildcard(),
count($calls),
$verb,
$this->util->stringifyCalls($calls)
), $method, $calls);
}
}
<?php
namespace Prophecy\Prediction;
use Prophecy\Call\Call;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
interface PredictionInterface
{
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method);
}
<?php
namespace Prophecy\Promise;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Exception\InvalidArgumentException;
use Closure;
class CallbackPromise implements PromiseInterface
{
private $callback;
public function __construct($callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'Callable expected as an argument to CallbackPromise, but got %s.',
gettype($callback)
));
}
$this->callback = $callback;
}
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
$callback = $this->callback;
if ($callback instanceof Closure && method_exists('Closure', 'bind')) {
$callback = Closure::bind($callback, $object);
}
return call_user_func($callback, $args, $object, $method);
}
}
<?php
namespace Prophecy\Promise;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
interface PromiseInterface
{
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method);
}
<?php
namespace Prophecy\Promise;
use Prophecy\Exception\InvalidArgumentException;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
class ReturnArgumentPromise implements PromiseInterface
{
private $index;
public function __construct($index = 0)
{
if (!is_int($index) || $index < 0) {
throw new InvalidArgumentException(sprintf(
'Zero-based index expected as argument to ReturnArgumentPromise, but got %s.',
$index
));
}
$this->index = $index;
}
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
return count($args) > $this->index ? $args[$this->index] : null;
}
}
<?php
namespace Prophecy\Promise;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
class ReturnPromise implements PromiseInterface
{
private $returnValues = array();
public function __construct(array $returnValues)
{
$this->returnValues = $returnValues;
}
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
$value = array_shift($this->returnValues);
if (!count($this->returnValues)) {
$this->returnValues[] = $value;
}
return $value;
}
}
<?php
namespace Prophecy\Promise;
use Doctrine\Instantiator\Instantiator;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Exception\InvalidArgumentException;
use ReflectionClass;
class ThrowPromise implements PromiseInterface
{
private $exception;
private $instantiator;
public function __construct($exception)
{
if (is_string($exception)) {
if (!class_exists($exception)
&& 'Exception' !== $exception
&& !is_subclass_of($exception, 'Exception')) {
throw new InvalidArgumentException(sprintf(
'Exception class or instance expected as argument to ThrowPromise, but got %s.',
$exception
));
}
} elseif (!$exception instanceof \Exception) {
throw new InvalidArgumentException(sprintf(
'Exception class or instance expected as argument to ThrowPromise, but got %s.',
is_object($exception) ? get_class($exception) : gettype($exception)
));
}
$this->exception = $exception;
}
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
if (is_string($this->exception)) {
$classname = $this->exception;
$reflection = new ReflectionClass($classname);
$constructor = $reflection->getConstructor();
if ($constructor->isPublic() && 0 == $constructor->getNumberOfRequiredParameters()) {
throw $reflection->newInstance();
}
if (!$this->instantiator) {
$this->instantiator = new Instantiator();
}
throw $this->instantiator->instantiate($classname);
}
throw $this->exception;
}
}
<?php
namespace Prophecy\Prophecy;
use Prophecy\Argument;
use Prophecy\Prophet;
use Prophecy\Promise;
use Prophecy\Prediction;
use Prophecy\Exception\Doubler\MethodNotFoundException;
use Prophecy\Exception\InvalidArgumentException;
use Prophecy\Exception\Prophecy\MethodProphecyException;
class MethodProphecy
{
private $objectProphecy;
private $methodName;
private $argumentsWildcard;
private $promise;
private $prediction;
private $checkedPredictions = array();
private $bound = false;
public function __construct(ObjectProphecy $objectProphecy, $methodName, $arguments = null)
{
$double = $objectProphecy->reveal();
if (!method_exists($double, $methodName)) {
throw new MethodNotFoundException(sprintf(
'Method `%s::%s()` is not defined.', get_class($double), $methodName
), get_class($double), $methodName, $arguments);
}
$this->objectProphecy = $objectProphecy;
$this->methodName = $methodName;
$reflectedMethod = new \ReflectionMethod($double, $methodName);
if ($reflectedMethod->isFinal()) {
throw new MethodProphecyException(sprintf(
"Can not add prophecy for a method `%s::%s()`\n".
"as it is a final method.",
get_class($double),
$methodName
), $this);
}
if (null !== $arguments) {
$this->withArguments($arguments);
}
if (version_compare(PHP_VERSION, '7.0', '>=') && true === $reflectedMethod->hasReturnType()) {
$type = (string) $reflectedMethod->getReturnType();
$this->will(function () use ($type) {
switch ($type) {
case 'string': return '';
case 'float': return 0.0;
case 'int': return 0;
case 'bool': return false;
case 'array': return array();
case 'callable':
case 'Closure':
return function () {};
case 'Traversable':
case 'Generator':
$generator = eval('return function () { yield; };');
return $generator();
default:
$prophet = new Prophet;
return $prophet->prophesize($type)->reveal();
}
});
}
}
public function withArguments($arguments)
{
if (is_array($arguments)) {
$arguments = new Argument\ArgumentsWildcard($arguments);
}
if (!$arguments instanceof Argument\ArgumentsWildcard) {
throw new InvalidArgumentException(sprintf(
"Either an array or an instance of ArgumentsWildcard expected as\n".
'a `MethodProphecy::withArguments()` argument, but got %s.',
gettype($arguments)
));
}
$this->argumentsWildcard = $arguments;
return $this;
}
public function will($promise)
{
if (is_callable($promise)) {
$promise = new Promise\CallbackPromise($promise);
}
if (!$promise instanceof Promise\PromiseInterface) {
throw new InvalidArgumentException(sprintf(
'Expected callable or instance of PromiseInterface, but got %s.',
gettype($promise)
));
}
$this->bindToObjectProphecy();
$this->promise = $promise;
return $this;
}
public function willReturn()
{
return $this->will(new Promise\ReturnPromise(func_get_args()));
}
public function willReturnArgument($index = 0)
{
return $this->will(new Promise\ReturnArgumentPromise($index));
}
public function willThrow($exception)
{
return $this->will(new Promise\ThrowPromise($exception));
}
public function should($prediction)
{
if (is_callable($prediction)) {
$prediction = new Prediction\CallbackPrediction($prediction);
}
if (!$prediction instanceof Prediction\PredictionInterface) {
throw new InvalidArgumentException(sprintf(
'Expected callable or instance of PredictionInterface, but got %s.',
gettype($prediction)
));
}
$this->bindToObjectProphecy();
$this->prediction = $prediction;
return $this;
}
public function shouldBeCalled()
{
return $this->should(new Prediction\CallPrediction);
}
public function shouldNotBeCalled()
{
return $this->should(new Prediction\NoCallsPrediction);
}
public function shouldBeCalledTimes($count)
{
return $this->should(new Prediction\CallTimesPrediction($count));
}
public function shouldHave($prediction)
{
if (is_callable($prediction)) {
$prediction = new Prediction\CallbackPrediction($prediction);
}
if (!$prediction instanceof Prediction\PredictionInterface) {
throw new InvalidArgumentException(sprintf(
'Expected callable or instance of PredictionInterface, but got %s.',
gettype($prediction)
));
}
if (null === $this->promise) {
$this->willReturn();
}
$calls = $this->getObjectProphecy()->findProphecyMethodCalls(
$this->getMethodName(),
$this->getArgumentsWildcard()
);
try {
$prediction->check($calls, $this->getObjectProphecy(), $this);
$this->checkedPredictions[] = $prediction;
} catch (\Exception $e) {
$this->checkedPredictions[] = $prediction;
throw $e;
}
return $this;
}
public function shouldHaveBeenCalled()
{
return $this->shouldHave(new Prediction\CallPrediction);
}
public function shouldNotHaveBeenCalled()
{
return $this->shouldHave(new Prediction\NoCallsPrediction);
}
public function shouldNotBeenCalled()
{
return $this->shouldNotHaveBeenCalled();
}
public function shouldHaveBeenCalledTimes($count)
{
return $this->shouldHave(new Prediction\CallTimesPrediction($count));
}
public function checkPrediction()
{
if (null === $this->prediction) {
return;
}
$this->shouldHave($this->prediction);
}
public function getPromise()
{
return $this->promise;
}
public function getPrediction()
{
return $this->prediction;
}
public function getCheckedPredictions()
{
return $this->checkedPredictions;
}
public function getObjectProphecy()
{
return $this->objectProphecy;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArgumentsWildcard()
{
return $this->argumentsWildcard;
}
private function bindToObjectProphecy()
{
if ($this->bound) {
return;
}
$this->getObjectProphecy()->addMethodProphecy($this);
$this->bound = true;
}
}
<?php
namespace Prophecy\Prophecy;
use SebastianBergmann\Comparator\ComparisonFailure;
use Prophecy\Comparator\Factory as ComparatorFactory;
use Prophecy\Call\Call;
use Prophecy\Doubler\LazyDouble;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Call\CallCenter;
use Prophecy\Exception\Prophecy\ObjectProphecyException;
use Prophecy\Exception\Prophecy\MethodProphecyException;
use Prophecy\Exception\Prediction\AggregateException;
use Prophecy\Exception\Prediction\PredictionException;
class ObjectProphecy implements ProphecyInterface
{
private $lazyDouble;
private $callCenter;
private $revealer;
private $comparatorFactory;
private $methodProphecies = array();
public function __construct(
LazyDouble $lazyDouble,
CallCenter $callCenter = null,
RevealerInterface $revealer = null,
ComparatorFactory $comparatorFactory = null
) {
$this->lazyDouble = $lazyDouble;
$this->callCenter = $callCenter ?: new CallCenter;
$this->revealer = $revealer ?: new Revealer;
$this->comparatorFactory = $comparatorFactory ?: ComparatorFactory::getInstance();
}
public function willExtend($class)
{
$this->lazyDouble->setParentClass($class);
return $this;
}
public function willImplement($interface)
{
$this->lazyDouble->addInterface($interface);
return $this;
}
public function willBeConstructedWith(array $arguments = null)
{
$this->lazyDouble->setArguments($arguments);
return $this;
}
public function reveal()
{
$double = $this->lazyDouble->getInstance();
if (null === $double || !$double instanceof ProphecySubjectInterface) {
throw new ObjectProphecyException(
"Generated double must implement ProphecySubjectInterface, but it does not.\n".
'It seems you have wrongly configured doubler without required ClassPatch.',
$this
);
}
$double->setProphecy($this);
return $double;
}
public function addMethodProphecy(MethodProphecy $methodProphecy)
{
$argumentsWildcard = $methodProphecy->getArgumentsWildcard();
if (null === $argumentsWildcard) {
throw new MethodProphecyException(sprintf(
"Can not add prophecy for a method `%s::%s()`\n".
"as you did not specify arguments wildcard for it.",
get_class($this->reveal()),
$methodProphecy->getMethodName()
), $methodProphecy);
}
$methodName = $methodProphecy->getMethodName();
if (!isset($this->methodProphecies[$methodName])) {
$this->methodProphecies[$methodName] = array();
}
$this->methodProphecies[$methodName][] = $methodProphecy;
}
public function getMethodProphecies($methodName = null)
{
if (null === $methodName) {
return $this->methodProphecies;
}
if (!isset($this->methodProphecies[$methodName])) {
return array();
}
return $this->methodProphecies[$methodName];
}
public function makeProphecyMethodCall($methodName, array $arguments)
{
$arguments = $this->revealer->reveal($arguments);
$return = $this->callCenter->makeCall($this, $methodName, $arguments);
return $this->revealer->reveal($return);
}
public function findProphecyMethodCalls($methodName, ArgumentsWildcard $wildcard)
{
return $this->callCenter->findCalls($methodName, $wildcard);
}
public function checkProphecyMethodsPredictions()
{
$exception = new AggregateException(sprintf("%s:\n", get_class($this->reveal())));
$exception->setObjectProphecy($this);
foreach ($this->methodProphecies as $prophecies) {
foreach ($prophecies as $prophecy) {
try {
$prophecy->checkPrediction();
} catch (PredictionException $e) {
$exception->append($e);
}
}
}
if (count($exception->getExceptions())) {
throw $exception;
}
}
public function __call($methodName, array $arguments)
{
$arguments = new ArgumentsWildcard($this->revealer->reveal($arguments));
foreach ($this->getMethodProphecies($methodName) as $prophecy) {
$argumentsWildcard = $prophecy->getArgumentsWildcard();
$comparator = $this->comparatorFactory->getComparatorFor(
$argumentsWildcard, $arguments
);
try {
$comparator->assertEquals($argumentsWildcard, $arguments);
return $prophecy;
} catch (ComparisonFailure $failure) {}
}
return new MethodProphecy($this, $methodName, $arguments);
}
public function __get($name)
{
return $this->reveal()->$name;
}
public function __set($name, $value)
{
$this->reveal()->$name = $this->revealer->reveal($value);
}
}
<?php
namespace Prophecy\Prophecy;
interface ProphecyInterface
{
public function reveal();
}
<?php
namespace Prophecy\Prophecy;
interface ProphecySubjectInterface
{
public function setProphecy(ProphecyInterface $prophecy);
public function getProphecy();
}
<?php
namespace Prophecy\Prophecy;
class Revealer implements RevealerInterface
{
public function reveal($value)
{
if (is_array($value)) {
return array_map(array($this, __FUNCTION__), $value);
}
if (!is_object($value)) {
return $value;
}
if ($value instanceof ProphecyInterface) {
$value = $value->reveal();
}
return $value;
}
}
<?php
namespace Prophecy\Prophecy;
interface RevealerInterface
{
public function reveal($value);
}
<?php
namespace Prophecy;
use Prophecy\Doubler\Doubler;
use Prophecy\Doubler\LazyDouble;
use Prophecy\Doubler\ClassPatch;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\RevealerInterface;
use Prophecy\Prophecy\Revealer;
use Prophecy\Call\CallCenter;
use Prophecy\Util\StringUtil;
use Prophecy\Exception\Prediction\PredictionException;
use Prophecy\Exception\Prediction\AggregateException;
class Prophet
{
private $doubler;
private $revealer;
private $util;
private $prophecies = array();
public function __construct(Doubler $doubler = null, RevealerInterface $revealer = null,
StringUtil $util = null)
{
if (null === $doubler) {
$doubler = new Doubler;
$doubler->registerClassPatch(new ClassPatch\SplFileInfoPatch);
$doubler->registerClassPatch(new ClassPatch\TraversablePatch);
$doubler->registerClassPatch(new ClassPatch\DisableConstructorPatch);
$doubler->registerClassPatch(new ClassPatch\ProphecySubjectPatch);
$doubler->registerClassPatch(new ClassPatch\ReflectionClassNewInstancePatch);
$doubler->registerClassPatch(new ClassPatch\HhvmExceptionPatch());
$doubler->registerClassPatch(new ClassPatch\MagicCallPatch);
$doubler->registerClassPatch(new ClassPatch\KeywordPatch);
}
$this->doubler = $doubler;
$this->revealer = $revealer ?: new Revealer;
$this->util = $util ?: new StringUtil;
}
public function prophesize($classOrInterface = null)
{
$this->prophecies[] = $prophecy = new ObjectProphecy(
new LazyDouble($this->doubler),
new CallCenter($this->util),
$this->revealer
);
if ($classOrInterface && class_exists($classOrInterface)) {
return $prophecy->willExtend($classOrInterface);
}
if ($classOrInterface && interface_exists($classOrInterface)) {
return $prophecy->willImplement($classOrInterface);
}
return $prophecy;
}
public function getProphecies()
{
return $this->prophecies;
}
public function getDoubler()
{
return $this->doubler;
}
public function checkPredictions()
{
$exception = new AggregateException("Some predictions failed:\n");
foreach ($this->prophecies as $prophecy) {
try {
$prophecy->checkProphecyMethodsPredictions();
} catch (PredictionException $e) {
$exception->append($e);
}
}
if (count($exception->getExceptions())) {
throw $exception;
}
}
}
<?php
namespace Prophecy\Util;
use Prophecy\Prophecy\ProphecyInterface;
use SebastianBergmann\RecursionContext\Context;
class ExportUtil
{
public static function export($value, $indentation = 0)
{
return self::recursiveExport($value, $indentation);
}
public static function toArray($value)
{
if (!is_object($value)) {
return (array) $value;
}
$array = array();
foreach ((array) $value as $key => $val) {
if (preg_match('/^\0.+\0(.+)$/', $key, $matches)) {
$key = $matches[1];
}
if ($key === "\0gcdata") {
continue;
}
$array[$key] = $val;
}
if ($value instanceof \SplObjectStorage) {
if (property_exists('\SplObjectStorage', '__storage')) {
unset($array['__storage']);
} elseif (property_exists('\SplObjectStorage', 'storage')) {
unset($array['storage']);
}
if (property_exists('\SplObjectStorage', '__key')) {
unset($array['__key']);
}
foreach ($value as $key => $val) {
$array[spl_object_hash($val)] = array(
'obj' => $val,
'inf' => $value->getInfo(),
);
}
}
return $array;
}
protected static 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) && floatval(intval($value)) === $value) {
return "$value.0";
}
if (is_resource($value)) {
return sprintf(
'resource(%d) of type (%s)',
$value,
get_resource_type($value)
);
}
if (is_string($value)) {
if (preg_match('/[^\x09-\x0d\x20-\xff]/', $value)) {
return 'Binary String: 0x' . bin2hex($value);
}
return "'" .
str_replace(array("\r\n", "\n\r", "\r"), array("\n", "\n", "\n"), $value) .
"'";
}
$whitespace = str_repeat(' ', 4 * $indentation);
if (!$processed) {
$processed = new Context;
}
if (is_array($value)) {
if (($key = $processed->contains($value)) !== false) {
return 'Array &' . $key;
}
$key = $processed->add($value);
$values = '';
if (count($value) > 0) {
foreach ($value as $k => $v) {
$values .= sprintf(
'%s %s => %s' . "\n",
$whitespace,
self::recursiveExport($k, $indentation),
self::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 ($value instanceof ProphecyInterface) {
return sprintf('%s Object (*Prophecy*)', $class);
} elseif ($hash = $processed->contains($value)) {
return sprintf('%s:%s Object', $class, $hash);
}
$hash = $processed->add($value);
$values = '';
$array = self::toArray($value);
if (count($array) > 0) {
foreach ($array as $k => $v) {
$values .= sprintf(
'%s %s => %s' . "\n",
$whitespace,
self::recursiveExport($k, $indentation),
self::recursiveExport($v, $indentation + 1, $processed)
);
}
$values = "\n" . $values . $whitespace;
}
return sprintf('%s:%s Object (%s)', $class, $hash, $values);
}
return var_export($value, true);
}
}
<?php
namespace Prophecy\Util;
use Prophecy\Call\Call;
class StringUtil
{
public function stringify($value, $exportObject = true)
{
if (is_array($value)) {
if (range(0, count($value) - 1) === array_keys($value)) {
return '['.implode(', ', array_map(array($this, __FUNCTION__), $value)).']';
}
$stringify = array($this, __FUNCTION__);
return '['.implode(', ', array_map(function ($item, $key) use ($stringify) {
return (is_integer($key) ? $key : '"'.$key.'"').
' => '.call_user_func($stringify, $item);
}, $value, array_keys($value))).']';
}
if (is_resource($value)) {
return get_resource_type($value).':'.$value;
}
if (is_object($value)) {
return $exportObject ? ExportUtil::export($value) : sprintf('%s:%s', get_class($value), spl_object_hash($value));
}
if (true === $value || false === $value) {
return $value ? 'true' : 'false';
}
if (is_string($value)) {
$str = sprintf('"%s"', str_replace("\n", '\\n', $value));
if (50 <= strlen($str)) {
return substr($str, 0, 50).'"...';
}
return $str;
}
if (null === $value) {
return 'null';
}
return (string) $value;
}
public function stringifyCalls(array $calls)
{
$self = $this;
return implode(PHP_EOL, array_map(function (Call $call) use ($self) {
return sprintf(' - %s(%s) @ %s',
$call->getMethodName(),
implode(', ', array_map(array($self, 'stringify'), $call->getArguments())),
str_replace(GETCWD().DIRECTORY_SEPARATOR, '', $call->getCallPlace())
);
}, $calls));
}
}
<?php
namespace DeepCopy;
use DeepCopy\Exception\CloneException;
use DeepCopy\Filter\Filter;
use DeepCopy\Matcher\Matcher;
use DeepCopy\TypeFilter\TypeFilter;
use DeepCopy\TypeMatcher\TypeMatcher;
use ReflectionProperty;
use DeepCopy\Reflection\ReflectionHelper;
class DeepCopy
{
private $hashMap = [];
private $filters = [];
private $typeFilters = [];
private $skipUncloneable = false;
private $useCloneMethod;
public function __construct($useCloneMethod = false)
{
$this->useCloneMethod = $useCloneMethod;
}
public function skipUncloneable($skipUncloneable = true)
{
$this->skipUncloneable = $skipUncloneable;
return $this;
}
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 addTypeFilter(TypeFilter $filter, TypeMatcher $matcher)
{
$this->typeFilters[] = [
'matcher' => $matcher,
'filter' => $filter,
];
}
private function recursiveCopy($var)
{
if ($filter = $this->getFirstMatchedTypeFilter($this->typeFilters, $var)) {
return $filter->apply($var);
}
if (is_resource($var)) {
return $var;
}
if (is_array($var)) {
return $this->copyArray($var);
}
if (! is_object($var)) {
return $var;
}
return $this->copyObject($var);
}
private function copyArray(array $array)
{
foreach ($array as $key => $value) {
$array[$key] = $this->recursiveCopy($value);
}
return $array;
}
private function copyObject($object)
{
$objectHash = spl_object_hash($object);
if (isset($this->hashMap[$objectHash])) {
return $this->hashMap[$objectHash];
}
$reflectedObject = new \ReflectionObject($object);
if (false === $isCloneable = $reflectedObject->isCloneable() and $this->skipUncloneable) {
$this->hashMap[$objectHash] = $object;
return $object;
}
if (false === $isCloneable) {
throw new CloneException(sprintf(
'Class "%s" is not cloneable.',
$reflectedObject->getName()
));
}
$newObject = clone $object;
$this->hashMap[$objectHash] = $newObject;
if ($this->useCloneMethod && $reflectedObject->hasMethod('__clone')) {
return $object;
}
if ($newObject instanceof \DateTimeInterface) {
return $newObject;
}
foreach (ReflectionHelper::getProperties($reflectedObject) as $property) {
$this->copyObjectProperty($newObject, $property);
}
return $newObject;
}
private function copyObjectProperty($object, ReflectionProperty $property)
{
if ($property->isStatic()) {
return;
}
foreach ($this->filters as $item) {
$matcher = $item['matcher'];
$filter = $item['filter'];
if ($matcher->matches($object, $property->getName())) {
$filter->apply(
$object,
$property->getName(),
function ($object) {
return $this->recursiveCopy($object);
}
);
return;
}
}
$property->setAccessible(true);
$propertyValue = $property->getValue($object);
$property->setValue($object, $this->recursiveCopy($propertyValue));
}
private function getFirstMatchedTypeFilter(array $filterRecords, $var)
{
$matched = $this->first(
$filterRecords,
function (array $record) use ($var) {
$matcher = $record['matcher'];
return $matcher->matches($var);
}
);
return isset($matched) ? $matched['filter'] : 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\Exception;
class CloneException extends \UnexpectedValueException
{
} <?php
namespace DeepCopy\Filter\Doctrine;
use DeepCopy\Filter\Filter;
use ReflectionProperty;
class DoctrineCollectionFilter implements Filter
{
public function apply($object, $property, $objectCopier)
{
$reflectionProperty = new ReflectionProperty($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;
use Doctrine\Common\Collections\ArrayCollection;
class DoctrineEmptyCollectionFilter implements Filter
{
public function apply($object, $property, $objectCopier)
{
$reflectionProperty = new \ReflectionProperty($object, $property);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, new ArrayCollection());
}
} <?php
namespace DeepCopy\Filter;
interface Filter
{
public function apply($object, $property, $objectCopier);
}
<?php
namespace DeepCopy\Filter;
class KeepFilter implements Filter
{
public function apply($object, $property, $objectCopier)
{
}
}
<?php
namespace DeepCopy\Filter;
class ReplaceFilter implements Filter
{
protected $callback;
public function __construct(callable $callable)
{
$this->callback = $callable;
}
public function apply($object, $property, $objectCopier)
{
$reflectionProperty = new \ReflectionProperty($object, $property);
$reflectionProperty->setAccessible(true);
$value = call_user_func($this->callback, $reflectionProperty->getValue($object));
$reflectionProperty->setValue($object, $value);
}
}
<?php
namespace DeepCopy\Filter;
use ReflectionProperty;
class SetNullFilter implements Filter
{
public function apply($object, $property, $objectCopier)
{
$reflectionProperty = new ReflectionProperty($object, $property);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, null);
}
}
<?php
namespace DeepCopy\Matcher;
interface Matcher
{
public function matches($object, $property);
}
<?php
namespace DeepCopy\Matcher;
class PropertyMatcher implements Matcher
{
private $class;
private $property;
public function __construct($class, $property)
{
$this->class = $class;
$this->property = $property;
}
public function matches($object, $property)
{
return ($object instanceof $this->class) && ($property == $this->property);
}
}
<?php
namespace DeepCopy\Matcher;
class PropertyNameMatcher implements Matcher
{
private $property;
public function __construct($property)
{
$this->property = $property;
}
public function matches($object, $property)
{
return $property == $this->property;
}
}
<?php
namespace DeepCopy\Matcher;
use ReflectionProperty;
class PropertyTypeMatcher implements Matcher
{
private $propertyType;
public function __construct($propertyType)
{
$this->propertyType = $propertyType;
}
public function matches($object, $property)
{
$reflectionProperty = new ReflectionProperty($object, $property);
$reflectionProperty->setAccessible(true);
return $reflectionProperty->getValue($object) instanceof $this->propertyType;
}
}
<?php
namespace DeepCopy\Reflection;
class ReflectionHelper
{
public static function getProperties(\ReflectionClass $ref)
{
$props = $ref->getProperties();
$propsArr = array();
foreach ($props as $prop) {
$f = $prop->getName();
$propsArr[$f] = $prop;
}
if ($parentClass = $ref->getParentClass()) {
$parentPropsArr = self::getProperties($parentClass);
if (count($parentPropsArr) > 0) {
$propsArr = array_merge($parentPropsArr, $propsArr);
}
}
return $propsArr;
}
}
<?php
namespace DeepCopy\TypeFilter;
class ReplaceFilter implements TypeFilter
{
protected $callback;
public function __construct(callable $callable)
{
$this->callback = $callable;
}
public function apply($element)
{
return call_user_func($this->callback, $element);
}
}
<?php
namespace DeepCopy\TypeFilter;
class ShallowCopyFilter implements TypeFilter
{
public function apply($element)
{
return clone $element;
}
}
<?php
namespace DeepCopy\TypeFilter;
interface TypeFilter
{
public function apply($element);
}
<?php
namespace DeepCopy\TypeMatcher;
class TypeMatcher
{
private $type;
public function __construct($type)
{
$this->type = $type;
}
public function matches($element)
{
return is_object($element) ? is_a($element, $this->type) : gettype($element) === $this->type;
}
}
<?php
namespace Psr\Log;
abstract class AbstractLogger implements LoggerInterface
{
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
}
<?php
namespace Psr\Log;
class InvalidArgumentException extends \InvalidArgumentException
{
}
<?php
namespace Psr\Log;
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;
interface LoggerAwareInterface
{
public function setLogger(LoggerInterface $logger);
}
<?php
namespace Psr\Log;
trait LoggerAwareTrait
{
protected $logger;
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
<?php
namespace Psr\Log;
interface LoggerInterface
{
public function emergency($message, array $context = array());
public function alert($message, array $context = array());
public function critical($message, array $context = array());
public function error($message, array $context = array());
public function warning($message, array $context = array());
public function notice($message, array $context = array());
public function info($message, array $context = array());
public function debug($message, array $context = array());
public function log($level, $message, array $context = array());
}
<?php
namespace Psr\Log;
trait LoggerTrait
{
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
abstract public function log($level, $message, array $context = array());
}
<?php
namespace Psr\Log;
class NullLogger extends AbstractLogger
{
public function log($level, $message, array $context = array())
{
}
}
<?php
namespace Psr\Log\Test;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
abstract class LoggerInterfaceTest extends \PHPUnit_Framework_TestCase
{
abstract public function getLogger();
abstract public function getLogs();
public function testImplements()
{
$this->assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger());
}
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}'),
);
}
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, 'createMock')) {
$dummy = $this->createMock('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()
{
$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'),
);
$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());
}
}
class DummyTest
{
public function __toString()
{
}
}
<?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
require_once 'phing/Task.php';
class ComposerLintTask extends Task
{
protected $dir = null;
protected $file = null;
protected $passthru = false;
protected $composer = null;
public function setDir($str)
{
$this->dir = $str;
}
public function setFile($str)
{
$this->file = $str;
}
public function setPassthru($passthru)
{
$this->passthru = (bool) $passthru;
}
public function setComposer($str)
{
$this->file = $str;
}
public function init()
{
}
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]);
}
}
}
}
protected function findFiles()
{
$ds = new DirectoryScanner();
$ds->setBasedir($this->dir);
$ds->setIncludes(array('**/composer.json'));
$ds->scan();
return $ds->getIncludedFiles();
}
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];
}
}
}
<?php
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');
}
$composer_file = file_get_contents((string) $this->basedir.'/.subsplit/composer.json');
$this->guzzleinfo = json_decode($composer_file, true);
$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->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');
}
passthru('aws s3 sync s3://pear.guzzlephp.org ./channel');
foreach (scandir('./') as $file) {
if (substr($file, -4) == '.tgz') {
passthru('pirum add ./channel ' . $file);
}
}
if ($this->getMakephar() && file_exists($basedir . '/build/artifacts/guzzle.phar')) {
rename($basedir . '/build/artifacts/guzzle.phar', './channel/guzzle.phar');
}
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'
);
$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);
$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());
}
}
$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);
$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
require_once 'phing/tasks/ext/git/GitBaseTask.php';
class GuzzleSubSplitTask extends GitBaseTask
{
protected $remote = null;
protected $heads = null;
protected $tags = null;
protected $base = null;
protected $subIndicatorFile = 'composer.json';
protected $dryRun = null;
protected $noHeads = false;
protected $noTags = false;
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;
}
protected $client = null;
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);
if (!is_dir('.subsplit')) {
$this->subsplitInit();
} else {
$this->subsplitUpdate();
}
$this->findSplits();
$this->verifyRepos();
$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);
}
}
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);
}
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);
}
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();
passthru("git checkout '$head'");
$ds = new DirectoryScanner();
$ds->setBasedir($repo . '/.subsplit' . $base);
$ds->setIncludes(array('**/'.$this->subIndicatorFile));
$ds->scan();
$files = $ds->getIncludedFiles();
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);
$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'];
}
}
passthru("git checkout master");
chdir($repo);
$this->splits = $splits;
}
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);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$repos = json_decode($result, true);
$existing_repos = array();
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));
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
namespace Guzzle\Batch;
abstract class AbstractBatchDecorator implements BatchInterface
{
protected $decoratedBatch;
public function __construct(BatchInterface $decoratedBatch)
{
$this->decoratedBatch = $decoratedBatch;
}
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();
}
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;
class Batch implements BatchInterface
{
protected $queue;
protected $dividedBatches;
protected $transferStrategy;
protected $divisionStrategy;
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);
}
}
unset($this->dividedBatches[$batchIndex]);
}
return $items;
}
public function isEmpty()
{
return count($this->queue) == 0 && count($this->dividedBatches) == 0;
}
protected function createBatches()
{
if (count($this->queue)) {
if ($batches = $this->divisionStrategy->createBatches($this->queue)) {
if (is_array($batches)) {
$batches = new \ArrayIterator($batches);
}
$this->dividedBatches[] = $batches;
}
}
}
}
<?php
namespace Guzzle\Batch;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
class BatchBuilder
{
protected $autoFlush = false;
protected $history = false;
protected $exceptionBuffering = false;
protected $afterFlush;
protected $transferStrategy;
protected $divisorStrategy;
protected static $mapping = array(
'request' => 'Guzzle\Batch\BatchRequestTransfer',
'command' => 'Guzzle\Batch\BatchCommandTransfer'
);
public static function factory()
{
return new self();
}
public function autoFlushAt($threshold)
{
$this->autoFlush = $threshold;
return $this;
}
public function keepHistory()
{
$this->history = true;
return $this;
}
public function bufferExceptions()
{
$this->exceptionBuffering = true;
return $this;
}
public function notify($callable)
{
$this->afterFlush = $callable;
return $this;
}
public function transferRequests($batchSize = 50)
{
$className = self::$mapping['request'];
$this->transferStrategy = new $className($batchSize);
$this->divisorStrategy = $this->transferStrategy;
return $this;
}
public function transferCommands($batchSize = 50)
{
$className = self::$mapping['command'];
$this->transferStrategy = new $className($batchSize);
$this->divisorStrategy = $this->transferStrategy;
return $this;
}
public function createBatchesWith(BatchDivisorInterface $divisorStrategy)
{
$this->divisorStrategy = $divisorStrategy;
return $this;
}
public function transferWith(BatchTransferInterface $transferStrategy)
{
$this->transferStrategy = $transferStrategy;
return $this;
}
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\Batch;
use Guzzle\Common\Exception\InvalidArgumentException;
class BatchClosureDivisor implements BatchDivisorInterface
{
protected $callable;
protected $context;
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;
use Guzzle\Common\Exception\InvalidArgumentException;
class BatchClosureTransfer implements BatchTransferInterface
{
protected $callable;
protected $context;
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;
class BatchCommandTransfer implements BatchTransferInterface, BatchDivisorInterface
{
protected $batchSize;
public function __construct($batchSize = 50)
{
$this->batchSize = $batchSize;
}
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;
}
$client = reset($batch)->getClient();
$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;
interface BatchDivisorInterface
{
public function createBatches(\SplQueue $queue);
}
<?php
namespace Guzzle\Batch;
interface BatchInterface
{
public function add($item);
public function flush();
public function isEmpty();
}
<?php
namespace Guzzle\Batch;
use Guzzle\Batch\BatchTransferInterface;
use Guzzle\Batch\BatchDivisorInterface;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
class BatchRequestTransfer implements BatchTransferInterface, BatchDivisorInterface
{
protected $batchSize;
public function __construct($batchSize = 50)
{
$this->batchSize = $batchSize;
}
public function createBatches(\SplQueue $queue)
{
$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;
class BatchSizeDivisor implements BatchDivisorInterface
{
protected $size;
public function __construct($size)
{
$this->size = $size;
}
public function setSize($size)
{
$this->size = $size;
return $this;
}
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 BatchTransferInterface
{
public function transfer(array $batch);
}
<?php
namespace Guzzle\Batch\Exception;
use Guzzle\Common\Exception\GuzzleException;
use Guzzle\Batch\BatchTransferInterface as TransferStrategy;
use Guzzle\Batch\BatchDivisorInterface as DivisorStrategy;
class BatchTransferException extends \Exception implements GuzzleException
{
protected $batch;
protected $transferStrategy;
protected $divisorStrategy;
protected $transferredItems;
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
);
}
public function getBatch()
{
return $this->batch;
}
public function getTransferredItems()
{
return $this->transferredItems;
}
public function getTransferStrategy()
{
return $this->transferStrategy;
}
public function getDivisorStrategy()
{
return $this->divisorStrategy;
}
}
<?php
namespace Guzzle\Batch;
use Guzzle\Batch\Exception\BatchTransferException;
class ExceptionBufferingBatch extends AbstractBatchDecorator
{
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;
}
public function getExceptions()
{
return $this->exceptions;
}
public function clearExceptions()
{
$this->exceptions = array();
}
}
<?php
namespace Guzzle\Batch;
class FlushingBatch extends AbstractBatchDecorator
{
protected $threshold;
protected $currentTotal = 0;
public function __construct(BatchInterface $decoratedBatch, $threshold)
{
$this->threshold = $threshold;
parent::__construct($decoratedBatch);
}
public function setThreshold($threshold)
{
$this->threshold = $threshold;
return $this;
}
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;
class HistoryBatch extends AbstractBatchDecorator
{
protected $history = array();
public function add($item)
{
$this->history[] = $item;
$this->decoratedBatch->add($item);
return $this;
}
public function getHistory()
{
return $this->history;
}
public function clearHistory()
{
$this->history = array();
}
}
<?php
namespace Guzzle\Batch;
use Guzzle\Common\Exception\InvalidArgumentException;
class NotifyingBatch extends AbstractBatchDecorator
{
protected $callable;
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\Cache;
abstract class AbstractCacheAdapter implements CacheAdapterInterface
{
protected $cache;
public function getCacheObject()
{
return $this->cache;
}
}
<?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;
class CacheAdapterFactory implements FromConfigInterface
{
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));
}
}
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 {
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])) {
$config[$required] = str_replace('.', '\\', $config[$required]);
if (!class_exists($config[$required])) {
throw new InvalidArgumentException("{$config[$required]} is not a valid class for {$required}");
}
}
}
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);
}
}
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'];
}
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;
interface CacheAdapterInterface
{
public function contains($id, array $options = null);
public function delete($id, array $options = null);
public function fetch($id, array $options = null);
public function save($id, $data, $lifeTime = false, array $options = null);
}
<?php
namespace Guzzle\Cache;
class ClosureCacheAdapter implements CacheAdapterInterface
{
protected $callables;
public function __construct(array $callables)
{
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;
use Doctrine\Common\Cache\Cache;
class DoctrineCacheAdapter extends AbstractCacheAdapter
{
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);
}
}
<?php
namespace Guzzle\Cache;
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 Guzzle\Common\Version;
class Zf1CacheAdapter extends AbstractCacheAdapter
{
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;
use Zend\Cache\Storage\StorageInterface;
class Zf2CacheAdapter extends AbstractCacheAdapter
{
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\Common;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AbstractHasDispatcher implements HasDispatcherInterface
{
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;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
class Collection implements \ArrayAccess, \IteratorAggregate, \Countable, ToArrayInterface
{
protected $data;
public function __construct(array $data = array())
{
$this->data = $data;
}
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;
}
public function clear()
{
$this->data = array();
return $this;
}
public function getAll(array $keys = null)
{
return $keys ? array_intersect_key($this->data, array_flip($keys)) : $this->data;
}
public function get($key)
{
return isset($this->data[$key]) ? $this->data[$key] : null;
}
public function set($key, $value)
{
$this->data[$key] = $value;
return $this;
}
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;
}
public function remove($key)
{
unset($this->data[$key]);
return $this;
}
public function getKeys()
{
return array_keys($this->data);
}
public function hasKey($key)
{
return array_key_exists($key, $this->data);
}
public function keySearch($key)
{
foreach (array_keys($this->data) as $k) {
if (!strcasecmp($k, $key)) {
return $k;
}
}
return false;
}
public function hasValue($value)
{
return array_search($value, $this->data);
}
public function replace(array $data)
{
$this->data = $data;
return $this;
}
public function merge($data)
{
foreach ($data as $key => $value) {
$this->add($key, $value);
}
return $this;
}
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;
}
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;
}
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]);
}
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;
}
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 {
$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;
}
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;
use Symfony\Component\EventDispatcher\Event as SymfonyEvent;
class Event extends SymfonyEvent implements ToArrayInterface, \ArrayAccess, \IteratorAggregate
{
private $context;
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\Exception;
class BadMethodCallException extends \BadMethodCallException implements GuzzleException {}
<?php
namespace Guzzle\Common\Exception;
class ExceptionCollection extends \Exception implements GuzzleException, \IteratorAggregate, \Countable
{
protected $exceptions = array();
private $shortMessage;
public function __construct($message = '', $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->shortMessage = $message;
}
public function setExceptions(array $exceptions)
{
$this->exceptions = array();
foreach ($exceptions as $exception) {
$this->add($exception);
}
return $this;
}
public function add($e)
{
$this->exceptions[] = $e;
if ($this->message) {
$this->message .= "\n";
}
$this->message .= $this->getExceptionMessage($e, 0);
return $this;
}
public function count()
{
return count($this->exceptions);
}
public function getIterator()
{
return new \ArrayIterator($this->exceptions);
}
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);
}
}
<?php
namespace Guzzle\Common\Exception;
interface GuzzleException {}
<?php
namespace Guzzle\Common\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException {}
<?php
namespace Guzzle\Common\Exception;
class RuntimeException extends \RuntimeException implements GuzzleException {}
<?php
namespace Guzzle\Common\Exception;
class UnexpectedValueException extends \UnexpectedValueException implements GuzzleException {}
<?php
namespace Guzzle\Common;
interface FromConfigInterface
{
public static function factory($config = array());
}
<?php
namespace Guzzle\Common;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
interface HasDispatcherInterface
{
public static function getAllEvents();
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher);
public function getEventDispatcher();
public function dispatch($eventName, array $context = array());
public function addSubscriber(EventSubscriberInterface $subscriber);
}
<?php
namespace Guzzle\Common;
interface ToArrayInterface
{
public function toArray();
}
<?php
namespace Guzzle\Common;
class Version
{
const VERSION = '3.8.1';
public static $emitWarnings = false;
public static function warn($message)
{
if (self::$emitWarnings) {
trigger_error('Deprecation warning: ' . $message, E_USER_DEPRECATED);
}
}
}
<?php
namespace Guzzle\Http;
use Guzzle\Stream\Stream;
class AbstractEntityBodyDecorator implements EntityBodyInterface
{
protected $body;
public function __construct(EntityBodyInterface $body)
{
$this->body = $body;
}
public function __toString()
{
return (string) $this->body;
}
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();
}
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\Common\Exception\RuntimeException;
class CachingEntityBody extends AbstractEntityBodyDecorator
{
protected $remoteStream;
protected $skipReadBytes = 0;
public function __construct(EntityBodyInterface $body)
{
$this->remoteStream = $body;
$this->body = new EntityBody(fopen('php://temp', 'r+'));
}
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());
}
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');
}
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);
}
public function setRewindFunction($callable)
{
throw new RuntimeException(__CLASS__ . ' does not support custom stream rewind functions');
}
public function read($length)
{
$data = $this->body->read($length);
$remaining = $length - strlen($data);
if ($remaining) {
$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)
{
$overflow = (strlen($string) + $this->ftell()) - $this->remoteStream->ftell();
if ($overflow > 0) {
$this->skipReadBytes += $overflow;
}
return $this->body->write($string);
}
public function readLine($maxLength = null)
{
$buffer = '';
$size = 0;
while (!$this->isConsumed()) {
$byte = $this->read(1);
$buffer .= $byte;
if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
break;
}
}
return $buffer;
}
public function isConsumed()
{
return $this->body->isConsumed() && $this->remoteStream->isConsumed();
}
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();
}
public function getCustomData($key)
{
return $this->remoteStream->getCustomData($key);
}
public function setCustomData($key, $value)
{
$this->remoteStream->setCustomData($key, $value);
return $this;
}
}
<?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;
class Client extends AbstractHasDispatcher implements ClientInterface
{
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;
protected $defaultHeaders;
protected $userAgent;
private $config;
private $baseUrl;
private $curlMulti;
private $uriTemplate;
protected $requestFactory;
public static function getAllEvents()
{
return array(self::CREATE_REQUEST);
}
public function __construct($baseUrl = '', $config = null)
{
if (!extension_loaded('curl')) {
throw new RuntimeException('The PHP cURL extension must be installed to use Guzzle.');
}
$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;
}
public function setDefaultOption($keyOrPath, $value)
{
$keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath;
$this->config->setPath($keyOrPath, $value);
return $this;
}
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) {
$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 (substr($uri, 0, 4) === 'http') {
$url = $this->expandTemplate($uri, $templateVars);
} else {
$url = Url::factory($this->getBaseUrl())->combine($this->expandTemplate($uri, $templateVars));
}
}
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;
}
public function getDefaultUserAgent()
{
return 'Guzzle/' . Version::VERSION
. ' curl/' . CurlVersion::getInstance()->get('version')
. ' PHP/' . PHP_VERSION;
}
public function get($uri = null, $headers = null, $options = array())
{
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 {
$this->getCurlMulti()->add($requests)->send();
return $requests->getResponse();
} catch (ExceptionCollection $e) {
throw $e->getFirst();
}
}
public function setCurlMulti(CurlMultiInterface $curlMulti)
{
$this->curlMulti = $curlMulti;
return $this;
}
public function getCurlMulti()
{
if (!$this->curlMulti) {
$this->curlMulti = new CurlMultiProxy();
}
return $this->curlMulti;
}
public function setRequestFactory(RequestFactoryInterface $factory)
{
$this->requestFactory = $factory;
return $this;
}
public function setUriTemplate(UriTemplateInterface $uriTemplate)
{
$this->uriTemplate = $uriTemplate;
return $this;
}
public function preparePharCacert($md5Check = true)
{
$from = __DIR__ . '/Resources/cacert.pem';
$certFile = sys_get_temp_dir() . '/guzzle-cacert.pem';
if (!file_exists($certFile) && !copy($from, $certFile)) {
throw new RuntimeException("Could not copy {$from} to {$certFile}: " . var_export(error_get_last(), true));
} elseif ($md5Check) {
$actualMd5 = md5_file($certFile);
$expectedMd5 = trim(file_get_contents("{$from}.md5"));
if ($actualMd5 != $expectedMd5) {
throw new RuntimeException("{$certFile} MD5 mismatch: expected {$expectedMd5} but got {$actualMd5}");
}
}
return $certFile;
}
protected function expandTemplate($template, array $variables = null)
{
$expansionVars = $this->getConfig()->toArray();
if ($variables) {
$expansionVars = $variables + $expansionVars;
}
return $this->getUriTemplate()->expand($template, $expansionVars);
}
protected function getUriTemplate()
{
if (!$this->uriTemplate) {
$this->uriTemplate = ParserRegistry::getInstance()->getParser('uri_template');
}
return $this->uriTemplate;
}
protected function sendMultiple(array $requests)
{
$curlMulti = $this->getCurlMulti();
foreach ($requests as $request) {
$curlMulti->add($request);
}
$curlMulti->send();
$result = array();
foreach ($requests as $request) {
$result[] = $request->getResponse();
}
return $result;
}
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;
}
protected function initSsl()
{
if ('system' == ($authority = $this->config[self::SSL_CERT_AUTHORITY])) {
return;
}
if ($authority === null) {
$authority = true;
}
if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') {
$authority = $this->preparePharCacert();
$that = $this;
$this->getEventDispatcher()->addListener('request.before_send', function ($event) use ($authority, $that) {
if ($authority == $event['request']->getCurlOptions()->get(CURLOPT_CAINFO)) {
$that->preparePharCacert(false);
}
});
}
$this->setSslVerification($authority);
}
public function getDefaultHeaders()
{
Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to retrieve default request options');
return $this->defaultHeaders;
}
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;
}
}
<?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;
interface ClientInterface extends HasDispatcherInterface
{
const CREATE_REQUEST = 'client.create_request';
const HTTP_DATE = 'D, d M Y H:i:s \G\M\T';
public function setConfig($config);
public function getConfig($key = false);
public function createRequest(
$method = RequestInterface::GET,
$uri = null,
$headers = null,
$body = null,
array $options = array()
);
public function get($uri = null, $headers = null, $options = array());
public function head($uri = null, $headers = null, array $options = array());
public function delete($uri = null, $headers = null, $body = null, array $options = array());
public function put($uri = null, $headers = null, $body = null, array $options = array());
public function patch($uri = null, $headers = null, $body = null, array $options = array());
public function post($uri = null, $headers = null, $postBody = null, array $options = array());
public function options($uri = null, array $options = array());
public function send($requests);
public function getBaseUrl($expand = true);
public function setBaseUrl($url);
public function setUserAgent($userAgent, $includeDefault = false);
public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2);
}
<?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;
class CurlHandle
{
const BODY_AS_STRING = 'body_as_string';
const PROGRESS = 'progress';
const DEBUG = 'debug';
protected $options;
protected $handle;
protected $errorNo = CURLE_OK;
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);
$url = (string)$request->getUrl();
if(($pos = strpos($url, '#')) !== false ){
$url = substr($url, 0, $pos);
}
$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,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2
);
if (defined('CURLOPT_PROTOCOLS')) {
$curlOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
}
if ($acceptEncodingHeader = $request->getHeader('Accept-Encoding')) {
$curlOptions[CURLOPT_ENCODING] = (string) $acceptEncodingHeader;
$request->removeHeader('Accept-Encoding');
}
if ($requestCurlOptions->get('debug')) {
$curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+');
if (false === $curlOptions[CURLOPT_STDERR]) {
throw new RuntimeException('Unable to create a stream for CURLOPT_STDERR');
}
$curlOptions[CURLOPT_VERBOSE] = true;
}
if ($method == 'GET') {
$curlOptions[CURLOPT_HTTPGET] = true;
} elseif ($method == 'HEAD') {
$curlOptions[CURLOPT_NOBODY] = true;
unset($curlOptions[CURLOPT_WRITEFUNCTION]);
} elseif (!($request instanceof EntityEnclosingRequest)) {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
} else {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
if ($request->getBody()) {
if ($bodyAsString) {
$curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody();
if ($tempContentLength = $request->getHeader('Content-Length')) {
$tempContentLength = (int) (string) $tempContentLength;
}
if (!$request->hasHeader('Content-Type')) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type:';
}
} else {
$curlOptions[CURLOPT_UPLOAD] = true;
if ($tempContentLength = $request->getHeader('Content-Length')) {
$tempContentLength = (int) (string) $tempContentLength;
$curlOptions[CURLOPT_INFILESIZE] = $tempContentLength;
}
$curlOptions[CURLOPT_READFUNCTION] = array($mediator, 'readRequestBody');
$request->getBody()->seek(0);
}
} else {
$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) {
$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 (!$request->hasHeader('Expect')) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:';
}
}
if (null !== $tempContentLength) {
$request->removeHeader('Content-Length');
}
foreach ($requestCurlOptions->toArray() as $key => $value) {
if (is_numeric($key)) {
$curlOptions[$key] = $value;
}
}
if (!isset($curlOptions[CURLOPT_ENCODING])) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Accept:';
}
foreach ($request->getHeaderLines() as $line) {
$curlOptions[CURLOPT_HTTPHEADER][] = $line;
}
if ($tempContentLength) {
$request->setHeader('Content-Length', $tempContentLength);
}
$handle = curl_init();
if ($requestCurlOptions->get('progress')) {
$curlOptions[CURLOPT_PROGRESSFUNCTION] = function () use ($mediator, $handle) {
$args = func_get_args();
$args[] = $handle;
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);
}
public function __construct($handle, $options)
{
if (!is_resource($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;
}
public function __destruct()
{
$this->close();
}
public function close()
{
if (is_resource($this->handle)) {
curl_close($this->handle);
}
$this->handle = null;
}
public function isAvailable()
{
return is_resource($this->handle);
}
public function getError()
{
return $this->isAvailable() ? curl_error($this->handle) : '';
}
public function getErrorNo()
{
if ($this->errorNo) {
return $this->errorNo;
}
return $this->isAvailable() ? curl_errno($this->handle) : CURLE_OK;
}
public function setErrorNo($error)
{
$this->errorNo = $error;
return $this;
}
public function getInfo($option = null)
{
if (!is_resource($this->handle)) {
return null;
}
if (null !== $option) {
return curl_getinfo($this->handle, $option) ?: null;
}
return curl_getinfo($this->handle) ?: array();
}
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;
}
public function getUrl()
{
return Url::factory($this->options->get(CURLOPT_URL));
}
public function getHandle()
{
return $this->isAvailable() ? $this->handle : null;
}
public function getOptions()
{
return $this->options;
}
public function updateRequestFromTransfer(RequestInterface $request)
{
if (!$request->getResponse()) {
return;
}
$request->getResponse()->setInfo($this->getInfo());
if (!$log = $this->getStderr(true)) {
return;
}
$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";
}
}
}
}
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']);
}
}
}
public static function parseCurlConfig($config)
{
$curlOptions = array();
foreach ($config as $key => $value) {
if (is_string($key) && defined($key)) {
$key = constant($key);
}
if (is_string($value) && defined($value)) {
$value = constant($value);
}
$curlOptions[$key] = $value;
}
return $curlOptions;
}
}
<?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;
class CurlMulti extends AbstractHasDispatcher implements CurlMultiInterface
{
protected $multiHandle;
protected $requests;
protected $handles;
protected $resourceHash;
protected $exceptions = array();
protected $successful = array();
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!')
);
public function __construct()
{
$this->multiHandle = curl_multi_init();
if ($this->multiHandle === false) {
throw new CurlException('Unable to create multi handle');
}
$this->reset();
}
public function __destruct()
{
if (is_resource($this->multiHandle)) {
curl_multi_close($this->multiHandle);
}
}
public function add(RequestInterface $request)
{
$this->requests[] = $request;
$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)
{
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);
}
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']);
}
foreach ($successful as $request) {
if (!$multiException->containsRequest($request)) {
$multiException->addSuccessfulRequest($request);
}
}
throw $multiException;
}
protected function beforeSend(RequestInterface $request)
{
try {
$state = $request->setState(RequestInterface::STATE_TRANSFER);
if ($state == RequestInterface::STATE_TRANSFER) {
$handle = $this->createCurlHandle($request)->getHandle();
$this->checkCurlResult(curl_multi_add_handle($this->multiHandle, $handle));
} else {
$this->remove($request);
if ($state == RequestInterface::STATE_COMPLETE) {
$this->successful[] = $request;
}
}
} catch (\Exception $e) {
$this->removeErroredRequest($request, $e);
}
}
protected function createCurlHandle(RequestInterface $request)
{
$wrapper = CurlHandle::factory($request);
$this->handles[$request] = $wrapper;
$this->resourceHash[(int) $wrapper->getHandle()] = $request;
return $wrapper;
}
protected function perform()
{
$event = new Event(array('curl_multi' => $this));
while ($this->requests) {
$blocking = $total = 0;
foreach ($this->requests as $request) {
++$total;
$event['request'] = $request;
$request->getEventDispatcher()->dispatch(self::POLLING_REQUEST, $event);
if ($request->getParams()->hasKey(self::BLOCKING)) {
++$blocking;
}
}
if ($blocking == $total) {
usleep(500);
} else {
$this->executeHandles();
}
}
}
private function executeHandles()
{
$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) {
usleep(150);
}
$selectTimeout = 1;
} while ($active);
}
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);
}
}
}
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));
}
protected function processResponse(RequestInterface $request, CurlHandle $handle, array $curl)
{
$handle->updateRequestFromTransfer($request);
$curlException = $this->isCurlException($request, $handle, $curl);
$this->removeHandle($request);
if (!$curlException) {
$state = $request->setState(RequestInterface::STATE_COMPLETE, array('handle' => $handle));
if ($state != RequestInterface::STATE_TRANSFER) {
$this->remove($request);
}
} else {
$state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $curlException));
if ($state != RequestInterface::STATE_TRANSFER) {
$this->remove($request);
}
if ($state == RequestInterface::STATE_ERROR) {
throw $curlException;
}
}
}
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();
}
}
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;
}
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
);
}
}
}
<?php
namespace Guzzle\Http\Curl;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\Exception\ExceptionCollection;
use Guzzle\Http\Message\RequestInterface;
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';
public function add(RequestInterface $request);
public function all();
public function remove(RequestInterface $request);
public function reset($hard = false);
public function send();
}
<?php
namespace Guzzle\Http\Curl;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Http\Message\RequestInterface;
class CurlMultiProxy extends AbstractHasDispatcher implements CurlMultiInterface
{
protected $handles = array();
protected $groups = array();
protected $queued = array();
protected $maxHandles;
public function __construct($maxHandles = 3)
{
$this->maxHandles = $maxHandles;
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();
$this->groups[] = $group;
while ($request = array_shift($this->queued)) {
$group->add($request);
}
try {
$group->send();
array_pop($this->groups);
$this->cleanupHandles();
} catch (\Exception $e) {
if (!$group->count()) {
array_pop($this->groups);
$this->cleanupHandles();
}
throw $e;
}
}
}
public function count()
{
return count($this->all());
}
protected function getAvailableHandle()
{
foreach ($this->handles as $h) {
if (!in_array($h, $this->groups, true)) {
return $h;
}
}
$handle = new CurlMulti();
$handle->setEventDispatcher($this->getEventDispatcher());
$this->handles[] = $handle;
return $handle;
}
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;
class CurlVersion
{
protected $version;
protected static $instance;
protected $userAgent;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function getAll()
{
if (!$this->version) {
$this->version = curl_version();
}
return $this->version;
}
public function get($type)
{
$version = $this->getAll();
return isset($version[$type]) ? $version[$type] : false;
}
}
<?php
namespace Guzzle\Http\Curl;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Response;
class RequestMediator
{
protected $request;
protected $emitIo;
public function __construct(RequestInterface $request, $emitIo = false)
{
$this->request = $request;
$this->emitIo = $emitIo;
}
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] : '';
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;
}
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
));
}
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 {
return 0;
}
}
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;
use Guzzle\Common\Version;
use Guzzle\Stream\Stream;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Mimetypes;
class EntityBody extends Stream implements EntityBodyInterface
{
protected $contentEncoding = false;
protected $rewindFunction;
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();
}
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;
if ($filter == 'zlib.inflate') {
if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
return false;
}
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;
}
}
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)
{
if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
return false;
}
$handle = fopen('php://temp', 'r+');
$filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE);
if (!$filter) {
return false;
}
$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);
$this->rewindFunction = null;
return true;
}
}
<?php
namespace Guzzle\Http;
use Guzzle\Stream\StreamInterface;
interface EntityBodyInterface extends StreamInterface
{
public function setRewindFunction($callable);
public function compress($filter = 'zlib.deflate');
public function uncompress($filter = 'zlib.inflate');
public function getContentLength();
public function getContentType();
public function getContentMd5($rawOutput = false, $base64Encode = false);
public function getContentEncoding();
}
<?php
namespace Guzzle\Http\Exception;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
class BadResponseException extends RequestException
{
private $response;
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;
}
public function setResponse(Response $response)
{
$this->response = $response;
}
public function getResponse()
{
return $this->response;
}
}
<?php
namespace Guzzle\Http\Exception;
class ClientErrorResponseException extends BadResponseException {}
<?php
namespace Guzzle\Http\Exception;
use Guzzle\Common\Exception\RuntimeException;
class CouldNotRewindStreamException extends RuntimeException implements HttpException {}
<?php
namespace Guzzle\Http\Exception;
use Guzzle\Http\Curl\CurlHandle;
class CurlException extends RequestException
{
private $curlError;
private $curlErrorNo;
private $handle;
private $curlInfo = array();
public function setError($error, $number)
{
$this->curlError = $error;
$this->curlErrorNo = $number;
return $this;
}
public function setCurlHandle(CurlHandle $handle)
{
$this->handle = $handle;
return $this;
}
public function getCurlHandle()
{
return $this->handle;
}
public function getError()
{
return $this->curlError;
}
public function getErrorNo()
{
return $this->curlErrorNo;
}
public function getCurlInfo()
{
return $this->curlInfo;
}
public function setCurlInfo(array $info)
{
$this->curlInfo = $info;
return $this;
}
}
<?php
namespace Guzzle\Http\Exception;
use Guzzle\Common\Exception\GuzzleException;
interface HttpException extends GuzzleException {}
<?php
namespace Guzzle\Http\Exception;
use Guzzle\Common\Exception\ExceptionCollection;
use Guzzle\Http\Message\RequestInterface;
class MultiTransferException extends ExceptionCollection
{
protected $successfulRequests = array();
protected $failedRequests = array();
protected $exceptionForRequest = array();
public function getAllRequests()
{
return array_merge($this->successfulRequests, $this->failedRequests);
}
public function addSuccessfulRequest(RequestInterface $request)
{
$this->successfulRequests[] = $request;
return $this;
}
public function addFailedRequest(RequestInterface $request)
{
$this->failedRequests[] = $request;
return $this;
}
public function addFailedRequestWithException(RequestInterface $request, \Exception $exception)
{
$this->add($exception)
->addFailedRequest($request)
->exceptionForRequest[spl_object_hash($request)] = $exception;
return $this;
}
public function getExceptionForFailedRequest(RequestInterface $request)
{
$oid = spl_object_hash($request);
return isset($this->exceptionForRequest[$oid]) ? $this->exceptionForRequest[$oid] : null;
}
public function setSuccessfulRequests(array $requests)
{
$this->successfulRequests = $requests;
return $this;
}
public function setFailedRequests(array $requests)
{
$this->failedRequests = $requests;
return $this;
}
public function getSuccessfulRequests()
{
return $this->successfulRequests;
}
public function getFailedRequests()
{
return $this->failedRequests;
}
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\Common\Exception\RuntimeException;
use Guzzle\Http\Message\RequestInterface;
class RequestException extends RuntimeException implements HttpException
{
protected $request;
public function setRequest(RequestInterface $request)
{
$this->request = $request;
return $this;
}
public function getRequest()
{
return $this->request;
}
}
<?php
namespace Guzzle\Http\Exception;
class ServerErrorResponseException extends BadResponseException {}
<?php
namespace Guzzle\Http\Exception;
class TooManyRedirectsException extends BadResponseException {}
<?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;
class IoEmittingEntityBody extends AbstractEntityBodyDecorator implements HasDispatcherInterface
{
protected $eventDispatcher;
public static function getAllEvents()
{
return array('body.read', 'body.write');
}
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;
}
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\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 class AbstractMessage implements MessageInterface
{
protected $headers;
protected $headerFactory;
protected $params;
protected $protocol = 'HTTP';
protected $protocolVersion = '1.1';
public function __construct()
{
$this->params = new Collection();
$this->headerFactory = new HeaderFactory();
$this->headers = new HeaderCollection();
}
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;
}
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;
}
}
public function setTokenizedHeader($header, $data, $token = ';')
{
Version::warn(__METHOD__ . ' is deprecated.');
return $this;
}
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);
}
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;
}
}
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;
}
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\Http\EntityBody;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\QueryString;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Exception\RequestException;
class EntityEnclosingRequest extends Request implements EntityEnclosingRequestInterface
{
protected $expectCutoff = 1048576;
protected $body;
protected $postFields;
protected $postFiles = array();
public function __construct($method, $url, $headers = array())
{
$this->postFields = new QueryString();
parent::__construct($method, $url, $headers);
}
public function __toString()
{
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);
if ($contentType === null && !$this->hasHeader('Content-Type')) {
$contentType = $this->body->getContentType();
}
if ($contentType) {
$this->setHeader('Content-Type', $contentType);
}
if (!$this->body->isSeekable() && $this->expectCutoff !== false) {
$this->setHeader('Expect', '100-Continue');
}
$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;
}
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)) {
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)) {
$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)) {
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;
}
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;
interface EntityEnclosingRequestInterface extends RequestInterface
{
const URL_ENCODED = 'application/x-www-form-urlencoded; charset=utf-8';
const MULTIPART = 'multipart/form-data';
public function setBody($body, $contentType = null);
public function getBody();
public function getPostField($field);
public function getPostFields();
public function setPostField($key, $value);
public function addPostFields($fields);
public function removePostField($field);
public function getPostFiles();
public function getPostFile($fieldName);
public function removePostFile($fieldName);
public function addPostFile($field, $filename = null, $contentType = null, $postname = null);
public function addPostFiles(array $files);
public function configureRedirects($strict = false, $maxRedirects = 5);
}
<?php
namespace Guzzle\Http\Message;
use Guzzle\Common\Version;
use Guzzle\Http\Message\Header\HeaderInterface;
class Header implements HeaderInterface
{
protected $values = array();
protected $header;
protected $glue;
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;
}
public function normalize()
{
$values = $this->toArray();
for ($i = 0, $total = count($values); $i < $total; $i++) {
if (strpos($values[$i], $this->glue) !== false) {
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');
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;
}
public function hasExactHeader($header)
{
Version::warn(__METHOD__ . ' is deprecated');
return $this->header == $header;
}
public function raw()
{
Version::warn(__METHOD__ . ' is deprecated. Use toArray()');
return $this->toArray();
}
protected function trimHeader($str)
{
static $trimmed = "\"' \n\t";
return trim($str, $trimmed);
}
}
<?php
namespace Guzzle\Http\Message\Header;
use Guzzle\Http\Message\Header;
class CacheControl extends Header
{
protected $directives;
public function add($value)
{
parent::add($value);
$this->directives = null;
}
public function removeValue($searchValue)
{
parent::removeValue($searchValue);
$this->directives = null;
}
public function hasDirective($param)
{
$directives = $this->getDirectives();
return isset($directives[$param]);
}
public function getDirective($param)
{
$directives = $this->getDirectives();
return isset($directives[$param]) ? $directives[$param] : null;
}
public function addDirective($param, $value)
{
$directives = $this->getDirectives();
$directives[$param] = $value;
$this->updateFromDirectives($directives);
return $this;
}
public function removeDirective($param)
{
$directives = $this->getDirectives();
unset($directives[$param]);
$this->updateFromDirectives($directives);
return $this;
}
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;
}
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\Common\ToArrayInterface;
class HeaderCollection implements \IteratorAggregate, \Countable, \ArrayAccess, ToArrayInterface
{
protected $headers;
public function __construct($headers = array())
{
$this->headers = $headers;
}
public function __clone()
{
foreach ($this->headers as &$header) {
$header = clone $header;
}
}
public function clear()
{
$this->headers = array();
}
public function add(HeaderInterface $header)
{
$this->headers[strtolower($header->getName())] = $header;
return $this;
}
public function getAll()
{
return $this->headers;
}
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;
class HeaderFactory implements HeaderFactoryInterface
{
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 HeaderFactoryInterface
{
public function createHeader($header, $value = null);
}
<?php
namespace Guzzle\Http\Message\Header;
use Guzzle\Common\ToArrayInterface;
interface HeaderInterface extends ToArrayInterface, \Countable, \IteratorAggregate
{
public function __toString();
public function add($value);
public function getName();
public function setName($name);
public function setGlue($glue);
public function getGlue();
public function hasValue($searchValue);
public function removeValue($searchValue);
public function parseParams();
}
<?php
namespace Guzzle\Http\Message\Header;
use Guzzle\Http\Message\Header;
class Link extends Header
{
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));
}
public function hasLink($rel)
{
return $this->getLink($rel) !== null;
}
public function getLink($rel)
{
foreach ($this->getLinks() as $link) {
if (isset($link['rel']) && $link['rel'] == $rel) {
return $link;
}
}
return null;
}
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;
interface MessageInterface
{
public function getParams();
public function addHeader($header, $value);
public function addHeaders(array $headers);
public function getHeader($header);
public function getHeaders();
public function hasHeader($header);
public function removeHeader($header);
public function setHeader($header, $value);
public function setHeaders(array $headers);
public function getHeaderLines();
public function getRawHeaders();
}
<?php
namespace Guzzle\Http\Message;
use Guzzle\Common\Version;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Mimetypes;
class PostFile implements PostFileInterface
{
protected $fieldName;
protected $contentType;
protected $filename;
protected $postname;
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)
{
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()
{
if (function_exists('curl_file_create')) {
return curl_file_create($this->filename, $this->contentType, $this->postname);
}
$value = "@{$this->filename};filename=" . $this->postname;
if ($this->contentType) {
$value .= ';type=' . $this->contentType;
}
return $value;
}
public function getCurlString()
{
Version::warn(__METHOD__ . ' is deprecated. Use getCurlValue()');
return $this->getCurlValue();
}
protected function guessContentType()
{
return Mimetypes::getInstance()->fromFilename($this->filename) ?: 'application/octet-stream';
}
}
<?php
namespace Guzzle\Http\Message;
use Guzzle\Common\Exception\InvalidArgumentException;
interface PostFileInterface
{
public function setFieldName($name);
public function getFieldName();
public function setFilename($path);
public function setPostname($name);
public function getFilename();
public function getPostname();
public function setContentType($type);
public function getContentType();
public function getCurlValue();
}
<?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;
class Request extends AbstractMessage implements RequestInterface
{
protected $eventDispatcher;
protected $url;
protected $method;
protected $client;
protected $response;
protected $responseBody;
protected $state;
protected $username;
protected $password;
protected $curlOptions;
protected $isRedirect = false;
public static function getAllEvents()
{
return array(
'curl.callback.read', 'curl.callback.write', 'curl.callback.progress',
'request.clone',
'request.before_send', 'request.sent', 'request.complete',
'request.success',
'request.error',
'request.exception',
'request.receive.status_line'
);
}
public function __construct($method, $url, $headers = array())
{
parent::__construct();
$this->method = strtoupper($method);
$this->curlOptions = new Collection();
$this->setUrl($url);
if ($headers) {
foreach ($headers as $key => $value) {
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));
}
public function __toString()
{
return $this->getRawHeaders() . "\r\n\r\n";
}
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);
}
$this->setPort($this->url->getPort());
if ($this->url->getUsername() || $this->url->getPassword()) {
$this->setAuth($this->url->getUsername(), $this->url->getPassword());
$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);
$scheme = $this->url->getScheme();
if (($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 (!$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;
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) {
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 ($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)
{
if (is_string($body)) {
if (!($body = fopen($body, 'w+'))) {
throw new InvalidArgumentException('Could not open ' . $body . ' for writing');
}
}
$this->responseBody = EntityBody::factory($body);
return $this;
}
public function getResponseBody()
{
if ($this->responseBody === null) {
$this->responseBody = EntityBody::factory()->setCustomData('default', true);
}
return $this->responseBody;
}
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}");
}
$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;
}
protected function getEventArray()
{
return array(
'request' => $this,
'response' => $this->response
);
}
protected function processResponse(array $context = array())
{
if (!$this->response) {
$e = new RequestException('Error completing request');
$e->setRequest($this);
throw $e;
}
$this->state = self::STATE_COMPLETE;
$this->dispatch('request.sent', $this->getEventArray() + $context);
if ($this->state == RequestInterface::STATE_COMPLETE) {
$this->dispatch('request.complete', $this->getEventArray());
if ($this->response->isError()) {
$event = new Event($this->getEventArray());
$this->getEventDispatcher()->dispatch('request.error', $event);
if ($event['response'] !== $this->response) {
$this->response = $event['response'];
}
}
if ($this->response->isSuccessful()) {
$this->dispatch('request.success', $this->getEventArray());
}
}
}
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;
}
}
public function setIsRedirect($isRedirect)
{
$this->isRedirect = $isRedirect;
return $this;
}
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\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Url;
use Guzzle\Parser\ParserRegistry;
class RequestFactory implements RequestFactoryInterface
{
protected static $instance;
protected $methods;
protected $requestClass = 'Guzzle\\Http\\Message\\Request';
protected $entityEnclosingRequestClass = 'Guzzle\\Http\\Message\\EntityEnclosingRequest';
public static function getInstance()
{
if (!static::$instance) {
static::$instance = new static();
}
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']);
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' || $method == 'OPTIONS') {
$request = new $this->requestClass($method, $url, $headers);
if ($body) {
$type = gettype($body);
if ($type == 'string' || $type == 'resource' || $type == 'object') {
$request->setResponseBody($body);
}
}
} else {
$request = new $this->entityEnclosingRequestClass($method, $url, $headers);
if ($body || $body === '0') {
if (is_array($body) || $body instanceof Collection) {
foreach ($body as $key => $value) {
if (is_string($value) && substr($value, 0, 1) == '@') {
$request->addPostFile($key, $value);
unset($body[$key]);
}
}
$request->addPostFields($body);
} else {
$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;
}
public function cloneRequestWithMethod(RequestInterface $request, $method)
{
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());
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)
{
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) {
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) {
$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;
use Guzzle\Common\Collection;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\Url;
interface RequestFactoryInterface
{
const OPTIONS_NONE = 0;
const OPTIONS_AS_DEFAULTS = 1;
public function fromMessage($message);
public function fromParts(
$method,
array $urlParts,
$headers = null,
$body = null,
$protocol = 'HTTP',
$protocolVersion = '1.1'
);
public function create($method, $url, $headers = null, $body = null, array $options = array());
public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE);
}
<?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;
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';
public function __toString();
public function send();
public function setClient(ClientInterface $client);
public function getClient();
public function setUrl($url);
public function getUrl($asObject = false);
public function getResource();
public function getQuery();
public function getMethod();
public function getScheme();
public function setScheme($scheme);
public function getHost();
public function setHost($host);
public function getPath();
public function setPath($path);
public function getPort();
public function setPort($port);
public function getUsername();
public function getPassword();
public function setAuth($user, $password = '', $scheme = 'Basic');
public function getProtocolVersion();
public function setProtocolVersion($protocol);
public function getResponse();
public function setResponse(Response $response, $queued = false);
public function startResponse(Response $response);
public function setResponseBody($body);
public function getResponseBody();
public function getState();
public function setState($state, array $context = array());
public function getCurlOptions();
public function getCookies();
public function getCookie($name);
public function addCookie($name, $value);
public function removeCookie($name);
}
<?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;
class Response extends AbstractMessage implements \Serializable
{
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',
);
protected $body;
protected $reasonPhrase;
protected $statusCode;
protected $info = array();
protected $effectiveUrl;
protected static $cacheResponseCodes = array(200, 203, 206, 300, 301, 410);
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']);
$contentLength = (string) $response->getHeader('Content-Length');
$actualLength = strlen($data['body']);
if (strlen($data['body']) > 0 && $contentLength != $actualLength) {
$response->setHeader('Content-Length', $actualLength);
}
return $response;
}
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');
}
}
}
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']);
}
public function getBody($asString = false)
{
return $asString ? (string) $this->body : $this->body;
}
public function setBody($body)
{
$this->body = EntityBody::factory($body);
return $this;
}
public function setProtocol($protocol, $version)
{
$this->protocol = $protocol;
$this->protocolVersion = $version;
return $this;
}
public function getProtocol()
{
return $this->protocol;
}
public function getProtocolVersion()
{
return $this->protocolVersion;
}
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;
}
}
public function setInfo(array $info)
{
$this->info = $info;
return $this;
}
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;
}
public function getStatusCode()
{
return $this->statusCode;
}
public function getMessage()
{
$message = $this->getRawHeaders();
$size = $this->body->getSize();
if ($size < 2097152) {
$message .= (string) $this->body;
}
return $message;
}
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";
}
public function getReasonPhrase()
{
return $this->reasonPhrase;
}
public function getAcceptRanges()
{
return (string) $this->getHeader('Accept-Ranges');
}
public function calculateAge()
{
$age = $this->getHeader('Age');
if ($age === null && $this->getDate()) {
$age = time() - strtotime($this->getDate());
}
return $age === null ? null : (int) (string) $age;
}
public function getAge()
{
return (string) $this->getHeader('Age');
}
public function getAllow()
{
return (string) $this->getHeader('Allow');
}
public function isMethodAllowed($method)
{
$allow = $this->getHeader('Allow');
if ($allow) {
foreach (explode(',', $allow) as $allowable) {
if (!strcasecmp(trim($allowable), $method)) {
return true;
}
}
}
return false;
}
public function getCacheControl()
{
return (string) $this->getHeader('Cache-Control');
}
public function getConnection()
{
return (string) $this->getHeader('Connection');
}
public function getContentEncoding()
{
return (string) $this->getHeader('Content-Encoding');
}
public function getContentLanguage()
{
return (string) $this->getHeader('Content-Language');
}
public function getContentLength()
{
return (int) (string) $this->getHeader('Content-Length');
}
public function getContentLocation()
{
return (string) $this->getHeader('Content-Location');
}
public function getContentDisposition()
{
return (string) $this->getHeader('Content-Disposition');
}
public function getContentMd5()
{
return (string) $this->getHeader('Content-MD5');
}
public function getContentRange()
{
return (string) $this->getHeader('Content-Range');
}
public function getContentType()
{
return (string) $this->getHeader('Content-Type');
}
public function isContentType($type)
{
return stripos($this->getHeader('Content-Type'), $type) !== false;
}
public function getDate()
{
return (string) $this->getHeader('Date');
}
public function getEtag()
{
return (string) $this->getHeader('ETag');
}
public function getExpires()
{
return (string) $this->getHeader('Expires');
}
public function getLastModified()
{
return (string) $this->getHeader('Last-Modified');
}
public function getLocation()
{
return (string) $this->getHeader('Location');
}
public function getPragma()
{
return (string) $this->getHeader('Pragma');
}
public function getProxyAuthenticate()
{
return (string) $this->getHeader('Proxy-Authenticate');
}
public function getRetryAfter()
{
return (string) $this->getHeader('Retry-After');
}
public function getServer()
{
return (string) $this->getHeader('Server');
}
public function getSetCookie()
{
return (string) $this->getHeader('Set-Cookie');
}
public function getTrailer()
{
return (string) $this->getHeader('Trailer');
}
public function getTransferEncoding()
{
return (string) $this->getHeader('Transfer-Encoding');
}
public function getVary()
{
return (string) $this->getHeader('Vary');
}
public function getVia()
{
return (string) $this->getHeader('Via');
}
public function getWarning()
{
return (string) $this->getHeader('Warning');
}
public function getWwwAuthenticate()
{
return (string) $this->getHeader('WWW-Authenticate');
}
public function isClientError()
{
return $this->statusCode >= 400 && $this->statusCode < 500;
}
public function isError()
{
return $this->isClientError() || $this->isServerError();
}
public function isInformational()
{
return $this->statusCode < 200;
}
public function isRedirect()
{
return $this->statusCode >= 300 && $this->statusCode < 400;
}
public function isServerError()
{
return $this->statusCode >= 500 && $this->statusCode < 600;
}
public function isSuccessful()
{
return ($this->statusCode >= 200 && $this->statusCode < 300) || $this->statusCode == 304;
}
public function canCache()
{
if (!in_array((int) $this->getStatusCode(), self::$cacheResponseCodes)) {
return false;
}
if ((!$this->getBody()->isReadable() || !$this->getBody()->isSeekable())
&& ($this->getContentLength() > 0 || $this->getTransferEncoding() == 'chunked')) {
return false;
}
if ($this->getHeader('Cache-Control') && $this->getHeader('Cache-Control')->hasDirective('no-store')) {
return false;
}
return $this->isFresh() || $this->getFreshness() === null || $this->canValidate();
}
public function getMaxAge()
{
if ($header = $this->getHeader('Cache-Control')) {
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;
}
public function isFresh()
{
$fresh = $this->getFreshness();
return $fresh === null ? null : $fresh >= 0;
}
public function canValidate()
{
return $this->getEtag() || $this->getLastModified();
}
public function getFreshness()
{
$maxAge = $this->getMaxAge();
$age = $this->calculateAge();
return $maxAge && $age ? ($maxAge - $age) : null;
}
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;
}
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;
}
public function getRedirectCount()
{
return (int) $this->params->get(RedirectPlugin::REDIRECT_COUNT);
}
public function setEffectiveUrl($url)
{
$this->effectiveUrl = $url;
return $this;
}
public function getEffectiveUrl()
{
return $this->effectiveUrl;
}
public function getPreviousResponse()
{
Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin.');
return null;
}
public function setRequest($request)
{
Version::warn(__METHOD__ . ' is deprecated');
return $this;
}
public function getRequest()
{
Version::warn(__METHOD__ . ' is deprecated');
return null;
}
}
<?php
namespace Guzzle\Http;
class Mimetypes
{
protected static $instance;
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'
);
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function fromExtension($extension)
{
$extension = strtolower($extension);
return isset($this->mimetypes[$extension]) ? $this->mimetypes[$extension] : null;
}
public function fromFilename($filename)
{
return $this->fromExtension(pathinfo($filename, PATHINFO_EXTENSION));
}
}
<?php
namespace Guzzle\Http\QueryAggregator;
use Guzzle\Http\QueryString;
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;
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\QueryAggregator;
use Guzzle\Http\QueryString;
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;
interface QueryAggregatorInterface
{
public function aggregate($key, $value, QueryString $query);
}
<?php
namespace Guzzle\Http;
use Guzzle\Common\Collection;
use Guzzle\Http\QueryAggregator\DuplicateAggregator;
use Guzzle\Http\QueryAggregator\QueryAggregatorInterface;
use Guzzle\Http\QueryAggregator\PhpAggregator;
class QueryString extends Collection
{
const RFC_3986 = 'RFC 3986';
const FORM_URLENCODED = 'application/x-www-form-urlencoded';
const BLANK = "_guzzle_blank_";
protected $fieldSeparator = '&';
protected $valueSeparator = '=';
protected $urlEncode = 'RFC 3986';
protected $aggregator;
private static $defaultAggregator = null;
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 {
$q->add($key, self::BLANK);
}
}
if ($foundDuplicates && !$foundPhpStyle) {
$q->setAggregator(new DuplicateAggregator());
}
return $q;
}
public function __toString()
{
if (!$this->data) {
return '';
}
$queryString = '';
foreach ($this->prepareData($this->data) as $name => $value) {
foreach ((array) $value as $v) {
if ($queryString) {
$queryString .= $this->fieldSeparator;
}
$queryString .= $name;
if ($v !== self::BLANK) {
$queryString .= $this->valueSeparator . $v;
}
}
}
return $queryString;
}
public function getFieldSeparator()
{
return $this->fieldSeparator;
}
public function getValueSeparator()
{
return $this->valueSeparator;
}
public function getUrlEncoding()
{
return $this->urlEncode;
}
public function isUrlEncoding()
{
return $this->urlEncode !== false;
}
public function setAggregator(QueryAggregatorInterface $aggregator = null)
{
if (!$aggregator) {
if (!self::$defaultAggregator) {
self::$defaultAggregator = new PhpAggregator();
}
$aggregator = self::$defaultAggregator;
}
$this->aggregator = $aggregator;
return $this;
}
public function useUrlEncoding($encode)
{
$this->urlEncode = ($encode === true) ? self::RFC_3986 : $encode;
return $this;
}
public function setFieldSeparator($separator)
{
$this->fieldSeparator = $separator;
return $this;
}
public function setValueSeparator($separator)
{
$this->valueSeparator = $separator;
return $this;
}
public function urlEncode()
{
return $this->prepareData($this->data);
}
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;
}
}
protected function prepareData(array $data)
{
if (!$this->aggregator) {
$this->setAggregator(null);
}
$temp = array();
foreach ($data as $key => $value) {
if (is_array($value)) {
$temp = array_merge($temp, $this->aggregator->aggregate($key, $value, $this));
} else {
$temp[$this->encodeValue($key)] = $this->encodeValue($value);
}
}
return $temp;
}
}
<?php
namespace Guzzle\Http;
class ReadLimitEntityBody extends AbstractEntityBodyDecorator
{
protected $limit;
protected $offset;
public function __construct(EntityBodyInterface $body, $limit, $offset = 0)
{
parent::__construct($body);
$this->setLimit($limit)->setOffset($offset);
}
public function __toString()
{
return substr((string) $this->body, $this->offset, $this->limit) ?: '';
}
public function isConsumed()
{
return (($this->offset + $this->limit) - $this->body->ftell()) <= 0;
}
public function getContentLength()
{
$length = $this->body->getContentLength();
return $length === false
? $this->limit
: min($this->limit, min($length, $this->offset + $this->limit) - $this->offset);
}
public function seek($offset, $whence = SEEK_SET)
{
return $whence === SEEK_SET
? $this->body->seek(max($this->offset, min($this->offset + $this->limit, $offset)))
: false;
}
public function setOffset($offset)
{
$this->body->seek($offset);
$this->offset = $offset;
return $this;
}
public function setLimit($limit)
{
$this->limit = $limit;
return $this;
}
public function read($length)
{
$remaining = ($this->offset + $this->limit) - $this->body->ftell();
if ($remaining > 0) {
return $this->body->read(min($remaining, $length));
} else {
return false;
}
}
}
<?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;
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';
protected $defaultMaxRedirects = 5;
public static function getSubscribedEvents()
{
return array(
'request.sent' => array('onRequestSent', 100),
'request.clone' => 'cleanupRequest',
'request.before_send' => 'cleanupRequest'
);
}
public function cleanupRequest(Event $event)
{
$params = $event['request']->getParams();
unset($params[self::REDIRECT_COUNT]);
unset($params[self::PARENT_REQUEST]);
}
public function onRequestSent(Event $event)
{
$response = $event['response'];
$request = $event['request'];
if (!$response || $request->getParams()->get(self::DISABLE)) {
return;
}
$original = $this->getOriginalRequest($request);
if (!$response->isRedirect() || !$response->hasHeader('Location')) {
if ($request !== $original) {
$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);
}
protected function getOriginalRequest(RequestInterface $request)
{
$original = $request;
while ($parent = $original->getParams()->get(self::PARENT_REQUEST)) {
$original = $parent;
}
return $original;
}
protected function createRedirectRequest(
RequestInterface $request,
$statusCode,
$location,
RequestInterface $original
) {
$redirectRequest = null;
$strict = $original->getParams()->get(self::STRICT_REDIRECTS);
if ($request instanceof EntityEnclosingRequestInterface && ($statusCode == 303 || (!$strict && $statusCode <= 302))) {
$redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET');
} else {
$redirectRequest = clone $request;
}
$redirectRequest->setIsRedirect(true);
$redirectRequest->setResponseBody($request->getResponseBody());
$location = Url::factory($location);
if (!$location->isAbsolute()) {
$originalUrl = $redirectRequest->getUrl(true);
$originalUrl->getQuery()->clear();
$location = $originalUrl->combine((string) $location, true);
}
$redirectRequest->setUrl($location);
$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);
}
);
if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) {
$body = $redirectRequest->getBody();
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;
}
protected function prepareRedirection(RequestInterface $original, RequestInterface $request, Response $response)
{
$params = $original->getParams();
$current = $params[self::REDIRECT_COUNT] + 1;
$params[self::REDIRECT_COUNT] = $current;
$max = isset($params[self::MAX_REDIRECTS]) ? $params[self::MAX_REDIRECTS] : $this->defaultMaxRedirects;
if ($current > $max) {
$this->throwTooManyRedirectsException($original, $max);
return false;
} else {
return $this->createRedirectRequest(
$request,
$response->getStatusCode(),
trim($response->getLocation()),
$original
);
}
}
protected function sendRedirectRequest(RequestInterface $original, RequestInterface $request, Response $response)
{
if ($redirectRequest = $this->prepareRedirection($original, $request, $response)) {
try {
$redirectRequest->send();
} catch (BadResponseException $e) {
$e->getResponse();
if (!$e->getResponse()) {
throw $e;
}
}
}
}
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);
}
);
}
}
<?php
namespace Guzzle\Http;
use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Guzzle\Stream\StreamRequestFactoryInterface;
use Guzzle\Stream\PhpStreamRequestFactory;
final class StaticClient
{
private static $client;
public static function mount($className = 'Guzzle', ClientInterface $client = null)
{
class_alias(__CLASS__, $className);
if ($client) {
self::$client = $client;
}
}
public static function request($method, $url, $options = array())
{
if (!self::$client) {
self::$client = new Client();
}
$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();
}
public static function get($url, $options = array())
{
return self::request('GET', $url, $options);
}
public static function head($url, $options = array())
{
return self::request('HEAD', $url, $options);
}
public static function delete($url, $options = array())
{
return self::request('DELETE', $url, $options);
}
public static function post($url, $options = array())
{
return self::request('POST', $url, $options);
}
public static function put($url, $options = array())
{
return self::request('PUT', $url, $options);
}
public static function patch($url, $options = array())
{
return self::request('PATCH', $url, $options);
}
public static function options($url, $options = array())
{
return self::request('OPTIONS', $url, $options);
}
}
<?php
namespace Guzzle\Http;
use Guzzle\Common\Exception\InvalidArgumentException;
class Url
{
protected $scheme;
protected $host;
protected $port;
protected $username;
protected $password;
protected $path = '';
protected $fragment;
protected $query;
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;
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']);
}
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'];
if (isset($parts['port'])
&& !(($scheme == 'http' && $parts['port'] == 80) || ($scheme == 'https' && $parts['port'] == 443))
) {
$url .= ':' . $parts['port'];
}
}
if (isset($parts['path']) && 0 !== strlen($parts['path'])) {
if ($url && $parts['path'][0] != '/' && substr($url, -1) != '/') {
$url .= '/';
}
$url .= $parts['path'];
}
if (isset($parts['query'])) {
$url .= '?' . $parts['query'];
}
if (isset($parts['fragment'])) {
$url .= '#' . $parts['fragment'];
}
return $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);
}
public function __clone()
{
$this->query = clone $this->query;
}
public function __toString()
{
return self::buildUrl($this->getParts());
}
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,
);
}
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;
}
public function getHost()
{
return $this->host;
}
public function setScheme($scheme)
{
$this->scheme = $scheme;
return $this;
}
public function getScheme()
{
return $this->scheme;
}
public function setPort($port)
{
$this->port = $port;
return $this;
}
public function getPort()
{
if ($this->port) {
return $this->port;
} elseif ($this->scheme == 'http') {
return 80;
} elseif ($this->scheme == 'https') {
return 443;
}
return null;
}
public function setPath($path)
{
static $pathReplace = array(' ' => '%20', '?' => '%3F');
if (is_array($path)) {
$path = '/' . implode('/', $path);
}
$this->path = strtr($path, $pathReplace);
return $this;
}
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;
}
}
$this->path = ($this->path[0] == '/' ? '/' : '') . implode('/', $results);
if ($this->path != '/' && end($segments) == '') {
$this->path .= '/';
}
return $this;
}
public function addPath($relativePath)
{
if (!$relativePath || $relativePath == '/') {
return $this;
}
if ($relativePath[0] != '/') {
$relativePath = '/' . $relativePath;
}
return $this->setPath(str_replace('//', '/', $this->getPath() . $relativePath));
}
public function getPath()
{
return $this->path;
}
public function getPathSegments()
{
return array_slice(explode('/', $this->getPath()), 1);
}
public function setPassword($password)
{
$this->password = $password;
return $this;
}
public function getPassword()
{
return $this->password;
}
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function getUsername()
{
return $this->username;
}
public function getQuery()
{
return $this->query;
}
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;
}
public function getFragment()
{
return $this->fragment;
}
public function setFragment($fragment)
{
$this->fragment = $fragment;
return $this;
}
public function isAbsolute()
{
return $this->scheme && $this->host;
}
public function combine($url, $strictRfc3986 = false)
{
$url = self::factory($url);
if (!$this->isAbsolute() && $url->isAbsolute()) {
$url = $url->combine($this);
}
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;
}
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\Inflection;
class Inflector implements InflectorInterface
{
protected static $default;
public static function getDefault()
{
if (!self::$default) {
self::$default = new MemoizingInflector(new self());
}
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\Inflection;
interface InflectorInterface
{
public function snake($word);
public function camel($word);
}
<?php
namespace Guzzle\Inflection;
class MemoizingInflector implements InflectorInterface
{
protected $cache = array(
'snake' => array(),
'camel' => array()
);
protected $maxCacheSize;
protected $decoratedInflector;
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];
}
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];
}
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;
class PreComputedInflector implements InflectorInterface
{
protected $mapping = array(
'snake' => array(),
'camel' => array()
);
protected $decoratedInflector;
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);
}
public function camel($word)
{
return isset($this->mapping['camel'][$word])
? $this->mapping['camel'][$word]
: $this->decoratedInflector->camel($word);
}
}
<?php
namespace Guzzle\Iterator;
class AppendIterator extends \AppendIterator
{
public function append(\Iterator $iterator)
{
$this->getArrayIterator()->append($iterator);
}
}
<?php
namespace Guzzle\Iterator;
class ChunkedIterator extends \IteratorIterator
{
protected $chunkSize;
protected $chunk;
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;
use Guzzle\Common\Exception\InvalidArgumentException;
class FilterIterator extends \FilterIterator
{
protected $callback;
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;
use Guzzle\Common\Exception\InvalidArgumentException;
class MapIterator extends \IteratorIterator
{
protected $callback;
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());
}
}
<?php
namespace Guzzle\Iterator;
class MethodProxyIterator extends \IteratorIterator
{
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);
}
}
<?php
namespace Guzzle\Log;
abstract class AbstractLogAdapter implements LogAdapterInterface
{
protected $log;
public function getLogObject()
{
return $this->log;
}
}
<?php
namespace Guzzle\Log;
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);
}
public function getLogs()
{
return $this->logs;
}
public function clearLogs()
{
$this->logs = array();
}
}
<?php
namespace Guzzle\Log;
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;
interface LogAdapterInterface
{
public function log($message, $priority = LOG_INFO, $extras = array());
}
<?php
namespace Guzzle\Log;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\Response;
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}';
protected $template;
public function __construct($template = self::DEFAULT_FORMAT)
{
$this->template = $template ?: self::DEFAULT_FORMAT;
}
public function setTemplate($template)
{
$this->template = $template;
return $this;
}
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 Monolog\Logger;
class MonologLogAdapter extends AbstractLogAdapter
{
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);
}
}
<?php
namespace Guzzle\Log;
use Psr\Log\LogLevel;
use Psr\Log\LoggerInterface;
class PsrLogAdapter extends AbstractLogAdapter
{
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;
use Guzzle\Common\Version;
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);
}
}
<?php
namespace Guzzle\Log;
use Zend\Log\Logger;
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\Parser\Cookie;
class CookieParser implements CookieParserInterface
{
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)
{
$pieces = array_filter(array_map('trim', explode(';', $cookie)));
if (empty($pieces) || !strpos($pieces[0], '=')) {
return false;
}
$data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array(
'cookies' => array(),
'data' => array(),
'path' => $path ?: '/',
'http_only' => false,
'discard' => false,
'domain' => $host
));
$foundNonCookies = 0;
foreach ($pieces as $part) {
$cookieParts = explode('=', $part, 2);
$key = trim($cookieParts[0]);
if (count($cookieParts) == 1) {
$value = true;
} else {
$value = trim($cookieParts[1], " \n\r\t\0\x0B\"");
if ($decode) {
$value = urldecode($value);
}
}
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;
}
}
}
$data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value;
}
if (!$data['expires'] && $data['max_age']) {
$data['expires'] = time() + (int) $data['max_age'];
}
return $data;
}
}
<?php
namespace Guzzle\Parser\Cookie;
interface CookieParserInterface
{
public function parseCookie($cookie, $host = null, $path = null, $decode = false);
}
<?php
namespace Guzzle\Parser\Message;
abstract class AbstractMessageParser implements MessageParserInterface
{
protected function getUrlPartsFromMessage($requestUrl, array $parts)
{
$urlParts = array(
'path' => $requestUrl,
'scheme' => 'http'
);
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';
}
}
$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;
class MessageParser extends AbstractMessageParser
{
public function parseRequest($message)
{
if (!$message) {
return false;
}
$parts = $this->parseMessage($message);
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($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']
);
}
protected function parseMessage($message)
{
$startLine = null;
$headers = array();
$body = '';
$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 (empty($line)) {
if ($i < $totalLines - 1) {
$body = implode('', array_slice($lines, $i + 2));
}
break;
}
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\Message;
interface MessageParserInterface
{
public function parseRequest($message);
public function parseResponse($message);
}
<?php
namespace Guzzle\Parser\Message;
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;
class ParserRegistry
{
protected static $instance;
protected $instances = array();
protected $mapping = array(
'message' => 'Guzzle\\Parser\\Message\\MessageParser',
'cookie' => 'Guzzle\\Parser\\Cookie\\CookieParser',
'url' => 'Guzzle\\Parser\\Url\\UrlParser',
'uri_template' => 'Guzzle\\Parser\\UriTemplate\\UriTemplate',
);
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new static;
}
return self::$instance;
}
public function __construct()
{
if (extension_loaded('uri_template')) {
$this->mapping['uri_template'] = 'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate';
}
}
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];
}
public function registerParser($name, $parser)
{
$this->instances[$name] = $parser;
}
}
<?php
namespace Guzzle\Parser\UriTemplate;
use Guzzle\Common\Exception\RuntimeException;
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;
class UriTemplate implements UriTemplateInterface
{
const DEFAULT_PATTERN = '/\{([^\}]+)\}/';
private $template;
private $variables;
private $regex = self::DEFAULT_PATTERN;
private static $operatorHash = array(
'+' => true, '#' => true, '.' => true, '/' => true, ';' => true, '?' => true, '&' => true
);
private static $delims = array(
':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '='
);
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);
}
public function setRegex($regexPattern)
{
$this->regex = $regexPattern;
}
private function parseExpression($expression)
{
$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
);
}
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) {
$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) {
$actuallyUseQueryString = false;
}
} else {
if ($isAssoc) {
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;
}
private function isAssoc(array $array)
{
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
private function decodeReserved($string)
{
return str_replace(self::$delimsPct, self::$delims, $string);
}
}
<?php
namespace Guzzle\Parser\UriTemplate;
interface UriTemplateInterface
{
public function expand($template, array $variables);
}
<?php
namespace Guzzle\Parser\Url;
use Guzzle\Common\Version;
class UrlParser implements UrlParserInterface
{
protected $utf8 = false;
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);
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;
interface UrlParserInterface
{
public function parseUrl($url);
}
<?php
namespace Guzzle\Plugin\Async;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\CurlException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AsyncPlugin implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
'request.before_send' => 'onBeforeSend',
'request.exception' => 'onRequestTimeout',
'request.sent' => 'onRequestSent',
'curl.callback.progress' => 'onCurlProgress'
);
}
public function onBeforeSend(Event $event)
{
$event['request']->getCurlOptions()->set('progress', true);
}
public function onCurlProgress(Event $event)
{
if ($event['handle'] &&
($event['downloaded'] || (isset($event['uploaded']) && $event['upload_size'] === $event['uploaded']))
) {
curl_setopt($event['handle'], CURLOPT_TIMEOUT_MS, 1);
if ($event['uploaded']) {
curl_setopt($event['handle'], CURLOPT_NOBODY, true);
}
}
}
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'
)));
}
}
public function onRequestSent(Event $event)
{
$event['request']->getResponse()->setHeader('X-Guzzle-Async', 'Did not wait for the response');
}
}
<?php
namespace Guzzle\Plugin\Backoff;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;
abstract class AbstractBackoffStrategy implements BackoffStrategyInterface
{
protected $next;
public function setNext(AbstractBackoffStrategy $next)
{
$this->next = $next;
}
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) {
return false;
} elseif ($delay === null) {
return !$this->next || !$this->next->makesDecision()
? false
: $this->next->getBackoffPeriod($retries, $request, $response, $e);
} elseif ($delay === true) {
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;
}
}
abstract public function makesDecision();
abstract protected function getDelay(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
);
}
<?php
namespace Guzzle\Plugin\Backoff;
abstract class AbstractErrorCodeBackoffStrategy extends AbstractBackoffStrategy
{
protected static $defaultErrorCodes = array();
protected $errorCodes;
public function __construct(array $codes = null, BackoffStrategyInterface $next = null)
{
$this->errorCodes = array_fill_keys($codes ?: static::$defaultErrorCodes, 1);
$this->next = $next;
}
public static function getDefaultFailureCodes()
{
return static::$defaultErrorCodes;
}
public function makesDecision()
{
return true;
}
}
<?php
namespace Guzzle\Plugin\Backoff;
use Guzzle\Common\Event;
use Guzzle\Log\LogAdapterInterface;
use Guzzle\Log\MessageFormatter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BackoffLogger implements EventSubscriberInterface
{
const DEFAULT_FORMAT = '[{ts}] {method} {url} - {code} {phrase} - Retries: {retries}, Delay: {delay}, Time: {connect_time}, {total_time}, cURL: {curl_code} {curl_error}';
protected $logger;
protected $formatter;
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');
}
public function setTemplate($template)
{
$this->formatter->setTemplate($template);
return $this;
}
public function onRequestRetry(Event $event)
{
$this->logger->log($this->formatter->format(
$event['request'],
$event['response'],
$event['handle'],
array(
'retries' => $event['retries'],
'delay' => $event['delay']
)
));
}
}
<?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;
class BackoffPlugin extends AbstractHasDispatcher implements EventSubscriberInterface
{
const DELAY_PARAM = CurlMultiInterface::BLOCKING;
const RETRY_PARAM = 'plugins.backoff.retry_count';
const RETRY_EVENT = 'plugins.backoff.retry';
protected $strategy;
public function __construct(BackoffStrategyInterface $strategy = null)
{
$this->strategy = $strategy;
}
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'
);
}
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) {
$params->set(self::RETRY_PARAM, ++$retries)
->set(self::DELAY_PARAM, microtime(true) + $delay);
$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
));
}
}
public function onRequestPoll(Event $event)
{
$request = $event['request'];
$delay = $request->getParams()->get(self::DELAY_PARAM);
if (null !== $delay && microtime(true) >= $delay) {
$request->getParams()->remove(self::DELAY_PARAM);
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;
interface BackoffStrategyInterface
{
public function getBackoffPeriod(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
);
}
<?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;
class CallbackBackoffStrategy extends AbstractBackoffStrategy
{
protected $callback;
protected $decision;
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;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;
class ConstantBackoffStrategy extends AbstractBackoffStrategy
{
protected $delay;
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;
use Guzzle\Http\Exception\CurlException;
class CurlBackoffStrategy extends AbstractErrorCodeBackoffStrategy
{
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\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;
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;
class HttpBackoffStrategy extends AbstractErrorCodeBackoffStrategy
{
protected static $defaultErrorCodes = array(500, 503);
protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
if ($response) {
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;
class LinearBackoffStrategy extends AbstractBackoffStrategy
{
protected $step;
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;
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;
class TruncatedBackoffStrategy extends AbstractBackoffStrategy
{
protected $max;
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\Cache;
\Guzzle\Common\Version::warn('Guzzle\Plugin\Cache\CacheKeyProviderInterface is no longer used');
interface CacheKeyProviderInterface {}
<?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;
class CachePlugin implements EventSubscriberInterface
{
protected $revalidation;
protected $canCache;
protected $storage;
protected $autoPurge;
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')) {
throw new InvalidArgumentException('No cache was provided and Doctrine is not installed');
}
}
$this->autoPurge = isset($options['auto_purge']) ? $options['auto_purge'] : false;
$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'];
}
$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),
);
}
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')
);
if ($this->canResponseSatisfyRequest($request, $response)) {
if (!isset($params['cache.hit'])) {
$params['cache.hit'] = true;
}
$request->setResponse($response);
}
}
}
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);
}
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();
}
}
}
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();
}
}
public function canResponseSatisfyRequest(RequestInterface $request, Response $response)
{
$responseAge = $response->calculateAge();
$reqc = $request->getHeader('Cache-Control');
$resc = $response->getHeader('Cache-Control');
if ($reqc && $reqc->hasDirective('max-age') &&
$responseAge > $reqc->getDirective('max-age')) {
return false;
}
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;
}
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;
}
public function purge($url)
{
$url = $url instanceof RequestInterface ? $url->getUrl() : $url;
$this->storage->purge($url);
}
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')) {
$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')) {
$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;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
interface CacheStorageInterface
{
public function fetch(RequestInterface $request);
public function cache(RequestInterface $request, Response $response);
public function delete(RequestInterface $request);
public function purge($url);
}
<?php
namespace Guzzle\Plugin\Cache;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
class CallbackCanCacheStrategy extends DefaultCanCacheStrategy
{
protected $requestCallback;
protected $responseCallback;
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\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
interface CanCacheStrategyInterface
{
public function canCacheRequest(RequestInterface $request);
public function canCacheResponse(Response $response);
}
<?php
namespace Guzzle\Plugin\Cache;
use Guzzle\Http\Message\RequestInterface;
\Guzzle\Common\Version::warn('Guzzle\Plugin\Cache\DefaultCacheKeyProvider is no longer used');
class DefaultCacheKeyProvider implements CacheKeyProviderInterface
{
public function getCacheKey(RequestInterface $request)
{
$key = $request->getParams()->get(self::CACHE_KEY);
if (!$key) {
$cloned = clone $request;
$cloned->removeHeader('Cache-Control');
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\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;
class DefaultCacheStorage implements CacheStorageInterface
{
protected $keyPrefix;
protected $cache;
protected $defaultTtl;
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();
$ttl = $request->getParams()->get('cache.override_ttl') ?: $response->getMaxAge() ?: $this->defaultTtl;
if ($cacheControl = $response->getHeader('Cache-Control')) {
$stale = $cacheControl->getDirective('stale-if-error');
$ttl += $stale == true ? $ttl : $stale;
}
$key = $this->getCacheKey($request);
$persistedRequest = $this->persistHeaders($request);
$entries = array();
if ($manifest = $this->cache->fetch($key)) {
$vary = $response->getVary();
foreach (unserialize($manifest) as $entry) {
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;
}
}
}
$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)) {
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;
}
$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 {
$response = -1;
}
}
}
if ($response === -1) {
unset($entries[$index]);
if ($entries) {
$this->cache->save($key, serialize($entries));
} else {
$this->cache->delete($key);
}
return null;
}
return $response;
}
protected function getCacheKey(RequestInterface $request)
{
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);
}
protected function getBodyKey($url, EntityBodyInterface $body)
{
return $this->keyPrefix . md5($url) . $body->getContentMd5();
}
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;
}
private function persistHeaders(MessageInterface $message)
{
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
);
$headers = $message->getHeaders()->getAll();
$headers = array_diff_key($headers, $noCache);
$headers = array_map(function ($h) { return (string) $h; }, $headers);
return $headers;
}
}
<?php
namespace Guzzle\Plugin\Cache;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
class DefaultCanCacheStrategy implements CanCacheStrategyInterface
{
public function canCacheRequest(RequestInterface $request)
{
if ($request->getMethod() != RequestInterface::GET && $request->getMethod() != RequestInterface::HEAD) {
return false;
}
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;
use Guzzle\Http\Exception\BadResponseException;
class DefaultRevalidation implements RevalidationInterface
{
protected $storage;
protected $canCache;
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);
}
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')));
if (!$revalidate && !$resCache && $response->hasHeader('ETag')) {
$revalidate = true;
}
return $revalidate;
}
protected function handleBadResponse(BadResponseException $e)
{
if ($e->getResponse()->getStatusCode() == 404) {
$this->storage->delete($e->getRequest());
throw $e;
}
}
protected function createRevalidationRequest(RequestInterface $request, Response $response)
{
$revalidate = clone $request;
$revalidate->removeHeader('Pragma')
->removeHeader('Cache-Control')
->setHeader('If-Modified-Since', $response->getLastModified() ?: $response->getDate());
if ($response->getEtag()) {
$revalidate->setHeader('If-None-Match', $response->getEtag());
}
$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;
}
protected function handle200Response(RequestInterface $request, Response $validateResponse)
{
$request->setResponse($validateResponse);
if ($this->canCache->canCacheResponse($validateResponse)) {
$this->storage->cache($request, $validateResponse);
}
return false;
}
protected function handle304Response(RequestInterface $request, Response $validateResponse, Response $response)
{
static $replaceHeaders = array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified');
if ($validateResponse->getEtag() != $response->getEtag()) {
return false;
}
$modified = false;
foreach ($replaceHeaders as $name) {
if ($validateResponse->hasHeader($name)) {
$modified = true;
$response->setHeader($name, $validateResponse->getHeader($name));
}
}
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;
class DenyRevalidation extends DefaultRevalidation
{
public function __construct() {}
public function revalidate(RequestInterface $request, Response $response)
{
return false;
}
}
<?php
namespace Guzzle\Plugin\Cache;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
interface RevalidationInterface
{
public function revalidate(RequestInterface $request, Response $response);
public function shouldRevalidate(RequestInterface $request, Response $response);
}
<?php
namespace Guzzle\Plugin\Cache;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
class SkipRevalidation extends DefaultRevalidation
{
public function __construct() {}
public function revalidate(RequestInterface $request, Response $response)
{
return true;
}
}
<?php
namespace Guzzle\Plugin\Cookie;
use Guzzle\Common\ToArrayInterface;
class Cookie implements ToArrayInterface
{
protected $data;
protected static $invalidCharString;
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;
}
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);
if (!$this->getExpires() && $this->getMaxAge()) {
$this->setExpires(time() + (int) $this->getMaxAge());
} elseif ($this->getExpires() && !is_numeric($this->getExpires())) {
$this->setExpires(strtotime($this->getExpires()));
}
}
public function toArray()
{
return $this->data;
}
public function getName()
{
return $this->data['name'];
}
public function setName($name)
{
return $this->setData('name', $name);
}
public function getValue()
{
return $this->data['value'];
}
public function setValue($value)
{
return $this->setData('value', $value);
}
public function getDomain()
{
return $this->data['domain'];
}
public function setDomain($domain)
{
return $this->setData('domain', $domain);
}
public function getPath()
{
return $this->data['path'];
}
public function setPath($path)
{
return $this->setData('path', $path);
}
public function getMaxAge()
{
return $this->data['max_age'];
}
public function setMaxAge($maxAge)
{
return $this->setData('max_age', $maxAge);
}
public function getExpires()
{
return $this->data['expires'];
}
public function setExpires($timestamp)
{
return $this->setData('expires', $timestamp);
}
public function getVersion()
{
return $this->data['version'];
}
public function setVersion($version)
{
return $this->setData('version', $version);
}
public function getSecure()
{
return $this->data['secure'];
}
public function setSecure($secure)
{
return $this->setData('secure', (bool) $secure);
}
public function getDiscard()
{
return $this->data['discard'];
}
public function setDiscard($discard)
{
return $this->setData('discard', $discard);
}
public function getComment()
{
return $this->data['comment'];
}
public function setComment($comment)
{
return $this->setData('comment', $comment);
}
public function getCommentUrl()
{
return $this->data['comment_url'];
}
public function setCommentUrl($commentUrl)
{
return $this->setData('comment_url', $commentUrl);
}
public function getPorts()
{
return $this->data['port'];
}
public function setPorts(array $ports)
{
return $this->setData('port', $ports);
}
public function getHttpOnly()
{
return $this->data['http_only'];
}
public function setHttpOnly($httpOnly)
{
return $this->setData('http_only', $httpOnly);
}
public function getAttributes()
{
return $this->data['data'];
}
public function getAttribute($name)
{
return array_key_exists($name, $this->data['data']) ? $this->data['data'][$name] : null;
}
public function setAttribute($name, $value)
{
$this->data['data'][$name] = $value;
return $this;
}
public function matchesPath($path)
{
return !$this->getPath() || 0 === stripos($path, $this->getPath());
}
public function matchesDomain($domain)
{
$cookieDomain = ltrim($this->getDomain(), '.');
if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
return true;
}
if (filter_var($domain, FILTER_VALIDATE_IP)) {
return false;
}
return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/i', $domain);
}
public function matchesPort($port)
{
return count($this->getPorts()) == 0 || in_array($port, $this->getPorts());
}
public function isExpired()
{
return $this->getExpires() && time() > $this->getExpires();
}
public function validate()
{
$name = $this->getName();
if (empty($name) && !is_numeric($name)) {
return 'The cookie name must not be empty';
}
if (strpbrk($name, self::getInvalidCharacters()) !== false) {
return 'The cookie name must not contain invalid characters: ' . $name;
}
$value = $this->getValue();
if (empty($value) && !is_numeric($value)) {
return 'The cookie value must not be empty';
}
$domain = $this->getDomain();
if (empty($domain) && !is_numeric($domain)) {
return 'The cookie domain must not be empty';
}
return true;
}
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;
class ArrayCookieJar implements CookieJarInterface, \Serializable
{
protected $cookies = array();
protected $strictMode;
public function __construct($strictMode = false)
{
$this->strictMode = $strictMode;
}
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)
{
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new InvalidCookieException($result);
} else {
return false;
}
}
foreach ($this->cookies as $i => $c) {
if ($c->getPath() != $cookie->getPath() ||
$c->getDomain() != $cookie->getDomain() ||
$c->getPorts() != $cookie->getPorts() ||
$c->getName() != $cookie->getName()
) {
continue;
}
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function serialize()
{
return json_encode(array_map(function (Cookie $cookie) {
return $cookie->toArray();
}, $this->all(null, null, null, true, true)));
}
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);
}
}
public function count()
{
return count($this->cookies);
}
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)
) {
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)
{
$cookies = $this->all($request->getHost(), $request->getPath());
foreach ($cookies as $index => $cookie) {
if (!$cookie->matchesPort($request->getPort()) || ($cookie->getSecure() && $request->getScheme() != 'https')) {
unset($cookies[$index]);
}
};
return $cookies;
}
}
<?php
namespace Guzzle\Plugin\Cookie\CookieJar;
use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
public function remove($domain = null, $path = null, $name = null);
public function removeTemporary();
public function removeExpired();
public function add(Cookie $cookie);
public function addCookiesFromResponse(Response $response, RequestInterface $request = null);
public function getMatchingCookies(RequestInterface $request);
public function all($domain = null, $path = null, $name = null, $skipDiscardable = false, $skipExpired = true);
}
<?php
namespace Guzzle\Plugin\Cookie\CookieJar;
use Guzzle\Common\Exception\RuntimeException;
class FileCookieJar extends ArrayCookieJar
{
protected $filename;
public function __construct($cookieFile)
{
$this->filename = $cookieFile;
$this->load();
}
public function __destruct()
{
$this->persist();
}
protected function persist()
{
if (false === file_put_contents($this->filename, $this->serialize())) {
throw new RuntimeException('Unable to open file ' . $this->filename);
}
}
protected function load()
{
$json = file_get_contents($this->filename);
if (false === $json) {
throw new RuntimeException('Unable to open file ' . $this->filename);
}
$this->unserialize($json);
$this->cookies = $this->cookies ?: array();
}
}
<?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;
class CookiePlugin implements EventSubscriberInterface
{
protected $cookieJar;
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)
);
}
public function getCookieJar()
{
return $this->cookieJar;
}
public function onRequestBeforeSend(Event $event)
{
$request = $event['request'];
if (!$request->getParams()->get('cookies.disable')) {
$request->removeHeader('Cookie');
foreach ($this->cookieJar->getMatchingCookies($request) as $cookie) {
$request->addCookie($cookie->getName(), $cookie->getValue());
}
}
}
public function onRequestSent(Event $event)
{
$this->cookieJar->addCookiesFromResponse($event['response'], $event['request']);
}
}
<?php
namespace Guzzle\Plugin\Cookie\Exception;
use Guzzle\Common\Exception\InvalidArgumentException;
class InvalidCookieException extends InvalidArgumentException {}
<?php
namespace Guzzle\Plugin\CurlAuth;
use Guzzle\Common\Event;
use Guzzle\Common\Version;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CurlAuthPlugin implements EventSubscriberInterface
{
private $username;
private $password;
private $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));
}
public function onRequestCreate(Event $event)
{
$event['request']->setAuth($this->username, $this->password, $this->scheme);
}
}
<?php
namespace Guzzle\Plugin\ErrorResponse;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
interface ErrorResponseExceptionInterface
{
public static function fromCommand(CommandInterface $command, Response $response);
}
<?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;
class ErrorResponsePlugin implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array('command.before_send' => array('onCommandBeforeSend', -1));
}
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));
}
}
}
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 (!is_subclass_of($className, $errorClassInterface)) {
throw new ErrorResponseException("{$className} must implement {$errorClassInterface}");
}
throw $className::fromCommand($command, $response);
}
};
}
}
<?php
namespace Guzzle\Plugin\ErrorResponse\Exception;
use Guzzle\Common\Exception\RuntimeException;
class ErrorResponseException extends RuntimeException {}
<?php
namespace Guzzle\Plugin\History;
use Guzzle\Common\Event;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HistoryPlugin implements EventSubscriberInterface, \IteratorAggregate, \Countable
{
protected $limit = 10;
protected $transactions = array();
public static function getSubscribedEvents()
{
return array('request.sent' => array('onRequestSent', 9999));
}
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);
}
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;
}
public function setLimit($limit)
{
$this->limit = (int) $limit;
return $this;
}
public function getLimit()
{
return $this->limit;
}
public function getAll()
{
return $this->transactions;
}
public function getIterator()
{
return new \ArrayIterator(array_map(function ($entry) {
$entry['request']->getParams()->set('actual_response', $entry['response']);
return $entry['request'];
}, $this->transactions));
}
public function count()
{
return count($this->transactions);
}
public function getLastRequest()
{
$last = end($this->transactions);
return $last['request'];
}
public function getLastResponse()
{
$last = end($this->transactions);
return isset($last['response']) ? $last['response'] : null;
}
public function clear()
{
$this->transactions = array();
return $this;
}
public function onRequestSent(Event $event)
{
$this->add($event['request'], $event['response']);
}
}
<?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;
class LogPlugin implements EventSubscriberInterface
{
protected $logAdapter;
protected $formatter;
protected $wireBodies;
public function __construct(
LogAdapterInterface $logAdapter,
$formatter = null,
$wireBodies = false
) {
$this->logAdapter = $logAdapter;
$this->formatter = $formatter instanceof MessageFormatter ? $formatter : new MessageFormatter($formatter);
$this->wireBodies = $wireBodies;
}
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)
);
}
public function onCurlRead(Event $event)
{
if ($wire = $event['request']->getParams()->get('request_wire')) {
$wire->write($event['read']);
}
}
public function onCurlWrite(Event $event)
{
if ($wire = $event['request']->getParams()->get('response_wire')) {
$wire->write($event['write']);
}
}
public function onRequestBeforeSend(Event $event)
{
if ($this->wireBodies) {
$request = $event['request'];
$request->getCurlOptions()->set('emit_io', true);
if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
&& (!$request->getBody()->isSeekable() || !$request->getBody()->isReadable())
) {
$request->getParams()->set('request_wire', EntityBody::factory());
}
if (!$request->getResponseBody()->isRepeatable()) {
$request->getParams()->set('response_wire', EntityBody::factory());
}
}
}
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);
}
$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
));
}
}
<?php
namespace Guzzle\Plugin\Md5;
use Guzzle\Common\Event;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CommandContentMd5Plugin implements EventSubscriberInterface
{
protected $contentMd5Param;
protected $validateMd5Param;
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();
if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
&& $command->getOperation()->hasParam($this->contentMd5Param)) {
if ($command[$this->contentMd5Param] === true) {
if (false !== ($md5 = $request->getBody()->getContentMd5(true, true))) {
$request->setHeader('Content-MD5', $md5);
}
}
}
if ($command[$this->validateMd5Param] === true) {
$request->addSubscriber(new Md5ValidatorPlugin(true, false));
}
}
}
<?php
namespace Guzzle\Plugin\Md5;
use Guzzle\Common\Event;
use Guzzle\Common\Exception\UnexpectedValueException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class Md5ValidatorPlugin implements EventSubscriberInterface
{
protected $contentLengthCutoff;
protected $contentEncoded;
public function __construct($contentEncoded = true, $contentLengthCutoff = false)
{
$this->contentLengthCutoff = $contentLengthCutoff;
$this->contentEncoded = $contentEncoded;
}
public static function getSubscribedEvents()
{
return array('request.complete' => array('onRequestComplete', 255));
}
public function onRequestComplete(Event $event)
{
$response = $event['response'];
if (!$contentMd5 = $response->getContentMd5()) {
return;
}
$contentEncoding = $response->getContentEncoding();
if ($contentEncoding && !$this->contentEncoded) {
return false;
}
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\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;
class MockPlugin extends AbstractHasDispatcher implements EventSubscriberInterface, \Countable
{
protected $queue = array();
protected $temporary = false;
protected $received = array();
protected $readBodies;
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()
{
return array('request.before_send' => array('onRequestBeforeSend', -999));
}
public static function getAllEvents()
{
return array('mock.request');
}
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));
}
public function readBodies($readBodies)
{
$this->readBodies = $readBodies;
return $this;
}
public function count()
{
return count($this->queue);
}
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;
}
public function addException(CurlException $e)
{
$this->queue[] = $e;
return $this;
}
public function clearQueue()
{
$this->queue = array();
return $this;
}
public function getQueue()
{
return $this->queue;
}
public function isTemporary()
{
return $this->temporary;
}
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));
$event['request']->getEventDispatcher()->removeListener('request.sent', $f);
});
}
$request->setResponse($item);
} elseif ($item instanceof CurlException) {
$item->setRequest($request);
$state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $item));
if ($state == RequestInterface::STATE_ERROR) {
throw $item;
}
}
return $this;
}
public function flush()
{
$this->received = array();
}
public function getReceivedRequests()
{
return $this->received;
}
public function onRequestBeforeSend(Event $event)
{
if ($this->queue) {
$request = $event['request'];
$this->received[] = $request;
if ($this->temporary && count($this->queue) == 1 && $request->getClient()) {
$request->getClient()->getEventDispatcher()->removeSubscriber($this);
}
$this->dequeue($request);
}
}
}
<?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;
class OauthPlugin implements EventSubscriberInterface
{
const REQUEST_METHOD_HEADER = 'header';
const REQUEST_METHOD_QUERY = 'query';
protected $config;
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)
);
}
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;
}
private function buildAuthorizationHeader($authorizationParams)
{
$authorizationString = 'OAuth ';
foreach ($authorizationParams as $key => $val) {
if ($val) {
$authorizationString .= $key . '="' . urlencode($val) . '", ';
}
}
return substr($authorizationString, 0, -2);
}
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));
}
public function getStringToSign(RequestInterface $request, $timestamp, $nonce)
{
$params = $this->getParamsToSign($request, $timestamp, $nonce);
$params = $this->prepareParameters($params);
$parameterString = new QueryString($params);
$url = Url::factory($request->getUrl())->setQuery('')->setFragment(null);
return strtoupper($request->getMethod()) . '&'
. rawurlencode($url) . '&'
. rawurlencode((string) $parameterString);
}
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,
));
$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;
}
public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
{
$params = $this->getOauthParams($timestamp, $nonce);
$params->merge($request->getQuery());
if ($this->shouldPostFieldsBeSigned($request))
{
$params->merge($request->getPostFields());
}
$params = $params->toArray();
ksort($params);
return $params;
}
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;
}
public function generateNonce(RequestInterface $request)
{
return sha1(uniqid('', true) . $request->getUrl());
}
public function getTimestamp(Event $event)
{
return $event['timestamp'] ?: time();
}
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;
}
}
<?php
namespace Guzzle\Service;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
abstract class AbstractConfigLoader implements ConfigLoaderInterface
{
protected $aliases = array();
protected $loadedFiles = array();
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())
{
$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);
}
public function addAlias($filename, $alias)
{
$this->aliases[$filename] = $alias;
return $this;
}
public function removeAlias($alias)
{
unset($this->aliases[$alias]);
return $this;
}
protected abstract function build($config, array $options);
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);
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);
}
$this->loadedFiles[$filename] = true;
$this->mergeIncludes($config, dirname($filename));
return $config;
}
protected function mergeIncludes(&$config, $basePath = null)
{
if (!empty($config['includes'])) {
foreach ($config['includes'] as &$path) {
if ($path[0] != DIRECTORY_SEPARATOR && !isset($this->aliases[$path]) && $basePath) {
$path = "{$basePath}/{$path}";
}
if (!isset($this->loadedFiles[$path])) {
$this->loadedFiles[$path] = true;
$config = $this->mergeData($this->loadFile($path), $config);
}
}
}
}
protected function mergeData(array $a, array $b)
{
return array_merge_recursive($a, $b);
}
}
<?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;
class ServiceBuilder extends AbstractHasDispatcher implements ServiceBuilderInterface, \ArrayAccess, \Serializable
{
protected $builderConfig = array();
protected $clients = array();
protected static $cachedFactory;
protected $plugins = array();
public static function factory($config = null, array $globalParameters = array())
{
if (!static::$cachedFactory) {
static::$cachedFactory = new ServiceBuilderLoader();
}
return self::$cachedFactory->load($config, $globalParameters);
}
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);
}
public function addGlobalPlugin(EventSubscriberInterface $plugin)
{
$this->plugins[] = $plugin;
return $this;
}
public function getData($name)
{
return isset($this->builderConfig[$name]) ? $this->builderConfig[$name] : null;
}
public function get($name, $throwAway = false)
{
if (!isset($this->builderConfig[$name])) {
if (isset($this->clients[$name])) {
return $this->clients[$name];
}
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];
foreach ($builder['params'] as &$v) {
if (is_string($v) && substr($v, 0, 1) == '{' && substr($v, -1) == '}') {
$v = $this->get(trim($v, '{} '));
}
}
$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);
}
$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\Builder;
use Guzzle\Service\Exception\ServiceNotFoundException;
interface ServiceBuilderInterface
{
public function get($name, $throwAway = false);
public function set($key, $service);
}
<?php
namespace Guzzle\Service\Builder;
use Guzzle\Service\AbstractConfigLoader;
use Guzzle\Service\Exception\ServiceNotFoundException;
class ServiceBuilderLoader extends AbstractConfigLoader
{
protected function build($config, array $options)
{
$class = !empty($config['class']) ? $config['class'] : __NAMESPACE__ . '\\ServiceBuilder';
$services = isset($config['services']) ? $config['services'] : $config;
foreach ($services as $name => &$service) {
$service['params'] = isset($service['params']) ? $service['params'] : array();
if (!empty($service['extends'])) {
if (!isset($services[$service['extends']])) {
throw new ServiceNotFoundException(
"{$name} is trying to extend a non-existent service: {$service['extends']}"
);
}
$extended = &$services[$service['extends']];
if (empty($service['class'])) {
$service['class'] = isset($extended['class']) ? $extended['class'] : '';
}
if ($extendsParams = isset($extended['params']) ? $extended['params'] : false) {
$service['params'] = $service['params'] + $extendsParams;
}
}
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;
if (isset($a['services']) && $b['services']) {
$result['services'] = $b['services'] + $a['services'];
foreach ($result['services'] as $name => &$service) {
if (isset($a['services'][$name]['extends'])
&& isset($b['services'][$name]['extends'])
&& $b['services'][$name]['extends'] == $name
) {
$service += $a['services'][$name];
$service['extends'] = $a['services'][$name]['extends'];
if (isset($a['services'][$name]['params'])) {
$service['params'] += $a['services'][$name]['params'];
}
}
}
}
return $result;
}
}
<?php
namespace Guzzle\Service;
use Guzzle\Cache\CacheAdapterInterface;
class CachingConfigLoader implements ConfigLoaderInterface
{
protected $loader;
protected $cache;
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;
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;
class Client extends HttpClient implements ClientInterface
{
const COMMAND_PARAMS = 'command.params';
protected $serviceDescription;
protected $commandFactory;
protected $resourceIteratorFactory;
protected $inflector;
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'
));
}
public function __call($method, $args)
{
return $this->getCommand($method, isset($args[0]) ? $args[0] : array())->getResult();
}
public function getCommand($name, array $args = array())
{
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;
}
public function setCommandFactory(CommandFactoryInterface $factory)
{
$this->commandFactory = $factory;
return $this;
}
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 ($baseUrl = $service->getBaseUrl()) {
$this->setBaseUrl($baseUrl);
}
return $this;
}
public function getDescription()
{
return $this->serviceDescription;
}
public function setInflector(InflectorInterface $inflector)
{
$this->inflector = $inflector;
return $this;
}
public function getInflector()
{
if (!$this->inflector) {
$this->inflector = Inflector::getDefault();
}
return $this->inflector;
}
protected function prepareCommand(CommandInterface $command)
{
$request = $command->setClient($this)->prepare();
$request->setState(RequestInterface::STATE_NEW);
$this->dispatch('command.before_send', array('command' => $command));
return $request;
}
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) {
$e = CommandTransferException::fromMultiTransferException($failureException);
foreach ($failureException->getFailedRequests() as $request) {
if (isset($commandRequests[$request])) {
$e->addFailedCommand($commandRequests[$request]);
unset($commandRequests[$request]);
}
}
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) {
$clientClass = get_class($this);
$prefix = substr($clientClass, 0, strrpos($clientClass, '\\'));
$this->resourceIteratorFactory = new ResourceIteratorClassFactory(array(
"{$prefix}\\Iterator",
"{$prefix}\\Model"
));
}
return $this->resourceIteratorFactory;
}
protected function getCommandFactory()
{
if (!$this->commandFactory) {
$this->commandFactory = CompositeFactory::getDefaultChain($this);
}
return $this->commandFactory;
}
public function enableMagicMethods($isEnabled)
{
Version::warn(__METHOD__ . ' is deprecated');
}
}
<?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;
interface ClientInterface extends HttpClientInterface, FromConfigInterface
{
public function getCommand($name, array $args = array());
public function execute($command);
public function setDescription(ServiceDescriptionInterface $service);
public function getDescription();
public function getIterator($command, array $commandOptions = null, array $iteratorOptions = array());
}
<?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;
abstract class AbstractCommand extends Collection implements CommandInterface
{
const HEADERS_OPTION = 'command.headers';
const ON_COMPLETE = 'command.on_complete';
const RESPONSE_BODY = 'command.response_body';
const REQUEST_OPTIONS = 'command.request_options';
const HIDDEN_PARAMS = 'command.hidden_params';
const DISABLE_VALIDATION = 'command.disable_validation';
const RESPONSE_PROCESSING = 'command.response_processing';
const TYPE_RAW = 'raw';
const TYPE_MODEL = 'model';
const TYPE_NO_TRANSLATION = 'no_translation';
protected $client;
protected $request;
protected $result;
protected $operation;
protected $onComplete;
protected $validator;
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 ($currentValue !== $configValue) {
$this[$name] = $configValue;
}
}
$headers = $this[self::HEADERS_OPTION];
if (!$headers instanceof Collection) {
$this[self::HEADERS_OPTION] = new Collection((array) $headers);
}
if ($onComplete = $this['command.on_complete']) {
unset($this['command.on_complete']);
$this->setOnComplete($onComplete);
}
if (!$this[self::HIDDEN_PARAMS]) {
$this[self::HIDDEN_PARAMS] = array(
self::HEADERS_OPTION,
self::RESPONSE_PROCESSING,
self::HIDDEN_PARAMS,
self::REQUEST_OPTIONS
);
}
$this->init();
}
public function __clone()
{
$this->request = null;
$this->result = null;
}
public function __invoke()
{
return $this->execute();
}
public function getName()
{
return $this->operation->getName();
}
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();
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 (!isset($this[self::RESPONSE_PROCESSING])) {
$this[self::RESPONSE_PROCESSING] = self::TYPE_MODEL;
}
$this->client->dispatch('command.before_prepare', array('command' => $this));
$this->validate();
$this->build();
if ($headers = $this[self::HEADERS_OPTION]) {
foreach ($headers as $key => $value) {
$this->request->setHeader($key, $value);
}
}
if ($options = $this[Client::CURL_OPTIONS]) {
$this->request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($options));
}
if ($responseBody = $this[self::RESPONSE_BODY]) {
$this->request->setResponseBody($responseBody);
}
$this->client->dispatch('command.after_prepare', array('command' => $this));
}
return $this->request;
}
public function setValidator(ValidatorInterface $validator)
{
$this->validator = $validator;
return $this;
}
public function getRequestHeaders()
{
return $this[self::HEADERS_OPTION];
}
protected function init() {}
abstract protected function build();
protected function createOperation()
{
return new Operation(array('name' => get_class($this)));
}
protected function process()
{
$this->result = $this[self::RESPONSE_PROCESSING] != self::TYPE_RAW
? DefaultResponseParser::getInstance()->parse($this)
: $this->request->getResponse();
}
protected function validate()
{
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]) {
$this->data[$name] = $value;
}
}
$hidden = $this[self::HIDDEN_PARAMS];
if ($properties = $this->operation->getAdditionalParameters()) {
foreach ($this->toArray() as $name => $value) {
if (!$this->operation->hasParam($name) && !in_array($name, $hidden)) {
$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;
}
}
protected function getValidator()
{
if (!$this->validator) {
$this->validator = SchemaValidator::getInstance();
}
return $this->validator;
}
public function getValidationErrors()
{
if (!$this->validator) {
return false;
}
return $this->validator->getErrors();
}
}
<?php
namespace Guzzle\Service\Command;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\UnexpectedValueException;
use Guzzle\Http\Message\RequestInterface;
class ClosureCommand extends AbstractCommand
{
protected function init()
{
if (!$this['closure']) {
throw new InvalidArgumentException('A closure must be passed in the parameters array');
}
}
protected function build()
{
$closure = $this['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;
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;
interface CommandInterface extends \ArrayAccess, ToArrayInterface
{
public function getName();
public function getOperation();
public function execute();
public function getClient();
public function setClient(ClientInterface $client);
public function getRequest();
public function getResponse();
public function getResult();
public function setResult($result);
public function isPrepared();
public function isExecuted();
public function prepare();
public function getRequestHeaders();
public function setOnComplete($callable);
}
<?php
namespace Guzzle\Service\Command;
use Guzzle\Common\Event;
class CreateResponseClassEvent extends Event
{
public function setResult($result)
{
$this['result'] = $result;
$this->stopPropagation();
}
public function getResult()
{
return $this['result'];
}
}
<?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;
class DefaultRequestSerializer implements RequestSerializerInterface
{
protected $factory;
protected static $instance;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self(VisitorFlyweight::getInstance());
}
return self::$instance;
}
public function __construct(VisitorFlyweight $factory)
{
$this->factory = $factory;
}
public function addVisitor($location, RequestVisitorInterface $visitor)
{
$this->factory->addRequestVisitor($location, $visitor);
return $this;
}
public function prepare(CommandInterface $command)
{
$request = $this->createRequest($command);
$foundVisitors = array();
$operation = $command->getOperation();
foreach ($operation->getParams() as $name => $arg) {
$location = $arg->getLocation();
if ($location && $location != 'uri') {
if (!isset($foundVisitors[$location])) {
$foundVisitors[$location] = $this->factory->getRequestVisitor($location);
}
$value = $command[$name];
if ($value !== null) {
$foundVisitors[$location]->visit($command, $request, $arg, $value);
}
}
}
if ($additional = $operation->getAdditionalParameters()) {
if ($visitor = $this->prepareAdditionalParameters($operation, $command, $request, $additional)) {
$foundVisitors[$additional->getLocation()] = $visitor;
}
}
foreach ($foundVisitors as $visitor) {
$visitor->after($command, $request);
}
return $request;
}
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) {
if ($value !== null
&& !in_array($key, $hidden)
&& !$operation->hasParam($key)
) {
$additional->setName($key);
$visitor->visit($command, $request, $additional, $value);
}
}
return $visitor;
}
protected function createRequest(CommandInterface $command)
{
$operation = $command->getOperation();
$client = $command->getClient();
$options = $command[AbstractCommand::REQUEST_OPTIONS] ?: array();
if (!($uri = $operation->getUri())) {
return $client->createRequest($operation->getHttpMethod(), $client->getBaseUrl(), null, null, $options);
}
$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;
class DefaultResponseParser implements ResponseParserInterface
{
protected static $instance;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
public function parse(CommandInterface $command)
{
$response = $command->getRequest()->getResponse();
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\Factory;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\ClientInterface;
class AliasFactory implements FactoryInterface
{
protected $aliases;
protected $client;
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;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\ClientInterface;
class CompositeFactory implements \IteratorAggregate, \Countable, FactoryInterface
{
protected $factories;
public static function getDefaultChain(ClientInterface $client)
{
$factories = array();
if ($description = $client->getDescription()) {
$factories[] = new ServiceDescriptionFactory($description);
}
$factories[] = new ConcreteClassFactory($client);
return new self($factories);
}
public function __construct(array $factories = array())
{
$this->factories = $factories;
}
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;
}
public function has($factory)
{
return (bool) $this->find($factory);
}
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;
}
public function find($factory)
{
foreach ($this->factories as $f) {
if ($factory === $f || (is_string($factory) && $f instanceof $factory)) {
return $f;
}
}
}
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\Inflection\InflectorInterface;
use Guzzle\Inflection\Inflector;
use Guzzle\Service\ClientInterface;
class ConcreteClassFactory implements FactoryInterface
{
protected $client;
protected $inflector;
public function __construct(ClientInterface $client, InflectorInterface $inflector = null)
{
$this->client = $client;
$this->inflector = $inflector ?: Inflector::getDefault();
}
public function factory($name, array $args = array())
{
$prefix = $this->client->getConfig('command.prefix');
if (!$prefix) {
$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))));
if (class_exists($class)) {
return new $class($args);
}
}
}
<?php
namespace Guzzle\Service\Command\Factory;
use Guzzle\Service\Command\CommandInterface;
interface FactoryInterface
{
public function factory($name, array $args = array());
}
<?php
namespace Guzzle\Service\Command\Factory;
class MapFactory implements FactoryInterface
{
protected $map;
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\Factory;
use Guzzle\Service\Description\ServiceDescriptionInterface;
use Guzzle\Inflection\InflectorInterface;
class ServiceDescriptionFactory implements FactoryInterface
{
protected $description;
protected $inflector;
public function __construct(ServiceDescriptionInterface $description, InflectorInterface $inflector = null)
{
$this->setServiceDescription($description);
$this->inflector = $inflector;
}
public function setServiceDescription(ServiceDescriptionInterface $description)
{
$this->description = $description;
return $this;
}
public function getServiceDescription()
{
return $this->description;
}
public function factory($name, array $args = array())
{
$command = $this->description->getOperation($name);
if (!$command) {
$command = $this->description->getOperation(ucfirst($name));
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\LocationVisitor\Request;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Description\Parameter;
abstract class AbstractRequestVisitor implements RequestVisitorInterface
{
public function after(CommandInterface $command, RequestInterface $request) {}
public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) {}
protected function prepareValue($value, Parameter $param)
{
return is_array($value)
? $this->resolveRecursively($value, $param)
: $param->filter($value);
}
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\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;
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'));
if ($encoding = $entityBody->getContentEncoding()) {
$request->setHeader('Content-Encoding', $encoding);
}
}
protected function addExpectHeader(EntityEnclosingRequestInterface $request, EntityBodyInterface $body, $expect)
{
if ($expect === false) {
$request->removeHeader('Expect');
} elseif ($expect !== true) {
$expect = $expect ?: 1048576;
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\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;
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);
}
}
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\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;
class JsonVisitor extends AbstractRequestVisitor
{
protected $jsonContentType = 'application/json';
protected $data;
public function __construct()
{
$this->data = new \SplObjectStorage();
}
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])) {
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\Request;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;
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\Http\Message\RequestInterface;
use Guzzle\Http\Message\PostFileInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;
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;
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\Http\Message\RequestInterface;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;
interface RequestVisitorInterface
{
public function after(CommandInterface $command, RequestInterface $request);
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\Parameter;
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\Operation;
use Guzzle\Service\Description\Parameter;
class XmlVisitor extends AbstractRequestVisitor
{
protected $data;
protected $contentType = 'application/xml';
public function __construct()
{
$this->data = new \SplObjectStorage();
}
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 (isset($this->data[$command])) {
$xml = $this->finishDocument($this->data[$command]);
unset($this->data[$command]);
} else {
$operation = $command->getOperation();
if ($operation->getData('xmlAllowEmpty')) {
$xmlWriter = $this->createRootElement($operation);
$xml = $this->finishDocument($xmlWriter);
}
}
if ($xml) {
if ($this->contentType && !$request->hasHeader('Content-Type')) {
$request->setHeader('Content-Type', $this->contentType);
}
$request->setBody($xml);
}
}
protected function createRootElement(Operation $operation)
{
static $defaultRoot = array('name' => 'Request');
$root = $operation->getData('xmlRoot') ?: $defaultRoot;
$encoding = $operation->getData('xmlEncoding');
$xmlWriter = $this->startDocument($encoding);
$xmlWriter->startElement($root['name']);
if (!empty($root['namespaces'])) {
foreach ((array) $root['namespaces'] as $prefix => $uri) {
$nsLabel = 'xmlns';
if (!is_numeric($prefix)) {
$nsLabel .= ':'.$prefix;
}
$xmlWriter->writeAttribute($nsLabel, $uri);
}
}
return $xmlWriter;
}
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);
}
}
protected function writeAttribute($xmlWriter, $prefix, $name, $namespace, $value)
{
if (empty($namespace)) {
$xmlWriter->writeAttribute($name, $value);
} else {
$xmlWriter->writeAttributeNS($prefix, $name, $namespace, $value);
}
}
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();
}
protected function startDocument($encoding)
{
$xmlWriter = new \XMLWriter();
$xmlWriter->openMemory();
$xmlWriter->startDocument('1.0', $encoding);
return $xmlWriter;
}
protected function finishDocument($xmlWriter)
{
$xmlWriter->endDocument();
return $xmlWriter->outputMemory();
}
protected function addXmlArray(\XMLWriter $xmlWriter, Parameter $param, &$value)
{
if ($items = $param->getItems()) {
foreach ($value as $v) {
$this->addXml($xmlWriter, $items, $v);
}
}
}
protected function addXmlObject(\XMLWriter $xmlWriter, Parameter $param, &$value)
{
$noAttributes = array();
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);
}
}
}
foreach ($noAttributes as $element) {
$this->addXml($xmlWriter, $element['property'], $element['value']);
}
}
}
<?php
namespace Guzzle\Service\Command\LocationVisitor\Response;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
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\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
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;
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()));
}
}
protected function processPrefixedHeaders(Response $response, Parameter $param, &$value)
{
if ($prefix = $param->getSentAs()) {
$container = $param->getName();
$len = strlen($prefix);
foreach ($response->getHeaders()->toArray() as $key => $header) {
if (stripos($key, $prefix) === 0) {
$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;
class JsonVisitor extends AbstractResponseVisitor
{
public function before(CommandInterface $command, array &$result)
{
$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]);
}
}
}
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])) {
$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]);
}
}
}
}
if ($param->getAdditionalProperties() === false) {
$value = array_intersect_key($value, $knownProperties);
} elseif (($additional = $param->getAdditionalProperties()) !== true) {
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;
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;
interface 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;
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\Response;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;
class XmlVisitor extends AbstractResponseVisitor
{
public function before(CommandInterface $command, array &$result)
{
$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]);
}
}
}
protected function recursiveProcess(Parameter $param, &$value)
{
$type = $param->getType();
if (!is_array($value)) {
if ($type == 'array') {
$this->recursiveProcess($param->getItems(), $value);
$value = array($value);
}
} elseif ($type == 'object') {
$this->processObject($param, $value);
} elseif ($type == 'array') {
$this->processArray($param, $value);
}
if ($value !== null) {
$value = $param->filter($value);
}
}
protected function processArray(Parameter $param, &$value)
{
if (!isset($value[0])) {
if ($param->getItems() && isset($value[$param->getItems()->getWireName()])) {
$value = $value[$param->getItems()->getWireName()];
if (!isset($value[0]) || !is_array($value)) {
$value = array($value);
}
} elseif (!empty($value)) {
$value = array($value);
}
}
foreach ($value as &$item) {
$this->recursiveProcess($param->getItems(), $item);
}
}
protected function processObject(Parameter $param, &$value)
{
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]);
}
}
}
if ($param->getAdditionalProperties() === false) {
$value = array_intersect_key($value, $knownProperties);
}
}
}
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;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\LocationVisitor\Request\RequestVisitorInterface;
use Guzzle\Service\Command\LocationVisitor\Response\ResponseVisitorInterface;
class VisitorFlyweight
{
protected static $instance;
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'
);
protected $mappings;
protected $cache = array();
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct(array $mappings = null)
{
$this->mappings = $mappings === null ? self::$defaultMappings : $mappings;
}
public function getRequestVisitor($visitor)
{
return $this->getKey('request.' . $visitor);
}
public function getResponseVisitor($visitor)
{
return $this->getKey('response.' . $visitor);
}
public function addRequestVisitor($name, RequestVisitorInterface $visitor)
{
$this->cache['request.' . $name] = $visitor;
return $this;
}
public function addResponseVisitor($name, ResponseVisitorInterface $visitor)
{
$this->cache['response.' . $name] = $visitor;
return $this;
}
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;
class OperationCommand extends AbstractCommand
{
protected $requestSerializer;
protected $responseParser;
public function setResponseParser(ResponseParserInterface $parser)
{
$this->responseParser = $parser;
return $this;
}
public function setRequestSerializer(RequestSerializerInterface $serializer)
{
$this->requestSerializer = $serializer;
return $this;
}
public function getRequestSerializer()
{
if (!$this->requestSerializer) {
$this->requestSerializer = DefaultRequestSerializer::getInstance();
}
return $this->requestSerializer;
}
public function getResponseParser()
{
if (!$this->responseParser) {
$this->responseParser = OperationResponseParser::getInstance();
}
return $this->responseParser;
}
protected function build()
{
$this->request = $this->getRequestSerializer()->prepare($this);
}
protected function process()
{
$this->result = $this[self::RESPONSE_PROCESSING] == self::TYPE_RAW
? $this->request->getResponse()
: $this->getResponseParser()->parse($this);
}
}
<?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;
class OperationResponseParser extends DefaultResponseParser
{
protected $factory;
protected static $instance;
private $schemaInModels;
public static function getInstance()
{
if (!static::$instance) {
static::$instance = new static(VisitorFlyweight::getInstance());
}
return static::$instance;
}
public function __construct(VisitorFlyweight $factory, $schemaInModels = false)
{
$this->factory = $factory;
$this->schemaInModels = $schemaInModels;
}
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 parent::handleParsing($command, $response, $contentType);
} elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) {
return new Model(parent::handleParsing($command, $response, $contentType));
} else {
return new Model($this->visitResult($model, $command, $response), $this->schemaInModels ? $model : null);
}
}
protected function parseClass(CommandInterface $command)
{
$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);
}
protected function visitResult(Parameter $model, CommandInterface $command, Response $response)
{
$foundVisitors = $result = $knownProps = array();
$props = $model->getProperties();
foreach ($props as $schema) {
if ($location = $schema->getLocation()) {
if (!isset($foundVisitors[$location])) {
$foundVisitors[$location] = $this->factory->getResponseVisitor($location);
$foundVisitors[$location]->before($command, $result);
}
}
}
if (($additional = $model->getAdditionalProperties()) instanceof Parameter) {
$this->visitAdditionalProperties($model, $command, $response, $additional, $result, $foundVisitors);
}
foreach ($props as $schema) {
$knownProps[$schema->getName()] = 1;
if ($location = $schema->getLocation()) {
$foundVisitors[$location]->visit($command, $response, $schema, $result);
}
}
if ($additional === false) {
$result = array_intersect_key($result, $knownProps);
}
foreach ($foundVisitors as $visitor) {
$visitor->after($command);
}
return $result;
}
protected function visitAdditionalProperties(
Parameter $model,
CommandInterface $command,
Response $response,
Parameter $additional,
&$result,
array &$foundVisitors
) {
if ($location = $additional->getLocation()) {
if (!isset($foundVisitors[$location])) {
$foundVisitors[$location] = $this->factory->getResponseVisitor($location);
$foundVisitors[$location]->before($command, $result);
}
if (is_array($result)) {
foreach (array_keys($result) as $key) {
if (!$model->getProperty($key)) {
$additional->setName($key);
$foundVisitors[$location]->visit($command, $response, $additional, $result);
}
}
$additional->setName(null);
}
}
}
}
<?php
namespace Guzzle\Service\Command;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
interface RequestSerializerInterface
{
public function prepare(CommandInterface $command);
}
<?php
namespace Guzzle\Service\Command;
interface ResponseClassInterface
{
public static function fromCommand(OperationCommand $command);
}
<?php
namespace Guzzle\Service\Command;
interface ResponseParserInterface
{
public function parse(CommandInterface $command);
}
<?php
namespace Guzzle\Service;
interface ConfigLoaderInterface
{
public function load($config, array $options = array());
}
<?php
namespace Guzzle\Service\Description;
use Guzzle\Common\Exception\InvalidArgumentException;
class Operation implements OperationInterface
{
const DEFAULT_COMMAND_CLASS = 'Guzzle\\Service\\Command\\OperationCommand';
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
);
protected $parameters = array();
protected $additionalParameters;
protected $name;
protected $httpMethod;
protected $summary;
protected $notes;
protected $documentationUrl;
protected $uri;
protected $class;
protected $responseClass;
protected $responseType;
protected $responseNotes;
protected $deprecated;
protected $errorResponses;
protected $description;
protected $data;
public function __construct(array $config = array(), ServiceDescriptionInterface $description = null)
{
$this->description = $description;
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) {
$this->setResponseType($this->responseType);
} else {
$this->inferResponseType();
}
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();
foreach (array_keys(self::$properties) as $check) {
if ($value = $this->{$check}) {
$result[$check] = $value;
}
}
unset($result['name']);
$result['parameters'] = array();
foreach ($this->parameters as $key => $param) {
$result['parameters'][$key] = $param->toArray();
}
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;
}
public function addParam(Parameter $param)
{
$this->parameters[$param->getName()] = $param;
$param->setParent($this);
return $this;
}
public function removeParam($name)
{
unset($this->parameters[$name]);
return $this;
}
public function getHttpMethod()
{
return $this->httpMethod;
}
public function setHttpMethod($httpMethod)
{
$this->httpMethod = $httpMethod;
return $this;
}
public function getClass()
{
return $this->class;
}
public function setClass($className)
{
$this->class = $className;
return $this;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getSummary()
{
return $this->summary;
}
public function setSummary($summary)
{
$this->summary = $summary;
return $this;
}
public function getNotes()
{
return $this->notes;
}
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
public function getDocumentationUrl()
{
return $this->documentationUrl;
}
public function setDocumentationUrl($docUrl)
{
$this->documentationUrl = $docUrl;
return $this;
}
public function getResponseClass()
{
return $this->responseClass;
}
public function setResponseClass($responseClass)
{
$this->responseClass = $responseClass;
$this->inferResponseType();
return $this;
}
public function getResponseType()
{
return $this->responseType;
}
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;
}
public function setResponseNotes($notes)
{
$this->responseNotes = $notes;
return $this;
}
public function getDeprecated()
{
return $this->deprecated;
}
public function setDeprecated($isDeprecated)
{
$this->deprecated = $isDeprecated;
return $this;
}
public function getUri()
{
return $this->uri;
}
public function setUri($uri)
{
$this->uri = $uri;
return $this;
}
public function getErrorResponses()
{
return $this->errorResponses;
}
public function addErrorResponse($code, $reason, $class)
{
$this->errorResponses[] = array('code' => $code, 'reason' => $reason, 'class' => $class);
return $this;
}
public function setErrorResponses(array $errorResponses)
{
$this->errorResponses = $errorResponses;
return $this;
}
public function getData($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
public function setData($name, $value)
{
$this->data[$name] = $value;
return $this;
}
public function getAdditionalParameters()
{
return $this->additionalParameters;
}
public function setAdditionalParameters($parameter)
{
if ($this->additionalParameters = $parameter) {
$this->additionalParameters->setParent($this);
}
return $this;
}
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\ToArrayInterface;
interface OperationInterface extends ToArrayInterface
{
const TYPE_PRIMITIVE = 'primitive';
const TYPE_CLASS = 'class';
const TYPE_DOCUMENTATION = 'documentation';
const TYPE_MODEL = 'model';
public function getServiceDescription();
public function setServiceDescription(ServiceDescriptionInterface $description);
public function getParams();
public function getParamNames();
public function hasParam($name);
public function getParam($param);
public function getHttpMethod();
public function getClass();
public function getName();
public function getSummary();
public function getNotes();
public function getDocumentationUrl();
public function getResponseClass();
public function getResponseType();
public function getResponseNotes();
public function getDeprecated();
public function getUri();
public function getErrorResponses();
public function getData($name);
}
<?php
namespace Guzzle\Service\Description;
use Guzzle\Common\Exception\InvalidArgumentException;
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;
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 ($extends = $description->getModel($data['extends'])) {
$data += $extends->toArray();
}
}
}
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;
}
}
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();
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;
}
public function getValue($value)
{
if ($this->static || ($this->default !== null && $value === null)) {
return $this->default;
}
return $value;
}
public function filter($value)
{
if ($this->format) {
return SchemaFormatter::format($this->format, $value);
}
if ($this->type == 'boolean' && !is_bool($value)) {
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
if ($this->filters) {
foreach ($this->filters as $filter) {
if (is_array($filter)) {
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;
}
public function getName()
{
return $this->name;
}
public function getWireName()
{
return $this->sentAs ?: $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
public function getRequired()
{
return $this->required;
}
public function setRequired($isRequired)
{
$this->required = (bool) $isRequired;
return $this;
}
public function getDefault()
{
return $this->default;
}
public function setDefault($default)
{
$this->default = $default;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
public function getMinimum()
{
return $this->minimum;
}
public function setMinimum($min)
{
$this->minimum = $min;
return $this;
}
public function getMaximum()
{
return $this->maximum;
}
public function setMaximum($max)
{
$this->maximum = $max;
return $this;
}
public function getMinLength()
{
return $this->minLength;
}
public function setMinLength($min)
{
$this->minLength = $min;
return $this;
}
public function getMaxLength()
{
return $this->maxLength;
}
public function setMaxLength($max)
{
$this->maxLength = $max;
return $this;
}
public function getMaxItems()
{
return $this->maxItems;
}
public function setMaxItems($max)
{
$this->maxItems = $max;
return $this;
}
public function getMinItems()
{
return $this->minItems;
}
public function setMinItems($min)
{
$this->minItems = $min;
return $this;
}
public function getLocation()
{
return $this->location;
}
public function setLocation($location)
{
$this->location = $location;
return $this;
}
public function getSentAs()
{
return $this->sentAs;
}
public function setSentAs($name)
{
$this->sentAs = $name;
return $this;
}
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;
}
public function setData($nameOrData, $data = null)
{
if (is_array($nameOrData)) {
$this->data = $nameOrData;
} else {
$this->data[$nameOrData] = $data;
}
return $this;
}
public function getStatic()
{
return $this->static;
}
public function setStatic($static)
{
$this->static = (bool) $static;
return $this;
}
public function getFilters()
{
return $this->filters ?: array();
}
public function setFilters(array $filters)
{
$this->filters = array();
foreach ($filters as $filter) {
$this->addFilter($filter);
}
return $this;
}
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;
}
public function getParent()
{
return $this->parent;
}
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
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;
}
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];
}
public function removeProperty($name)
{
unset($this->properties[$name]);
$this->propertiesCache = null;
return $this;
}
public function addProperty(Parameter $property)
{
$this->properties[$property->getName()] = $property;
$property->setParent($this);
$this->propertiesCache = null;
return $this;
}
public function getAdditionalProperties()
{
if (is_array($this->additionalProperties)) {
$this->additionalProperties = new static($this->additionalProperties, $this->serviceDescription);
$this->additionalProperties->setParent($this);
}
return $this->additionalProperties;
}
public function setAdditionalProperties($additional)
{
$this->additionalProperties = $additional;
return $this;
}
public function setItems(Parameter $items = null)
{
if ($this->items = $items) {
$this->items->setParent($this);
}
return $this;
}
public function getItems()
{
if (is_array($this->items)) {
$this->items = new static($this->items, $this->serviceDescription);
$this->items->setParent($this);
}
return $this->items;
}
public function getInstanceOf()
{
return $this->instanceOf;
}
public function setInstanceOf($instanceOf)
{
$this->instanceOf = $instanceOf;
return $this;
}
public function getEnum()
{
return $this->enum;
}
public function setEnum(array $enum = null)
{
$this->enum = $enum;
return $this;
}
public function getPattern()
{
return $this->pattern;
}
public function setPattern($pattern)
{
$this->pattern = $pattern;
return $this;
}
public function getFormat()
{
return $this->format;
}
public function setFormat($format)
{
$this->format = $format;
return $this;
}
}
<?php
namespace Guzzle\Service\Description;
use Guzzle\Common\Exception\InvalidArgumentException;
class SchemaFormatter
{
protected static $utcTimeZone;
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;
}
}
public static function formatDateTime($value)
{
return self::dateFormatter($value, 'Y-m-d\TH:i:s\Z');
}
public static function formatDateTimeHttp($value)
{
return self::dateFormatter($value, 'D, d M Y H:i:s \G\M\T');
}
public static function formatDate($value)
{
return self::dateFormatter($value, 'Y-m-d');
}
public static function formatTime($value)
{
return self::dateFormatter($value, 'H:i:s');
}
public static function formatBooleanAsString($value)
{
return filter_var($value, FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false';
}
public static function formatTimestamp($value)
{
return (int) self::dateFormatter($value, 'U');
}
protected static function getUtcTimeZone()
{
if (!self::$utcTimeZone) {
self::$utcTimeZone = new \DateTimeZone('UTC');
}
return self::$utcTimeZone;
}
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;
class SchemaValidator implements ValidatorInterface
{
protected static $instance;
protected $castIntegerToStringType;
protected $errors;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
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;
}
}
public function getErrors()
{
return $this->errors ?: array();
}
protected function recursiveProcess(Parameter $param, &$value, $path = '', $depth = 0)
{
$value = $param->getValue($value);
$required = $param->getRequired();
if ((null === $value && !$required) || $param->getStatic()) {
return true;
}
$type = $param->getType();
$valueIsArray = is_array($value);
if ($name = $param->getName()) {
$path .= "[{$name}]";
}
if ($type == 'object') {
if ($param->getInstanceOf()) {
$instance = $param->getInstanceOf();
if (!($value instanceof $instance)) {
$this->errors[] = "{$path} must be an instance of {$instance}";
return false;
}
}
$traverse = $temporaryValue = false;
if (!$valueIsArray && $value instanceof ToArrayInterface) {
$value = $value->toArray();
}
if ($valueIsArray) {
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) {
$value = array();
$temporaryValue = $valueIsArray = $traverse = true;
}
if ($traverse) {
if ($properties = $param->getProperties()) {
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);
if (null !== $current) {
$value[$name] = $current;
}
}
}
}
$additional = $param->getAdditionalProperties();
if ($additional !== true) {
$keys = array_keys($value);
$diff = array_diff($keys, array_keys($properties));
if (!empty($diff)) {
if ($additional instanceOf Parameter) {
foreach ($diff as $key) {
$this->recursiveProcess($additional, $value[$key], "{$path}[{$key}]", $depth);
}
} else {
$keys = array_keys($value);
$this->errors[] = sprintf('%s[%s] is not an allowed property', $path, reset($keys));
}
}
}
if ($temporaryValue && empty($value)) {
$value = null;
$valueIsArray = false;
}
}
} elseif ($type == 'array' && $valueIsArray && $param->getItems()) {
foreach ($value as $i => &$item) {
$this->recursiveProcess($param->getItems(), $item, $path . "[{$i}]", $depth + 1);
}
}
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;
}
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());
}
}
if ($type == 'string') {
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));
}
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);
}
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\Exception\InvalidArgumentException;
use Guzzle\Common\ToArrayInterface;
class ServiceDescription implements ServiceDescriptionInterface, ToArrayInterface
{
protected $operations = array();
protected $models = array();
protected $name;
protected $apiVersion;
protected $description;
protected $extraData = array();
protected static $descriptionLoader;
protected $baseUrl;
public static function factory($config, array $options = array())
{
if (!self::$descriptionLoader) {
self::$descriptionLoader = new ServiceDescriptionLoader();
}
return self::$descriptionLoader->load($config, $options);
}
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;
}
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)
{
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];
}
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()
{
foreach (array_keys($this->models) as $id) {
$this->getModel($id);
}
return $this->models;
}
public function hasModel($id)
{
return isset($this->models[$id]);
}
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;
}
protected function fromArray(array $config)
{
static $defaultKeys = array('name', 'models', 'apiVersion', 'baseUrl', 'description');
foreach ($defaultKeys as $key) {
if (isset($config[$key])) {
$this->{$key} = $config[$key];
}
}
if (isset($config['basePath'])) {
$this->baseUrl = $config['basePath'];
}
$this->models = (array) $this->models;
$this->operations = (array) $this->operations;
$defaultKeys[] = 'operations';
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;
}
}
foreach (array_diff(array_keys($config), $defaultKeys) as $key) {
$this->extraData[$key] = $config[$key];
}
}
}
<?php
namespace Guzzle\Service\Description;
interface ServiceDescriptionInterface extends \Serializable
{
public function getBaseUrl();
public function getOperations();
public function hasOperation($name);
public function getOperation($name);
public function getModel($id);
public function getModels();
public function hasModel($id);
public function getApiVersion();
public function getName();
public function getDescription();
public function getData($key);
public function setData($key, $value);
}
<?php
namespace Guzzle\Service\Description;
use Guzzle\Service\AbstractConfigLoader;
use Guzzle\Service\Exception\DescriptionBuilderException;
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;
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);
}
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;
interface ValidatorInterface
{
public function validate(Parameter $param, &$value);
public function getErrors();
}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Common\Exception\RuntimeException;
class CommandException extends RuntimeException {}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Service\Command\CommandInterface;
class CommandTransferException extends MultiTransferException
{
protected $successfulCommands = array();
protected $failedCommands = array();
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);
}
}
if (count($alreadyAddedExceptions) < count($e)) {
foreach ($e as $ex) {
if (!in_array($ex, $alreadyAddedExceptions)) {
$ce->add($ex);
}
}
}
return $ce;
}
public function getAllCommands()
{
return array_merge($this->successfulCommands, $this->failedCommands);
}
public function addSuccessfulCommand(CommandInterface $command)
{
$this->successfulCommands[] = $command;
return $this;
}
public function addFailedCommand(CommandInterface $command)
{
$this->failedCommands[] = $command;
return $this;
}
public function getSuccessfulCommands()
{
return $this->successfulCommands;
}
public function getFailedCommands()
{
return $this->failedCommands;
}
public function getExceptionForFailedCommand(CommandInterface $command)
{
return $this->getExceptionForFailedRequest($command->getRequest());
}
}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Common\Exception\RuntimeException;
class DescriptionBuilderException extends RuntimeException {}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Common\Exception\RuntimeException;
class InconsistentClientTransferException extends RuntimeException
{
private $invalidCommands = array();
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.'
);
}
public function getCommands()
{
return $this->invalidCommands;
}
}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Common\Exception\RuntimeException;
class ResponseClassException extends RuntimeException
{
}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Common\Exception\RuntimeException;
class ServiceBuilderException extends RuntimeException {}
<?php
namespace Guzzle\Service\Exception;
class ServiceNotFoundException extends ServiceBuilderException {}
<?php
namespace Guzzle\Service\Exception;
use Guzzle\Common\Exception\RuntimeException;
class ValidationException extends RuntimeException
{
protected $errors = array();
public function setErrors(array $errors)
{
$this->errors = $errors;
}
public function getErrors()
{
return $this->errors;
}
}
<?php
namespace Guzzle\Service\Resource;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\CommandInterface;
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);
}
abstract protected function getClassName(CommandInterface $command);
}
<?php
namespace Guzzle\Service\Resource;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\CommandInterface;
class CompositeResourceIteratorFactory implements ResourceIteratorFactoryInterface
{
protected $factories;
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;
}
public function addFactory(ResourceIteratorFactoryInterface $factory)
{
$this->factories[] = $factory;
return $this;
}
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\Service\Command\CommandInterface;
class MapResourceIteratorFactory extends AbstractResourceIteratorFactory
{
protected $map;
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['*'])) {
return $this->map['*'];
}
return null;
}
}
<?php
namespace Guzzle\Service\Resource;
use Guzzle\Common\Collection;
use Guzzle\Service\Description\Parameter;
class Model extends Collection
{
protected $structure;
public function __construct(array $data = array(), Parameter $structure = null)
{
$this->data = $data;
$this->structure = $structure;
}
public function getStructure()
{
return $this->structure ?: new Parameter();
}
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
{
protected $command;
protected $originalCommand;
protected $resources;
protected $retrievedCount = 0;
protected $iteratedCount = 0;
protected $nextToken = false;
protected $pageSize;
protected $limit;
protected $requestCount = 0;
protected $data = array();
protected $invalid;
public static function getAllEvents()
{
return array(
'resource_iterator.before_send',
'resource_iterator.after_send'
);
}
public function __construct(CommandInterface $command, array $data = array())
{
$this->originalCommand = $command;
$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;
}
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;
}
public function get($key)
{
return array_key_exists($key, $this->data) ? $this->data[$key] : null;
}
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;
}
public function getRequestCount()
{
return $this->requestCount;
}
public function rewind()
{
$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++;
$sendRequest = false;
if (!$this->resources) {
$sendRequest = true;
} else {
$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
));
$this->command = clone $this->originalCommand;
$this->resources = $this->sendRequest();
$this->requestCount++;
if (empty($this->resources)) {
$this->invalid = true;
} else {
$this->retrievedCount += count($this->resources);
reset($this->resources);
}
$this->dispatch('resource_iterator.after_send', array(
'iterator' => $this,
'resources' => $this->resources
));
}
}
public function getNextToken()
{
return $this->nextToken;
}
protected function calculatePageSize()
{
if ($this->limit && $this->iteratedCount + $this->pageSize > $this->limit) {
return 1 + ($this->limit - $this->iteratedCount);
}
return (int) $this->pageSize;
}
protected function resetState()
{
$this->iteratedCount = 0;
$this->retrievedCount = 0;
$this->nextToken = false;
$this->resources = null;
$this->invalid = false;
}
abstract protected function sendRequest();
}
<?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;
class ResourceIteratorApplyBatched extends AbstractHasDispatcher
{
protected $callback;
protected $iterator;
protected $batches = 0;
protected $iterated = 0;
public static function getAllEvents()
{
return array(
'iterator_batch.before_batch',
'iterator_batch.after_batch',
'iterator_batch.created_batch'
);
}
public function __construct(ResourceIteratorInterface $iterator, $callback)
{
$this->iterator = $iterator;
$this->callback = $callback;
Version::warn(__CLASS__ . ' is deprecated');
}
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;
}
public function getBatchCount()
{
return $this->batches;
}
public function getIteratedCount()
{
return $this->iterated;
}
}
<?php
namespace Guzzle\Service\Resource;
use Guzzle\Inflection\InflectorInterface;
use Guzzle\Inflection\Inflector;
use Guzzle\Service\Command\CommandInterface;
class ResourceIteratorClassFactory extends AbstractResourceIteratorFactory
{
protected $namespaces;
protected $inflector;
public function __construct($namespaces = array(), InflectorInterface $inflector = null)
{
$this->namespaces = (array) $namespaces;
$this->inflector = $inflector ?: Inflector::getDefault();
}
public function registerNamespace($namespace)
{
array_unshift($this->namespaces, $namespace);
return $this;
}
protected function getClassName(CommandInterface $command)
{
$iteratorName = $this->inflector->camel($command->getName()) . 'Iterator';
foreach ($this->namespaces as $namespace) {
$potentialClassName = $namespace . '\\' . $iteratorName;
if (class_exists($potentialClassName)) {
return $potentialClassName;
}
}
return false;
}
}
<?php
namespace Guzzle\Service\Resource;
use Guzzle\Service\Command\CommandInterface;
interface ResourceIteratorFactoryInterface
{
public function build(CommandInterface $command, array $options = array());
public function canBuild(CommandInterface $command);
}
<?php
namespace Guzzle\Service\Resource;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\ToArrayInterface;
interface ResourceIteratorInterface extends ToArrayInterface, HasDispatcherInterface, \Iterator, \Countable
{
public function getNextToken();
public function setLimit($limit);
public function setPageSize($pageSize);
public function get($key);
public function set($key, $value);
}
<?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;
class PhpStreamRequestFactory implements StreamRequestFactoryInterface
{
protected $context;
protected $contextOptions;
protected $url;
protected $lastResponseHeaders;
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');
}
$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);
return $this->createStream($params)
->setCustomData('request', $request)
->setCustomData('response_headers', $this->getLastResponseHeaders());
}
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);
}
protected function createContext(array $params)
{
$options = $this->contextOptions;
$this->context = $this->createResource(function () use ($params, $options) {
return stream_context_create($options, $params);
});
}
public function getLastResponseHeaders()
{
return $this->lastResponseHeaders;
}
protected function addDefaultContextOptions(RequestInterface $request)
{
$this->setContextValue('http', 'method', $request->getMethod());
$headers = $request->getHeaderLines();
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);
}
protected function setUrl(RequestInterface $request)
{
$this->url = $request->getUrl(true);
if ($request->getUsername()) {
$this->url->setUsername($request->getUsername());
}
if ($request->getPassword()) {
$this->url->setPassword($request->getPassword());
}
}
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);
}
}
protected function addBodyOptions(RequestInterface $request)
{
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);
}
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);
}
}
protected function addProxyOptions(RequestInterface $request)
{
if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) {
$this->setContextValue('http', 'proxy', $proxy);
}
}
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);
});
$className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream';
$stream = new $className($fp);
if (isset($http_response_header)) {
$this->lastResponseHeaders = $http_response_header;
$this->processResponseHeaders($stream);
}
return $stream;
}
protected function processResponseHeaders(StreamInterface $stream)
{
foreach ($this->lastResponseHeaders as $header) {
if ((stripos($header, 'Content-Length:')) === 0) {
$stream->setSize(trim(substr($header, 15)));
}
}
}
protected function createResource($callback)
{
$level = error_reporting(0);
$resource = call_user_func($callback);
error_reporting($level);
if (false === $resource) {
$message = 'Error creating resource. ';
foreach (error_get_last() as $key => $value) {
$message .= "[{$key}] {$value} ";
}
throw new RuntimeException(trim($message));
}
return $resource;
}
}
<?php
namespace Guzzle\Stream;
use Guzzle\Common\Exception\InvalidArgumentException;
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';
protected $stream;
protected $size;
protected $cache = array();
protected $customData = array();
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
)
);
public function __construct($stream, $size = null)
{
$this->setStream($stream, $size);
}
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;
}
public static function getHash(StreamInterface $stream, $algo, $rawOutput = false)
{
$pos = $stream->ftell();
if (!$stream->seek(0)) {
return false;
}
$ctx = hash_init($algo);
while ($data = $stream->read(8192)) {
hash_update($ctx, $data);
}
$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;
}
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]) {
$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)
{
$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;
}
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;
interface StreamInterface
{
public function __toString();
public function close();
public function getMetaData($key = null);
public function getStream();
public function setStream($stream, $size = null);
public function detachStream();
public function getWrapper();
public function getWrapperData();
public function getStreamType();
public function getUri();
public function getSize();
public function isReadable();
public function isRepeatable();
public function isWritable();
public function isConsumed();
public function feof();
public function isLocal();
public function isSeekable();
public function setSize($size);
public function seek($offset, $whence = SEEK_SET);
public function read($length);
public function write($string);
public function ftell();
public function rewind();
public function readLine($maxLength = null);
public function setCustomData($key, $value);
public function getCustomData($key);
}
<?php
namespace Guzzle\Stream;
use Guzzle\Http\Message\RequestInterface;
interface StreamRequestFactoryInterface
{
public function fromRequest(RequestInterface $request, $context = array(), array $params = array());
}
<?php
namespace Satooshi\Bundle\CoverallsBundle\Console;
use Satooshi\Bundle\CoverallsV1Bundle\Command\CoverallsV1JobsCommand;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Input\InputInterface;
class Application extends BaseApplication
{
private $rootDir;
public function __construct($rootDir, $name = 'UNKNOWN', $version = 'UNKNOWN')
{
$this->rootDir = $rootDir;
parent::__construct($name, $version);
}
protected function getCommandName(InputInterface $input)
{
return 'coveralls:v1:jobs';
}
protected function getDefaultCommands()
{
$defaultCommands = parent::getDefaultCommands();
$defaultCommands[] = $this->createCoverallsV1JobsCommand();
return $defaultCommands;
}
protected function createCoverallsV1JobsCommand()
{
$command = new CoverallsV1JobsCommand();
$command->setRootDir($this->rootDir);
return $command;
}
public function getDefinition()
{
$inputDefinition = parent::getDefinition();
$inputDefinition->setArguments();
return $inputDefinition;
}
}
<?php
namespace Satooshi\Bundle\CoverallsBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CoverallsBundle extends Bundle
{
}
<?php
namespace Satooshi\Bundle\CoverallsBundle\Entity;
interface ArrayConvertable
{
public function toArray();
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Api;
use Satooshi\Bundle\CoverallsV1Bundle\Config\Configuration;
use Guzzle\Http\Client;
abstract class CoverallsApi
{
protected $config;
protected $client;
public function __construct(Configuration $config, Client $client = null)
{
$this->config = $config;
$this->client = $client;
}
public function getConfiguration()
{
return $this->config;
}
public function setHttpClient(Client $client)
{
$this->client = $client;
return $this;
}
public function getHttpClient()
{
return $this->client;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Api;
use Satooshi\Bundle\CoverallsV1Bundle\Collector\CiEnvVarsCollector;
use Satooshi\Bundle\CoverallsV1Bundle\Collector\CloverXmlCoverageCollector;
use Satooshi\Bundle\CoverallsV1Bundle\Collector\GitInfoCollector;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\JsonFile;
use Satooshi\Component\System\Git\GitCommand;
class Jobs extends CoverallsApi
{
const URL = 'https://coveralls.io/api/v1/jobs';
const FILENAME = 'json_file';
protected $jsonFile;
public function collectCloverXml()
{
$rootDir = $this->config->getRootDir();
$cloverXmlPaths = $this->config->getCloverXmlPaths();
$xmlCollector = new CloverXmlCoverageCollector();
foreach ($cloverXmlPaths as $cloverXmlPath) {
$xml = simplexml_load_file($cloverXmlPath);
$xmlCollector->collect($xml, $rootDir);
}
$this->jsonFile = $xmlCollector->getJsonFile();
if ($this->config->isExcludeNoStatements()) {
$this->jsonFile->excludeNoStatementsFiles();
}
$this->jsonFile->sortSourceFiles();
return $this;
}
public function collectGitInfo()
{
$command = new GitCommand();
$gitCollector = new GitInfoCollector($command);
$this->jsonFile->setGit($gitCollector->collect());
return $this;
}
public function collectEnvVars(array $env)
{
$envCollector = new CiEnvVarsCollector($this->config);
try {
$this->jsonFile->fillJobs($envCollector->collect($env));
} catch (\Satooshi\Bundle\CoverallsV1Bundle\Entity\Exception\RequirementsNotSatisfiedException $e) {
$e->setReadEnv($envCollector->getReadEnv());
throw $e;
}
return $this;
}
public function dumpJsonFile()
{
$jsonPath = $this->config->getJsonPath();
file_put_contents($jsonPath, $this->jsonFile);
return $this;
}
public function send()
{
if ($this->config->isDryRun()) {
return;
}
$jsonPath = $this->config->getJsonPath();
return $this->upload(static::URL, $jsonPath, static::FILENAME);
}
protected function upload($url, $path, $filename)
{
$request = $this->client->post($url)->addPostFiles(array($filename => $path));
return $request->send();
}
public function setJsonFile(JsonFile $jsonFile)
{
$this->jsonFile = $jsonFile;
return $this;
}
public function getJsonFile()
{
if (isset($this->jsonFile)) {
return $this->jsonFile;
}
return;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Collector;
use Satooshi\Bundle\CoverallsV1Bundle\Config\Configuration;
class CiEnvVarsCollector
{
protected $config;
protected $env;
protected $readEnv;
public function __construct(Configuration $config)
{
$this->config = $config;
}
public function collect(array $env)
{
$this->env = $env;
$this->readEnv = array();
$this->fillTravisCi()
->fillCircleCi()
->fillJenkins()
->fillLocal()
->fillRepoToken();
return $this->env;
}
protected function fillTravisCi()
{
if (isset($this->env['TRAVIS']) && $this->env['TRAVIS'] && isset($this->env['TRAVIS_JOB_ID'])) {
$this->env['CI_JOB_ID'] = $this->env['TRAVIS_JOB_ID'];
if ($this->config->hasServiceName()) {
$this->env['CI_NAME'] = $this->config->getServiceName();
} else {
$this->env['CI_NAME'] = 'travis-ci';
}
$this->readEnv['TRAVIS'] = $this->env['TRAVIS'];
$this->readEnv['TRAVIS_JOB_ID'] = $this->env['TRAVIS_JOB_ID'];
$this->readEnv['CI_NAME'] = $this->env['CI_NAME'];
}
return $this;
}
protected function fillCircleCi()
{
if (isset($this->env['CIRCLECI']) && $this->env['CIRCLECI'] && isset($this->env['CIRCLE_BUILD_NUM'])) {
$this->env['CI_BUILD_NUMBER'] = $this->env['CIRCLE_BUILD_NUM'];
$this->env['CI_NAME'] = 'circleci';
$this->readEnv['CIRCLECI'] = $this->env['CIRCLECI'];
$this->readEnv['CIRCLE_BUILD_NUM'] = $this->env['CIRCLE_BUILD_NUM'];
$this->readEnv['CI_NAME'] = $this->env['CI_NAME'];
}
return $this;
}
protected function fillJenkins()
{
if (isset($this->env['JENKINS_URL']) && isset($this->env['BUILD_NUMBER'])) {
$this->env['CI_BUILD_NUMBER'] = $this->env['BUILD_NUMBER'];
$this->env['CI_BUILD_URL'] = $this->env['JENKINS_URL'];
$this->env['CI_NAME'] = 'jenkins';
$this->readEnv['BUILD_NUMBER'] = $this->env['BUILD_NUMBER'];
$this->readEnv['JENKINS_URL'] = $this->env['JENKINS_URL'];
$this->readEnv['CI_NAME'] = $this->env['CI_NAME'];
}
return $this;
}
protected function fillLocal()
{
if (isset($this->env['COVERALLS_RUN_LOCALLY']) && $this->env['COVERALLS_RUN_LOCALLY']) {
$this->env['CI_JOB_ID'] = null;
$this->env['CI_NAME'] = 'php-coveralls';
$this->env['COVERALLS_EVENT_TYPE'] = 'manual';
$this->readEnv['COVERALLS_RUN_LOCALLY'] = $this->env['COVERALLS_RUN_LOCALLY'];
$this->readEnv['COVERALLS_EVENT_TYPE'] = $this->env['COVERALLS_EVENT_TYPE'];
$this->readEnv['CI_NAME'] = $this->env['CI_NAME'];
}
return $this;
}
protected function fillRepoToken()
{
if ($this->config->hasRepoToken()) {
$this->env['COVERALLS_REPO_TOKEN'] = $this->config->getRepoToken();
}
if (isset($this->env['COVERALLS_REPO_TOKEN'])) {
$this->readEnv['COVERALLS_REPO_TOKEN'] = $this->env['COVERALLS_REPO_TOKEN'];
}
return $this;
}
public function getReadEnv()
{
return $this->readEnv;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Collector;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\JsonFile;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\SourceFile;
class CloverXmlCoverageCollector
{
protected $jsonFile;
public function collect(\SimpleXMLElement $xml, $rootDir)
{
$root = rtrim($rootDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if (!isset($this->jsonFile)) {
$this->jsonFile = new JsonFile();
}
$runAt = $this->collectRunAt($xml);
$this->jsonFile->setRunAt($runAt);
$xpaths = array(
'/coverage/project/file',
'/coverage/project/package/file',
);
foreach ($xpaths as $xpath) {
foreach ($xml->xpath($xpath) as $file) {
$srcFile = $this->collectFileCoverage($file, $root);
if ($srcFile !== null) {
$this->jsonFile->addSourceFile($srcFile);
}
}
}
return $this->jsonFile;
}
protected function collectRunAt(\SimpleXMLElement $xml, $format = 'Y-m-d H:i:s O')
{
$timestamp = $xml->project['timestamp'];
$runAt = new \DateTime('@' . $timestamp);
return $runAt->format($format);
}
protected function collectFileCoverage(\SimpleXMLElement $file, $root)
{
$absolutePath = realpath((string) ($file['path'] ?: $file['name']));
if (false === strpos($absolutePath, $root)) {
return;
}
if ($root !== DIRECTORY_SEPARATOR) {
$filename = str_replace($root, '', $absolutePath);
} else {
$filename = $absolutePath;
}
return $this->collectCoverage($file, $absolutePath, $filename);
}
protected function collectCoverage(\SimpleXMLElement $file, $path, $filename)
{
if ($this->jsonFile->hasSourceFile($path)) {
$srcFile = $this->jsonFile->getSourceFile($path);
} else {
$srcFile = new SourceFile($path, $filename);
}
foreach ($file->line as $line) {
if ((string) $line['type'] === 'stmt') {
$lineNum = (int) $line['num'];
if ($lineNum > 0) {
$srcFile->addCoverage($lineNum - 1, (int) $line['count']);
}
}
}
return $srcFile;
}
public function getJsonFile()
{
return $this->jsonFile;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Collector;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Git\Commit;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Git\Git;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Git\Remote;
use Satooshi\Component\System\Git\GitCommand;
class GitInfoCollector
{
protected $command;
public function __construct(GitCommand $command)
{
$this->command = $command;
}
public function collect()
{
$branch = $this->collectBranch();
$commit = $this->collectCommit();
$remotes = $this->collectRemotes();
return new Git($branch, $commit, $remotes);
}
protected function collectBranch()
{
$branchesResult = $this->command->getBranches();
foreach ($branchesResult as $result) {
if (strpos($result, '* ') === 0) {
$exploded = explode('* ', $result, 2);
return $exploded[1];
}
}
throw new \RuntimeException();
}
protected function collectCommit()
{
$commitResult = $this->command->getHeadCommit();
if (count($commitResult) !== 6 || array_keys($commitResult) !== range(0, 5)) {
throw new \RuntimeException();
}
$commit = new Commit();
return $commit
->setId($commitResult[0])
->setAuthorName($commitResult[1])
->setAuthorEmail($commitResult[2])
->setCommitterName($commitResult[3])
->setCommitterEmail($commitResult[4])
->setMessage($commitResult[5]);
}
protected function collectRemotes()
{
$remotesResult = $this->command->getRemotes();
if (count($remotesResult) === 0) {
throw new \RuntimeException();
}
$results = array();
foreach ($remotesResult as $result) {
if (strpos($result, ' ') !== false) {
list($remote) = explode(' ', $result, 2);
$results[] = $remote;
}
}
$results = array_unique($results);
$remotes = array();
foreach ($results as $result) {
if (strpos($result, "\t") !== false) {
list($name, $url) = explode("\t", $result, 2);
$remote = new Remote();
$remotes[] = $remote->setName($name)->setUrl($url);
}
}
return $remotes;
}
public function getCommand()
{
return $this->command;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Command;
use Satooshi\Bundle\CoverallsV1Bundle\Api\Jobs;
use Satooshi\Bundle\CoverallsV1Bundle\Config\Configuration;
use Satooshi\Bundle\CoverallsV1Bundle\Config\Configurator;
use Satooshi\Bundle\CoverallsV1Bundle\Repository\JobsRepository;
use Satooshi\Component\Log\ConsoleLogger;
use Satooshi\Component\File\Path;
use Guzzle\Http\Client;
use Psr\Log\NullLogger;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Stopwatch\Stopwatch;
class CoverallsV1JobsCommand extends Command
{
protected $rootDir;
protected $logger;
protected function configure()
{
$this
->setName('coveralls:v1:jobs')
->setDescription('Coveralls Jobs API v1')
->addOption(
'config',
'-c',
InputOption::VALUE_OPTIONAL,
'.coveralls.yml path',
'.coveralls.yml'
)
->addOption(
'dry-run',
null,
InputOption::VALUE_NONE,
'Do not send json_file to Jobs API'
)
->addOption(
'exclude-no-stmt',
null,
InputOption::VALUE_NONE,
'Exclude source files that have no executable statements'
)
->addOption(
'env',
'-e',
InputOption::VALUE_OPTIONAL,
'Runtime environment name: test, dev, prod',
'prod'
)
->addOption(
'coverage_clover',
'-x',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'Coverage clover xml files(allowing multiple values).',
array()
)
->addOption(
'root_dir',
'-r',
InputOption::VALUE_OPTIONAL,
'Root directory of the project.',
'.'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$stopwatch = new Stopwatch();
$stopwatch->start(__CLASS__);
$file = new Path();
if ($input->getOption('root_dir') !== '.') {
$this->rootDir = $file->toAbsolutePath(
$input->getOption('root_dir'),
$this->rootDir
);
}
$config = $this->loadConfiguration($input, $this->rootDir);
$this->logger = $config->isVerbose() && !$config->isTestEnv() ? new ConsoleLogger($output) : new NullLogger();
$this->executeApi($config);
$event = $stopwatch->stop(__CLASS__);
$time = number_format($event->getDuration() / 1000, 3);
$mem = number_format($event->getMemory() / (1024 * 1024), 2);
$this->logger->info(sprintf('elapsed time: <info>%s</info> sec memory: <info>%s</info> MB', $time, $mem));
return 0;
}
protected function loadConfiguration(InputInterface $input, $rootDir)
{
$coverallsYmlPath = $input->getOption('config');
$ymlPath = $this->rootDir . DIRECTORY_SEPARATOR . $coverallsYmlPath;
$configurator = new Configurator();
return $configurator
->load($ymlPath, $rootDir, $input)
->setDryRun($input->getOption('dry-run'))
->setExcludeNoStatementsUnlessFalse($input->getOption('exclude-no-stmt'))
->setVerbose($input->getOption('verbose'))
->setEnv($input->getOption('env'));
}
protected function executeApi(Configuration $config)
{
$client = new Client();
$api = new Jobs($config, $client);
$repository = new JobsRepository($api, $config);
$repository->setLogger($this->logger);
$repository->persist();
}
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Config;
class Configuration
{
protected $repoToken;
protected $serviceName;
protected $rootDir;
protected $cloverXmlPaths = array();
protected $jsonPath;
protected $dryRun = true;
protected $excludeNoStatements = false;
protected $verbose = false;
protected $env = 'prod';
public function setRepoToken($repoToken)
{
$this->repoToken = $repoToken;
return $this;
}
public function hasRepoToken()
{
return isset($this->repoToken);
}
public function getRepoToken()
{
return $this->repoToken;
}
public function setServiceName($serviceName)
{
$this->serviceName = $serviceName;
return $this;
}
public function hasServiceName()
{
return isset($this->serviceName);
}
public function getServiceName()
{
return $this->serviceName;
}
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
return $this;
}
public function getRootDir()
{
return $this->rootDir;
}
public function setCloverXmlPaths(array $cloverXmlPaths)
{
$this->cloverXmlPaths = $cloverXmlPaths;
return $this;
}
public function addCloverXmlPath($cloverXmlPath)
{
$this->cloverXmlPaths[] = $cloverXmlPath;
return $this;
}
public function getCloverXmlPaths()
{
return $this->cloverXmlPaths;
}
public function setJsonPath($jsonPath)
{
$this->jsonPath = $jsonPath;
return $this;
}
public function getJsonPath()
{
return $this->jsonPath;
}
public function setDryRun($dryRun)
{
$this->dryRun = $dryRun;
return $this;
}
public function isDryRun()
{
return $this->dryRun;
}
public function setExcludeNoStatements($excludeNoStatements)
{
$this->excludeNoStatements = $excludeNoStatements;
return $this;
}
public function setExcludeNoStatementsUnlessFalse($excludeNoStatements)
{
if ($excludeNoStatements) {
$this->excludeNoStatements = true;
}
return $this;
}
public function isExcludeNoStatements()
{
return $this->excludeNoStatements;
}
public function setVerbose($verbose)
{
$this->verbose = $verbose;
return $this;
}
public function isVerbose()
{
return $this->verbose;
}
public function setEnv($env)
{
$this->env = $env;
return $this;
}
public function getEnv()
{
return $this->env;
}
public function isTestEnv()
{
return $this->env === 'test';
}
public function isDevEnv()
{
return $this->env === 'dev';
}
public function isProdEnv()
{
return $this->env === 'prod';
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Config;
use Satooshi\Component\File\Path;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Yaml\Parser;
class Configurator
{
public function load($coverallsYmlPath, $rootDir, InputInterface $input = null)
{
$yml = $this->parse($coverallsYmlPath);
$options = $this->process($yml);
return $this->createConfiguration($options, $rootDir, $input);
}
protected function parse($coverallsYmlPath)
{
$file = new Path();
$path = realpath($coverallsYmlPath);
if ($file->isRealFileReadable($path)) {
$parser = new Parser();
$yml = $parser->parse(file_get_contents($path));
return empty($yml) ? array() : $yml;
}
return array();
}
protected function process(array $yml)
{
$processor = new Processor();
$configuration = new CoverallsConfiguration();
return $processor->processConfiguration($configuration, array('coveralls' => $yml));
}
protected function createConfiguration(array $options, $rootDir, InputInterface $input = null)
{
$configuration = new Configuration();
$file = new Path();
$repoToken = $options['repo_token'];
$repoSecretToken = $options['repo_secret_token'];
if ($input !== null
&& $input->hasOption('coverage_clover')
&& count($input->getOption('coverage_clover')) > 0) {
$coverage_clover = $input->getOption('coverage_clover');
} else {
$coverage_clover = $options['coverage_clover'];
}
return $configuration
->setRepoToken($repoToken !== null ? $repoToken : $repoSecretToken)
->setServiceName($options['service_name'])
->setRootDir($rootDir)
->setCloverXmlPaths($this->ensureCloverXmlPaths($coverage_clover, $rootDir, $file))
->setJsonPath($this->ensureJsonPath($options['json_path'], $rootDir, $file))
->setExcludeNoStatements($options['exclude_no_stmt']);
}
protected function ensureCloverXmlPaths($option, $rootDir, Path $file)
{
if (is_array($option)) {
return $this->getGlobPathsFromArrayOption($option, $rootDir, $file);
}
return $this->getGlobPathsFromStringOption($option, $rootDir, $file);
}
protected function getGlobPaths($path)
{
$paths = array();
$iterator = new \GlobIterator($path);
foreach ($iterator as $fileInfo) {
$paths[] = $fileInfo->getPathname();
}
if (count($paths) === 0) {
throw new InvalidConfigurationException('coverage_clover XML file is not readable');
}
return $paths;
}
protected function getGlobPathsFromStringOption($option, $rootDir, Path $file)
{
if (!is_string($option)) {
throw new InvalidConfigurationException('coverage_clover XML file is not readable');
}
$path = $file->toAbsolutePath($option, $rootDir);
return $this->getGlobPaths($path);
}
protected function getGlobPathsFromArrayOption(array $options, $rootDir, Path $file)
{
$paths = array();
foreach ($options as $option) {
$paths = array_merge($paths, $this->getGlobPathsFromStringOption($option, $rootDir, $file));
}
return $paths;
}
protected function ensureJsonPath($option, $rootDir, Path $file)
{
$realpath = $file->getRealWritingFilePath($option, $rootDir);
$realFilePath = $file->getRealPath($realpath, $rootDir);
if ($realFilePath !== false && !$file->isRealFileWritable($realFilePath)) {
throw new InvalidConfigurationException('json_path is not writable');
}
$realDir = $file->getRealDir($realpath, $rootDir);
if (!$file->isRealDirWritable($realDir)) {
throw new InvalidConfigurationException('json_path is not writable');
}
return $realpath;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Config;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class CoverallsConfiguration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('coveralls');
$rootNode
->children()
->scalarNode('repo_token')
->defaultNull()
->end()
->scalarNode('repo_secret_token')
->defaultNull()
->end()
->scalarNode('service_name')
->defaultNull()
->end()
->variableNode('coverage_clover')
->defaultValue('build/logs/clover.xml')
->end()
->scalarNode('json_path')
->defaultValue('build/logs/coveralls-upload.json')
->end()
->booleanNode('exclude_no_stmt')
->defaultFalse()
->end()
->end();
return $treeBuilder;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CoverallsV1Bundle extends Bundle
{
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity;
use Satooshi\Bundle\CoverallsBundle\Entity\ArrayConvertable;
abstract class Coveralls implements ArrayConvertable
{
public function __toString()
{
return json_encode($this->toArray());
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity\Exception;
class RequirementsNotSatisfiedException extends \RuntimeException
{
protected $message = 'Requirements are not satisfied.';
protected $readEnv;
private static $secretEnvVars = array(
'COVERALLS_REPO_TOKEN',
);
protected function format($key, $value)
{
if (in_array($key, self::$secretEnvVars, true)
&& is_string($value)
&& strlen($value) > 0) {
$value = '********(HIDDEN)';
}
return sprintf(" - %s=%s\n", $key, var_export($value, true));
}
public function getHelpMessage()
{
$message = $this->message . "\n";
if (isset($this->readEnv) && is_array($this->readEnv)) {
foreach ($this->readEnv as $envVarName => $value) {
$message .= $this->format($envVarName, $value);
}
}
$message .= <<< EOL
Set environment variables properly like the following.
For Travis users:
- TRAVIS
- TRAVIS_JOB_ID
For CircleCI users:
- CIRCLECI
- CIRCLE_BUILD_NUM
- COVERALLS_REPO_TOKEN
For Jenkins users:
- JENKINS_URL
- BUILD_NUMBER
- COVERALLS_REPO_TOKEN
From local environment:
- COVERALLS_RUN_LOCALLY
- COVERALLS_REPO_TOKEN
EOL;
return $message;
}
public function setReadEnv(array $readEnv)
{
$this->readEnv = $readEnv;
}
public function getReadEnv()
{
return $this->readEnv;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity\Git;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Coveralls;
class Commit extends Coveralls
{
protected $id;
protected $authorName;
protected $authorEmail;
protected $committerName;
protected $committerEmail;
protected $message;
public function toArray()
{
return array(
'id' => $this->id,
'author_name' => $this->authorName,
'author_email' => $this->authorEmail,
'committer_name' => $this->committerName,
'committer_email' => $this->committerEmail,
'message' => $this->message,
);
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getId()
{
if (isset($this->id)) {
return $this->id;
}
return;
}
public function setAuthorName($authorName)
{
$this->authorName = $authorName;
return $this;
}
public function getAuthorName()
{
if (isset($this->authorName)) {
return $this->authorName;
}
return;
}
public function setAuthorEmail($authorEmail)
{
$this->authorEmail = $authorEmail;
return $this;
}
public function getAuthorEmail()
{
if (isset($this->authorEmail)) {
return $this->authorEmail;
}
return;
}
public function setCommitterName($committerName)
{
$this->committerName = $committerName;
return $this;
}
public function getCommitterName()
{
if (isset($this->committerName)) {
return $this->committerName;
}
return;
}
public function setCommitterEmail($committerEmail)
{
$this->committerEmail = $committerEmail;
return $this;
}
public function getCommitterEmail()
{
if (isset($this->committerEmail)) {
return $this->committerEmail;
}
return;
}
public function setMessage($message)
{
$this->message = $message;
return $this;
}
public function getMessage()
{
if (isset($this->message)) {
return $this->message;
}
return;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity\Git;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Coveralls;
class Git extends Coveralls
{
protected $branch;
protected $head;
protected $remotes;
public function __construct($branch, Commit $head, array $remotes)
{
$this->branch = $branch;
$this->head = $head;
$this->remotes = $remotes;
}
public function toArray()
{
$remotes = array();
foreach ($this->remotes as $remote) {
$remotes[] = $remote->toArray();
}
return array(
'branch' => $this->branch,
'head' => $this->head->toArray(),
'remotes' => $remotes,
);
}
public function getBranch()
{
return $this->branch;
}
public function getHead()
{
return $this->head;
}
public function getRemotes()
{
return $this->remotes;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity\Git;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Coveralls;
class Remote extends Coveralls
{
protected $name;
protected $url;
public function toArray()
{
return array(
'name' => $this->name,
'url' => $this->url,
);
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
if (isset($this->name)) {
return $this->name;
}
return;
}
public function setUrl($url)
{
$this->url = $url;
return $this;
}
public function getUrl()
{
if (isset($this->url)) {
return $this->url;
}
return;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Exception\RequirementsNotSatisfiedException;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\Git\Git;
use Satooshi\Bundle\CoverallsV1Bundle\Version;
class JsonFile extends Coveralls
{
protected $serviceName;
protected $serviceJobId;
protected $serviceNumber;
protected $serviceEventType;
protected $serviceBuildUrl;
protected $serviceBranch;
protected $servicePullRequest;
protected $repoToken;
protected $sourceFiles = array();
protected $git;
protected $runAt;
protected $metrics;
public function toArray()
{
$array = array();
$arrayMap = array(
'service_name' => 'serviceName',
'service_job_id' => 'serviceJobId',
'service_number' => 'serviceNumber',
'service_build_url' => 'serviceBuildUrl',
'service_branch' => 'serviceBranch',
'service_pull_request' => 'servicePullRequest',
'service_event_type' => 'serviceEventType',
'repo_token' => 'repoToken',
'git' => 'git',
'run_at' => 'runAt',
'source_files' => 'sourceFiles',
);
foreach ($arrayMap as $jsonKey => $propName) {
if (isset($this->$propName)) {
$array[$jsonKey] = $this->toJsonProperty($this->$propName);
}
}
$array['environment'] = array(
'packagist_version' => Version::VERSION,
);
return $array;
}
public function fillJobs(array $env)
{
return $this
->fillStandardizedEnvVars($env)
->ensureJobs();
}
public function excludeNoStatementsFiles()
{
$this->sourceFiles = array_filter(
$this->sourceFiles,
function (SourceFile $sourceFile) {
return $sourceFile->getMetrics()->hasStatements();
}
);
}
public function sortSourceFiles()
{
ksort($this->sourceFiles);
}
public function reportLineCoverage()
{
$metrics = $this->getMetrics();
foreach ($this->sourceFiles as $sourceFile) {
$metrics->merge($sourceFile->getMetrics());
}
return $metrics->getLineCoverage();
}
protected function toJsonProperty($prop)
{
if ($prop instanceof Coveralls) {
return $prop->toArray();
} elseif (is_array($prop)) {
return $this->toJsonPropertyArray($prop);
}
return $prop;
}
protected function toJsonPropertyArray(array $propArray)
{
$array = array();
foreach ($propArray as $prop) {
$array[] = $this->toJsonProperty($prop);
}
return $array;
}
protected function fillStandardizedEnvVars(array $env)
{
$map = array(
'serviceName' => 'CI_NAME',
'serviceNumber' => 'CI_BUILD_NUMBER',
'serviceBuildUrl' => 'CI_BUILD_URL',
'serviceBranch' => 'CI_BRANCH',
'servicePullRequest' => 'CI_PULL_REQUEST',
'serviceJobId' => 'CI_JOB_ID',
'serviceEventType' => 'COVERALLS_EVENT_TYPE',
'repoToken' => 'COVERALLS_REPO_TOKEN',
);
foreach ($map as $propName => $envName) {
if (isset($env[$envName])) {
$this->$propName = $env[$envName];
}
}
return $this;
}
protected function ensureJobs()
{
if (!$this->hasSourceFiles()) {
throw new \RuntimeException('source_files must be set');
}
if ($this->requireServiceJobId()) {
return $this;
}
if ($this->requireServiceNumber()) {
return $this;
}
if ($this->requireServiceEventType()) {
return $this;
}
if ($this->requireRepoToken()) {
return $this;
}
if ($this->isUnsupportedServiceJob()) {
return $this;
}
throw new RequirementsNotSatisfiedException();
}
protected function requireServiceJobId()
{
return isset($this->serviceName) && isset($this->serviceJobId) && !isset($this->repoToken);
}
protected function requireServiceNumber()
{
return isset($this->serviceName) && isset($this->serviceNumber) && isset($this->repoToken);
}
protected function requireServiceEventType()
{
return isset($this->serviceName) && isset($this->serviceEventType) && isset($this->repoToken);
}
protected function requireRepoToken()
{
return isset($this->serviceName) && $this->serviceName === 'travis-pro' && isset($this->repoToken);
}
protected function isUnsupportedServiceJob()
{
return !isset($this->serviceJobId) && !isset($this->serviceNumber) && !isset($this->serviceEventType) && isset($this->repoToken);
}
public function hasSourceFile($path)
{
return isset($this->sourceFiles[$path]);
}
public function getSourceFile($path)
{
if ($this->hasSourceFile($path)) {
return $this->sourceFiles[$path];
}
return;
}
public function addSourceFile(SourceFile $sourceFile)
{
$this->sourceFiles[$sourceFile->getPath()] = $sourceFile;
}
public function hasSourceFiles()
{
return count($this->sourceFiles) > 0;
}
public function getSourceFiles()
{
return $this->sourceFiles;
}
public function setServiceName($serviceName)
{
$this->serviceName = $serviceName;
return $this;
}
public function getServiceName()
{
if (isset($this->serviceName)) {
return $this->serviceName;
}
return;
}
public function setRepoToken($repoToken)
{
$this->repoToken = $repoToken;
return $this;
}
public function getRepoToken()
{
if (isset($this->repoToken)) {
return $this->repoToken;
}
return;
}
public function setServiceJobId($serviceJobId)
{
$this->serviceJobId = $serviceJobId;
return $this;
}
public function getServiceJobId()
{
if (isset($this->serviceJobId)) {
return $this->serviceJobId;
}
return;
}
public function getServiceNumber()
{
return $this->serviceNumber;
}
public function getServiceEventType()
{
return $this->serviceEventType;
}
public function getServiceBuildUrl()
{
return $this->serviceBuildUrl;
}
public function getServiceBranch()
{
return $this->serviceBranch;
}
public function getServicePullRequest()
{
return $this->servicePullRequest;
}
public function setGit(Git $git)
{
$this->git = $git;
return $this;
}
public function getGit()
{
if (isset($this->git)) {
return $this->git;
}
return;
}
public function setRunAt($runAt)
{
$this->runAt = $runAt;
return $this;
}
public function getRunAt()
{
if (isset($this->runAt)) {
return $this->runAt;
}
return;
}
public function getMetrics()
{
if (!isset($this->metrics)) {
$this->metrics = new Metrics();
}
return $this->metrics;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity;
class Metrics
{
protected $statements;
protected $coveredStatements;
protected $lineCoverage;
public function __construct(array $coverage = array())
{
if (!empty($coverage)) {
$statementsArray = array_filter(
$coverage,
function ($line) {
return $line !== null;
}
);
$this->statements = count($statementsArray);
$coveredArray = array_filter(
$statementsArray,
function ($line) {
return $line > 0;
}
);
$this->coveredStatements = count($coveredArray);
} else {
$this->statements = 0;
$this->coveredStatements = 0;
}
}
public function merge(Metrics $that)
{
$this->statements += $that->statements;
$this->coveredStatements += $that->coveredStatements;
$this->lineCoverage = null;
}
protected function calculateLineCoverage($statements, $coveredStatements)
{
if ($statements === 0) {
return 0;
}
return ($coveredStatements / $statements) * 100;
}
public function hasStatements()
{
return $this->statements !== 0;
}
public function getStatements()
{
return $this->statements;
}
public function getCoveredStatements()
{
return $this->coveredStatements;
}
public function getLineCoverage()
{
if (!isset($this->lineCoverage)) {
$this->lineCoverage = $this->calculateLineCoverage($this->statements, $this->coveredStatements);
}
return $this->lineCoverage;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity;
class SourceFile extends Coveralls
{
protected $name;
protected $source;
protected $coverage;
protected $path;
protected $fileLines;
protected $metrics;
public function __construct($path, $name, $eol = "\n")
{
$this->path = $path;
$this->name = $name;
$this->source = trim(file_get_contents($path));
$lines = explode($eol, $this->source);
$this->fileLines = count($lines);
$this->coverage = array_fill(0, $this->fileLines, null);
}
public function toArray()
{
return array(
'name' => $this->name,
'source' => $this->source,
'coverage' => $this->coverage,
);
}
public function addCoverage($lineNum, $count)
{
if (array_key_exists($lineNum, $this->coverage)) {
$this->coverage[$lineNum] += $count;
}
}
public function reportLineCoverage()
{
return $this->getMetrics()->getLineCoverage();
}
public function getName()
{
return $this->name;
}
public function getSource()
{
return $this->source;
}
public function getCoverage()
{
return $this->coverage;
}
public function getPath()
{
return $this->path;
}
public function getFileLines()
{
return $this->fileLines;
}
public function getMetrics()
{
if (!isset($this->metrics)) {
$this->metrics = new Metrics($this->coverage);
}
return $this->metrics;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Repository;
use Guzzle\Http\Client;
use Guzzle\Http\Message\Response;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Satooshi\Bundle\CoverallsV1Bundle\Api\Jobs;
use Satooshi\Bundle\CoverallsV1Bundle\Config\Configuration;
use Satooshi\Bundle\CoverallsV1Bundle\Entity\JsonFile;
class JobsRepository implements LoggerAwareInterface
{
protected $api;
protected $config;
protected $logger;
public function __construct(Jobs $api, Configuration $config)
{
$this->api = $api;
$this->config = $config;
}
public function persist()
{
try {
$this
->collectCloverXml()
->collectGitInfo()
->collectEnvVars()
->dumpJsonFile()
->send();
} catch (\Satooshi\Bundle\CoverallsV1Bundle\Entity\Exception\RequirementsNotSatisfiedException $e) {
$this->logger->error(sprintf('%s', $e->getHelpMessage()));
} catch (\Exception $e) {
$this->logger->error(sprintf("%s\n\n%s", $e->getMessage(), $e->getTraceAsString()));
}
}
protected function collectCloverXml()
{
$this->logger->info('Load coverage clover log:');
foreach ($this->config->getCloverXmlPaths() as $path) {
$this->logger->info(sprintf(' - %s', $path));
}
$jsonFile = $this->api->collectCloverXml()->getJsonFile();
if ($jsonFile->hasSourceFiles()) {
$this->logCollectedSourceFiles($jsonFile);
}
return $this;
}
protected function collectGitInfo()
{
$this->logger->info('Collect git info');
$this->api->collectGitInfo();
return $this;
}
protected function collectEnvVars()
{
$this->logger->info('Read environment variables');
$this->api->collectEnvVars($_SERVER);
return $this;
}
protected function dumpJsonFile()
{
$jsonPath = $this->config->getJsonPath();
$this->logger->info(sprintf('Dump submitting json file: %s', $jsonPath));
$this->api->dumpJsonFile();
$filesize = number_format(filesize($jsonPath) / 1024, 2);
$this->logger->info(sprintf('File size: <info>%s</info> kB', $filesize));
return $this;
}
protected function send()
{
$this->logger->info(sprintf('Submitting to %s', Jobs::URL));
try {
$response = $this->api->send();
$message = $response
? sprintf('Finish submitting. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase())
: 'Finish dry run';
$this->logger->info($message);
if ($response instanceof Response) {
$this->logResponse($response);
}
return;
} catch (\Guzzle\Http\Exception\CurlException $e) {
$message = sprintf("Connection error occurred. %s\n\n%s", $e->getMessage(), $e->getTraceAsString());
} catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
$response = $e->getResponse();
$message = sprintf('Client error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase());
} catch (\Guzzle\Http\Exception\ServerErrorResponseException $e) {
$response = $e->getResponse();
$message = sprintf('Server error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase());
}
$this->logger->error($message);
if (isset($response)) {
$this->logResponse($response);
}
}
protected function colorizeCoverage($coverage, $format)
{
if ($coverage >= 90) {
return sprintf('<info>%s</info>', $format);
} elseif ($coverage >= 80) {
return sprintf('<comment>%s</comment>', $format);
} else {
return sprintf('<fg=red>%s</fg=red>', $format);
}
}
protected function logCollectedSourceFiles(JsonFile $jsonFile)
{
$sourceFiles = $jsonFile->getSourceFiles();
$numFiles = count($sourceFiles);
$this->logger->info(sprintf('Found <info>%s</info> source file%s:', number_format($numFiles), $numFiles > 1 ? 's' : ''));
foreach ($sourceFiles as $sourceFile) {
$coverage = $sourceFile->reportLineCoverage();
$template = ' - ' . $this->colorizeCoverage($coverage, '%6.2f%%') . ' %s';
$this->logger->info(sprintf($template, $coverage, $sourceFile->getName()));
}
$coverage = $jsonFile->reportLineCoverage();
$template = 'Coverage: ' . $this->colorizeCoverage($coverage, '%6.2f%% (%d/%d)');
$metrics = $jsonFile->getMetrics();
$this->logger->info(sprintf($template, $coverage, $metrics->getCoveredStatements(), $metrics->getStatements()));
}
protected function logResponse(Response $response)
{
$raw_body = $response->getBody(true);
$body = json_decode($raw_body, true);
if ($body === null) {
$this->logger->error($raw_body);
} elseif (isset($body['error'])) {
if (isset($body['message'])) {
$this->logger->error($body['message']);
}
} else {
if (isset($body['message'])) {
$this->logger->info(sprintf('Accepted %s', $body['message']));
}
if (isset($body['url'])) {
$this->logger->info(sprintf('You can see the build on %s', $body['url']));
}
}
}
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle;
final class Version
{
const VERSION = '1.0.1';
}
<?php
namespace Satooshi\Component\File;
class Path
{
public function isRelativePath($path)
{
if (strlen($path) === 0) {
return true;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return !preg_match('/^[a-z]+\:\\\\/i', $path);
}
return strpos($path, DIRECTORY_SEPARATOR) !== 0;
}
public function toAbsolutePath($path, $rootDir)
{
if (!is_string($path)) {
return false;
}
if ($this->isRelativePath($path)) {
return $rootDir . DIRECTORY_SEPARATOR . $path;
}
return $path;
}
public function getRealPath($path, $rootDir)
{
if (!is_string($path)) {
return false;
}
if ($this->isRelativePath($path)) {
return realpath($rootDir . DIRECTORY_SEPARATOR . $path);
}
return realpath($path);
}
public function getRealDir($path, $rootDir)
{
if (!is_string($path)) {
return false;
}
if ($this->isRelativePath($path)) {
return realpath($rootDir . DIRECTORY_SEPARATOR . dirname($path));
}
return realpath(dirname($path));
}
public function getRealWritingFilePath($path, $rootDir)
{
$realDir = $this->getRealDir($path, $rootDir);
if (!is_string($realDir)) {
return false;
}
return $realDir . DIRECTORY_SEPARATOR . basename($path);
}
public function isRealPathExist($realpath)
{
return $realpath !== false && file_exists($realpath);
}
public function isRealFileExist($realpath)
{
return $this->isRealPathExist($realpath) && is_file($realpath);
}
public function isRealFileReadable($realpath)
{
return $this->isRealFileExist($realpath) && is_readable($realpath);
}
public function isRealFileWritable($realpath)
{
return $this->isRealFileExist($realpath) && is_writable($realpath);
}
public function isRealDirExist($realpath)
{
return $this->isRealPathExist($realpath) && is_dir($realpath);
}
public function isRealDirWritable($realpath)
{
return $this->isRealDirExist($realpath) && is_writable($realpath);
}
}
<?php
namespace Satooshi\Component\Log;
use Psr\Log\AbstractLogger;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleLogger extends AbstractLogger
{
protected $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
public function log($level, $message, array $context = array())
{
$this->output->writeln($message);
}
}
<?php
namespace Satooshi\Component\System\Git;
use Satooshi\Component\System\SystemCommand;
class GitCommand extends SystemCommand
{
protected $commandPath = 'git';
public function getBranches()
{
$command = $this->createCommand('branch');
return $this->executeCommand($command);
}
public function getHeadCommit()
{
$command = $this->createCommand("log -1 --pretty=format:'%H%n%aN%n%ae%n%cN%n%ce%n%s'");
return $this->executeCommand($command);
}
public function getRemotes()
{
$command = $this->createCommand('remote -v');
return $this->executeCommand($command);
}
}
<?php
namespace Satooshi\Component\System;
abstract class SystemCommand
{
protected $commandPath;
public function execute()
{
$command = $this->createCommand();
return $this->executeCommand($command);
}
protected function executeCommand($command)
{
exec($command, $result, $returnValue);
if ($returnValue === 0) {
return $result;
}
throw new \RuntimeException(sprintf('Failed to execute command: %s', $command), $returnValue);
}
protected function createCommand($args = null)
{
if ($args === null) {
return $this->commandPath;
}
return sprintf('%s %s', $this->commandPath, $args);
}
public function setCommandPath($commandPath)
{
$this->commandPath = $commandPath;
}
public function getCommandPath()
{
return $this->commandPath;
}
}
<?php
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit9d67f5014a965adc352c6ef25d43195e::getLoader();
<?php
namespace Symfony\CS\Config;
use Symfony\CS\Config as BaseConfig;
class Config extends BaseConfig
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__CLASS__,
'Symfony\CS\Config'
),
E_USER_DEPRECATED
);
parent::__construct();
}
}
<?php
namespace Symfony\CS\Config;
use Symfony\CS\Finder\MagentoFinder;
class MagentoConfig extends Config
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__CLASS__,
'Symfony\CS\Config'
),
E_USER_DEPRECATED
);
parent::__construct();
$this->finder = new MagentoFinder();
}
public function getName()
{
return 'magento';
}
public function getDescription()
{
return 'The configuration for a Magento application';
}
}
<?php
namespace Symfony\CS\Config;
use Symfony\CS\Finder\Symfony23Finder;
class Symfony23Config extends Config
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__CLASS__,
'Symfony\CS\Config'
),
E_USER_DEPRECATED
);
parent::__construct();
$this->finder = new Symfony23Finder();
}
public function getName()
{
return 'sf23';
}
public function getDescription()
{
return 'The configuration for the Symfony 2.3+ branch';
}
}
<?php
namespace Symfony\CS\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\CS\Config\Config;
use Symfony\CS\ConfigInterface;
use Symfony\CS\ConfigurationException\InvalidConfigurationException;
use Symfony\CS\ConfigurationResolver;
use Symfony\CS\ErrorsManager;
use Symfony\CS\Fixer;
use Symfony\CS\FixerFileProcessedEvent;
use Symfony\CS\FixerInterface;
use Symfony\CS\LintManager;
use Symfony\CS\StdinFileInfo;
use Symfony\CS\Utils;
class FixCommand extends Command
{
const EXIT_STATUS_FLAG_HAS_INVALID_CONFIG = 16;
const EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG = 32;
protected $eventDispatcher;
protected $errorsManager;
protected $stopwatch;
protected $fixer;
protected $defaultConfig;
public function __construct(Fixer $fixer = null, ConfigInterface $config = null)
{
$this->defaultConfig = $config ?: new Config();
$this->eventDispatcher = new EventDispatcher();
$this->errorsManager = new ErrorsManager();
$this->stopwatch = new Stopwatch();
$this->fixer = $fixer ?: new Fixer();
$this->fixer->registerBuiltInFixers();
$this->fixer->registerBuiltInConfigs();
$this->fixer->setStopwatch($this->stopwatch);
$this->fixer->setErrorsManager($this->errorsManager);
parent::__construct();
}
protected function configure()
{
$this
->setName('fix')
->setDefinition(
array(
new InputArgument('path', InputArgument::OPTIONAL, 'The path', null),
new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The configuration name', null),
new InputOption('config-file', '', InputOption::VALUE_OPTIONAL, 'The path to a .php_cs file ', null),
new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified'),
new InputOption('level', '', InputOption::VALUE_REQUIRED, 'The level of fixes (can be psr0, psr1, psr2, or symfony (formerly all))', null),
new InputOption('fixers', '', InputOption::VALUE_REQUIRED, 'A list of fixers to run'),
new InputOption('diff', '', InputOption::VALUE_NONE, 'Also produce diff for each file'),
new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats', 'txt'),
)
)
->setDescription('Fixes a directory or a file')
->setHelp(<<<EOF
The <info>%command.name%</info> command tries to fix as much coding standards
problems as possible on a given file or files in a given directory and its subdirectories:
<info>$ php %command.full_name% /path/to/dir</info>
<info>$ php %command.full_name% /path/to/file</info>
The <comment>--format</comment> option for the output format. Supported formats are ``txt`` (default one), ``json`` and ``xml``.
The <comment>--verbose</comment> option will show the applied fixers. When using the ``txt`` format it will also displays progress notifications.
The <comment>--level</comment> option limits the fixers to apply on the
project:
<info>$ php %command.full_name% /path/to/project --level=psr0</info>
<info>$ php %command.full_name% /path/to/project --level=psr1</info>
<info>$ php %command.full_name% /path/to/project --level=psr2</info>
<info>$ php %command.full_name% /path/to/project --level=symfony</info>
By default, all PSR-2 fixers and some additional ones are run. The "contrib
level" fixers cannot be enabled via this option; you should instead set them
manually by their name via the <comment>--fixers</comment> option.
The <comment>--fixers</comment> option lets you choose the exact fixers to
apply (the fixer names must be separated by a comma):
<info>$ php %command.full_name% /path/to/dir --fixers=linefeed,short_tag,indentation</info>
You can also blacklist the fixers you don't want by placing a dash in front of the fixer name, if this is more convenient,
using <comment>-name_of_fixer</comment>:
<info>$ php %command.full_name% /path/to/dir --fixers=-short_tag,-indentation</info>
When using combination with exact and blacklist fixers, apply exact fixers along with above blacklisted result:
<info>$ php php-cs-fixer.phar fix /path/to/dir --fixers=linefeed,-short_tag</info>
A combination of <comment>--dry-run</comment> and <comment>--diff</comment> will
display summary of proposed fixes, leaving your files unchanged.
The command can also read from standard input, in which case it won't
automatically fix anything:
<info>$ cat foo.php | php %command.full_name% --diff -</info>
Choose from the list of available fixers:
{$this->getFixersHelp()}
The <comment>--config</comment> option customizes the files to analyse, based
on some well-known directory structures:
<comment># For the Symfony 2.3+ branch</comment>
<info>$ php %command.full_name% /path/to/sf23 --config=sf23</info>
Choose from the list of available configurations:
{$this->getConfigsHelp()}
The <comment>--dry-run</comment> option displays the files that need to be
fixed but without actually modifying them:
<info>$ php %command.full_name% /path/to/code --dry-run</info>
Instead of using command line options to customize the fixer, you can save the
configuration in a <comment>.php_cs</comment> file in the root directory of
your project. The file must return an instance of
``Symfony\CS\ConfigInterface``, which lets you configure the fixers, the level, the files,
and directories that need to be analyzed. The example below will add two contrib fixers
to the default list of symfony-level fixers:
<?php
\$finder = Symfony\CS\Finder::create()
->exclude('somedir')
->notPath('src/Symfony/Component/Translation/Tests/fixtures/resources.php')
->in(__DIR__)
;
return Symfony\CS\Config::create()
->fixers(array('strict_param', 'short_array_syntax'))
->finder(\$finder)
;
?>
**NOTE**: ``exclude`` will work only for directories, so if you need to exclude file, try ``notPath``.
See `Symfony\\\\Finder <http://symfony.com/doc/current/components/finder.html>`_
online documentation for other `Finder` methods.
If you want complete control over which fixers you use, you may use the empty level and
then specify all fixers to be used:
<?php
\$finder = Symfony\CS\Finder::create()
->in(__DIR__)
;
return Symfony\CS\Config::create()
->level(Symfony\CS\FixerInterface::NONE_LEVEL)
->fixers(array('trailing_spaces', 'encoding'))
->finder(\$finder)
;
?>
You may also use a blacklist for the Fixers instead of the above shown whitelist approach.
The following example shows how to use all ``symfony`` Fixers but the ``psr0`` fixer.
Note the additional <comment>-</comment> in front of the Fixer name.
<?php
\$finder = Symfony\CS\Finder::create()
->exclude('somedir')
->in(__DIR__)
;
return Symfony\CS\Config::create()
->fixers(array('-psr0'))
->finder(\$finder)
;
?>
The ``symfony`` level is set by default, you can also change the default level:
<?php
return Symfony\CS\Config::create()
->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
;
?>
In combination with these config and command line options, you can choose various usage.
For example, default level is ``symfony``, but if you also don't want to use
the ``psr0`` fixer, you can specify the ``--fixers="-psr0"`` option.
But if you use the ``--fixers`` option with only exact fixers,
only those exact fixers are enabled whether or not level is set.
With the <comment>--config-file</comment> option you can specify the path to the
<comment>.php_cs</comment> file.
Caching
-------
You can enable caching by returning a custom config with caching enabled. This will
speed up further runs.
<?php
return Symfony\CS\Config::create()
->setUsingCache(true)
;
?>
Exit codes
----------
* 0 OK
* 1 No changes made
* 16 Configuration error of the application
* 32 Configuration error of a Fixer
EOF
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$stdErr = $output instanceof ConsoleOutputInterface
? $output->getErrorOutput()
: ('txt' === $input->getOption('format') ? $output : null)
;
if (null !== $stdErr && extension_loaded('xdebug')) {
$stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.'));
}
$verbosity = $output->getVerbosity();
$path = $input->getArgument('path');
$stdin = false;
if ('-' === $path) {
$stdin = true;
$input->setOption('dry-run', true);
}
if (null !== $path) {
$filesystem = new Filesystem();
if (!$filesystem->isAbsolutePath($path)) {
$path = getcwd().DIRECTORY_SEPARATOR.$path;
}
}
$configFile = $input->getOption('config-file');
if (null === $configFile) {
$configDir = $path;
if (is_file($path) && $dirName = pathinfo($path, PATHINFO_DIRNAME)) {
$configDir = $dirName;
} elseif ($stdin || null === $path) {
$configDir = getcwd();
}
$configFile = $configDir.DIRECTORY_SEPARATOR.'.php_cs';
}
if ($input->getOption('config')) {
$config = null;
foreach ($this->fixer->getConfigs() as $c) {
if ($c->getName() === $input->getOption('config')) {
$config = $c;
break;
}
}
if (null === $config) {
throw new InvalidConfigurationException(sprintf('The configuration "%s" is not defined.', $input->getOption('config')));
}
} elseif (file_exists($configFile)) {
$config = include $configFile;
if (!$config instanceof ConfigInterface) {
throw new InvalidConfigurationException(sprintf('The config file "%s" does not return a "Symfony\CS\ConfigInterface" instance. Got: "%s".', $configFile, is_object($config) ? get_class($config) : gettype($config)));
}
if (null !== $stdErr && $configFile) {
$stdErr->writeln(sprintf('Loaded config from "%s".', $configFile));
}
} else {
$config = $this->defaultConfig;
}
if (is_file($path)) {
$config->finder(new \ArrayIterator(array(new \SplFileInfo($path))));
} elseif ($stdin) {
$config->finder(new \ArrayIterator(array(new StdinFileInfo())));
} elseif (null !== $path) {
$config->setDir($path);
}
if ($config->usingLinter()) {
$this->fixer->setLintManager(new LintManager());
}
$this->fixer->registerCustomFixers($config->getCustomFixers());
$resolver = new ConfigurationResolver();
$resolver
->setAllFixers($this->fixer->getFixers())
->setConfig($config)
->setOptions(array(
'level' => $input->getOption('level'),
'fixers' => $input->getOption('fixers'),
'progress' => (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) && 'txt' === $input->getOption('format'),
'format' => $input->getOption('format'),
))
->resolve();
$config->fixers($resolver->getFixers());
$showProgress = null !== $stdErr && $resolver->getProgress();
if ($showProgress) {
$fileProcessedEventListener = function (FixerFileProcessedEvent $event) use ($stdErr) {
$stdErr->write($event->getStatusAsString());
};
$this->fixer->setEventDispatcher($this->eventDispatcher);
$this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
}
$isDiff = $input->getOption('diff');
$this->stopwatch->start('fixFiles');
$changed = $this->fixer->fix($config, $input->getOption('dry-run'), $isDiff);
$this->stopwatch->stop('fixFiles');
if ($showProgress) {
$this->fixer->setEventDispatcher(null);
$this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
$stdErr->writeln('');
$legend = array();
foreach (FixerFileProcessedEvent::getStatusMap() as $status) {
if ($status['symbol'] && $status['description']) {
$legend[] = $status['symbol'].'-'.$status['description'];
}
}
$stdErr->writeln('Legend: '.implode(', ', array_unique($legend)));
}
$i = 1;
switch ($resolver->getFormat()) {
case 'txt':
$fixerDetailLine = false;
if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$fixerDetailLine = $output->isDecorated() ? ' (<comment>%s</comment>)' : ' %s';
}
foreach ($changed as $file => $fixResult) {
$output->write(sprintf('%4d) %s', $i++, $file));
if ($fixerDetailLine) {
$output->write(sprintf($fixerDetailLine, implode(', ', $fixResult['appliedFixers'])));
}
if ($isDiff) {
$output->writeln('');
$output->writeln('<comment> ---------- begin diff ----------</comment>');
if ($output->isDecorated()) {
$diff = implode(
PHP_EOL,
array_map(
function ($string) {
$string = preg_replace('/^(\+){3}/', '<info>+++</info>', $string);
$string = preg_replace('/^(\+){1}/', '<info>+</info>', $string);
$string = preg_replace('/^(\-){3}/', '<error>---</error>', $string);
$string = preg_replace('/^(\-){1}/', '<error>-</error>', $string);
$string = str_repeat(' ', 6).$string;
return $string;
},
explode(PHP_EOL, OutputFormatter::escape($fixResult['diff']))
)
);
$output->writeln($diff);
} else {
$output->writeln($fixResult['diff'], OutputInterface::OUTPUT_RAW);
}
$output->writeln('<comment> ---------- end diff ----------</comment>');
}
$output->writeln('');
}
if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
$output->writeln('Fixing time per file:');
foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
if ('__section__' === $file) {
continue;
}
$output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
}
$output->writeln('');
}
$fixEvent = $this->stopwatch->getEvent('fixFiles');
$output->writeln(sprintf('%s all files in %.3f seconds, %.3f MB memory used', $input->getOption('dry-run') ? 'Checked' : 'Fixed', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
break;
case 'xml':
$dom = new \DOMDocument('1.0', 'UTF-8');
$filesXML = $dom->createElement('files');
$dom->appendChild($filesXML);
foreach ($changed as $file => $fixResult) {
$fileXML = $dom->createElement('file');
$fileXML->setAttribute('id', $i++);
$fileXML->setAttribute('name', $file);
$filesXML->appendChild($fileXML);
if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$appliedFixersXML = $dom->createElement('applied_fixers');
$fileXML->appendChild($appliedFixersXML);
foreach ($fixResult['appliedFixers'] as $appliedFixer) {
$appliedFixerXML = $dom->createElement('applied_fixer');
$appliedFixerXML->setAttribute('name', $appliedFixer);
$appliedFixersXML->appendChild($appliedFixerXML);
}
}
if ($isDiff) {
$diffXML = $dom->createElement('diff');
$diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
$fileXML->appendChild($diffXML);
}
}
$dom->formatOutput = true;
$output->write($dom->saveXML(), false, OutputInterface::OUTPUT_RAW);
break;
case 'json':
$jFiles = array();
foreach ($changed as $file => $fixResult) {
$jfile = array('name' => $file);
if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$jfile['appliedFixers'] = $fixResult['appliedFixers'];
}
if ($isDiff) {
$jfile['diff'] = $fixResult['diff'];
}
$jFiles[] = $jfile;
}
$fixEvent = $this->stopwatch->getEvent('fixFiles');
$json = array(
'files' => $jFiles,
'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3),
'time' => array(
'total' => round($fixEvent->getDuration() / 1000, 3),
),
);
if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
$jFileTime = array();
foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
if ('__section__' === $file) {
continue;
}
$jFileTime[$file] = round($event->getDuration() / 1000, 3);
}
$json['time']['files'] = $jFileTime;
}
$output->write(json_encode($json), false, OutputInterface::OUTPUT_RAW);
break;
}
if (null !== $stdErr && !$this->errorsManager->isEmpty()) {
$stdErr->writeln('');
$stdErr->writeln('Files that were not fixed due to internal error:');
foreach ($this->errorsManager->getErrors() as $i => $error) {
$stdErr->writeln(sprintf('%4d) %s', $i + 1, $error['filepath']));
}
}
return 0 === count($changed) ? 0 : 1;
}
protected function getFixersHelp()
{
$help = '';
$fixers = $this->fixer->getFixers();
usort(
$fixers,
function (FixerInterface $a, FixerInterface $b) {
$cmp = Utils::cmpInt($a->getLevel(), $b->getLevel());
if (0 !== $cmp) {
return $cmp;
}
return strcmp($a->getName(), $b->getName());
}
);
$count = count($fixers) - 1;
foreach ($fixers as $i => $fixer) {
$description = str_replace("\n", "\n ", wordwrap($fixer->getDescription(), 72, "\n"));
$help .= sprintf(" * <comment>%s</comment> [%s]\n %s\n", $fixer->getName(), $this->fixer->getLevelAsString($fixer), $description);
if ($count !== $i) {
$help .= "\n";
}
}
return $help;
}
protected function getConfigsHelp()
{
$help = '';
$maxName = 0;
$configs = $this->fixer->getConfigs();
usort(
$configs,
function (ConfigInterface $a, ConfigInterface $b) {
return strcmp($a->getName(), $b->getName());
}
);
foreach ($configs as $config) {
if (strlen($config->getName()) > $maxName) {
$maxName = strlen($config->getName());
}
}
$count = count($this->fixer->getConfigs()) - 1;
foreach ($configs as $i => $config) {
$chunks = explode("\n", wordwrap($config->getDescription(), 72 - $maxName, "\n"));
$help .= sprintf(" * <comment>%s</comment>%s %s\n", $config->getName(), str_repeat(' ', $maxName - strlen($config->getName())), array_shift($chunks));
while ($c = array_shift($chunks)) {
$help .= str_repeat(' ', $maxName + 4).$c."\n";
}
if ($count !== $i) {
$help .= "\n";
}
}
return $help;
}
}
<?php
namespace Symfony\CS\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ReadmeCommand extends Command
{
protected function configure()
{
$this
->setName('readme')
->setDescription('Generates the README content, based on the fix command help')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$header = <<<'EOF'
PHP Coding Standards Fixer
==========================
The PHP Coding Standards Fixer tool fixes *most* issues in your code when you
want to follow the PHP coding standards as defined in the PSR-1 and PSR-2
documents and many more.
If you are already using a linter to identify coding standards problems in your
code, you know that fixing them by hand is tedious, especially on large
projects. This tool does not only detect them, but also fixes them for you.
Requirements
------------
PHP needs to be a minimum version of PHP 5.3.6.
Installation
------------
Locally
~~~~~~~
Download the `php-cs-fixer.phar`_ file and store it somewhere on your computer.
Globally (manual)
~~~~~~~~~~~~~~~~~
You can run these commands to easily access ``php-cs-fixer`` from anywhere on
your system:
.. code-block:: bash
$ wget %download.url% -O php-cs-fixer
or with curl:
.. code-block:: bash
$ curl -L %download.url% -o php-cs-fixer
then:
.. code-block:: bash
$ sudo chmod a+x php-cs-fixer
$ sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer
Then, just run ``php-cs-fixer``.
Globally (Composer)
~~~~~~~~~~~~~~~~~~~
To install PHP CS Fixer, install Composer and issue the following command:
.. code-block:: bash
$ ./composer.phar global require friendsofphp/php-cs-fixer
Please be aware that before v1.12 package name was different:
.. code-block:: bash
$ ./composer.phar global require fabpot/php-cs-fixer
Then make sure you have ``~/.composer/vendor/bin`` in your ``PATH`` and
you're good to go:
.. code-block:: bash
$ export PATH="$PATH:$HOME/.composer/vendor/bin"
Globally (homebrew)
~~~~~~~~~~~~~~~~~~~
PHP-CS-Fixer is part of the homebrew-php project. Follow the installation
instructions at https://github.com/homebrew/homebrew-php if you don't
already have it.
.. code-block:: bash
$ brew install homebrew/php/php-cs-fixer
Update
------
Locally
~~~~~~~
The ``self-update`` command tries to update ``php-cs-fixer`` itself:
.. code-block:: bash
$ php php-cs-fixer.phar self-update
Globally (manual)
~~~~~~~~~~~~~~~~~
You can update ``php-cs-fixer`` through this command:
.. code-block:: bash
$ sudo php-cs-fixer self-update
Globally (Composer)
~~~~~~~~~~~~~~~~~~~
You can update ``php-cs-fixer`` through this command:
.. code-block:: bash
$ ./composer.phar global update friendsofphp/php-cs-fixer
Globally (homebrew)
~~~~~~~~~~~~~~~~~~~
You can update ``php-cs-fixer`` through this command:
.. code-block:: bash
$ brew upgrade php-cs-fixer
Usage
-----
EOF;
$footer = <<<'EOF'
Helpers
-------
Dedicated plugins exist for:
* `Atom`_
* `NetBeans`_
* `PhpStorm`_
* `Sublime Text`_
* `Vim`_
Contribute
----------
The tool comes with quite a few built-in fixers and finders, but everyone is
more than welcome to `contribute`_ more of them.
Fixers
~~~~~~
A *fixer* is a class that tries to fix one CS issue (a ``Fixer`` class must
implement ``FixerInterface``).
Configs
~~~~~~~
A *config* knows about the CS level and the files and directories that must be
scanned by the tool when run in the directory of your project. It is useful for
projects that follow a well-known directory structures (like for Symfony
projects for instance).
.. _php-cs-fixer.phar: %download.url%
.. _Atom: https://github.com/Glavin001/atom-beautify
.. _NetBeans: http://plugins.netbeans.org/plugin/49042/php-cs-fixer
.. _PhpStorm: http://tzfrs.de/2015/01/automatically-format-code-to-match-psr-standards-with-phpstorm
.. _Sublime Text: https://github.com/benmatselby/sublime-phpcs
.. _Vim: https://github.com/stephpy/vim-php-cs-fixer
.. _contribute: https://github.com/FriendsOfPhp/php-cs-fixer/blob/master/CONTRIBUTING.md
EOF;
$downloadUrl = $this->getLatestDownloadUrl();
$command = $this->getApplication()->get('fix');
$help = $command->getHelp();
$help = str_replace('%command.full_name%', 'php-cs-fixer.phar '.$command->getName(), $help);
$help = str_replace('%command.name%', $command->getName(), $help);
$help = preg_replace('#</?(comment|info)>#', '``', $help);
$help = preg_replace('#^(\s+)``(.+)``$#m', '$1$2', $help);
$help = preg_replace('#^ \* ``(.+)``#m', '* **$1**', $help);
$help = preg_replace("#^\n( +)#m", "\n.. code-block:: bash\n\n$1", $help);
$help = preg_replace("#^\.\. code-block:: bash\n\n( +<\?(\w+))#m", ".. code-block:: $2\n\n$1", $help);
$help = preg_replace_callback(
"#^\s*<\?(\w+).*?\?>#ms",
function ($matches) {
$result = preg_replace("#^\.\. code-block:: bash\n\n#m", '', $matches[0]);
if ('php' !== $matches[1]) {
$result = preg_replace("#<\?{$matches[1]}\s*#", '', $result);
}
$result = preg_replace("#\n\n +\?>#", '', $result);
return $result;
},
$help
);
$help = preg_replace('#^ #m', ' ', $help);
$help = preg_replace('#\*\* +\[#', '** [', $help);
$header = str_replace('%download.url%', $downloadUrl, $header);
$footer = str_replace('%download.url%', $downloadUrl, $footer);
$output->write($header."\n".$help."\n".$footer);
}
private function getLatestDownloadUrl()
{
$version = $this->getApplication()->getVersion();
$changelogFile = __DIR__.'/../../../../CHANGELOG.md';
if (is_file($changelogFile)) {
$currentMajor = (int) $version;
$changelog = file_get_contents($changelogFile);
preg_match('/Changelog for v('.$currentMajor.'.\d+.\d+)/', $changelog, $matches);
if (2 !== count($matches)) {
throw new \RuntimeException('Invalid changelog data!');
}
$version = $matches[1];
}
return sprintf(
'https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v%s/php-cs-fixer.phar',
$version
);
}
}
<?php
namespace Symfony\CS\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\CS\ToolInfo;
class SelfUpdateCommand extends Command
{
protected function configure()
{
$this
->setName('self-update')
->setAliases(array('selfupdate'))
->setDescription('Update php-cs-fixer.phar to the latest stable version.')
->setHelp(<<<'EOT'
The <info>%command.name%</info> command replace your php-cs-fixer.phar by the
latest version from cs.sensiolabs.org.
<info>$ php php-cs-fixer.phar %command.name%</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (!ToolInfo::isInstalledAsPhar()) {
$output->writeln('<error>Self-update is available only for PHAR version.</error>');
return 1;
}
$remoteTag = $this->getRemoteTag();
if (null === $remoteTag) {
$output->writeln('<error>Unable to determine newest version.</error>');
return;
}
if ('v'.$this->getApplication()->getVersion() === $remoteTag) {
$output->writeln('<info>php-cs-fixer is already up to date.</info>');
return;
}
$remoteFilename = $this->buildVersionFileUrl($remoteTag);
$localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
$tempFilename = basename($localFilename, '.phar').'-tmp.phar';
try {
$copyResult = @copy($remoteFilename, $tempFilename);
if (false === $copyResult) {
$output->writeln('<error>Unable to download new versions from the server.</error>');
return 1;
}
chmod($tempFilename, 0777 & ~umask());
$phar = new \Phar($tempFilename);
unset($phar);
rename($tempFilename, $localFilename);
$output->writeln('<info>php-cs-fixer updated.</info>');
} catch (\Exception $e) {
if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
throw $e;
}
unlink($tempFilename);
$output->writeln(sprintf('<error>The download is corrupt (%s).</error>', $e->getMessage()));
$output->writeln('<error>Please re-run the self-update command to try again.</error>');
return 1;
}
}
private function buildVersionFileUrl($tag)
{
return sprintf('https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar', $tag);
}
private function getRemoteTag()
{
$raw = file_get_contents(
'https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/releases/latest',
null,
stream_context_create(array(
'http' => array(
'header' => 'User-Agent: FriendsOfPHP/PHP-CS-Fixer',
),
))
);
if (false === $raw) {
return;
}
$json = json_decode($raw, true);
if (null === $json) {
return;
}
return $json['tag_name'];
}
}
<?php
namespace Symfony\CS\Console;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\CS\Console\Command\FixCommand;
use Symfony\CS\Console\Command\ReadmeCommand;
use Symfony\CS\Console\Command\SelfUpdateCommand;
use Symfony\CS\Fixer;
class Application extends BaseApplication
{
public function __construct()
{
error_reporting(-1);
parent::__construct('PHP CS Fixer', Fixer::VERSION);
$this->add(new FixCommand());
$this->add(new ReadmeCommand());
$this->add(new SelfUpdateCommand());
}
public function getLongVersion()
{
$version = parent::getLongVersion().' by <comment>Fabien Potencier</comment> and <comment>Dariusz Ruminski</comment>';
$commit = 'baa7112bef3b86c65fcfaae9a7a50436e3902b41';
if ('@'.'git-commit@' !== $commit) {
$version .= ' ('.substr($commit, 0, 7).')';
}
return $version;
}
}
<?php
namespace Symfony\CS\DocBlock;
class Annotation
{
private static $tags = array(
'method',
'param',
'property',
'property-read',
'property-write',
'return',
'throws',
'type',
'var',
);
private $lines;
private $start;
private $end;
private $tag;
private $typesContent;
public function __construct(array $lines)
{
$this->lines = array_values($lines);
$keys = array_keys($lines);
$this->start = $keys[0];
$this->end = end($keys);
}
public function __toString()
{
return $this->getContent();
}
public static function getTagsWithTypes()
{
return self::$tags;
}
public function getStart()
{
return $this->start;
}
public function getEnd()
{
return $this->end;
}
public function getTag()
{
if (null === $this->tag) {
$values = array_values($this->lines);
$this->tag = new Tag($values[0]->getContent());
}
return $this->tag;
}
public function getTypes()
{
return explode('|', $this->getTypesContent());
}
public function setTypes(array $types)
{
$pattern = '/'.preg_quote($this->getTypesContent()).'/';
$this->lines[0]->setContent(preg_replace($pattern, implode('|', $types), $this->lines[0]->getContent(), 1));
$this->typesContent = null;
}
public function remove()
{
foreach ($this->lines as $line) {
$line->remove();
}
}
public function getContent()
{
return implode($this->lines);
}
private function getTypesContent()
{
if (null === $this->typesContent) {
$name = $this->getTag()->getName();
if (!in_array($name, self::$tags, true)) {
throw new \RuntimeException('This tag does not support types');
}
$tagSplit = preg_split('/\s*\@'.$name.'\s*/', $this->lines[0]->getContent(), 2);
$spaceSplit = preg_split('/\s/', $tagSplit[1], 2);
$this->typesContent = $spaceSplit[0];
}
return $this->typesContent;
}
}
<?php
namespace Symfony\CS\DocBlock;
use Symfony\CS\Utils;
class DocBlock
{
private $lines = array();
private $annotations;
public function __construct($content)
{
foreach (Utils::splitLines($content) as $line) {
$this->lines[] = new Line($line);
}
}
public function __toString()
{
return $this->getContent();
}
public function getLines()
{
return $this->lines;
}
public function getLine($pos)
{
if (isset($this->lines[$pos])) {
return $this->lines[$pos];
}
}
public function getAnnotations()
{
if (null === $this->annotations) {
$this->annotations = array();
$total = count($this->lines);
for ($index = 0; $index < $total; ++$index) {
if ($this->lines[$index]->containsATag()) {
$lines = array_slice($this->lines, $index, $this->findAnnotationLength($index), true);
$annotation = new Annotation($lines);
$index = $annotation->getEnd();
$this->annotations[] = $annotation;
}
}
}
return $this->annotations;
}
public function getAnnotation($pos)
{
$annotations = $this->getAnnotations();
if (isset($annotations[$pos])) {
return $annotations[$pos];
}
}
public function getAnnotationsOfType($types)
{
$annotations = array();
$types = (array) $types;
foreach ($this->getAnnotations() as $annotation) {
$tag = $annotation->getTag()->getName();
foreach ($types as $type) {
if ($type === $tag) {
$annotations[] = $annotation;
}
}
}
return $annotations;
}
public function getContent()
{
return implode($this->lines);
}
private function findAnnotationLength($start)
{
$index = $start;
while ($line = $this->getLine(++$index)) {
if ($line->containsATag()) {
break;
}
if (!$line->containsUsefulContent()) {
$next = $this->getLine($index + 1);
if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) {
break;
}
}
}
return $index - $start;
}
}
<?php
namespace Symfony\CS\DocBlock;
class Line
{
private $content;
public function __construct($content)
{
$this->content = $content;
}
public function __toString()
{
return $this->content;
}
public function getContent()
{
return $this->content;
}
public function containsUsefulContent()
{
return 0 !== preg_match('/\\*\s*\S+/', $this->content) && !$this->isTheStart() && !$this->isTheEnd();
}
public function containsATag()
{
return 0 !== preg_match('/\\*\s*@/', $this->content);
}
public function isTheStart()
{
return false !== strpos($this->content, '/**');
}
public function isTheEnd()
{
return false !== strpos($this->content, '*/');
}
public function setContent($content)
{
$this->content = $content;
}
public function remove()
{
$this->content = '';
}
public function addBlank()
{
preg_match_all('/\ *\*/', $this->content, $matches);
$this->content .= $matches[0][0]."\n";
}
}
<?php
namespace Symfony\CS\DocBlock;
class Tag
{
private static $tags = array(
'api', 'author', 'category', 'copyright', 'deprecated', 'example',
'global', 'internal', 'license', 'link', 'method', 'package', 'param',
'property', 'property-read', 'property-write', 'return', 'see',
'since', 'struct', 'subpackage', 'throws', 'todo', 'typedef', 'uses',
'var', 'version',
);
private $name;
public function __construct($content)
{
$this->name = 'other';
preg_match_all('/@[a-zA-Z0-9_-]+(?=\s|$)/', $content, $matches);
if (isset($matches[0][0])) {
$this->name = ltrim($matches[0][0], '@');
}
}
public function getName()
{
return $this->name;
}
public function valid()
{
return in_array($this->name, self::$tags, true);
}
}
<?php
namespace Symfony\CS\DocBlock;
class TagComparator
{
private static $groups = array(
array('deprecated', 'link', 'see', 'since'),
array('author', 'copyright', 'license'),
array('category', 'package', 'subpackage'),
array('property', 'property-read', 'property-write'),
);
public static function shouldBeTogether(Tag $first, Tag $second)
{
$firstName = $first->getName();
$secondName = $second->getName();
if ($firstName === $secondName) {
return true;
}
foreach (self::$groups as $group) {
if (in_array($firstName, $group, true) && in_array($secondName, $group, true)) {
return true;
}
}
return false;
}
}
<?php
namespace Symfony\CS\Finder;
use Symfony\CS\Finder as BaseFinder;
use Symfony\CS\FinderInterface;
class DefaultFinder extends BaseFinder implements FinderInterface
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__CLASS__,
'Symfony\CS\Finder'
),
E_USER_DEPRECATED
);
parent::__construct();
$files = $this->getFilesToExclude();
$this
->name('*.xml')
->name('*.yml')
->filter(
function (\SplFileInfo $file) use ($files) {
return !in_array($file->getRelativePathname(), $files, true);
}
)
;
}
public function setDir($dir)
{
@trigger_error(
sprintf(
'The "%s" method is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__METHOD__,
'in'
),
E_USER_DEPRECATED
);
$this->in($this->getDirs($dir));
}
protected function getDirs($dir)
{
return array($dir);
}
protected function getFilesToExclude()
{
return array();
}
}
<?php
namespace Symfony\CS\Finder;
class MagentoFinder extends DefaultFinder
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__CLASS__,
'Symfony\CS\Finder'
),
E_USER_DEPRECATED
);
parent::__construct();
$this
->name('*.php')
->name('*.phtml')
->name('*.xml')
->exclude(
array(
'lib',
'shell',
'app/Mage.php',
'app/code/core',
'app/code/community',
'app/design/frontend/default',
'app/design/frontend/enterprise/default',
'app/design/frontend/base',
'app/design/adminhtml/default',
)
)
;
}
public function setDir($dir)
{
$this->in($this->getDirs($dir));
}
protected function getDirs($dir)
{
return array($dir);
}
protected function getFilesToExclude()
{
return array();
}
}
<?php
namespace Symfony\CS\Finder;
class Symfony23Finder extends DefaultFinder
{
public function __construct()
{
@trigger_error(
sprintf(
'The "%s" class is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "%s" instead.',
__CLASS__,
'Symfony\CS\Finder'
),
E_USER_DEPRECATED
);
parent::__construct();
}
protected function getDirs($dir)
{
return array($dir.'/src');
}
protected function getFilesToExclude()
{
return array(
'Symfony/Component/Console/Tests/Fixtures/application_1.xml',
'Symfony/Component/Console/Tests/Fixtures/application_2.xml',
'Symfony/Component/Console/Tests/Helper/TableHelperTest.php',
'Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services1.yml',
'Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services8.yml',
'Symfony/Component/Yaml/Tests/Fixtures/sfTests.yml',
);
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractAlignFixer;
use Symfony\CS\Tokenizer\Tokens;
class AlignDoubleArrowFixer extends AbstractAlignFixer
{
private $currentLevel;
private $deepestLevel;
public function fix(\SplFileInfo $file, $content)
{
$this->currentLevel = 0;
$this->deepestLevel = 0;
$tokens = Tokens::fromCode($content);
$this->injectAlignmentPlaceholders($tokens, 0, count($tokens));
return $this->replacePlaceholder($tokens, $this->deepestLevel);
}
public function getDescription()
{
return 'Align double arrow symbols in consecutive lines.';
}
public function getPriority()
{
return -10;
}
private function injectAlignmentPlaceholders(Tokens $tokens, $startAt, $endAt)
{
for ($index = $startAt; $index < $endAt; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(array(T_FOREACH, T_FOR, T_WHILE, T_IF, T_SWITCH))) {
$index = $tokens->getNextMeaningfulToken($index);
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}
if ($token->isGivenKind(T_ARRAY)) {
$from = $tokens->getNextMeaningfulToken($index);
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $from);
$index = $until;
$this->injectArrayAlignmentPlaceholders($tokens, $from, $until);
continue;
}
if ($tokens->isShortArray($index)) {
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevToken->isGivenKind(array(T_STRING, T_VARIABLE))) {
continue;
}
$from = $index;
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $from);
$index = $until;
$this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1);
continue;
}
if ($token->isGivenKind(T_DOUBLE_ARROW)) {
$tokenContent = sprintf(self::ALIGNABLE_PLACEHOLDER, $this->currentLevel).$token->getContent();
$nextToken = $tokens[$index + 1];
if (!$nextToken->isWhitespace()) {
$tokenContent .= ' ';
} elseif ($nextToken->isWhitespace(array('whitespaces' => " \t"))) {
$nextToken->setContent(' ');
}
$token->setContent($tokenContent);
continue;
}
if ($token->equals(';')) {
++$this->deepestLevel;
++$this->currentLevel;
continue;
}
if ($token->equals(',')) {
for ($i = $index; $i < $endAt - 1; ++$i) {
if (false !== strpos($tokens[$i - 1]->getContent(), "\n")) {
break;
}
if ($tokens->isArray($i + 1)) {
$arrayStartIndex = $tokens[$i + 1]->isGivenKind(T_ARRAY)
? $tokens->getNextMeaningfulToken($i + 1)
: $i + 1
;
$blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]);
$arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex);
if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) {
break;
}
}
++$index;
}
}
}
}
private function injectArrayAlignmentPlaceholders(Tokens $tokens, $from, $until)
{
if ($tokens->isPartialCodeMultiline($from, $until)) {
++$this->deepestLevel;
++$this->currentLevel;
$this->injectAlignmentPlaceholders($tokens, $from, $until);
--$this->currentLevel;
}
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractAlignFixer;
use Symfony\CS\Tokenizer\Tokens;
class AlignEqualsFixer extends AbstractAlignFixer
{
public function fix(\SplFileInfo $file, $content)
{
$data = $this->injectAlignmentPlaceholders($content);
return $this->replacePlaceholder($data['tokens'], $data['deepestLevel']);
}
public function getDescription()
{
return 'Align equals symbols in consecutive lines.';
}
public function getPriority()
{
return -10;
}
private function injectAlignmentPlaceholders($content)
{
$deepestLevel = 0;
$parenCount = 0;
$bracketCount = 0;
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
$tokenContent = $token->getContent();
if (0 === $parenCount && 0 === $bracketCount && $token->equals('=')) {
$token->setContent(sprintf(self::ALIGNABLE_PLACEHOLDER, $deepestLevel).$tokenContent);
continue;
}
if ($token->isGivenKind(T_FUNCTION)) {
++$deepestLevel;
} elseif ($token->equals('(')) {
++$parenCount;
} elseif ($token->equals(')')) {
--$parenCount;
} elseif ($token->equals('[')) {
++$bracketCount;
} elseif ($token->equals(']')) {
--$bracketCount;
}
}
return array(
'tokens' => $tokens,
'deepestLevel' => $deepestLevel,
);
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class ClassKeywordRemoveFixer extends AbstractFixer
{
private $imports = array();
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$this->replaceClassKeywords($tokens);
return $tokens->generateCode();
}
public function getDescription()
{
return 'Converts ::class keywords to FQCN strings.';
}
private function replaceClassKeywords(Tokens $tokens, $namespaceNumber = -1)
{
$namespaceIndexes = array_keys($tokens->findGivenKind(T_NAMESPACE));
if (!empty($namespaceIndexes) && isset($namespaceIndexes[$namespaceNumber])) {
$startIndex = $namespaceIndexes[$namespaceNumber];
$namespaceBlockStartIndex = $tokens->getNextTokenOfKind($startIndex, array(';', '{'));
$endIndex = $tokens[$namespaceBlockStartIndex]->equals('{')
? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $namespaceBlockStartIndex)
: $tokens->getNextTokenOfKind($namespaceBlockStartIndex, array(T_NAMESPACE));
$endIndex = $endIndex ?: $tokens->count() - 1;
} elseif (-1 === $namespaceNumber) {
$startIndex = 0;
$endIndex = !empty($namespaceIndexes) ? $namespaceIndexes[0] : $tokens->count() - 1;
} else {
return;
}
$this->storeImports($tokens, $startIndex, $endIndex);
$tokens->rewind();
$this->replaceClassKeywordsSection($tokens, $startIndex, $endIndex);
$this->replaceClassKeywords($tokens, $namespaceNumber + 1);
}
private function storeImports(Tokens $tokens, $startIndex, $endIndex)
{
$this->imports = array();
foreach ($tokens->getImportUseIndexes() as $index) {
if ($index < $startIndex || $index > $endIndex) {
continue;
}
$import = '';
while (($index = $tokens->getNextMeaningfulToken($index))) {
if ($tokens[$index]->equalsAny(array(';', '{')) || $tokens[$index]->isGivenKind(T_AS)) {
break;
}
$import .= $tokens[$index]->getContent();
}
if ($tokens[$index]->equals('{')) {
$groupEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
$groupImports = array_map(
'trim',
explode(',', $tokens->generatePartialCode($index + 1, $groupEndIndex - 1))
);
foreach ($groupImports as $groupImport) {
$groupImportParts = array_map('trim', explode(' as ', $groupImport));
if (2 === count($groupImportParts)) {
$this->imports[$groupImportParts[1]] = $import.$groupImportParts[0];
} else {
$this->imports[] = $import.$groupImport;
}
}
} elseif ($tokens[$index]->isGivenKind(T_AS)) {
$aliasIndex = $tokens->getNextMeaningfulToken($index);
$alias = $tokens[$aliasIndex]->getContent();
$this->imports[$alias] = $import;
} else {
$this->imports[] = $import;
}
}
}
private function replaceClassKeywordsSection(Tokens $tokens, $startIndex, $endIndex)
{
$CTClassTokens = $tokens->findGivenKind(CT_CLASS_CONSTANT, $startIndex, $endIndex);
if (!empty($CTClassTokens)) {
$this->replaceClassKeyword($tokens, current(array_keys($CTClassTokens)));
$this->replaceClassKeywordsSection($tokens, $startIndex, $endIndex);
}
}
private function replaceClassKeyword(Tokens $tokens, $classIndex)
{
$classEndIndex = $classIndex - 2;
$classBeginIndex = $classEndIndex;
while ($tokens[--$classBeginIndex]->isGivenKind(array(T_NS_SEPARATOR, T_STRING)));
++$classBeginIndex;
$classString = $tokens->generatePartialCode($classBeginIndex, $classEndIndex);
$classImport = false;
foreach ($this->imports as $alias => $import) {
if ($classString === $alias) {
$classImport = $import;
break;
}
$classStringArray = explode('\\', $classString);
$namespaceToTest = $classStringArray[0];
if (0 === strcmp($namespaceToTest, substr($import, -strlen($namespaceToTest)))) {
$classImport = $import;
break;
}
}
$tokens->clearRange($classBeginIndex, $classIndex);
$tokens->insertAt($classBeginIndex, new Token(array(
T_CONSTANT_ENCAPSED_STRING,
"'".$this->makeClassFQN($classImport, $classString)."'",
)));
}
private function makeClassFQN($classImport, $classString)
{
if (false === $classImport) {
return $classString;
}
$classStringArray = explode('\\', $classString);
$classStringLength = count($classStringArray);
$classImportArray = explode('\\', $classImport);
$classImportLength = count($classImportArray);
if (1 === $classStringLength) {
return $classImport;
}
return implode('\\', array_merge(
array_slice($classImportArray, 0, $classImportLength - $classStringLength + 1),
$classStringArray
));
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class CombineConsecutiveUnsetsFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind(T_UNSET)) {
continue;
}
$previousUnsetCall = $this->getPreviousUnsetCall($tokens, $index);
if (is_int($previousUnsetCall)) {
$index = $previousUnsetCall;
continue;
}
list($previousUnset, $previousUnsetBraceStart, $previousUnsetBraceEnd, $previousUnsetSemicolon) = $previousUnsetCall;
$tokensAddCount = $this->moveTokens(
$tokens,
$nextUnsetContentStart = $tokens->getNextTokenOfKind($index, array('(')),
$nextUnsetContentEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextUnsetContentStart),
$previousUnsetBraceEnd - 1
);
if (!$tokens[$previousUnsetBraceEnd]->isWhitespace()) {
$tokens->insertAt($previousUnsetBraceEnd, new Token(array(T_WHITESPACE, ' ')));
++$tokensAddCount;
}
$tokens->insertAt($previousUnsetBraceEnd, new Token(','));
++$tokensAddCount;
$this->clearOffsetTokens($tokens, $tokensAddCount, array($index, $nextUnsetContentStart, $nextUnsetContentEnd));
$nextUnsetSemicolon = $tokens->getNextMeaningfulToken($nextUnsetContentEnd);
if (null !== $nextUnsetSemicolon && $tokens[$nextUnsetSemicolon]->equals(';')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($nextUnsetSemicolon);
}
$index = $previousUnset + 1;
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Calling unset on multiple items should be done in one call.';
}
public function getPriority()
{
return 24;
}
private function clearOffsetTokens(Tokens $tokens, $offset, array $indices)
{
foreach ($indices as $index) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index + $offset);
}
}
private function getPreviousUnsetCall(Tokens $tokens, $index)
{
$previousUnsetSemicolon = $tokens->getPrevMeaningfulToken($index);
if (null === $previousUnsetSemicolon) {
return $index;
}
if (!$tokens[$previousUnsetSemicolon]->equals(';')) {
return $previousUnsetSemicolon;
}
$previousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetSemicolon);
if (null === $previousUnsetBraceEnd) {
return $index;
}
if (!$tokens[$previousUnsetBraceEnd]->equals(')')) {
return $previousUnsetBraceEnd;
}
$previousUnsetBraceStart = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $previousUnsetBraceEnd, false);
$previousUnset = $tokens->getPrevMeaningfulToken($previousUnsetBraceStart);
if (null === $previousUnset) {
return $index;
}
if (!$tokens[$previousUnset]->isGivenKind(T_UNSET)) {
return $previousUnset;
}
return array(
$previousUnset,
$previousUnsetBraceStart,
$previousUnsetBraceEnd,
$previousUnsetSemicolon,
);
}
private function moveTokens(Tokens $tokens, $start, $end, $to)
{
$added = 0;
for ($i = $start + 1; $i < $end; $i += 2) {
if ($tokens[$i]->isWhitespace() && $tokens[$to + 1]->isWhitespace()) {
$tokens[$to + 1]->setContent($tokens[$to + 1]->getContent().$tokens[$i]->getContent());
} else {
$tokens->insertAt(++$to, clone $tokens[$i]);
++$end;
++$added;
}
$tokens[$i + 1]->clear();
}
return $added;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class ConcatWithSpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->equals('.')) {
continue;
}
$this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1);
$this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Concatenation should be used with at least one whitespace around.';
}
public function getPriority()
{
return -10;
}
private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, $index, $offset)
{
$offsetIndex = $index + $offset;
if (!$tokens[$offsetIndex]->isWhitespace()) {
$tokens->insertAt($index + (1 === $offset ?: 0), new Token(array(T_WHITESPACE, ' ')));
return;
}
if (false !== strpos($tokens[$offsetIndex]->getContent(), "\n")) {
return;
}
if ($tokens[$index + $offset * 2]->isComment()) {
return;
}
$tokens[$offsetIndex]->setContent(' ');
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class EchoToPrintFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$echoTokens = $tokens->findGivenKind(T_ECHO);
if (defined('HHVM_VERSION')) {
$echoTokens = array_filter(
$echoTokens,
function (Token $token) {
return 0 !== strpos($token->getContent(), '<?=');
}
);
}
foreach ($echoTokens as $echoIndex => $echoToken) {
$nextTokenIndex = $tokens->getNextMeaningfulToken($echoIndex);
$endTokenIndex = $tokens->getNextTokenOfKind($echoIndex, array(';', array(T_CLOSE_TAG)));
$canBeConverted = true;
for ($i = $nextTokenIndex; $i < $endTokenIndex; ++$i) {
if ($tokens[$i]->equalsAny(array('(', '['))) {
$blockType = $tokens->detectBlockType($tokens[$i]);
$i = $tokens->findBlockEnd($blockType['type'], $i);
}
if ($tokens[$i]->equals(',')) {
$canBeConverted = false;
break;
}
}
if (false === $canBeConverted) {
continue;
}
$tokens->overrideAt($echoIndex, array(T_PRINT, 'print'));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Converts echo language construct to print if possible.';
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class EmptyReturnFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_RETURN) as $index => $token) {
if ($this->needFixing($tokens, $index)) {
$this->clear($tokens, $index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'A return statement wishing to return nothing should be simply "return".';
}
public function getPriority()
{
return -17;
}
private function needFixing(Tokens $tokens, $index)
{
$content = '';
while (!$tokens[$index]->equals(';')) {
$index = $tokens->getNextMeaningfulToken($index);
$content .= $tokens[$index]->getContent();
}
$content = rtrim($content, ';');
$content = ltrim($content, '(');
$content = rtrim($content, ')');
return 'null' === strtolower($content);
}
private function clear(Tokens $tokens, $index)
{
while (!$tokens[++$index]->equals(';')) {
if ($this->shouldClearToken($tokens, $index)) {
$tokens[$index]->clear();
}
}
}
private function shouldClearToken(Tokens $tokens, $index)
{
$token = $tokens[$index];
if ($token->isComment()) {
return false;
}
if ($token->isWhitespace() && $tokens[$index + 1]->isComment()) {
return false;
}
return true;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;
class EregToPregFixer extends AbstractFixer
{
private static $functions = array(
array('ereg', 'preg_match', ''),
array('eregi', 'preg_match', 'i'),
array('ereg_replace', 'preg_replace', ''),
array('eregi_replace', 'preg_replace', 'i'),
array('split', 'preg_split', ''),
array('spliti', 'preg_split', 'i'),
);
private static $delimiters = array('/', '#', '!');
public function fix(\SplFileInfo $file, $content)
{
if (!$this->cursoryMatch($content)) {
return $content;
}
$tokens = Tokens::fromCode($content);
$end = $tokens->count() - 1;
foreach (self::$functions as $map) {
$seq = array(array(T_STRING, $map[0]), '(', array(T_CONSTANT_ENCAPSED_STRING));
$currIndex = 0;
while (null !== $currIndex) {
$match = $tokens->findSequence($seq, $currIndex, $end, false);
if (null === $match) {
break;
}
$match = array_keys($match);
$currIndex = $match[2];
$prev = $tokens->getPrevMeaningfulToken($match[0]);
if (null === $prev || $tokens[$prev]->isGivenKind(array(T_OBJECT_OPERATOR, T_DOUBLE_COLON))) {
continue;
}
$next = $tokens->getNextMeaningfulToken($match[2]);
if (null === $next || !$tokens[$next]->equalsAny(array(',', ')'))) {
continue;
}
$string = substr($tokens[$match[2]]->getContent(), 1, -1);
$quote = substr($tokens[$match[2]]->getContent(), 0, 1);
$delim = $this->getBestDelimiter($string);
$preg = $delim.addcslashes($string, $delim).$delim.'D'.$map[2];
if (!$this->checkPreg($preg)) {
continue;
}
$tokens[$match[2]]->setContent($quote.$preg.$quote);
$tokens[$match[0]]->setContent($map[1]);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Replace deprecated ereg regular expression functions with preg. Warning! This could change code behavior.';
}
private function checkPreg($pattern)
{
return false !== @preg_match($pattern, '');
}
private function getBestDelimiter($pattern)
{
$delimiters = array();
foreach (self::$delimiters as $k => $d) {
if (false === strpos($pattern, $d)) {
return $d;
}
$delimiters[$d] = array(substr_count($pattern, $d), $k);
}
uasort($delimiters, function ($a, $b) {
if ($a[0] === $b[0]) {
return Utils::cmpInt($a, $b);
}
return $a[0] < $b[0] ? -1 : 1;
});
return key($delimiters);
}
private function cursoryMatch($content)
{
return false !== stripos($content, 'ereg') || false !== stripos($content, 'split');
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\ConfigurationException\InvalidFixerConfigurationException;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class HeaderCommentFixer extends AbstractFixer
{
private static $header = '';
private static $headerComment = '';
public static function setHeader($header)
{
if (!is_string($header)) {
throw new InvalidFixerConfigurationException('header_comment', sprintf('Header configuration is invalid. Expected "string", got "%s".', is_object($header) ? get_class($header) : gettype($header)));
}
self::$header = trim((string) $header);
self::$headerComment = '';
if ('' !== self::$header) {
self::$headerComment = self::encloseTextInComment(self::$header);
}
}
public static function getHeader()
{
return self::$header;
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
return $content;
}
$this->removeHeaderComment($tokens);
$insertionIndex = $this->findHeaderCommentInsertionIndex($tokens);
$tokens->clearRange(1, $insertionIndex - 1);
$this->insertHeaderComment($tokens, $insertionIndex);
return $tokens->generateCode();
}
public function getDescription()
{
return 'Add, replace or remove header comment.';
}
private static function encloseTextInComment($header)
{
$comment = "/*\n";
$lines = explode("\n", str_replace("\r", '', $header));
foreach ($lines as $line) {
$comment .= rtrim(' * '.$line)."\n";
}
$comment .= ' */';
return $comment;
}
private function removeHeaderComment(Tokens $tokens)
{
$index = $tokens->getNextNonWhitespace(0);
if (null !== $index && $tokens[$index]->isGivenKind(T_COMMENT)) {
$tokens[$index]->clear();
}
}
private function findHeaderCommentInsertionIndex(Tokens $tokens)
{
$index = $tokens->getNextNonWhitespace(0);
if (null === $index) {
$index = $tokens->getSize();
}
return $index;
}
private function insertHeaderComment(Tokens $tokens, $index)
{
$headCommentTokens = array(
new Token(array(T_WHITESPACE, "\n")),
);
if ('' !== self::$headerComment) {
$headCommentTokens[] = new Token(array(T_COMMENT, self::$headerComment));
$headCommentTokens[] = new Token(array(T_WHITESPACE, "\n\n"));
}
$tokens->insertAt($index, $headCommentTokens);
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class LogicalNotOperatorsWithSpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($tokens->isUnaryPredecessorOperator($index) && $token->equals('!')) {
if (!$tokens[$index + 1]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
}
if (!$tokens[$index - 1]->isWhitespace()) {
$tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Logical NOT operators (!) should have leading and trailing whitespaces.';
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class LogicalNotOperatorsWithSuccessorSpaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($tokens->isUnaryPredecessorOperator($index) && $token->equals('!')) {
if (!$tokens[$index + 1]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
} else {
$tokens[$index + 1]->setContent(' ');
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Logical NOT operators (!) should have one trailing whitespace.';
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class LongArraySyntaxFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
if (!$tokens->isShortArray($index)) {
continue;
}
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $index);
$tokens->overrideAt($index, '(');
$tokens->overrideAt($closeIndex, ')');
$tokens->insertAt($index, new Token(array(T_ARRAY, 'array')));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Arrays should use the long syntax.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class MbStrFunctionsFixer extends AbstractFixer
{
private static $functions = array(
'strlen' => 'mb_strlen',
'strpos' => 'mb_strpos',
'strrpos' => 'mb_strrpos',
'substr' => 'mb_substr',
'strtolower' => 'mb_strtolower',
'strtoupper' => 'mb_strtoupper',
'stripos' => 'mb_stripos',
'strripos' => 'mb_strripos',
'strstr' => 'mb_strstr',
'stristr' => 'mb_stristr',
'strrchr' => 'mb_strrchr',
'substr_count' => 'mb_substr_count',
);
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$end = $tokens->count() - 1;
foreach (self::$functions as $originalName => $mbFunctionName) {
$seq = array(array(T_STRING, $originalName), '(');
$currIndex = 0;
while (null !== $currIndex) {
$match = $tokens->findSequence($seq, $currIndex, $end, false);
if (null === $match) {
break;
}
$match = array_keys($match);
$currIndex = $match[1];
$prev = $tokens->getPrevMeaningfulToken($match[0]);
if (null === $prev || $tokens[$prev]->isGivenKind(array(T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_NEW))) {
continue;
}
if ($tokens[$prev]->isGivenKind(T_NS_SEPARATOR)) {
$nsPrev = $tokens->getPrevMeaningfulToken($prev);
if ($tokens[$nsPrev]->isGivenKind(array(T_STRING, T_NEW))) {
continue;
}
}
$tokens[$match[0]]->setContent($mbFunctionName);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Replace non multibyte-safe functions with corresponding mb function. Warning! This could change code behavior.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class MultilineSpacesBeforeSemicolonFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->equals(';')) {
continue;
}
$previous = $tokens[$index - 1];
if ($previous->isWhitespace() && false !== strpos($previous->getContent(), "\n")) {
$previous->clear();
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Multi-line whitespace before closing semicolon are prohibited.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class NewlineAfterOpenTagFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
return $content;
}
$newlineFound = false;
foreach ($tokens as $token) {
if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) {
$newlineFound = true;
break;
}
}
if (!$newlineFound) {
return $content;
}
$token = $tokens[0];
$token->setContent(rtrim($token->getContent())."\n");
return $tokens->generateCode();
}
public function getDescription()
{
return 'Ensure there is no code on the same line as the PHP open tag.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractLinesBeforeNamespaceFixer;
use Symfony\CS\Tokenizer\Tokens;
class NoBlankLinesBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_NAMESPACE)) {
$this->fixLinesBeforeNamespace($tokens, $index, 1);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should be no blank lines before a namespace declaration.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NoUselessElseFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_ELSE)) {
continue;
}
if ($tokens[$tokens->getNextMeaningfulToken($index)]->equalsAny(array(':', array(T_IF)))) {
continue;
}
$this->fixEmptyElse($tokens, $index);
if ($token->isEmpty()) {
continue;
}
$this->fixElse($tokens, $index);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should not be useless else cases.';
}
public function getPriority()
{
return 25;
}
private function fixElse(Tokens $tokens, $index)
{
$previousBlockStart = $index;
do {
list($previousBlockStart, $previousBlockEnd) = $this->getPreviousBlock($tokens, $previousBlockStart);
$previous = $previousBlockEnd;
if ($tokens[$previous]->equals('}')) {
$previous = $tokens->getPrevMeaningfulToken($previous);
}
if (
!$tokens[$previous]->equals(';') ||
$tokens[$tokens->getPrevMeaningfulToken($previous)]->equals('{')
) {
return;
}
$candidateIndex = $tokens->getTokenOfKindSibling(
$previous,
-1,
array(
';',
array(T_CLOSE_TAG),
array(T_BREAK),
array(T_CONTINUE),
array(T_EXIT),
array(T_GOTO),
array(T_RETURN),
array(T_THROW),
)
);
if (
null === $candidateIndex ||
$tokens[$candidateIndex]->equals(';') ||
$tokens[$candidateIndex]->isGivenKind(T_CLOSE_TAG) ||
$this->isInConditional($tokens, $candidateIndex, $previousBlockStart)
) {
return;
}
} while (!$tokens[$previousBlockStart]->isGivenKind(T_IF));
$this->clearElse($tokens, $index);
}
private function getPreviousBlock(Tokens $tokens, $index)
{
$close = $previous = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$close]->equals('}')) {
$previous = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $close, false);
}
$open = $tokens->getPrevTokenOfKind($previous, array(array(T_IF), array(T_ELSE), array(T_ELSEIF)));
if ($tokens[$open]->isGivenKind(T_IF)) {
$elseCandidate = $tokens->getPrevMeaningfulToken($open);
if ($tokens[$elseCandidate]->isGivenKind(T_ELSE)) {
$open = $elseCandidate;
}
}
return array($open, $close);
}
private function fixEmptyElse(Tokens $tokens, $index)
{
$next = $tokens->getNextMeaningfulToken($index);
if ($tokens[$next]->equals('{')) {
$close = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next);
if (1 === $close - $next) {
$this->clearElse($tokens, $index);
} elseif ($tokens->getNextMeaningfulToken($next) === $close) {
$this->clearElse($tokens, $index);
}
return;
}
$end = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
if ($next === $end) {
$this->clearElse($tokens, $index);
}
}
private function clearElse(Tokens $tokens, $index)
{
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
$next = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$next]->equals('{')) {
return;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next));
$tokens->clearTokenAndMergeSurroundingWhitespace($next);
}
private function isInConditional(Tokens $tokens, $index, $lowerLimitIndex)
{
$candidateIndex = $tokens->getTokenOfKindSibling($index, -1, array(')', ';', ':'));
if ($tokens[$candidateIndex]->equals(':')) {
return true;
}
if (!$tokens[$candidateIndex]->equals(')')) {
return false;
}
$open = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $candidateIndex, false);
return $tokens->getPrevMeaningfulToken($open) > $lowerLimitIndex;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NoUselessReturnFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_FUNCTION)) {
continue;
}
$index = $tokens->getNextTokenOfKind($index, array(';', '{'));
if ($tokens[$index]->equals('{')) {
$this->fixFunction($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should not be an empty return statement at the end of a function.';
}
public function getPriority()
{
return -18;
}
private function fixFunction(Tokens $tokens, $start, $end)
{
for ($index = $end; $index > $start; --$index) {
if (!$tokens[$index]->isGivenKind(T_RETURN)) {
continue;
}
$nextAt = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$nextAt]->equals(';')) {
continue;
}
if ($tokens->getNextMeaningfulToken($nextAt) !== $end) {
continue;
}
$previous = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$previous]->equalsAny(array(array(T_ELSE), ')'))) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
$tokens->clearTokenAndMergeSurroundingWhitespace($nextAt);
}
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class OrderedUseFixer extends AbstractFixer
{
const IMPORT_TYPE_CLASS = 1;
const IMPORT_TYPE_CONST = 2;
const IMPORT_TYPE_FUNCTION = 3;
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$namespacesImports = $tokens->getImportUseIndexes(true);
if (0 === count($namespacesImports)) {
return $content;
}
$usesOrder = array();
foreach ($namespacesImports as $uses) {
$usesOrder = array_replace($usesOrder, $this->getNewOrder(array_reverse($uses), $tokens));
}
foreach ($usesOrder as $use) {
$tokens->clearRange($use['startIndex'], $use['endIndex']);
}
$usesOrder = array_reverse($usesOrder, true);
foreach ($usesOrder as $index => $use) {
$declarationTokens = Tokens::fromCode('<?php use '.$use['namespace'].';');
$declarationTokens->clearRange(0, 2);
$declarationTokens[count($declarationTokens) - 1]->clear();
$declarationTokens->clearEmptyTokens();
$tokens->insertAt($index, $declarationTokens);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Ordering use statements.';
}
public function getPriority()
{
return -30;
}
public static function sortingCallBack(array $first, array $second)
{
if ($first['importType'] !== $second['importType']) {
return $first['importType'] > $second['importType'] ? 1 : -1;
}
$firstNamespace = trim(preg_replace('%/\*(.*)\*/%s', '', $first['namespace']));
$secondNamespace = trim(preg_replace('%/\*(.*)\*/%s', '', $second['namespace']));
$firstNamespace = str_replace('\\', ' ', $firstNamespace);
$secondNamespace = str_replace('\\', ' ', $secondNamespace);
return strcasecmp($firstNamespace, $secondNamespace);
}
private function getNewOrder(array $uses, Tokens $tokens)
{
$uses = array_reverse($uses);
$indexes = array();
$originalIndexes = array();
foreach ($uses as $index) {
$startIndex = $tokens->getTokenNotOfKindSibling($index + 1, 1, array(array(T_WHITESPACE)));
$endIndex = $tokens->getNextTokenOfKind($startIndex, array(';', array(T_CLOSE_TAG)));
$previous = $tokens->getPrevMeaningfulToken($endIndex);
$group = $tokens[$previous]->equals('}');
if ($tokens[$startIndex]->isGivenKind(array(T_CONST))) {
$type = self::IMPORT_TYPE_CONST;
} elseif ($tokens[$startIndex]->isGivenKind(array(T_FUNCTION))) {
$type = self::IMPORT_TYPE_FUNCTION;
} else {
$type = self::IMPORT_TYPE_CLASS;
}
$namespace = '';
$index = $startIndex;
while ($index <= $endIndex) {
$token = $tokens[$index];
if ($index === $endIndex || (!$group && $token->equals(','))) {
$indexes[$startIndex] = array(
'namespace' => $namespace,
'startIndex' => $startIndex,
'endIndex' => $index - 1,
'importType' => $type,
);
$originalIndexes[] = $startIndex;
if ($index === $endIndex) {
break;
}
$namespace = '';
$nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, array(array(','), array(T_WHITESPACE)));
$startIndex = $nextPartIndex;
$index = $nextPartIndex;
continue;
}
$namespace .= $token->getContent();
++$index;
}
}
uasort($indexes, 'self::sortingCallBack');
$index = -1;
$usesOrder = array();
foreach ($indexes as $v) {
$usesOrder[$originalIndexes[++$index]] = $v;
}
return $usesOrder;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class Php4ConstructorFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$classes = array_keys($tokens->findGivenKind(T_CLASS));
$numClasses = count($classes);
for ($i = 0; $i < $numClasses; ++$i) {
$index = $classes[$i];
if ($tokens->isAnonymousClass($index)) {
continue;
}
$nspIndex = $tokens->getPrevTokenOfKind($index, array(array(T_NAMESPACE, 'namespace')));
if (null !== $nspIndex) {
$nspIndex = $tokens->getNextMeaningfulToken($nspIndex);
if (!$tokens[$nspIndex]->equals('{')) {
$nspIndex = $tokens->getNextTokenOfKind($nspIndex, array(';', '{'));
if ($tokens[$nspIndex]->equals(';')) {
break;
}
$nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nspIndex);
if ($index < $nspEnd) {
for ($j = $i + 1; $j < $numClasses; ++$j) {
if ($classes[$j] < $nspEnd) {
++$i;
}
}
continue;
}
}
}
$classNameIndex = $tokens->getNextMeaningfulToken($index);
$className = $tokens[$classNameIndex]->getContent();
$classStart = $tokens->getNextTokenOfKind($classNameIndex, array('{'));
$classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart);
$this->fixConstructor($tokens, $className, $classStart, $classEnd);
$this->fixParent($tokens, $classStart, $classEnd);
}
return $tokens->generateCode();
}
public function getName()
{
return 'php4_constructor';
}
public function getDescription()
{
return 'Convert PHP4-style constructors to __construct. Warning! This could change code behavior.';
}
private function fixConstructor(Tokens $tokens, $className, $classStart, $classEnd)
{
$php4 = $this->findFunction($tokens, $className, $classStart, $classEnd);
if (null === $php4) {
return;
}
if (!empty($php4['modifiers'][T_ABSTRACT]) || !empty($php4['modifiers'][T_STATIC])) {
return;
}
$php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd);
if (null === $php5) {
$tokens[$php4['nameIndex']]->setContent('__construct');
$this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']);
return;
}
list($seq, $case) = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']);
if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) {
for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) {
$tokens[$i]->clear();
}
return;
}
list($seq, $case) = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']);
if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) {
for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) {
$tokens[$i]->clear();
}
$tokens[$php4['nameIndex']]->setContent('__construct');
}
}
private function fixParent(Tokens $tokens, $classStart, $classEnd)
{
foreach ($tokens->findGivenKind(T_EXTENDS) as $index => $token) {
$parentIndex = $tokens->getNextMeaningfulToken($index);
$parentClass = $tokens[$parentIndex]->getContent();
$parentSeq = $tokens->findSequence(array(
array(T_STRING),
array(T_DOUBLE_COLON),
array(T_STRING, $parentClass),
'(',
), $classStart, $classEnd, array(2 => false));
if (null !== $parentSeq) {
$parentSeq = array_keys($parentSeq);
if ($tokens[$parentSeq[0]]->equalsAny(array(array(T_STRING, 'parent'), array(T_STRING, $parentClass)), false)) {
$tokens[$parentSeq[0]]->setContent('parent');
$tokens[$parentSeq[2]]->setContent('__construct');
}
}
$parentSeq = $tokens->findSequence(array(
array(T_VARIABLE, '$this'),
array(T_OBJECT_OPERATOR),
array(T_STRING, $parentClass),
'(',
), $classStart, $classEnd, array(2 => false));
if (null !== $parentSeq) {
$parentSeq = array_keys($parentSeq);
$tokens[$parentSeq[0]] = new Token(array(
T_STRING,
'parent',
$tokens[$parentSeq[0]]->getLine(),
));
$tokens[$parentSeq[1]] = new Token(array(
T_DOUBLE_COLON,
'::',
$tokens[$parentSeq[1]]->getLine(),
));
$tokens[$parentSeq[2]]->setContent('__construct');
}
}
}
private function fixInfiniteRecursion(Tokens $tokens, $start, $end)
{
$seq = array(
array(T_VARIABLE, '$this'),
array(T_OBJECT_OPERATOR),
array(T_STRING, '__construct'),
);
while (true) {
$callSeq = $tokens->findSequence($seq, $start, $end, array(2 => false));
if (null === $callSeq) {
return;
}
$callSeq = array_keys($callSeq);
$tokens[$callSeq[0]] = new Token(array(
T_STRING,
'parent',
$tokens[$callSeq[0]]->getLine(),
));
$tokens[$callSeq[1]] = new Token(array(
T_DOUBLE_COLON,
'::',
$tokens[$callSeq[1]]->getLine(),
));
}
}
private function getWrapperMethodSequence(Tokens $tokens, $method, $startIndex, $bodyIndex)
{
$seq = array(
'{',
array(T_VARIABLE, '$this'),
array(T_OBJECT_OPERATOR),
array(T_STRING, $method),
'(',
);
$case = array(3 => false);
$index = $startIndex;
while (true) {
$index = $tokens->getNextTokenOfKind($index, array(array(T_VARIABLE)));
if (null === $index || $index >= $bodyIndex) {
break;
}
if (count($seq) > 5) {
$seq[] = ',';
}
$seq[] = array(T_VARIABLE, $tokens[$index]->getContent());
}
$seq[] = ')';
$seq[] = ';';
$seq[] = '}';
return array($seq, $case);
}
private function findFunction(Tokens $tokens, $name, $startIndex, $endIndex)
{
$function = $tokens->findSequence(array(
array(T_FUNCTION),
array(T_STRING, $name),
'(',
), $startIndex, $endIndex, false);
if (null === $function) {
return;
}
$function = array_keys($function);
$possibleModifiers = array(T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_ABSTRACT, T_FINAL);
$modifiers = array();
$prevBlock = $tokens->getPrevMeaningfulToken($function[0]);
while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) {
$modifiers[$tokens[$prevBlock]->getId()] = $prevBlock;
$prevBlock = $tokens->getPrevMeaningfulToken($prevBlock);
}
if (isset($modifiers[T_ABSTRACT])) {
$bodyStart = null;
$funcEnd = $tokens->getNextTokenOfKind($function[2], array(';'));
} else {
$bodyStart = $tokens->getNextTokenOfKind($function[2], array('{'));
$funcEnd = $bodyStart !== null ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStart) : null;
}
return array(
'nameIndex' => $function[1],
'startIndex' => $prevBlock + 1,
'endIndex' => $funcEnd,
'bodyIndex' => $bodyStart,
'modifiers' => $modifiers,
);
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\ConfigurationException\InvalidFixerConfigurationException;
use Symfony\CS\Tokenizer\Tokens;
final class PhpUnitConstructFixer extends AbstractFixer
{
private $configuration = array(
'assertSame' => true,
'assertEquals' => true,
'assertNotEquals' => true,
'assertNotSame' => true,
);
private $assertionFixers = array(
'assertSame' => 'fixAssertPositive',
'assertEquals' => 'fixAssertPositive',
'assertNotEquals' => 'fixAssertNegative',
'assertNotSame' => 'fixAssertNegative',
);
public function configure(array $usingMethods)
{
foreach ($usingMethods as $method => $fix) {
if (!array_key_exists($method, $this->configuration)) {
throw new InvalidFixerConfigurationException($this->getName(), sprintf('Configured method "%s" cannot be fixed by this fixer.', $method));
}
$this->configuration[$method] = $fix;
}
}
public function fix(\SplFileInfo $file, $content)
{
if (!in_array(true, $this->configuration, true)) {
return $content;
}
$tokens = Tokens::fromCode($content);
foreach ($this->configuration as $assertionMethod => $assertionShouldBeFixed) {
if (true !== $assertionShouldBeFixed) {
continue;
}
$assertionFixer = $this->assertionFixers[$assertionMethod];
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$index = $this->$assertionFixer($tokens, $index, $assertionMethod);
if (null === $index) {
break;
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHPUnit assertion method calls like "->assertSame(true, $foo)" should be written with dedicated method like "->assertTrue($foo)". Warning! This could change code behavior.';
}
public function getPriority()
{
return -10;
}
private function fixAssertNegative(Tokens $tokens, $index, $method)
{
static $map = array(
'false' => 'assertNotFalse',
'null' => 'assertNotNull',
'true' => 'assertNotTrue',
);
return $this->fixAssert($map, $tokens, $index, $method);
}
private function fixAssertPositive(Tokens $tokens, $index, $method)
{
static $map = array(
'false' => 'assertFalse',
'null' => 'assertNull',
'true' => 'assertTrue',
);
return $this->fixAssert($map, $tokens, $index, $method);
}
private function fixAssert(array $map, Tokens $tokens, $index, $method)
{
$sequence = $tokens->findSequence(
array(
array(T_VARIABLE, '$this'),
array(T_OBJECT_OPERATOR, '->'),
array(T_STRING, $method),
'(',
),
$index
);
if (null === $sequence) {
return;
}
$sequenceIndexes = array_keys($sequence);
$sequenceIndexes[4] = $tokens->getNextMeaningfulToken($sequenceIndexes[3]);
$firstParameterToken = $tokens[$sequenceIndexes[4]];
if (!$firstParameterToken->isNativeConstant()) {
return;
}
$sequenceIndexes[5] = $tokens->getNextMeaningfulToken($sequenceIndexes[4]);
if (!$tokens[$sequenceIndexes[5]]->equals(',')) {
return;
}
$tokens[$sequenceIndexes[2]]->setContent($map[$firstParameterToken->getContent()]);
$tokens->clearRange($sequenceIndexes[4], $tokens->getNextNonWhitespace($sequenceIndexes[5]) - 1);
return $sequenceIndexes[5];
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\ConfigurationException\InvalidFixerConfigurationException;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class PhpUnitDedicateAssertFixer extends AbstractFixer
{
private $fixMap = array(
'array_key_exists' => array('assertArrayNotHasKey', 'assertArrayHasKey'),
'empty' => array('assertNotEmpty', 'assertEmpty'),
'file_exists' => array('assertFileNotExists', 'assertFileExists'),
'is_infinite' => array('assertFinite', 'assertInfinite'),
'is_nan' => array(false, 'assertNan'),
'is_null' => array('assertNotNull', 'assertNull'),
'is_array' => true,
'is_bool' => true,
'is_boolean' => true,
'is_callable' => true,
'is_double' => true,
'is_float' => true,
'is_int' => true,
'is_integer' => true,
'is_long' => true,
'is_â€numeric' => true,
'is_object' => true,
'is_real' => true,
'is_â€resource' => true,
'is_scalar' => true,
'is_string' => true,
);
private $configuration = array(
'array_key_exists',
'empty',
'file_exists',
'is_infinite',
'is_nan',
'is_null',
'is_array',
'is_bool',
'is_boolean',
'is_callable',
'is_double',
'is_float',
'is_int',
'is_integer',
'is_long',
'is_â€numeric',
'is_object',
'is_real',
'is_â€resource',
'is_scalar',
'is_string',
);
public function configure(array $configuration = null)
{
if (null === $configuration) {
return;
}
$this->configuration = array();
foreach ($configuration as $method) {
if (!array_key_exists($method, $this->fixMap)) {
throw new InvalidFixerConfigurationException($this->getName(), sprintf('Unknown configuration method "%s".', $method));
}
$this->configuration[] = $method;
}
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
static $searchSequence = array(
array(T_VARIABLE, '$this'),
array(T_OBJECT_OPERATOR, '->'),
array(T_STRING),
);
$index = 1;
$candidate = $tokens->findSequence($searchSequence, $index);
while (null !== $candidate) {
end($candidate);
$index = $this->getAssertCandidate($tokens, key($candidate));
if (is_array($index)) {
$index = $this->fixAssert($tokens, $index);
}
++$index;
$candidate = $tokens->findSequence($searchSequence, $index);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHPUnit assertions like "assertInternalType", "assertFileExists", should be used over "assertTrue". Warning! This could change code behavior.';
}
public function getPriority()
{
return -15;
}
private function getAssertCandidate(Tokens $tokens, $assertCallIndex)
{
$content = strtolower($tokens[$assertCallIndex]->getContent());
if ('asserttrue' === $content) {
$isPositive = 1;
} elseif ('assertfalse' === $content) {
$isPositive = 0;
} else {
return $assertCallIndex;
}
$assertCallOpenIndex = $tokens->getNextMeaningfulToken($assertCallIndex);
if (!$tokens[$assertCallOpenIndex]->equals('(')) {
return $assertCallIndex;
}
$testDefaultNamespaceTokenIndex = false;
$testIndex = $tokens->getNextMeaningfulToken($assertCallOpenIndex);
if (!$tokens[$testIndex]->isGivenKind(array(T_EMPTY, T_STRING))) {
if (!$tokens[$testIndex]->isGivenKind(T_NS_SEPARATOR)) {
return $testIndex;
}
$testDefaultNamespaceTokenIndex = $testIndex;
$testIndex = $tokens->getNextMeaningfulToken($testIndex);
}
$testOpenIndex = $tokens->getNextMeaningfulToken($testIndex);
if (!$tokens[$testOpenIndex]->equals('(')) {
return $testOpenIndex;
}
$testCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $testOpenIndex);
$assertCallCloseIndex = $tokens->getNextMeaningfulToken($testCloseIndex);
if (!$tokens[$assertCallCloseIndex]->equalsAny(array(')', ','))) {
return $assertCallCloseIndex;
}
return array(
$isPositive,
$assertCallIndex,
$assertCallOpenIndex,
$testDefaultNamespaceTokenIndex,
$testIndex,
$testOpenIndex,
$testCloseIndex,
$assertCallCloseIndex,
);
}
private function fixAssert(Tokens $tokens, array $assertIndexes)
{
list(
$isPositive,
$assertCallIndex,
$assertCallOpenIndex,
$testDefaultNamespaceTokenIndex,
$testIndex,
$testOpenIndex,
$testCloseIndex,
$assertCallCloseIndex
) = $assertIndexes;
$content = strtolower($tokens[$testIndex]->getContent());
if (!in_array($content, $this->configuration, true)) {
return $assertCallCloseIndex;
}
if (is_array($this->fixMap[$content])) {
if (false !== $this->fixMap[$content][$isPositive]) {
$tokens[$assertCallIndex]->setContent($this->fixMap[$content][$isPositive]);
$this->removeFunctionCall($tokens, $testDefaultNamespaceTokenIndex, $testIndex, $testOpenIndex, $testCloseIndex);
}
return $assertCallCloseIndex;
}
$type = substr($content, 3);
$tokens[$assertCallIndex]->setContent($isPositive ? 'assertInternalType' : 'assertNotInternalType');
$tokens->overrideAt($testIndex, array(T_CONSTANT_ENCAPSED_STRING, "'".$type."'", $tokens[$testIndex]->getLine()));
$tokens->overrideAt($testOpenIndex, ',');
$tokens->clearTokenAndMergeSurroundingWhitespace($testCloseIndex);
if (!$tokens[$testOpenIndex + 1]->isWhitespace()) {
$tokens->insertAt($testOpenIndex + 1, new Token(array(T_WHITESPACE, ' ')));
}
if (false !== $testDefaultNamespaceTokenIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($testDefaultNamespaceTokenIndex);
}
return $assertCallCloseIndex;
}
private function removeFunctionCall(Tokens $tokens, $callNSIndex, $callIndex, $openIndex, $closeIndex)
{
$tokens->clearTokenAndMergeSurroundingWhitespace($callIndex);
if (false !== $callNSIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($callNSIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($openIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex);
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class PhpUnitStrictFixer extends AbstractFixer
{
private $configuration = array(
'assertAttributeEquals' => 'assertAttributeSame',
'assertAttributeNotEquals' => 'assertAttributeNotSame',
'assertEquals' => 'assertSame',
'assertNotEquals' => 'assertNotSame',
);
public function configure(array $usingMethods)
{
foreach (array_keys($this->configuration) as $method) {
if (!in_array($method, $usingMethods, true)) {
unset($this->configuration[$method]);
}
}
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($this->configuration as $methodBefore => $methodAfter) {
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$sequence = $tokens->findSequence(
array(
array(T_VARIABLE, '$this'),
array(T_OBJECT_OPERATOR, '->'),
array(T_STRING, $methodBefore),
'(',
),
$index
);
if (null === $sequence) {
break;
}
$sequenceIndexes = array_keys($sequence);
$tokens[$sequenceIndexes[2]]->setContent($methodAfter);
$index = $sequenceIndexes[3];
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHPUnit methods like "assertSame" should be used instead of "assertEquals". Warning! This could change code behavior.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocOrderFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$content = $token->getContent();
$content = $this->moveParamAnnotations($content);
$content = $this->moveReturnAnnotations($content);
$token->setContent($content);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Annotations in phpdocs should be ordered so that param annotations come first, then throws annotations, then return annotations.';
}
public function getPriority()
{
return 5;
}
private function moveParamAnnotations($content)
{
$doc = new DocBlock($content);
$params = $doc->getAnnotationsOfType('param');
if (empty($params)) {
return $content;
}
$others = $doc->getAnnotationsOfType(array('throws', 'return'));
if (empty($others)) {
return $content;
}
$end = end($params)->getEnd();
$line = $doc->getLine($end);
foreach ($others as $other) {
if ($other->getStart() < $end) {
$line->setContent($line->getContent().$other->getContent());
$other->remove();
}
}
return $doc->getContent();
}
private function moveReturnAnnotations($content)
{
$doc = new DocBlock($content);
$returns = $doc->getAnnotationsOfType('return');
if (empty($returns)) {
return $content;
}
$others = $doc->getAnnotationsOfType(array('param', 'throws'));
if (empty($others)) {
return $content;
}
$start = $returns[0]->getStart();
$line = $doc->getLine($start);
foreach (array_reverse($others) as $other) {
if ($other->getEnd() > $start) {
$line->setContent($other->getContent().$line->getContent());
$other->remove();
}
}
return $doc->getContent();
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocVarToTypeFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotationsOfType('var');
if (empty($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
$line = $doc->getLine($annotation->getStart());
$line->setContent(str_replace('@var', '@type', $line->getContent()));
}
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return '@var should always be written as @type.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ShortArraySyntaxFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_ARRAY) as $index => $token) {
$openIndex = $tokens->getNextTokenOfKind($index, array('('));
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$tokens->overrideAt($openIndex, '[');
$tokens->overrideAt($closeIndex, ']');
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHP arrays should use the PHP 5.4 short-syntax.';
}
public function getPriority()
{
return 1;
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class ShortEchoTagFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$i = count($tokens);
while ($i--) {
$token = $tokens[$i];
$nextIndex = $i + 1;
if (
!$token->isGivenKind(T_OPEN_TAG_WITH_ECHO)
&& !(
defined('HHVM_VERSION')
&& $token->equals(array(T_ECHO, '<?='))
)
) {
continue;
}
$tokens->overrideAt($i, array(T_OPEN_TAG, '<?php ', $token->getLine()));
if (!$tokens[$nextIndex]->isWhitespace()) {
$tokens->insertAt($nextIndex, new Token(array(T_WHITESPACE, ' ')));
}
$tokens->insertAt($nextIndex, new Token(array(T_ECHO, 'echo')));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Replace short-echo <?= with long format <?php echo syntax.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class SilencedDeprecationErrorFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->equals(array(T_STRING, 'trigger_error'), false)) {
continue;
}
$start = $index;
$prev = $tokens->getPrevMeaningfulToken($start);
if ($tokens[$prev]->isGivenKind(T_NS_SEPARATOR)) {
$start = $prev;
$prev = $tokens->getPrevMeaningfulToken($start);
}
if ($tokens[$prev]->isGivenKind(T_STRING) || $tokens[$prev]->equals('@')) {
continue;
}
$end = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, array(T_STRING, '(')));
if ($tokens[$tokens->getPrevMeaningfulToken($end)]->equals(array(T_STRING, 'E_USER_DEPRECATED'))) {
$tokens->insertAt($start, new Token('@'));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Ensures deprecation notices are silenced. Warning! This could change code behavior.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class StrictFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $map = array(
T_IS_EQUAL => array(
'id' => T_IS_IDENTICAL,
'content' => '===',
),
T_IS_NOT_EQUAL => array(
'id' => T_IS_NOT_IDENTICAL,
'content' => '!==',
),
);
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
$tokenId = $token->getId();
if (isset($map[$tokenId])) {
$tokens->overrideAt($index, array($map[$tokenId]['id'], $map[$tokenId]['content'], $token->getLine()));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Comparison should be strict. Warning! This could change code behavior.';
}
}
<?php
namespace Symfony\CS\Fixer\Contrib;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class StrictParamFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $map = null;
if (null === $map) {
$trueToken = new Token(array(T_STRING, 'true'));
$map = array(
'in_array' => array(null, null, $trueToken),
'base64_decode' => array(null, $trueToken),
'array_search' => array(null, null, $trueToken),
'array_keys' => array(null, null, $trueToken),
'mb_detect_encoding' => array(null, array(new Token(array(T_STRING, 'mb_detect_order')), new Token('('), new Token(')')), $trueToken),
);
}
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_STRING) && isset($map[$token->getContent()])) {
$this->fixFunction($tokens, $index, $map[$token->getContent()]);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Functions should be used with $strict param. Warning! This could change code behavior.';
}
private function fixFunction(Tokens $tokens, $functionIndex, array $functionParams)
{
$startBraceIndex = $tokens->getNextTokenOfKind($functionIndex, array('('));
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex);
$commaCounter = 0;
$sawParameter = false;
for ($index = $startBraceIndex + 1; $index < $endBraceIndex; ++$index) {
$token = $tokens[$index];
if (!$token->isWhitespace() && !$token->isComment()) {
$sawParameter = true;
}
if ($token->equals('(')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}
if ($token->equals('[')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $index);
continue;
}
if ($token->equals(',')) {
++$commaCounter;
continue;
}
}
$functionParamsQuantity = count($functionParams);
$paramsQuantity = ($sawParameter ? 1 : 0) + $commaCounter;
if ($paramsQuantity === $functionParamsQuantity) {
return;
}
$tokensToInsert = array();
for ($i = $paramsQuantity; $i < $functionParamsQuantity; ++$i) {
if (!$functionParams[$i]) {
return;
}
$tokensToInsert[] = new Token(',');
$tokensToInsert[] = new Token(array(T_WHITESPACE, ' '));
if (!is_array($functionParams[$i])) {
$tokensToInsert[] = clone $functionParams[$i];
continue;
}
foreach ($functionParams[$i] as $param) {
$tokensToInsert[] = clone $param;
}
}
$beforeEndBraceIndex = $tokens->getPrevNonWhitespace($endBraceIndex, array());
$tokens->insertAt($beforeEndBraceIndex + 1, $tokensToInsert);
}
}
<?php
namespace Symfony\CS\Fixer\PSR0;
use Symfony\CS\AbstractFixer;
use Symfony\CS\ConfigAwareInterface;
use Symfony\CS\ConfigInterface;
use Symfony\CS\StdinFileInfo;
use Symfony\CS\Tokenizer\Tokens;
class Psr0Fixer extends AbstractFixer implements ConfigAwareInterface
{
protected $config;
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$namespace = false;
$namespaceIndex = 0;
$namespaceEndIndex = 0;
$classyName = null;
$classyIndex = 0;
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_NAMESPACE)) {
if (false !== $namespace) {
return $content;
}
$namespaceIndex = $tokens->getNextMeaningfulToken($index);
$namespaceEndIndex = $tokens->getNextTokenOfKind($index, array(';'));
$namespace = trim($tokens->generatePartialCode($namespaceIndex, $namespaceEndIndex - 1));
} elseif ($token->isClassy()) {
if (null !== $classyName) {
return $content;
}
$classyIndex = $tokens->getNextMeaningfulToken($index);
$classyName = $tokens[$classyIndex]->getContent();
}
}
if (null === $classyName) {
return $content;
}
if (false !== $namespace) {
$normNamespace = str_replace('\\', '/', $namespace);
$path = str_replace('\\', '/', $file->getRealPath());
$dir = dirname($path);
if ($this->config) {
$dir = substr($dir, strlen(realpath($this->config->getDir())) + 1);
if (strlen($normNamespace) > strlen($dir)) {
if ('' !== $dir) {
$normNamespace = substr($normNamespace, -strlen($dir));
} else {
$normNamespace = '';
}
}
}
$dir = substr($dir, -strlen($normNamespace));
if (false === $dir) {
$dir = '';
}
$filename = basename($path, '.php');
if ($classyName !== $filename) {
$tokens[$classyIndex]->setContent($filename);
}
if ($normNamespace !== $dir && strtolower($normNamespace) === strtolower($dir)) {
for ($i = $namespaceIndex; $i <= $namespaceEndIndex; ++$i) {
$tokens[$i]->clear();
}
$namespace = substr($namespace, 0, -strlen($dir)).str_replace('/', '\\', $dir);
$newNamespace = Tokens::fromCode('<?php namespace '.$namespace.';');
$newNamespace[0]->clear();
$newNamespace[1]->clear();
$newNamespace[2]->clear();
$tokens->insertAt($namespaceIndex, $newNamespace);
}
} else {
$normClass = str_replace('_', '/', $classyName);
$path = str_replace('\\', '/', $file->getRealPath());
$filename = substr($path, -strlen($normClass) - 4, -4);
if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) {
$tokens[$classyIndex]->setContent(str_replace('/', '_', $filename));
}
}
return $tokens->generateCode();
}
public function setConfig(ConfigInterface $config)
{
$this->config = $config;
}
public function getPriority()
{
return -10;
}
public function getDescription()
{
return 'Classes must be in a path that matches their namespace, be at least one namespace deep, and the class name should match the file name.';
}
public function supports(\SplFileInfo $file)
{
if ($file instanceof StdinFileInfo) {
return false;
}
$filenameParts = explode('.', $file->getBasename(), 2);
if (
(!isset($filenameParts[1]) || 'php' !== $filenameParts[1])
|| 0 === preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $filenameParts[0])
|| '__halt_compiler' === $filenameParts[0]
) {
return false;
}
try {
$tokens = Tokens::fromCode(sprintf('<?php class %s {}', $filenameParts[0]));
if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) {
return false;
}
} catch (\ParseError $e) {
return false;
}
return !preg_match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath());
}
}
<?php
namespace Symfony\CS\Fixer\PSR1;
use Symfony\CS\AbstractFixer;
class EncodingFixer extends AbstractFixer
{
private $BOM;
public function __construct()
{
$this->BOM = pack('CCC', 0xef, 0xbb, 0xbf);
}
public function fix(\SplFileInfo $file, $content)
{
if (0 === strncmp($content, $this->BOM, 3)) {
return substr($content, 3);
}
return $content;
}
public function getDescription()
{
return 'PHP code MUST use only UTF-8 without BOM (remove BOM).';
}
public function getPriority()
{
return 100;
}
}
<?php
namespace Symfony\CS\Fixer\PSR1;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ShortTagFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$newContent = preg_replace('/<\?(\s|$)/', '<?php$1', $content, -1, $count);
if (0 === $count) {
return $content;
}
$tokens = Tokens::fromCode($newContent);
$tokensOldContent = '';
$tokensOldContentLength = 0;
foreach ($tokens as $token) {
if ($token->isGivenKind(T_OPEN_TAG)) {
$tokenContent = $token->getContent();
if ('<?php' !== substr($content, $tokensOldContentLength, 5)) {
$tokenContent = '<? ';
}
$tokensOldContent .= $tokenContent;
$tokensOldContentLength += strlen($tokenContent);
continue;
}
if ($token->isGivenKind(array(T_COMMENT, T_DOC_COMMENT, T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_STRING))) {
$tokenContent = '';
$tokenContentLength = 0;
$parts = explode('<?php', $token->getContent());
$iLast = count($parts) - 1;
foreach ($parts as $i => $part) {
$tokenContent .= $part;
$tokenContentLength += strlen($part);
if ($i !== $iLast) {
if ('<?php' === substr($content, $tokensOldContentLength + $tokenContentLength, 5)) {
$tokenContent .= '<?php';
$tokenContentLength += 5;
} else {
$tokenContent .= '<?';
$tokenContentLength += 2;
}
}
}
$token->setContent($tokenContent);
}
$tokensOldContent .= $token->getContent();
$tokensOldContentLength += strlen($token->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHP code must use the long <?php ?> tags or the short-echo <?= ?> tags; it must not use the other tag variations.';
}
public function getPriority()
{
return 98;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class BracesFixer extends AbstractFixer
{
private $singleLineWhitespaceOptions = array('whitespaces' => " \t");
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$this->fixCommentBeforeBrace($tokens);
$this->fixMissingControlBraces($tokens);
$this->fixIndents($tokens);
$this->fixControlContinuationBraces($tokens);
$this->fixSpaceAroundToken($tokens);
$this->fixDoWhile($tokens);
$code = $tokens->generateCode();
$tokens->setCode($code);
return $code;
}
public function getDescription()
{
return 'The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.';
}
public function getPriority()
{
return -25;
}
private function fixCommentBeforeBrace(Tokens $tokens)
{
$controlTokens = $this->getControlTokens();
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind($controlTokens)) {
$prevIndex = $this->findParenthesisEnd($tokens, $index);
} elseif (
$token->isGivenKind(T_FUNCTION) && $tokens->isLambda($index) ||
$token->isGivenKind(T_CLASS) && $tokens->isAnonymousClass($index)
) {
$prevIndex = $tokens->getNextTokenOfKind($index, array('{'));
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
} else {
continue;
}
$commentIndex = $tokens->getNextNonWhitespace($prevIndex);
$commentToken = $tokens[$commentIndex];
if (!$commentToken->isGivenKind(T_COMMENT) || '/*' === substr($commentToken->getContent(), 0, 2)) {
continue;
}
$braceIndex = $tokens->getNextMeaningfulToken($commentIndex);
$braceToken = $tokens[$braceIndex];
if (!$braceToken->equals('{')) {
continue;
}
$tokenTmp = $tokens[$braceIndex];
$trimIndex = $tokens->getPrevNonWhitespace($braceIndex);
$tokens[$trimIndex]->setContent(rtrim($tokens[$trimIndex]->getContent()));
$newBraceIndex = $prevIndex + 1;
for ($i = $braceIndex; $i > $newBraceIndex; --$i) {
$tokens[$i] = $tokens[$i - 1];
}
$tokens[$newBraceIndex] = $tokenTmp;
if ($tokens[$braceIndex]->isWhitespace()) {
$tokens[$braceIndex]->clear();
}
}
}
private function fixControlContinuationBraces(Tokens $tokens)
{
$controlContinuationTokens = $this->getControlContinuationTokens();
for ($index = count($tokens) - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($controlContinuationTokens)) {
continue;
}
$prevIndex = $tokens->getPrevNonWhitespace($index);
$prevToken = $tokens[$prevIndex];
if (!$prevToken->equals('}')) {
continue;
}
$tokens->ensureWhitespaceAtIndex($index - 1, 1, ' ');
}
}
private function fixDoWhile(Tokens $tokens)
{
for ($index = count($tokens) - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_DO)) {
continue;
}
$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
$startBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex);
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($endBraceIndex);
$nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];
if (!$nextNonWhitespaceToken->isGivenKind(T_WHILE)) {
continue;
}
$tokens->ensureWhitespaceAtIndex($nextNonWhitespaceIndex - 1, 1, ' ');
}
}
private function fixIndents(Tokens $tokens)
{
$classyTokens = $this->getClassyTokens();
$classyAndFunctionTokens = array_merge(array(T_FUNCTION), $classyTokens);
$controlTokens = $this->getControlTokens();
$indentTokens = array_filter(
array_merge($classyAndFunctionTokens, $controlTokens),
function ($item) {
return T_SWITCH !== $item;
}
);
for ($index = 0, $limit = count($tokens); $index < $limit; ++$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($indentTokens)) {
continue;
}
if (
$token->isGivenKind(T_FUNCTION)
&& $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_USE)
) {
continue;
}
if ($token->isGivenKind($classyAndFunctionTokens)) {
$startBraceIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
$startBraceToken = $tokens[$startBraceIndex];
} else {
$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
$startBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
$startBraceToken = $tokens[$startBraceIndex];
}
if (!$startBraceToken->equals('{')) {
continue;
}
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex);
$indent = $this->detectIndent($tokens, $index);
$tokens->ensureWhitespaceAtIndex($endBraceIndex - 1, 1, "\n".$indent);
$lastCommaIndex = $tokens->getPrevTokenOfKind($endBraceIndex - 1, array(';', '}'));
$nestLevel = 1;
for ($nestIndex = $lastCommaIndex; $nestIndex >= $startBraceIndex; --$nestIndex) {
$nestToken = $tokens[$nestIndex];
if ($nestToken->equals(')')) {
$nestIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nestIndex, false);
continue;
}
if (1 === $nestLevel && $nestToken->equalsAny(array(';', '}'))) {
$nextNonWhitespaceNestToken = $tokens[$tokens->getNextNonWhitespace($nestIndex)];
if (
!$nextNonWhitespaceNestToken->isComment() &&
!($nestToken->equals('}') && $nextNonWhitespaceNestToken->equalsAny(array(';', ',', ']'))) &&
!($nestToken->equals('}') && $nextNonWhitespaceNestToken->equals('(')) &&
!($nestToken->equals('}') && $tokens[$nestIndex - 1]->equalsAny(array('"', "'", array(T_CONSTANT_ENCAPSED_STRING)))) &&
!($nestToken->equals('}') && $nextNonWhitespaceNestToken->equalsAny(array('=', array(T_OBJECT_OPERATOR))))
) {
if ($nextNonWhitespaceNestToken->isGivenKind($this->getControlContinuationTokens()) || $nextNonWhitespaceNestToken->isGivenKind(T_CLOSE_TAG)) {
$whitespace = ' ';
} else {
$nextToken = $tokens[$nestIndex + 1];
$nextWhitespace = '';
if ($nextToken->isWhitespace()) {
$nextWhitespace = rtrim($nextToken->getContent(), " \t");
if (strlen($nextWhitespace) && "\n" === $nextWhitespace[strlen($nextWhitespace) - 1]) {
$nextWhitespace = substr($nextWhitespace, 0, -1);
}
}
$whitespace = $nextWhitespace."\n".$indent;
if (!$nextNonWhitespaceNestToken->equals('}')) {
$whitespace .= ' ';
}
}
$tokens->ensureWhitespaceAtIndex($nestIndex + 1, 0, $whitespace);
}
}
if ($nestToken->equals('}')) {
++$nestLevel;
continue;
}
if ($nestToken->equals('{')) {
--$nestLevel;
continue;
}
}
if (isset($tokens[$startBraceIndex + 2]) && $tokens[$startBraceIndex + 2]->equals('}')) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, "\n".$indent);
} else {
$nextToken = $tokens[$startBraceIndex + 1];
$nextNonWhitespaceToken = $tokens[$tokens->getNextNonWhitespace($startBraceIndex)];
if (
!$nextNonWhitespaceToken->isComment()
|| !($nextToken->isWhitespace() && $nextToken->isWhitespace(array('whitespaces' => " \t")))
&& substr_count($nextToken->getContent(), "\n") === 1
) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, "\n".$indent.' ');
}
}
if ($token->isGivenKind($classyTokens) && !$tokens->isAnonymousClass($index)) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, "\n".$indent);
} elseif ($token->isGivenKind(T_FUNCTION) && !$tokens->isLambda($index)) {
$closingParenthesisIndex = $tokens->getPrevTokenOfKind($startBraceIndex, array(')'));
if (null === $closingParenthesisIndex) {
continue;
}
$prevToken = $tokens[$closingParenthesisIndex - 1];
if ($prevToken->isWhitespace() && false !== strpos($prevToken->getContent(), "\n")) {
if (!$tokens[$startBraceIndex - 2]->isComment()) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
}
} else {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, "\n".$indent);
}
} else {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
}
$limit = count($tokens);
}
}
private function fixMissingControlBraces(Tokens $tokens)
{
$controlTokens = $this->getControlTokens();
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($controlTokens)) {
continue;
}
$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
$tokenAfterParenthesis = $tokens[$tokens->getNextMeaningfulToken($parenthesisEndIndex)];
if ($tokenAfterParenthesis->equals('{')) {
$tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' ');
continue;
}
if ($tokenAfterParenthesis->equalsAny(array(';', '{', ':'))) {
continue;
}
$statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);
$tokens->insertAt($statementEndIndex + 1, array(new Token(array(T_WHITESPACE, ' ')), new Token('}')));
if (!$tokens[$statementEndIndex]->equalsAny(array(';', '}'))) {
$tokens->insertAt($statementEndIndex + 1, new Token(';'));
}
$tokens->insertAt($parenthesisEndIndex + 1, new Token('{'));
$tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' ');
}
}
private function fixSpaceAroundToken(Tokens $tokens)
{
$controlTokens = $this->getControlTokens();
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_DECLARE)) {
$this->fixDeclareStatement($tokens, $index);
} elseif ($token->isGivenKind($controlTokens) || $token->isGivenKind(T_USE)) {
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index);
if (!$tokens[$nextNonWhitespaceIndex]->equals(':')) {
$tokens->ensureWhitespaceAtIndex($index + 1, 0, ' ');
}
$prevToken = $tokens[$index - 1];
if (!$prevToken->isWhitespace() && !$prevToken->isComment() && !$prevToken->isGivenKind(T_OPEN_TAG)) {
$tokens->ensureWhitespaceAtIndex($index - 1, 1, ' ');
}
}
}
}
private function detectIndent(Tokens $tokens, $index)
{
while (true) {
$whitespaceIndex = $tokens->getPrevTokenOfKind($index, array(array(T_WHITESPACE)));
if (null === $whitespaceIndex) {
return '';
}
$whitespaceToken = $tokens[$whitespaceIndex];
if (false !== strpos($whitespaceToken->getContent(), "\n")) {
break;
}
$prevToken = $tokens[$whitespaceIndex - 1];
if ($prevToken->isGivenKind(array(T_OPEN_TAG, T_COMMENT)) && "\n" === substr($prevToken->getContent(), -1)) {
break;
}
$index = $whitespaceIndex;
}
$explodedContent = explode("\n", $whitespaceToken->getContent());
return end($explodedContent);
}
private function findParenthesisEnd(Tokens $tokens, $structureTokenIndex)
{
$nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex);
$nextToken = $tokens[$nextIndex];
if (!$nextToken->equals('(')) {
return $structureTokenIndex;
}
return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);
}
private function findStatementEnd(Tokens $tokens, $parenthesisEndIndex)
{
$nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex);
$nextToken = $tokens[$nextIndex];
if (!$nextToken) {
return $parenthesisEndIndex;
}
if ($nextToken->equals('{')) {
return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex);
}
if ($nextToken->isGivenKind($this->getControlTokens())) {
$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex);
$endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);
if ($nextToken->isGivenKind(array(T_IF, T_TRY))) {
$openingTokenKind = $nextToken->getId();
while (true) {
$nextIndex = $tokens->getNextMeaningfulToken($endIndex);
$nextToken = isset($nextIndex) ? $tokens[$nextIndex] : null;
if ($nextToken && $nextToken->isGivenKind($this->getControlContinuationTokensForOpeningToken($openingTokenKind))) {
$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex);
$endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);
if ($nextToken->isGivenKind($this->getFinalControlContinuationTokensForOpeningToken($openingTokenKind))) {
return $endIndex;
}
} else {
break;
}
}
}
return $endIndex;
}
$index = $parenthesisEndIndex;
while (true) {
$token = $tokens[++$index];
if ($token->equals('{')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if ($token->equals(';')) {
return $index;
}
if ($token->isGivenKind(T_CLOSE_TAG)) {
return $tokens->getPrevNonWhitespace($index);
}
}
throw new \RuntimeException('Statement end not found');
}
private function getClassyTokens()
{
static $tokens = null;
if (null === $tokens) {
$tokens = array(T_CLASS, T_INTERFACE);
if (defined('T_TRAIT')) {
$tokens[] = T_TRAIT;
}
}
return $tokens;
}
private function getControlTokens()
{
static $tokens = null;
if (null === $tokens) {
$tokens = array(
T_DECLARE,
T_DO,
T_ELSE,
T_ELSEIF,
T_FOR,
T_FOREACH,
T_IF,
T_WHILE,
T_TRY,
T_CATCH,
T_SWITCH,
);
if (defined('T_FINALLY')) {
$tokens[] = T_FINALLY;
}
}
return $tokens;
}
private function getControlContinuationTokens()
{
static $tokens = null;
if (null === $tokens) {
$tokens = array(
T_ELSE,
T_ELSEIF,
T_CATCH,
);
if (defined('T_FINALLY')) {
$tokens[] = T_FINALLY;
}
}
return $tokens;
}
private function getControlContinuationTokensForOpeningToken($openingTokenKind)
{
if ($openingTokenKind === T_IF) {
return array(
T_ELSE,
T_ELSEIF,
);
}
if ($openingTokenKind === T_TRY) {
$tokens = array(T_CATCH);
if (defined('T_FINALLY')) {
$tokens[] = T_FINALLY;
}
return $tokens;
}
return array();
}
private function getFinalControlContinuationTokensForOpeningToken($openingTokenKind)
{
if ($openingTokenKind === T_IF) {
return array(T_ELSE);
}
if ($openingTokenKind === T_TRY && defined('T_FINALLY')) {
return array(T_FINALLY);
}
return array();
}
private function fixDeclareStatement(Tokens $tokens, $index)
{
$tokens->removeTrailingWhitespace($index);
$startParenthesisIndex = $tokens->getNextTokenOfKind($index, array('('));
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, array(';', '{'));
$startBraceToken = $tokens[$startBraceIndex];
if ($startBraceToken->equals('{')) {
$this->fixSingleLineWhitespaceForDeclare($tokens, $startBraceIndex);
}
$this->removeWhitespaceInParenthesis($tokens, $startParenthesisIndex, $endParenthesisIndex);
}
private function fixSingleLineWhitespaceForDeclare(Tokens $tokens, $startBraceIndex)
{
if (
!$tokens[$startBraceIndex - 1]->isWhitespace() ||
$tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions)
) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
}
}
private function removeWhitespaceInParenthesis(Tokens $tokens, $startParenthesisIndex, $endParenthesisIndex)
{
for ($i = $startParenthesisIndex; $i < $endParenthesisIndex; ++$i) {
if ($tokens[$i]->isWhitespace()) {
$tokens[$i]->clear();
}
}
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class ClassDefinitionFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->getSize() - 1; $index > 0; --$index) {
if (!$tokens[$index]->isClassy()) {
continue;
}
$this->fixClassDefinition($tokens, $index, $tokens->getNextTokenOfKind($index, array('{')));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Whitespace around the key words of a class, trait or interfaces definition should be one space.';
}
public function getPriority()
{
return 21;
}
private function fixClassDefinition(Tokens $tokens, $start, $classyOpen)
{
$implementsInfo = $this->getMultiLineInfo($tokens, $start, $classyOpen);
if ($implementsInfo['numberOfInterfaces'] > 1 && $implementsInfo['multiLine']) {
$classyOpen += $this->ensureWhiteSpaceSeparation($tokens, $start, $implementsInfo['breakAt']);
$this->fixMultiLineImplements($tokens, $implementsInfo['breakAt'], $classyOpen);
} else {
$classyOpen -= $tokens[$classyOpen - 1]->isWhitespace() ? 2 : 1;
$this->ensureWhiteSpaceSeparation($tokens, $start, $classyOpen);
}
}
private function getMultiLineInfo(Tokens $tokens, $start, $classyOpen)
{
$implementsInfo = array('breakAt' => 0, 'numberOfInterfaces' => 0, 'multiLine' => false);
$breakAtToken = $tokens->findGivenKind($tokens[$start]->isGivenKind(T_INTERFACE) ? T_EXTENDS : T_IMPLEMENTS, $start, $classyOpen);
if (count($breakAtToken) < 1) {
return $implementsInfo;
}
$implementsInfo['breakAt'] = key($breakAtToken);
$classyOpen = $tokens->getPrevNonWhitespace($classyOpen);
for ($j = $implementsInfo['breakAt'] + 1; $j < $classyOpen; ++$j) {
if ($tokens[$j]->isGivenKind(T_STRING)) {
++$implementsInfo['numberOfInterfaces'];
continue;
}
if (!$implementsInfo['multiLine'] && ($tokens[$j]->isWhitespace() || $tokens[$j]->isComment()) && false !== strpos($tokens[$j]->getContent(), "\n")) {
$implementsInfo['multiLine'] = true;
}
}
return $implementsInfo;
}
private function fixMultiLineImplements(Tokens $tokens, $breakAt, $classyOpen)
{
for ($index = $classyOpen - 1; $index > $breakAt - 1; --$index) {
if ($tokens[$index]->isWhitespace()) {
if ($tokens[$index + 1]->equals(',')) {
$tokens[$index]->clear();
} elseif ($tokens[$index + 1]->isComment() && ' ' !== $tokens[$index]->getContent()) {
$tokens[$index]->setContent(' ');
}
}
if ($tokens[$index]->isGivenKind(T_STRING)) {
$index = $this->ensureOnNewLine($tokens, $index);
}
}
}
private function ensureWhiteSpaceSeparation(Tokens $tokens, $start, $end)
{
$insertCount = 0;
for ($i = $end; $i > $start; --$i) {
if ($tokens[$i]->isWhitespace()) {
if (' ' !== $tokens[$i]->getContent()) {
$tokens[$i]->setContent(' ');
}
continue;
}
if ($tokens[$i - 1]->isWhitespace() || "\n" === substr($tokens[$i - 1]->getContent(), -1)) {
continue;
}
if ($tokens[$i - 1]->isComment() || $tokens[$i]->isComment()) {
$tokens->insertAt($i, new Token(array(T_WHITESPACE, ' ')));
++$insertCount;
continue;
}
}
return $insertCount;
}
private function ensureOnNewLine(Tokens $tokens, $index)
{
for (--$index; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(array(T_NS_SEPARATOR, T_STRING))) {
break;
}
}
if ("\n" === substr($tokens[$index]->getContent(), -1)) {
return $index;
}
if (!$tokens[$index]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, "\n")));
return $index;
}
if (false !== strpos($tokens[$index]->getContent(), "\n")) {
return $index;
}
$tokens[$index]->setContent($tokens[$index]->getContent()."\n");
return $index;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ElseifFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$tokens[$index]->isGivenKind(T_ELSE)) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$nextIndex]->isGivenKind(T_IF)) {
continue;
}
for ($i = $index + 1; $i < $nextIndex; ++$i) {
if ($tokens[$i]->isWhitespace()) {
$tokens[$i]->clear();
}
}
$tokens->overrideAt($index, array(T_ELSEIF, 'elseif', $tokens[$index]->getLine()));
$tokens[$nextIndex]->clear();
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'The keyword elseif should be used instead of else if so that all control keywords looks like single words.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class EofEndingFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$count = $tokens->count();
if (0 === $count) {
return '';
}
$token = $tokens[$count - 1];
if ($token->isGivenKind(array(T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG))) {
return $content;
}
$isSingleLineComment = function (Token $token) {
return $token->isComment() && '/*' !== substr($token->getContent(), 0, 2);
};
$clearSingleLineComment = function (Token $token) {
$content = $token->getContent();
$content = rtrim($content, "\n")."\n";
$token->setContent($content);
};
if ($token->isWhitespace()) {
if ($count > 1 && $isSingleLineComment($tokens[$count - 2])) {
$clearSingleLineComment($tokens[$count - 2]);
$token->clear();
} else {
$lineBreak = false === strrpos($token->getContent(), "\r") ? "\n" : "\r\n";
$token->setContent($lineBreak);
}
} elseif ($isSingleLineComment($token)) {
$clearSingleLineComment($token);
} else {
$tokens->insertAt($count, new Token(array(T_WHITESPACE, "\n")));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'A file must always end with a single empty line feed.';
}
public function getPriority()
{
return -50;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class FunctionCallSpaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$functionyTokens = $this->getFunctionyTokenKinds();
$languageConstructionTokens = $this->getLanguageConstructionTokenKinds();
foreach ($tokens as $index => $token) {
if (!$token->equals('(')) {
continue;
}
$lastTokenIndex = $tokens->getPrevNonWhitespace($index);
if (null === $lastTokenIndex) {
continue;
}
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex);
if (
null !== $nextNonWhiteSpace
&& $tokens[$nextNonWhiteSpace]->equals('?')
&& $tokens[$lastTokenIndex]->isGivenKind($languageConstructionTokens)
) {
continue;
}
if ($tokens[$lastTokenIndex]->isGivenKind($functionyTokens)) {
$this->fixFunctionCall($tokens, $index);
} elseif ($tokens[$lastTokenIndex]->isGivenKind(T_STRING)) {
$possibleDefinitionIndex = $tokens->getPrevMeaningfulToken($lastTokenIndex);
if (!$tokens[$possibleDefinitionIndex]->isGivenKind(T_FUNCTION)) {
$this->fixFunctionCall($tokens, $index);
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis.';
}
private function fixFunctionCall(Tokens $tokens, $index)
{
if ($tokens[$index - 1]->isWhitespace()) {
$tokens[$index - 1]->clear();
}
}
private function getFunctionyTokenKinds()
{
static $tokens = null;
if (null === $tokens) {
$tokens = array(
T_ARRAY,
T_ECHO,
T_EMPTY,
T_EVAL,
T_EXIT,
T_INCLUDE,
T_INCLUDE_ONCE,
T_ISSET,
T_LIST,
T_PRINT,
T_REQUIRE,
T_REQUIRE_ONCE,
T_UNSET,
);
}
return $tokens;
}
private function getLanguageConstructionTokenKinds()
{
static $languageConstructionTokens = array(
T_ECHO,
T_PRINT,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
);
return $languageConstructionTokens;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class FunctionDeclarationFixer extends AbstractFixer
{
private $singleLineWhitespaceOptions = array('whitespaces' => " \t");
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_FUNCTION)) {
continue;
}
$startParenthesisIndex = $tokens->getNextTokenOfKind($index, array('(', ';', array(T_CLOSE_TAG)));
if (!$tokens[$startParenthesisIndex]->equals('(')) {
continue;
}
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, array(';', '{'));
if (
$tokens[$tokens->getPrevNonWhitespace($startBraceIndex)]->equals(')') &&
$tokens[$startBraceIndex]->equals('{') &&
(
!$tokens[$startBraceIndex - 1]->isWhitespace() ||
$tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions)
)
) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
}
$afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex);
$afterParenthesisToken = $tokens[$afterParenthesisIndex];
if ($afterParenthesisToken->isGivenKind(T_USE)) {
$useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, array('('));
$useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex);
$tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' ');
$this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex);
$tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' ');
}
$this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex);
if ($tokens[$startParenthesisIndex - 1]->isWhitespace()) {
$tokens[$startParenthesisIndex - 1]->clear();
}
$tokens->ensureWhitespaceAtIndex($index + 1, 0, ' ');
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Spaces should be properly placed in a function declaration.';
}
private function fixParenthesisInnerEdge(Tokens $tokens, $start, $end)
{
if ($tokens[$end - 1]->isWhitespace($this->singleLineWhitespaceOptions)) {
$tokens[$end - 1]->clear();
}
if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) {
$tokens[$start + 1]->clear();
}
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class IndentationFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isComment()) {
$content = preg_replace('/^(?:(?<! ) {1,3})?\t/m', '\1 ', $token->getContent(), -1, $count);
while ($count !== 0) {
$content = preg_replace('/^(\ +)?\t/m', '\1 ', $content, -1, $count);
}
$tokens[$index]->setContent($content);
continue;
}
if ($token->isWhitespace()) {
$tokens[$index]->setContent(preg_replace('/(?:(?<! ) {1,3})?\t/', ' ', $token->getContent()));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting.';
}
public function getPriority()
{
return 50;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class LineAfterNamespaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$lastIndex = $tokens->count() - 1;
for ($index = $lastIndex; $index >= 0; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_NAMESPACE)) {
$semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{', array(T_CLOSE_TAG)));
$semicolonToken = $tokens[$semicolonIndex];
if (!isset($tokens[$semicolonIndex + 1]) || !$semicolonToken->equals(';')) {
continue;
}
$nextIndex = $semicolonIndex + 1;
$nextToken = $tokens[$nextIndex];
if (!$nextToken->isWhitespace()) {
$tokens->insertAt($semicolonIndex + 1, new Token(array(T_WHITESPACE, "\n\n")));
} else {
$nextToken->setContent(
($nextIndex === $lastIndex ? "\n" : "\n\n").ltrim($nextToken->getContent())
);
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There MUST be one blank line after the namespace declaration.';
}
public function getPriority()
{
return -20;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
class LinefeedFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
return str_replace("\r\n", "\n", $content);
}
public function getDescription()
{
return 'All PHP files must use the Unix LF (linefeed) line ending.';
}
public function getPriority()
{
return 50;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class LowercaseConstantsFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isNativeConstant()) {
continue;
}
if (
$this->isNeighbourAccepted($tokens, $tokens->getPrevMeaningfulToken($index)) &&
$this->isNeighbourAccepted($tokens, $tokens->getNextMeaningfulToken($index))
) {
$token->setContent(strtolower($token->getContent()));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'The PHP constants true, false, and null MUST be in lower case.';
}
private function isNeighbourAccepted(Tokens $tokens, $index)
{
static $forbiddenTokens = null;
if (null === $forbiddenTokens) {
$forbiddenTokens = array(
T_AS,
T_CLASS,
T_CONST,
T_EXTENDS,
T_IMPLEMENTS,
T_INSTANCEOF,
T_INTERFACE,
T_NEW,
T_NS_SEPARATOR,
T_PAAMAYIM_NEKUDOTAYIM,
T_USE,
);
if (defined('T_TRAIT')) {
$forbiddenTokens[] = T_TRAIT;
}
if (defined('T_INSTEADOF')) {
$forbiddenTokens[] = T_INSTEADOF;
}
}
$token = $tokens[$index];
if ($token->equalsAny(array('{', '}'))) {
return false;
}
return !$token->isGivenKind($forbiddenTokens);
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class LowercaseKeywordsFixer extends AbstractFixer
{
private static $excludedTokens = array(T_HALT_COMPILER);
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
if ($token->isKeyword() && !$token->isGivenKind(self::$excludedTokens)) {
$token->setContent(strtolower($token->getContent()));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHP keywords MUST be in lower case.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class MethodArgumentSpaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->equals('(') || $tokens[$index - 1]->isGivenKind(T_ARRAY)) {
continue;
}
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
for ($i = $endIndex - 1; $i > $index; --$i) {
if (!$tokens[$i]->equals(',')) {
continue;
}
$this->fixSpace($tokens, $i);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma.';
}
public function fixSpace(Tokens $tokens, $index)
{
if ($tokens[$index - 1]->isWhitespace()) {
$prevIndex = $tokens->getPrevNonWhitespace($index - 1);
if (!$tokens[$prevIndex]->equalsAny(array(',', array(T_END_HEREDOC)))) {
$tokens[$index - 1]->clear();
}
}
if (!$tokens[$index + 1]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
}
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class MultipleUseFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$uses = array_reverse($tokens->getImportUseIndexes());
foreach ($uses as $index) {
$endIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
$previous = $tokens->getPrevMeaningfulToken($endIndex);
if ($tokens[$previous]->equals('}')) {
$start = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $previous, false);
$declarationContent = $tokens->generatePartialCode($start + 1, $previous - 1);
$prefix = '';
for ($i = $index + 1; $i < $start; ++$i) {
$prefix .= $tokens[$i]->getContent();
}
$prefix = ' '.ltrim($prefix);
} else {
$declarationContent = $tokens->generatePartialCode($index + 1, $endIndex - 1);
$prefix = ' ';
}
$declarationParts = explode(',', $declarationContent);
if (1 === count($declarationParts)) {
continue;
}
$declarationContent = array();
foreach ($declarationParts as $declarationPart) {
$declarationContent[] = 'use'.$prefix.trim($declarationPart).';';
}
$declarationContent = implode("\n".$this->detectIndent($tokens, $index), $declarationContent);
for ($i = $index; $i < $endIndex; ++$i) {
$tokens[$i]->clear();
}
if ($tokens[$endIndex]->equals(';')) {
$tokens[$endIndex]->clear();
}
$declarationTokens = Tokens::fromCode('<?php '.$declarationContent);
$declarationTokens[0]->clear();
$tokens->insertAt($index, $declarationTokens);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There MUST be one use keyword per declaration.';
}
private function detectIndent(Tokens $tokens, $index)
{
$prevIndex = $index - 1;
$prevToken = $tokens[$prevIndex];
if (!$prevToken->isWhitespace()) {
return '';
}
$explodedContent = explode("\n", $prevToken->getContent());
return end($explodedContent);
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NoTrailingWhitespaceInCommentFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
if ($token->isComment()) {
$token->setContent(
preg_replace('/[ \t]+$/m', '', $token->getContent())
);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There MUST be no trailing spaces inside comments and phpdocs.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ParenthesisFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->equals('(')) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(T_ARRAY)) {
continue;
}
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$this->removeSpaceAroundToken($tokens, $index, 1);
if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) {
$this->removeSpaceAroundToken($tokens, $endIndex, -1);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There MUST NOT be a space after the opening parenthesis. There MUST NOT be a space before the closing parenthesis.';
}
private function removeSpaceAroundToken(Tokens $tokens, $index, $offset)
{
if (!isset($tokens[$index + $offset])) {
return;
}
$token = $tokens[$index + $offset];
if ($token->isWhitespace() && false === strpos($token->getContent(), "\n")) {
if (isset($tokens[$index + $offset - 1])) {
$prevToken = $tokens[$index + $offset - 1];
if ($prevToken->isComment() && false !== strpos($prevToken->getContent(), "\n")) {
return;
}
}
$token->clear();
}
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class PhpClosingTagFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if (!$tokens->isMonolithicPhp()) {
return $content;
}
$closeTags = $tokens->findGivenKind(T_CLOSE_TAG);
if (empty($closeTags)) {
return $content;
}
list($index, $token) = each($closeTags);
$tokens->removeLeadingWhitespace($index);
$token->clear();
$prevIndex = $tokens->getPrevNonWhitespace($index);
$prevToken = $tokens[$prevIndex];
if (!$prevToken->equalsAny(array(';', '}'))) {
$tokens->insertAt($prevIndex + 1, new Token(';'));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'The closing ?> tag MUST be omitted from files containing only PHP.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;
class SingleLineAfterImportsFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->getImportUseIndexes() as $index) {
$indent = '';
if ($tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$index - 2]->isGivenKind(T_COMMENT)) {
$indent = $tokens[$index - 1]->getContent();
} elseif ($tokens[$index - 1]->isWhitespace()) {
$indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]);
}
$semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
$insertIndex = $semicolonIndex;
if ($tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG)) {
if ($tokens[$insertIndex - 1]->isWhitespace()) {
--$insertIndex;
}
$tokens->insertAt($insertIndex, new Token(';'));
}
if ($semicolonIndex === count($tokens) - 1) {
$tokens->insertAt($insertIndex + 1, new Token(array(T_WHITESPACE, "\n\n".$indent)));
} else {
$newline = "\n";
$tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex;
if ($tokens[$insertIndex]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$insertIndex + 1]->isComment()) {
++$insertIndex;
}
if ($tokens[$insertIndex]->isGivenKind(T_COMMENT) && false !== strpos($tokens[$insertIndex]->getContent(), "\n")) {
$newline = '';
}
if ($tokens[$insertIndex]->isComment()) {
++$insertIndex;
}
$afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(T_USE)) {
$newline .= "\n";
}
if ($tokens[$insertIndex]->isWhitespace()) {
$nextToken = $tokens[$insertIndex];
$nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex);
if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(T_USE)) {
if (substr_count($nextToken->getContent(), "\n") < 2) {
$nextToken->setContent($newline.$indent.ltrim($nextToken->getContent()));
}
} else {
$nextToken->setContent($newline.$indent.ltrim($nextToken->getContent()));
}
} else {
if ('' !== $newline.$indent) {
$tokens->insertAt($insertIndex, new Token(array(T_WHITESPACE, $newline.$indent)));
}
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class SwitchCaseSemicolonToColonFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(array(T_CASE, T_DEFAULT))) {
continue;
}
$ternariesCount = 0;
for ($colonIndex = $index + 1; ; ++$colonIndex) {
if ($tokens[$colonIndex]->equals('?')) {
++$ternariesCount;
}
if ($tokens[$colonIndex]->equalsAny(array(':', ';'))) {
if (0 === $ternariesCount) {
break;
}
--$ternariesCount;
}
}
if ($tokens[$colonIndex]->equals(';')) {
$tokens[$colonIndex]->setContent(':');
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'A case should be followed by a colon and not a semicolon.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class SwitchCaseSpaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(array(T_CASE, T_DEFAULT))) {
continue;
}
$ternariesCount = 0;
for ($colonIndex = $index + 1; ; ++$colonIndex) {
if ($tokens[$colonIndex]->equals('?')) {
++$ternariesCount;
}
if ($tokens[$colonIndex]->equalsAny(array(':', ';'))) {
if (0 === $ternariesCount) {
break;
}
--$ternariesCount;
}
}
$valueIndex = $tokens->getPrevNonWhitespace($colonIndex);
if (2 + $valueIndex === $colonIndex) {
$tokens[$valueIndex + 1]->clear();
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Removes extra spaces between colon and case value.';
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class TrailingSpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isWhitespace()) {
continue;
}
$lines = preg_split("/([\r\n]+)/", $token->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE);
$linesSize = count($lines);
if ($linesSize > 1 || !isset($tokens[$index + 1])) {
$lines[0] = rtrim($lines[0], " \t");
for ($i = 1; $i < $linesSize; ++$i) {
$trimmedLine = rtrim($lines[$i], " \t");
if ('' !== $trimmedLine) {
$lines[$i] = $trimmedLine;
}
}
$token->setContent(implode($lines));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Remove trailing whitespace at the end of non-blank lines.';
}
public function getPriority()
{
return 0;
}
}
<?php
namespace Symfony\CS\Fixer\PSR2;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class VisibilityFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$elements = $tokens->getClassyElements();
foreach (array_reverse($elements, true) as $index => $element) {
if ('method' === $element['type']) {
$this->applyAttribs($tokens, $index, $this->grabAttribsBeforeMethodToken($tokens, $index));
$tokens[++$index]->setContent(' ');
} elseif ('property' === $element['type']) {
$prevIndex = $tokens->getPrevTokenOfKind($index, array(';', ',', '{'));
if (!$prevIndex || !$tokens[$prevIndex]->equals(',')) {
$this->applyAttribs($tokens, $index, $this->grabAttribsBeforePropertyToken($tokens, $index));
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility.';
}
private function applyAttribs(Tokens $tokens, $index, array $attribs)
{
$toInsert = array();
foreach ($attribs as $attrib) {
if (null !== $attrib && '' !== $attrib->getContent()) {
$toInsert[] = $attrib;
$toInsert[] = new Token(array(T_WHITESPACE, ' '));
}
}
if (!empty($toInsert)) {
$tokens->insertAt($index, $toInsert);
}
}
private function grabAttribsBeforeMethodToken(Tokens $tokens, $index)
{
static $tokenAttribsMap = array(
T_PRIVATE => 'visibility',
T_PROTECTED => 'visibility',
T_PUBLIC => 'visibility',
T_ABSTRACT => 'abstract',
T_FINAL => 'final',
T_STATIC => 'static',
);
return $this->grabAttribsBeforeToken(
$tokens,
$index,
$tokenAttribsMap,
array(
'abstract' => null,
'final' => null,
'visibility' => new Token(array(T_PUBLIC, 'public')),
'static' => null,
)
);
}
private function grabAttribsBeforePropertyToken(Tokens $tokens, $index)
{
static $tokenAttribsMap = array(
T_VAR => null,
T_PRIVATE => 'visibility',
T_PROTECTED => 'visibility',
T_PUBLIC => 'visibility',
T_STATIC => 'static',
);
return $this->grabAttribsBeforeToken(
$tokens,
$index,
$tokenAttribsMap,
array(
'visibility' => new Token(array(T_PUBLIC, 'public')),
'static' => null,
)
);
}
private function grabAttribsBeforeToken(Tokens $tokens, $index, array $tokenAttribsMap, array $attribs)
{
while (true) {
$token = $tokens[--$index];
if (!$token->isArray()) {
if ($token->equalsAny(array('{', '}', '(', ')'))) {
break;
}
continue;
}
if (array_key_exists($token->getId(), $tokenAttribsMap)) {
if ($tokenAttribsMap[$token->getId()]) {
$attribs[$tokenAttribsMap[$token->getId()]] = clone $token;
}
$tokens[$index]->clear();
$tokens[$index + 1]->clear();
continue;
}
if ($token->isGivenKind(array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) {
continue;
}
break;
}
return $attribs;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class ArrayElementNoSpaceBeforeCommaFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens->isArray($index)) {
continue;
}
$this->fixSpacing($index, $tokens);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'In array declaration, there MUST NOT be a whitespace before each comma.';
}
private function fixSpacing($index, Tokens $tokens)
{
if ($tokens->isShortArray($index)) {
$startIndex = $index;
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
} else {
$startIndex = $tokens->getNextTokenOfKind($index, array('('));
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
}
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
$i = $this->skipNonArrayElements($i, $tokens);
$currentToken = $tokens[$i];
$prevIndex = $tokens->getPrevNonWhitespace($i - 1);
if ($currentToken->equals(',') && !$tokens[$prevIndex]->equals(array(T_END_HEREDOC))) {
$tokens->removeLeadingWhitespace($i);
}
}
}
private function skipNonArrayElements($index, Tokens $tokens)
{
if ($tokens[$index]->equals('}')) {
return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index, false);
}
if ($tokens[$index]->equals(')')) {
$startIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index, false);
$startIndex = $tokens->getPrevMeaningfulToken($startIndex);
if (!$tokens->isArray($startIndex)) {
return $startIndex;
}
}
return $index;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class ArrayElementWhiteSpaceAfterCommaFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens->isArray($index)) {
continue;
}
$this->fixSpacing($index, $tokens);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'In array declaration, there MUST be a whitespace after each comma.';
}
private function fixSpacing($index, Tokens $tokens)
{
if ($tokens->isShortArray($index)) {
$startIndex = $index;
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
} else {
$startIndex = $tokens->getNextTokenOfKind($index, array('('));
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
}
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
$i = $this->skipNonArrayElements($i, $tokens);
if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) {
$tokens->insertAt($i + 1, new Token(array(T_WHITESPACE, ' ')));
}
}
}
private function skipNonArrayElements($index, Tokens $tokens)
{
if ($tokens[$index]->equals('}')) {
return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index, false);
}
if ($tokens[$index]->equals(')')) {
$startIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index, false);
$startIndex = $tokens->getPrevMeaningfulToken($startIndex);
if (!$tokens->isArray($startIndex)) {
return $startIndex;
}
}
return $index;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class BlanklineAfterOpenTagFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
return $content;
}
$newlineFound = false;
foreach ($tokens as $token) {
if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) {
$newlineFound = true;
break;
}
}
if (!$newlineFound) {
return $content;
}
$token = $tokens[0];
if (false === strpos($token->getContent(), "\n")) {
$token->setContent(rtrim($token->getContent())."\n");
}
if (!$tokens[1]->isWhitespace() && false === strpos($tokens[1]->getContent(), "\n")) {
$tokens->insertAt(1, new Token(array(T_WHITESPACE, "\n")));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Ensure there is no code on the same line as the PHP open tag and it is followed by a blankline.';
}
public function getPriority()
{
return 1;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ConcatWithoutSpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$whitespaces = array('whitespaces' => " \t");
foreach ($tokens as $index => $token) {
if ($token->equals('.')) {
$previousNonWhiteIndex = $tokens->getPrevNonWhitespace($index);
if (!$tokens[$previousNonWhiteIndex]->isGivenKind(T_LNUMBER) && false === strpos($tokens[$previousNonWhiteIndex]->getContent(), "\n")) {
$tokens->removeLeadingWhitespace($index, $whitespaces);
}
$nextNonWhiteIndex = $tokens->getNextNonWhitespace($index);
if (!$tokens[$nextNonWhiteIndex]->isGivenKind(array(T_LNUMBER, T_COMMENT, T_DOC_COMMENT))) {
$tokens->removeTrailingWhitespace($index, $whitespaces);
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Concatenation should be used without spaces.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class DeclareEqualNormalizeFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$count = $tokens->count();
for ($index = 0; $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind(T_DECLARE)) {
continue;
}
while (!$tokens[++$index]->equals('='));
$tokens->removeLeadingWhitespace($index);
$tokens->removeTrailingWhitespace($index);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Equal sign in declare statement should not be surrounded by spaces.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class DoubleArrowMultilineWhitespacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOUBLE_ARROW) as $index => $token) {
$this->fixWhitespace($tokens[$index - 1]);
if (!$tokens[$index + 2]->isComment()) {
$this->fixWhitespace($tokens[$index + 1]);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Operator => should not be surrounded by multi-line whitespaces.';
}
public function getPriority()
{
return 1;
}
private function fixWhitespace(Token $token)
{
if ($token->isWhitespace() && !$token->isWhitespace(array('whitespaces' => " \t"))) {
$token->setContent(rtrim($token->getContent()).' ');
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class DuplicateSemicolonFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_FOR)) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($index)) + 1;
continue;
}
if (!$token->equals(';') || !$tokens[$tokens->getPrevMeaningfulToken($index)]->equals(';')) {
continue;
}
$tokens->removeLeadingWhitespace($index);
$token->clear();
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Remove duplicated semicolons.';
}
public function getPriority()
{
return 26;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class ExtraEmptyLinesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_WHITESPACE) as $index => $token) {
$content = '';
$count = 0;
if ($index > 0 && $tokens[$index - 1]->isComment()) {
$prevContent = $tokens[$index - 1]->getContent();
$count = strrpos($prevContent, "\n") === strlen($prevContent) - 1 ? 1 : 0;
}
$parts = explode("\n", $token->getContent());
for ($i = 0, $last = count($parts) - 1; $i <= $last; ++$i) {
if ('' === $parts[$i]) {
++$count;
} else {
$content .= $parts[$i];
}
if ($i !== $last && $count < 3) {
$content .= "\n";
}
}
$token->setContent($content);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Removes extra empty lines.';
}
public function getPriority()
{
return -20;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class FunctionTypehintSpaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_FUNCTION)) {
continue;
}
$startParenthesisIndex = $tokens->getNextTokenOfKind($index, array('(', ';', array(T_CLOSE_TAG)));
if (!$tokens[$startParenthesisIndex]->equals('(')) {
continue;
}
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
for ($iter = $endParenthesisIndex - 1; $iter > $startParenthesisIndex; --$iter) {
if (!$tokens[$iter]->isGivenKind(T_VARIABLE)) {
continue;
}
if (defined('T_ELLIPSIS')) {
$prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($iter);
if ($tokens[$prevNonWhitespaceIndex]->isGivenKind(T_ELLIPSIS)) {
$iter = $prevNonWhitespaceIndex;
}
}
$prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($iter);
if ($tokens[$prevNonWhitespaceIndex]->equals('&')) {
$iter = $prevNonWhitespaceIndex;
}
if (!$tokens[$iter - 1]->equalsAny(array(array(T_WHITESPACE), array(T_COMMENT), array(T_DOC_COMMENT), '(', ','))) {
$tokens->insertAt($iter, new Token(array(T_WHITESPACE, ' ', $tokens[$iter]->getLine())));
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Add missing space between function\'s argument and its typehint.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class HashToSlashCommentFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($i = 0, $count = count($tokens); $i < $count - 1; ++$i) {
if ($tokens[$i]->isGivenKind(T_COMMENT) && '#' === substr($tokens[$i]->getContent(), 0, 1)) {
$tokens[$i]->setContent('//'.substr($tokens[$i]->getContent(), 1));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Single line comments should use double slashes (//) and not hash (#).';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class HeredocToNowdocFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_START_HEREDOC) || false !== strpos($token->getContent(), "'")) {
continue;
}
if ($tokens[$index + 1]->isGivenKind(T_END_HEREDOC)) {
$this->convertToNowdoc($token);
continue;
}
if (
!$tokens[$index + 1]->isGivenKind(T_ENCAPSED_AND_WHITESPACE) ||
!$tokens[$index + 2]->isGivenKind(T_END_HEREDOC)
) {
continue;
}
$content = $tokens[$index + 1]->getContent();
if (preg_match('/(?<!\\\\)(?:\\\\{2})*\\\\(?![$\\\\])/', $content)) {
continue;
}
$this->convertToNowdoc($token);
$content = str_replace(array('\\\\', '\\$'), array('\\', '$'), $content);
$tokens[$index + 1]->setContent($content);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Convert heredoc to nowdoc if possible.';
}
private function convertToNowdoc(Token $token)
{
$token->setContent(preg_replace('/(?<=^<<<)(\s*)"?(.*?)"?$/', '$1\'$2\'', $token->getContent()));
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class IncludeFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$includies = $this->findIncludies($tokens);
$this->clearIncludies($tokens, $includies);
return $tokens->generateCode();
}
public function getDescription()
{
return 'Include/Require and file path should be divided with a single space. File path should not be placed under brackets.';
}
private function clearIncludies(Tokens $tokens, array $includies)
{
foreach (array_reverse($includies) as $includy) {
if ($includy['end']) {
$tokens->removeLeadingWhitespace($includy['end']);
}
$braces = $includy['braces'];
if ($braces) {
$nextToken = $tokens[$tokens->getNextMeaningfulToken($braces['close'])];
if ($nextToken->equalsAny(array(';', array(T_CLOSE_TAG)))) {
$tokens->removeLeadingWhitespace($braces['open']);
$tokens->removeTrailingWhitespace($braces['open']);
$tokens->removeLeadingWhitespace($braces['close']);
$tokens->removeTrailingWhitespace($braces['close']);
$tokens[$braces['open']] = new Token(array(T_WHITESPACE, ' '));
$tokens[$braces['close']]->clear();
}
}
$nextIndex = $includy['begin'] + 1;
$nextToken = $tokens[$nextIndex];
while ($nextToken->isEmpty()) {
$nextToken = $tokens[++$nextIndex];
}
if ($nextToken->isWhitespace()) {
$nextToken->setContent(' ');
} elseif ($braces || $tokens[$nextIndex]->isGivenKind(array(T_VARIABLE, T_CONSTANT_ENCAPSED_STRING, T_COMMENT))) {
$tokens->insertAt($includy['begin'] + 1, new Token(array(T_WHITESPACE, ' ')));
}
}
}
private function findIncludies(Tokens $tokens)
{
static $includyTokenKinds = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE);
$includies = array();
foreach ($tokens->findGivenKind($includyTokenKinds) as $includyTokens) {
foreach ($includyTokens as $index => $token) {
$includy = array(
'begin' => $index,
'braces' => null,
'end' => $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG))),
);
$nextTokenIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextTokenIndex];
if ($nextToken->equals('(')) {
$braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextTokenIndex);
if ($tokens[$tokens->getNextMeaningfulToken($braceCloseIndex)]->equalsAny(array(';', array(T_CLOSE_TAG)))) {
$includy['braces'] = array(
'open' => $nextTokenIndex,
'close' => $braceCloseIndex,
);
}
}
$includies[] = $includy;
}
}
return $includies;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class JoinFunctionFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_STRING) as $index => $token) {
if ('join' !== $token->getContent()) {
continue;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevToken->isGivenKind(array(T_DOUBLE_COLON, T_NEW, T_NS_SEPARATOR, T_OBJECT_OPERATOR, T_FUNCTION))) {
continue;
}
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if ($nextToken->isGivenKind(array(T_DOUBLE_COLON, T_NS_SEPARATOR))) {
continue;
}
$token->setContent('implode');
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Implode function should be used instead of join function.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ListCommasFixer extends AbstractFixer
{
public function getDescription()
{
return 'Remove trailing commas in list function calls.';
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_LIST)) {
continue;
}
$openIndex = $tokens->getNextMeaningfulToken($index);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$markIndex = null;
$prevIndex = $tokens->getPrevNonWhitespace($closeIndex);
while ($tokens[$prevIndex]->equals(',')) {
$markIndex = $prevIndex;
$prevIndex = $tokens->getPrevNonWhitespace($prevIndex);
}
if (null !== $markIndex) {
$tokens->clearRange(
$tokens->getPrevNonWhitespace($markIndex) + 1,
$closeIndex - 1
);
}
}
return $tokens->generateCode();
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class LowercaseCastFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if (!$tokens[$index]->isCast()) {
continue;
}
$tokens[$index]->setContent(strtolower($tokens[$index]->getContent()));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Cast should be written in lower case.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class MethodArgumentDefaultValueFixer extends AbstractFixer
{
public function getDescription()
{
return 'In method arguments there must not be arguments with default values before non-default ones.';
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($i = 0, $l = $tokens->count(); $i < $l; ++$i) {
if (!$tokens[$i]->isGivenKind(T_FUNCTION)) {
continue;
}
$startIndex = $tokens->getNextTokenOfKind($i, array('('));
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
$this->fixFunctionDefinition($tokens, $startIndex, $i);
}
return $tokens->generateCode();
}
private function fixFunctionDefinition(Tokens $tokens, $startIndex, $endIndex)
{
$lastArgumentIndex = $this->getLastNonDefaultArgumentIndex($tokens, $startIndex, $endIndex);
if (!$lastArgumentIndex) {
return;
}
for ($i = $lastArgumentIndex; $i > $startIndex; --$i) {
$token = $tokens[$i];
if ($token->isGivenKind(T_VARIABLE)) {
$lastArgumentIndex = $i;
continue;
}
if (!$token->equals('=') || $this->isTypehintedNullableVariable($tokens, $i)) {
continue;
}
$endIndex = $tokens->getPrevTokenOfKind($lastArgumentIndex, array(','));
$endIndex = $tokens->getPrevMeaningfulToken($endIndex);
$this->removeDefaultArgument($tokens, $i, $endIndex);
}
}
private function getLastNonDefaultArgumentIndex(Tokens $tokens, $startIndex, $endIndex)
{
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
$token = $tokens[$i];
if ($token->equals('=')) {
$i = $tokens->getPrevMeaningfulToken($i);
continue;
}
if ($token->isGivenKind(T_VARIABLE) && !$this->isEllipsis($tokens, $i)) {
return $i;
}
}
}
private function isEllipsis(Tokens $tokens, $variableIndex)
{
if (!defined('T_ELLIPSIS')) {
return $tokens[$tokens->getPrevMeaningfulToken($variableIndex)]->equals('.');
}
return $tokens[$tokens->getPrevMeaningfulToken($variableIndex)]->isGivenKind(T_ELLIPSIS);
}
private function removeDefaultArgument(Tokens $tokens, $startIndex, $endIndex)
{
for ($i = $startIndex; $i <= $endIndex;) {
$tokens[$i]->clear();
$this->clearWhitespacesBeforeIndex($tokens, $i);
$i = $tokens->getNextMeaningfulToken($i);
}
}
private function isTypehintedNullableVariable(Tokens $tokens, $index)
{
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if (!$nextToken->equals(array(T_STRING, 'null'), false)) {
return false;
}
$variableIndex = $tokens->getPrevMeaningfulToken($index);
$searchTokens = array(',', '(', array(T_STRING), array(CT_ARRAY_TYPEHINT));
$typehintKinds = array(T_STRING, CT_ARRAY_TYPEHINT);
if (defined('T_CALLABLE')) {
$searchTokens[] = array(T_CALLABLE);
$typehintKinds[] = T_CALLABLE;
}
$prevIndex = $tokens->getPrevTokenOfKind($variableIndex, $searchTokens);
return $tokens[$prevIndex]->isGivenKind($typehintKinds);
}
private function clearWhitespacesBeforeIndex(Tokens $tokens, $index)
{
$token = $tokens[$index - 1];
if ($token->isGivenKind(T_WHITESPACE)) {
$token->clear();
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class MultilineArrayTrailingCommaFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if ($tokens->isArray($index)) {
$this->fixArray($tokens, $index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHP multi-line arrays should have a trailing comma.';
}
private function fixArray(Tokens $tokens, $index)
{
if (!$tokens->isArrayMultiLine($index)) {
return;
}
$startIndex = $index;
if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
$startIndex = $tokens->getNextTokenOfKind($startIndex, array('('));
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
} else {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
}
$beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex);
$beforeEndToken = $tokens[$beforeEndIndex];
if ($startIndex !== $beforeEndIndex && !$beforeEndToken->equalsAny(array(',', array(T_END_HEREDOC)))) {
$tokens->insertAt($beforeEndIndex + 1, new Token(','));
$endToken = $tokens[$endIndex];
if (!$endToken->isComment() && !$endToken->isWhitespace()) {
$tokens->ensureWhitespaceAtIndex($endIndex, 1, ' ');
}
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class NamespaceNoLeadingWhitespaceFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = count($tokens) - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_NAMESPACE)) {
continue;
}
$beforeNamespace = $tokens[$index - 1];
if (!$beforeNamespace->isWhitespace()) {
if (!self::endsWithWhitespace($beforeNamespace->getContent())) {
$tokens->insertAt($index, new Token(array(T_WHITESPACE, "\n")));
}
continue;
}
$lastNewline = strrpos($beforeNamespace->getContent(), "\n");
if (false === $lastNewline) {
$beforeBeforeNamespace = $tokens[$index - 2];
if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) {
$beforeNamespace->clear();
} else {
$beforeNamespace->setContent(' ');
}
} else {
$beforeNamespace->setContent(substr($beforeNamespace->getContent(), 0, $lastNewline + 1));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'The namespace declaration line shouldn\'t contain leading whitespace.';
}
private static function endsWithWhitespace($str)
{
if ('' === $str) {
return false;
}
return '' === trim(substr($str, -1));
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NativeFunctionCasingFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $nativeFunctionNames = null;
if (null === $nativeFunctionNames) {
$nativeFunctionNames = $this->getNativeFunctionNames();
}
$tokens = Tokens::fromCode($content);
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind(T_STRING)) {
continue;
}
$next = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$next]->equals('(')) {
$index = $next;
continue;
}
$functionNamePrefix = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$functionNamePrefix]->isGivenKind(array(T_DOUBLE_COLON, T_NEW, T_OBJECT_OPERATOR, T_FUNCTION))) {
continue;
}
if ($tokens[$functionNamePrefix]->isGivenKind(T_NS_SEPARATOR)) {
$prev = $tokens->getPrevMeaningfulToken($functionNamePrefix);
if ($tokens[$prev]->isGivenKind(array(T_STRING, T_NEW))) {
continue;
}
}
$lower = strtolower($tokens[$index]->getContent());
if (!array_key_exists($lower, $nativeFunctionNames)) {
continue;
}
$tokens[$index]->setContent($nativeFunctionNames[$lower]);
$index = $next;
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Function defined by PHP should be called using the correct casing.';
}
private function getNativeFunctionNames()
{
$allFunctions = get_defined_functions();
$functions = array();
foreach ($allFunctions['internal'] as $function) {
$functions[strtolower($function)] = $function;
}
return $functions;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class NewWithBracesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $nextTokenKinds = null;
if (null === $nextTokenKinds) {
$nextTokenKinds = array(
'?',
';',
',',
'(',
')',
'[',
']',
':',
'<',
'>',
'+',
'-',
'*',
'/',
'%',
'&',
'^',
'|',
array(T_CLASS),
array(T_IS_SMALLER_OR_EQUAL),
array(T_IS_GREATER_OR_EQUAL),
array(T_IS_EQUAL),
array(T_IS_NOT_EQUAL),
array(T_IS_IDENTICAL),
array(T_IS_NOT_IDENTICAL),
array(T_CLOSE_TAG),
array(T_LOGICAL_AND),
array(T_LOGICAL_OR),
array(T_LOGICAL_XOR),
array(T_BOOLEAN_AND),
array(T_BOOLEAN_OR),
array(T_SL),
array(T_SR),
array(T_INSTANCEOF),
array(T_AS),
array(T_DOUBLE_ARROW),
);
if (defined('T_POW')) {
$nextTokenKinds[] = array(T_POW);
}
if (defined('T_SPACESHIP')) {
$nextTokenKinds[] = array(T_SPACESHIP);
}
}
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 3; $index > 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_NEW)) {
continue;
}
$nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds);
$nextToken = $tokens[$nextIndex];
if ($nextToken->isGivenKind(T_CLASS)) {
if (!$tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals('(')) {
$this->insertBracesAfter($tokens, $nextIndex);
}
continue;
}
while ($nextToken->equals('[')) {
$nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $nextIndex) + 1;
$nextToken = $tokens[$nextIndex];
}
if ($nextToken->isGivenKind(T_WHITESPACE)) {
$nextIndex = $tokens->getNextNonWhitespace($nextIndex);
$nextToken = $tokens[$nextIndex];
}
if ($nextToken->equals('(')) {
continue;
}
$this->insertBracesAfter($tokens, $tokens->getPrevMeaningfulToken($nextIndex));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'All instances created with new keyword must be followed by braces.';
}
private function insertBracesAfter(Tokens $tokens, $index)
{
$tokens->insertAt(++$index, array(new Token('('), new Token(')')));
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;
class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isClassy()) {
continue;
}
$startBraceIndex = $tokens->getNextTokenOfKind($index, array('{'));
if (!$tokens[$startBraceIndex + 1]->isWhitespace()) {
continue;
}
$this->fixWhitespace($tokens[$startBraceIndex + 1]);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should be no empty lines after class opening brace.';
}
private function fixWhitespace(Token $token)
{
$content = $token->getContent();
if (substr_count($content, "\n") > 1) {
$lines = Utils::splitLines($content);
$token->setContent("\n".end($lines));
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NoEmptyCommentFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_COMMENT)) {
$this->fixComment($tokens, $index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should not be an empty comments.';
}
public function getPriority()
{
return 2;
}
private function fixComment(Tokens $tokens, $index)
{
$content = $tokens[$index]->getContent();
if ('#' === $content[0]) {
if (preg_match('|^#\s*$|', $content)) {
$this->clearCommentToken($tokens, $index);
}
return;
}
if ('/' === $content[1]) {
if (preg_match('|^//\s*$|', $content)) {
$this->clearCommentToken($tokens, $index);
}
return;
}
if (preg_match('|^/\*\s*\*/$|', $content)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
private function clearCommentToken(Tokens $tokens, $index)
{
if ("\n" !== substr($tokens[$index]->getContent(), -1, 1)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
$previous = $tokens->getNonEmptySibling($index, -1);
if ($tokens[$previous]->isWhitespace()) {
$tokens[$previous]->setContent($tokens[$previous]->getContent()."\n");
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
$next = $tokens->getNonEmptySibling($index, 1);
if (null !== $next && $tokens[$next]->isWhitespace()) {
$tokens[$next]->setContent("\n".$tokens[$next]->getContent());
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
$tokens->overrideAt($index, array(T_WHITESPACE, "\n", $tokens[$index]->getLine()));
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;
class NoEmptyLinesAfterPhpdocsFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $forbiddenSuccessors = array(
T_DOC_COMMENT,
T_COMMENT,
T_WHITESPACE,
T_RETURN,
T_THROW,
T_GOTO,
T_CONTINUE,
T_BREAK,
);
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
$next = $tokens->getNextNonWhitespace($index);
if ($index + 2 === $next && false === $tokens[$next]->isGivenKind($forbiddenSuccessors)) {
$this->fixWhitespace($tokens[$index + 1]);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should not be blank lines between docblock and the documented element.';
}
private function fixWhitespace(Token $token)
{
$content = $token->getContent();
if (substr_count($content, "\n") > 1) {
$lines = Utils::splitLines($content);
$token->setContent("\n".end($lines));
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NoEmptyPhpdocFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
if (preg_match('#^/\*\*[\s\*]*\*/$#', $token->getContent())) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should not be empty PHPDoc blocks.';
}
public function getPriority()
{
return 5;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class NoEmptyStatementFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind(T_FOR)) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($index)) + 1;
continue;
}
if (!$tokens[$index]->equals(';')) {
continue;
}
$previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$previousMeaningfulIndex]->equalsAny(array('{', ';', array(T_OPEN_TAG)))) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
continue;
}
if ($tokens[$previousMeaningfulIndex]->equals('}')) {
$this->fixSemicolonAfterCurlyBraceClose($tokens, $index, $previousMeaningfulIndex);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Remove useless semicolon statements.';
}
public function getPriority()
{
return 25;
}
private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, $index, $curlyCloseIndex)
{
static $beforeCurlyOpeningKinds = null;
if (null === $beforeCurlyOpeningKinds) {
$beforeCurlyOpeningKinds = array(T_ELSE, T_NAMESPACE, T_OPEN_TAG);
if (defined('T_FINALLY')) {
$beforeCurlyOpeningKinds[] = T_FINALLY;
}
}
$curlyOpeningIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $curlyCloseIndex, false);
$beforeCurlyOpening = $tokens->getPrevMeaningfulToken($curlyOpeningIndex);
if ($tokens[$beforeCurlyOpening]->isGivenKind($beforeCurlyOpeningKinds) || $tokens[$beforeCurlyOpening]->equalsAny(array(';', '{', '}'))) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
if ($tokens[$beforeCurlyOpening]->isGivenKind(T_STRING)) {
$classyTest = $tokens->getPrevMeaningfulToken($beforeCurlyOpening);
while ($tokens[$classyTest]->equals(',') || $tokens[$classyTest]->isGivenKind(array(T_STRING, T_NS_SEPARATOR, T_EXTENDS, T_IMPLEMENTS))) {
$classyTest = $tokens->getPrevMeaningfulToken($classyTest);
}
if (
$tokens[$classyTest]->isGivenKind(T_NAMESPACE) ||
($tokens[$classyTest]->isClassy() && !$this->isAnonymousClass($tokens, $classyTest))
) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
return;
}
if (!$tokens[$beforeCurlyOpening]->equals(')')) {
return;
}
$openingBrace = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeCurlyOpening, false);
$beforeOpeningBrace = $tokens->getPrevMeaningfulToken($openingBrace);
if ($tokens[$beforeOpeningBrace]->isGivenKind(array(T_IF, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE, T_SWITCH, T_CATCH, T_DECLARE))) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
if ($tokens[$beforeOpeningBrace]->isGivenKind(T_STRING)) {
$beforeString = $tokens->getPrevMeaningfulToken($beforeOpeningBrace);
if ($tokens[$beforeString]->isGivenKind(T_FUNCTION)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
}
private function isAnonymousClass(Tokens $tokens, $index)
{
return $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW);
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class ObjectOperatorFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_OBJECT_OPERATOR) as $index => $token) {
if ($tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t")) && !$tokens[$index - 2]->isComment()) {
$tokens[$index - 1]->clear();
}
if ($tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t")) && !$tokens[$index + 2]->isComment()) {
$tokens[$index + 1]->clear();
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should not be space before or after object T_OBJECT_OPERATOR.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class OperatorsSpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 2; $index > 0; --$index) {
if (!$tokens->isBinaryOperator($index)) {
continue;
}
$isDeclare = $this->isDeclareStatement($tokens, $index);
if (false !== $isDeclare) {
$index = $isDeclare;
} else {
$this->fixWhiteSpaceAroundOperator($tokens, $index);
}
--$index;
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Binary operators should be surrounded by at least one space.';
}
private function fixWhiteSpaceAroundOperator(Tokens $tokens, $index)
{
$preserveAlignment = $tokens[$index]->isGivenKind(T_DOUBLE_ARROW) || $tokens[$index]->equals('=');
if ($tokens[$index + 1]->isWhitespace()) {
$content = $tokens[$index + 1]->getContent();
if (!$preserveAlignment && ' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) {
$tokens[$index + 1]->setContent(' ');
}
} else {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
}
if ($tokens[$index - 1]->isWhitespace()) {
$content = $tokens[$index - 1]->getContent();
if (!$preserveAlignment && ' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) {
$tokens[$index - 1]->setContent(' ');
}
} else {
$tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
}
}
private function isDeclareStatement(Tokens $tokens, $index)
{
$prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_STRING)) {
$prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
if ($tokens[$prevMeaningfulIndex]->equals('(')) {
$prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_DECLARE)) {
return $prevMeaningfulIndex;
}
}
}
return false;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocAnnotationWithoutDotFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotations();
if (empty($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
if ($annotation->getTag()->valid()) {
$line = $doc->getLine($annotation->getEnd());
$content = preg_replace('/(?<![.。])[.。](\s+)$/u', '\1', $line->getContent());
if (null !== $content) {
$line->setContent($content);
}
}
}
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Phpdocs annotation descriptions should not end with a full stop.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;
class PhpdocIndentFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) {
continue;
}
$prevToken = $tokens[$index - 1];
if (
$prevToken->isGivenKind(T_OPEN_TAG)
|| ($prevToken->isWhitespace(array('whitespaces' => " \t")) && !$tokens[$index - 2]->isGivenKind(T_OPEN_TAG))
|| $prevToken->equalsAny(array(';', '{'))
) {
continue;
}
$indent = '';
if ($tokens[$nextIndex - 1]->isWhitespace()) {
$indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]);
}
$prevToken->setContent($this->fixWhitespaceBefore($prevToken->getContent(), $indent));
$token->setContent($this->fixDocBlock($token->getContent(), $indent));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Docblocks should have the same indentation as the documented subject.';
}
public function getPriority()
{
return 20;
}
private function fixDocBlock($content, $indent)
{
return ltrim(preg_replace('/^[ \t]*/m', $indent.' ', $content));
}
private function fixWhitespaceBefore($content, $indent)
{
return rtrim($content, " \t").$indent;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class PhpdocInlineTagFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$content = $token->getContent();
$content = preg_replace_callback(
'#(?:@{+|{+[ \t]*@)[ \t]*(example|id|internal|inheritdoc|link|source|toc|tutorial)s?([^}]*)(?:}+)#i',
function (array $matches) {
$doc = trim($matches[2]);
if ('' === $doc) {
return '{@'.strtolower($matches[1]).'}';
}
return '{@'.strtolower($matches[1]).' '.$doc.'}';
},
$content
);
$content = preg_replace(
'#(?<!{)@inheritdocs?(?!})#i',
'{@inheritdoc}',
$content
);
$token->setContent($content);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Fix phpdoc inline tags, make inheritdoc always inline.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractAnnotationRemovalFixer;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocNoAccessFixer extends AbstractAnnotationRemovalFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$this->removeAnnotations($tokens, array('access'));
return $tokens->generateCode();
}
public function getDescription()
{
return '@access annotations should be omitted from phpdocs.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocNoEmptyReturnFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotationsOfType('return');
if (empty($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
$this->fixAnnotation($doc, $annotation);
}
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return '@return void and @return null annotations should be omitted from phpdocs.';
}
public function getPriority()
{
return 10;
}
private function fixAnnotation(DocBlock $doc, Annotation $annotation)
{
if (1 === preg_match('/@return\s+(void|null)(?!\|)/', $doc->getLine($annotation->getStart())->getContent())) {
$annotation->remove();
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractAnnotationRemovalFixer;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocNoPackageFixer extends AbstractAnnotationRemovalFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$this->removeAnnotations($tokens, array('package', 'subpackage'));
return $tokens->generateCode();
}
public function getDescription()
{
return '@package and @subpackage annotations should be omitted from phpdocs.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;
class PhpdocParamsFixer extends AbstractFixer
{
private $regex;
private $regexCommentLine;
public function __construct()
{
$paramTag = '(?P<tag>param)\s+(?P<hint>[^$]+?)\s+(?P<var>&?\$[^\s]+)';
$otherTags = '(?P<tag2>return|throws|var|type)\s+(?P<hint2>[^\s]+?)';
$desc = '(?:\s+(?P<desc>.*)|\s*)';
$this->regex = '/^(?P<indent>(?: {4})*) \* @(?:'.$paramTag.'|'.$otherTags.')'.$desc.'$/';
$this->regexCommentLine = '/^(?P<indent>(?: {4})*) \*(?! @)(?:\s+(?P<desc>.+))(?<!\*\/)$/';
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$token->setContent($this->fixDocBlock($token->getContent()));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'All items of the @param, @throws, @return, @var, and @type phpdoc tags must be aligned vertically.';
}
public function getPriority()
{
return -11;
}
private function fixDocBlock($content)
{
$lines = Utils::splitLines($content);
$l = count($lines);
for ($i = 0; $i < $l; ++$i) {
$items = array();
$matches = $this->getMatches($lines[$i]);
if (null === $matches) {
continue;
}
$current = $i;
$items[] = $matches;
while ($matches = $this->getMatches($lines[++$i], true)) {
$items[] = $matches;
}
$tagMax = 0;
$hintMax = 0;
$varMax = 0;
foreach ($items as $item) {
if (null === $item['tag']) {
continue;
}
$tagMax = max($tagMax, strlen($item['tag']));
$hintMax = max($hintMax, strlen($item['hint']));
$varMax = max($varMax, strlen($item['var']));
}
$currTag = null;
foreach ($items as $j => $item) {
if (null === $item['tag']) {
if ($item['desc'][0] === '@') {
$lines[$current + $j] = $item['indent'].' * '.$item['desc']."\n";
continue;
}
$line =
$item['indent']
.' * '
.str_repeat(' ', $tagMax + $hintMax + $varMax + ('param' === $currTag ? 3 : 2))
.$item['desc']
."\n";
$lines[$current + $j] = $line;
continue;
}
$currTag = $item['tag'];
$line =
$item['indent']
.' * @'
.$item['tag']
.str_repeat(' ', $tagMax - strlen($item['tag']) + 1)
.$item['hint']
;
if (!empty($item['var'])) {
$line .=
str_repeat(' ', $hintMax - strlen($item['hint']) + 1)
.$item['var']
.(
!empty($item['desc'])
? str_repeat(' ', $varMax - strlen($item['var']) + 1).$item['desc']."\n"
: "\n"
)
;
} elseif (!empty($item['desc'])) {
$line .= str_repeat(' ', $hintMax - strlen($item['hint']) + 1).$item['desc']."\n";
} else {
$line .= "\n";
}
$lines[$current + $j] = $line;
}
}
return implode($lines);
}
private function getMatches($line, $matchCommentOnly = false)
{
if (preg_match($this->regex, $line, $matches)) {
if (!empty($matches['tag2'])) {
$matches['tag'] = $matches['tag2'];
$matches['hint'] = $matches['hint2'];
}
return $matches;
}
if ($matchCommentOnly && preg_match($this->regexCommentLine, $line, $matches)) {
$matches['tag'] = null;
$matches['var'] = '';
$matches['hint'] = '';
return $matches;
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractPhpdocTypesFixer;
class PhpdocScalarFixer extends AbstractPhpdocTypesFixer
{
private static $types = array(
'boolean' => 'bool',
'double' => 'float',
'integer' => 'int',
'real' => 'float',
);
public function getDescription()
{
return 'Scalar types should always be written in the same form. "int", not "integer"; "bool", not "boolean"; "float", not "real" or "double".';
}
public function getPriority()
{
return 15;
}
protected function normalize($type)
{
if (array_key_exists($type, self::$types)) {
return self::$types[$type];
}
return $type;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\TagComparator;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocSeparationFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
$doc = new DocBlock($token->getContent());
$this->fixDescription($doc);
$this->fixAnnotations($doc);
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Annotations in phpdocs should be grouped together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line.';
}
private function fixDescription(DocBlock $doc)
{
foreach ($doc->getLines() as $index => $line) {
if ($line->containsATag()) {
break;
}
if ($line->containsUsefulContent()) {
$next = $doc->getLine($index + 1);
if ($next->containsATag()) {
$line->addBlank();
break;
}
}
}
}
private function fixAnnotations(DocBlock $doc)
{
foreach ($doc->getAnnotations() as $index => $annotation) {
$next = $doc->getAnnotation($index + 1);
if (null === $next) {
break;
}
if (true === $next->getTag()->valid()) {
if (TagComparator::shouldBeTogether($annotation->getTag(), $next->getTag())) {
$this->ensureAreTogether($doc, $annotation, $next);
} else {
$this->ensureAreSeparate($doc, $annotation, $next);
}
}
}
return $doc->getContent();
}
private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second)
{
$pos = $first->getEnd();
$final = $second->getStart();
for ($pos = $pos + 1; $pos < $final; ++$pos) {
$doc->getLine($pos)->remove();
}
}
private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second)
{
$pos = $first->getEnd();
$final = $second->getStart() - 1;
if ($pos === $final) {
$doc->getLine($pos)->addBlank();
return;
}
for ($pos = $pos + 1; $pos < $final; ++$pos) {
$doc->getLine($pos)->remove();
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocShortDescriptionFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$doc = new DocBlock($token->getContent());
$end = $this->findShortDescriptionEnd($doc->getLines());
if (null !== $end) {
$line = $doc->getLine($end);
$content = rtrim($line->getContent());
if (!$this->isCorrectlyFormatted($content)) {
$line->setContent($content.".\n");
$token->setContent($doc->getContent());
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Phpdocs short descriptions should end in either a full stop, exclamation mark, or question mark.';
}
private function findShortDescriptionEnd(array $lines)
{
$reachedContent = false;
foreach ($lines as $index => $line) {
if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) {
return $index - 1;
}
if ($line->containsATag()) {
return;
}
if ($line->containsUsefulContent()) {
$reachedContent = true;
}
}
}
private function isCorrectlyFormatted($content)
{
if (false !== strpos(strtolower($content), '{@inheritdoc}')) {
return true;
}
return $content !== rtrim($content, '.。!?¡¿ï¼<C3AF>?');
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class PhpdocSingleLineVarSpacingFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_DOC_COMMENT)) {
$token->setContent($this->fixTokenContent($token->getContent()));
continue;
}
if (!$token->isGivenKind(T_COMMENT)) {
continue;
}
$content = $token->getContent();
$fixedContent = $this->fixTokenContent($content);
if ($content !== $fixedContent) {
$tokens->overrideAt($index, array(T_DOC_COMMENT, $fixedContent, $token->getLine()));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Single line @var PHPDoc should have proper spacing.';
}
public function getPriority()
{
return -10;
}
private function fixTokenContent($content)
{
return preg_replace_callback(
'#^/\*\*[ \t]*@var[ \t]+(\S+)[ \t]*(\$\S+)?[ \t]*([^\n]*)\*/$#',
function (array $matches) {
$content = '/** @var';
for ($i = 1, $m = count($matches); $i < $m; ++$i) {
if ('' !== $matches[$i]) {
$content .= ' '.$matches[$i];
}
}
$content = rtrim($content);
return $content.' */';
},
$content
);
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocToCommentFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $controlStructures = array(
T_FOREACH,
T_IF,
T_SWITCH,
T_WHILE,
T_FOR,
);
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = null !== $nextIndex ? $tokens[$nextIndex] : null;
if (null === $nextToken || $nextToken->equals('}')) {
$tokens->overrideAt($index, array(T_COMMENT, '/*'.ltrim($token->getContent(), '/*'), $token->getLine()));
continue;
}
if ($this->isStructuralElement($nextToken)) {
continue;
}
if ($nextToken->isGivenKind($controlStructures) && $this->isValidControl($tokens, $token, $nextIndex)) {
continue;
}
if ($nextToken->isGivenKind(T_VARIABLE) && $this->isValidVariable($tokens, $token, $nextIndex)) {
continue;
}
if ($nextToken->isGivenKind(T_LIST) && $this->isValidList($tokens, $token, $nextIndex)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(array(T_OPEN_TAG, T_NAMESPACE))) {
continue;
}
$tokens->overrideAt($index, array(T_COMMENT, '/*'.ltrim($token->getContent(), '/*'), $token->getLine()));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Docblocks should only be used on structural elements.';
}
public function getPriority()
{
return 25;
}
private function isStructuralElement(Token $token)
{
static $skip = array(
T_PRIVATE,
T_PROTECTED,
T_PUBLIC,
T_FUNCTION,
T_ABSTRACT,
T_CONST,
T_NAMESPACE,
T_REQUIRE,
T_REQUIRE_ONCE,
T_INCLUDE,
T_INCLUDE_ONCE,
T_FINAL,
T_STATIC,
);
return $token->isClassy() || $token->isGivenKind($skip);
}
private function isValidControl(Tokens $tokens, Token $docsToken, $controlIndex)
{
$index = $tokens->getNextMeaningfulToken($controlIndex);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$docsContent = $docsToken->getContent();
for ($index = $index + 1; $index < $endIndex; ++$index) {
$token = $tokens[$index];
if (
$token->isGivenKind(T_VARIABLE) &&
false !== strpos($docsContent, $token->getContent())
) {
return true;
}
}
return false;
}
private function isValidVariable(Tokens $tokens, Token $docsToken, $variableIndex)
{
$nextIndex = $tokens->getNextMeaningfulToken($variableIndex);
return $tokens[$nextIndex]->equals('=');
}
private function isValidList(Tokens $tokens, Token $docsToken, $listIndex)
{
$endIndex = $tokens->getNextTokenOfKind($listIndex, array(')'));
$docsContent = $docsToken->getContent();
for ($index = $listIndex + 1; $index < $endIndex; ++$index) {
$token = $tokens[$index];
if (
$token->isGivenKind(T_VARIABLE)
&& false !== strpos($docsContent, $token->getContent())
) {
return true;
}
}
return false;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocTrimFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$content = $token->getContent();
$content = $this->fixStart($content);
$content = $this->fixEnd($content);
$token->setContent($content);
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Phpdocs should start and end with content, excluding the very first and last line of the docblocks.';
}
public function getPriority()
{
return -5;
}
private function fixStart($content)
{
$doc = new DocBlock($content);
$lines = $doc->getLines();
$total = count($lines);
foreach ($lines as $index => $line) {
if (!$line->isTheStart()) {
if ($total - $index < 3 || $line->containsUsefulContent()) {
break;
}
$line->remove();
}
}
return $doc->getContent();
}
private function fixEnd($content)
{
$doc = new DocBlock($content);
$lines = array_reverse($doc->getLines());
$total = count($lines);
foreach ($lines as $index => $line) {
if (!$line->isTheEnd()) {
if ($total - $index < 3 || $line->containsUsefulContent()) {
break;
}
$line->remove();
}
}
return $doc->getContent();
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocTypeToVarFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotationsOfType('type');
if (empty($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
$line = $doc->getLine($annotation->getStart());
$line->setContent(str_replace('@type', '@var', $line->getContent()));
}
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return '@type should always be written as @var.';
}
public function getPriority()
{
return -9;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractPhpdocTypesFixer;
final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer
{
private static $types = array(
'array',
'bool',
'boolean',
'callable',
'double',
'false',
'float',
'int',
'integer',
'iterable',
'mixed',
'null',
'object',
'real',
'resource',
'self',
'static',
'string',
'true',
'void',
'$this',
);
public function getDescription()
{
return 'The correct case must be used for standard PHP types in phpdoc.';
}
public function getPriority()
{
return 16;
}
protected function normalize($type)
{
$lower = strtolower($type);
if (in_array($lower, self::$types, true)) {
return $lower;
}
return $type;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;
use Symfony\CS\Tokenizer\Tokens;
class PhpdocVarWithoutNameFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
$doc = new DocBlock($token->getContent());
if (1 === count($doc->getLines())) {
continue;
}
$annotations = $doc->getAnnotationsOfType(array('param', 'return', 'type', 'var'));
if (!isset($annotations[0]) || !in_array($annotations[0]->getTag()->getName(), array('type', 'var'), true)) {
continue;
}
$this->fixLine($doc->getLine($annotations[0]->getStart()));
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
public function getDescription()
{
return '@var and @type annotations should not contain the variable name.';
}
private function fixLine(Line $line)
{
$content = $line->getContent();
preg_match_all('/ \$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $content, $matches);
if (isset($matches[0][0])) {
$line->setContent(str_replace($matches[0][0], '', $content));
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class PreIncrementFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(array(T_INC, T_DEC)) || !$tokens->isUnarySuccessorOperator($index)) {
continue;
}
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if (!$nextToken->equalsAny(array(';', ')'))) {
continue;
}
$startIndex = $this->findStart($tokens, $index);
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($startIndex)];
if ($prevToken->equalsAny(array(';', '{', '}', array(T_OPEN_TAG)))) {
$tokens->insertAt($startIndex, clone $token);
$token->clear();
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Pre incrementation/decrementation should be used if possible.';
}
private function findStart(Tokens $tokens, $index)
{
do {
$index = $tokens->getPrevMeaningfulToken($index);
$token = $tokens[$index];
$blockType = $tokens->detectBlockType($token);
if (null !== $blockType && !$blockType['isStart']) {
$index = $tokens->findBlockEnd($blockType['type'], $index, false);
$token = $tokens[$index];
}
} while (!$token->equalsAny(array('$', array(T_VARIABLE))));
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->equals('$')) {
$index = $prevIndex;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
}
if ($prevToken->isGivenKind(T_OBJECT_OPERATOR)) {
return $this->findStart($tokens, $prevIndex);
}
if ($prevToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) {
$prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if (!$tokens[$prevPrevIndex]->isGivenKind(T_STRING)) {
return $this->findStart($tokens, $prevIndex);
}
$index = $tokens->getTokenNotOfKindSibling($prevIndex, -1, array(array(T_NS_SEPARATOR), array(T_STRING)));
$index = $tokens->getNextMeaningfulToken($index);
}
return $index;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class PrintToEchoFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$printTokens = $tokens->findGivenKind(T_PRINT);
foreach ($printTokens as $printIndex => $printToken) {
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($printIndex)];
if (!$prevToken->equalsAny(array(';', '{', '}', array(T_OPEN_TAG)))) {
continue;
}
$tokens->overrideAt($printIndex, array(T_ECHO, 'echo'));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Converts print language construct to echo if possible.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class RemoveLeadingSlashUseFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$foundNamespace = $tokens->findGivenKind(T_NAMESPACE);
if (empty($foundNamespace)) {
return $content;
}
$firstNamespaceIdx = key($foundNamespace);
$usesIdxs = $tokens->getImportUseIndexes();
foreach ($usesIdxs as $idx) {
if ($idx < $firstNamespaceIdx) {
continue;
}
$nextTokenIdx = $tokens->getNextNonWhitespace($idx);
$nextToken = $tokens[$nextTokenIdx];
if ($nextToken->isGivenKind(T_NS_SEPARATOR)) {
$nextToken->clear();
}
}
return $tokens->generateCode();
}
public function getPriority()
{
return -20;
}
public function getDescription()
{
return 'Remove leading slashes in use clauses.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class RemoveLinesBetweenUsesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$this->removeLineBreaksBetweenUseStatements($tokens);
return $tokens->generateCode();
}
public function getPriority()
{
return -5;
}
public function getDescription()
{
return 'Removes line breaks between use statements.';
}
private function removeLineBreaksBetweenUseStatements(Tokens $tokens)
{
$namespacesImports = $tokens->getImportUseIndexes(true);
if (!count($namespacesImports)) {
return;
}
foreach ($namespacesImports as $uses) {
$uses = array_reverse($uses);
$this->fixLineBreaksPerImportGroup($tokens, $uses);
}
}
private function fixLineBreaksPerImportGroup(Tokens $tokens, array $uses)
{
foreach ($uses as $index) {
$endIndex = $tokens->getNextTokenOfKind($index, array(';', T_CLOSE_TAG));
if ($endIndex === count($tokens) - 1) {
continue;
}
$afterSemicolonIndex = $tokens->getNextNonWhitespace($endIndex);
if (null === $afterSemicolonIndex || !$tokens[$afterSemicolonIndex]->isGivenKind(T_USE)) {
continue;
}
$nextToken = $tokens[$endIndex + 1];
if ($nextToken->isWhitespace()) {
$nextToken->setContent(preg_replace('/\n{2,}/', "\n", $nextToken->getContent()));
}
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class ReturnFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_RETURN)) {
continue;
}
$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
if (!$prevNonWhitespaceToken->equalsAny(array(';', '}'))) {
continue;
}
$prevToken = $tokens[$index - 1];
if ($prevToken->isWhitespace()) {
$parts = explode("\n", $prevToken->getContent());
$countParts = count($parts);
if (1 === $countParts) {
$prevToken->setContent(rtrim($prevToken->getContent(), " \t")."\n\n");
} elseif (count($parts) <= 2) {
$prevToken->setContent("\n".$prevToken->getContent());
}
} else {
$tokens->insertAt($index, new Token(array(T_WHITESPACE, "\n\n")));
++$index;
++$limit;
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'An empty line feed should precede a return statement.';
}
public function getPriority()
{
return -19;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class SelfAccessorFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($i = 0, $c = $tokens->count(); $i < $c; ++$i) {
if (!$tokens[$i]->isClassy() || $tokens->isAnonymousClass($i)) {
continue;
}
$nameIndex = $tokens->getNextTokenOfKind($i, array(array(T_STRING)));
$startIndex = $tokens->getNextTokenOfKind($nameIndex, array('{'));
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex);
$name = $tokens[$nameIndex]->getContent();
$this->replaceNameOccurrences($tokens, $name, $startIndex, $endIndex);
$i = $endIndex;
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Inside a classy element "self" should be preferred to the class name itself.';
}
private function replaceNameOccurrences(Tokens $tokens, $name, $startIndex, $endIndex)
{
for ($i = $startIndex; $i < $endIndex; ++$i) {
$token = $tokens[$i];
if (
$token->isGivenKind(T_CLASS) && $tokens->isAnonymousClass($i) ||
$token->isGivenKind(T_FUNCTION) && $tokens->isLambda($i)
) {
$i = $tokens->getNextTokenOfKind($i, array('{'));
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i);
continue;
}
if (!$token->equals(array(T_STRING, $name), false)) {
continue;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($i)];
$nextToken = $tokens[$tokens->getNextMeaningfulToken($i)];
if ($prevToken->isGivenKind(T_NS_SEPARATOR) || $nextToken->isGivenKind(T_NS_SEPARATOR)) {
continue;
}
if (
$prevToken->isGivenKind(array(T_INSTANCEOF, T_NEW)) ||
$nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)
) {
$token->setContent('self');
}
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class ShortBoolCastFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = count($tokens) - 1; $index > 1; --$index) {
if ($tokens[$index]->equals('!')) {
$index = $this->fixShortCast($tokens, $index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Short cast bool using double exclamation mark should not be used.';
}
public function getPriority()
{
return -9;
}
private function fixShortCast(Tokens $tokens, $index)
{
for ($i = $index - 1; $i > 1; --$i) {
if ($tokens[$i]->equals('!')) {
$this->fixShortCastToBoolCast($tokens, $i, $index);
break;
}
if (!$tokens[$i]->isComment() && !$tokens[$i]->isWhitespace()) {
break;
}
}
return $i;
}
private function fixShortCastToBoolCast(Tokens $tokens, $start, $end)
{
for (; $start <= $end; ++$start) {
if (!$tokens[$start]->isComment()) {
$tokens[$start]->clear();
}
}
$tokens->insertAt($start, new Token(array(T_BOOL_CAST, '(bool)')));
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class ShortScalarCastFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $castMap = array(
'boolean' => 'bool',
'integer' => 'int',
'double' => 'float',
'real' => 'float',
);
$tokens = Tokens::fromCode($content);
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if (!$tokens[$index]->isCast()) {
continue;
}
$castFrom = trim(substr($tokens[$index]->getContent(), 1, -1));
$castFromLowered = strtolower($castFrom);
if (!array_key_exists($castFromLowered, $castMap)) {
continue;
}
$tokens[$index]->setContent(str_replace($castFrom, $castMap[$castFromLowered], $tokens[$index]->getContent()));
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Cast "(boolean)" and "(integer)" should be written as "(bool)" and "(int)". "(double)" and "(real)" as "(float)".';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class SingleArrayNoTrailingCommaFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) {
if ($tokens->isArray($index)) {
$this->fixArray($tokens, $index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'PHP single-line arrays should not have trailing comma.';
}
private function fixArray(Tokens $tokens, $index)
{
if ($tokens->isArrayMultiLine($index)) {
return;
}
$startIndex = $index;
if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
$startIndex = $tokens->getNextTokenOfKind($startIndex, array('('));
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
} else {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
}
$beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex);
$beforeEndToken = $tokens[$beforeEndIndex];
if ($beforeEndToken->equals(',')) {
$tokens->removeTrailingWhitespace($beforeEndIndex);
$beforeEndToken->clear();
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractLinesBeforeNamespaceFixer;
use Symfony\CS\Tokenizer\Tokens;
class SingleBlankLineBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_NAMESPACE)) {
$this->fixLinesBeforeNamespace($tokens, $index, 2);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'There should be exactly one blank line before a namespace declaration.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class SingleQuoteFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
if (!$token->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) {
continue;
}
$content = $token->getContent();
if (
'"' === $content[0] &&
false === strpos($content, "'") &&
!preg_match('/(?<!\\\\)(?:\\\\{2})*\\\\(?!["$\\\\])/', $content)
) {
$content = substr($content, 1, -1);
$content = str_replace(array('\\"', '\\$'), array('"', '$'), $content);
$token->setContent('\''.$content.'\'');
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Convert double quotes to single quotes for simple strings.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
final class SpacesAfterSemicolonFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = count($tokens) - 2; $index > 0; --$index) {
if (!$tokens[$index]->equals(';')) {
continue;
}
if (!$tokens[$index + 1]->isWhitespace()) {
if (!$tokens[$index + 1]->equalsAny(array(')', array(T_INLINE_HTML)))) {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
}
} elseif (
isset($tokens[$index + 2])
&& !$tokens[$index + 1]->equals(array(T_WHITESPACE, ' '))
&& $tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t"))
&& !$tokens[$index + 2]->isComment()
&& !$tokens[$index + 2]->equals(')')
) {
$tokens[$index + 1]->setContent(' ');
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Fix whitespace after a semicolon.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class SpacesBeforeSemicolonFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t"))) {
continue;
}
if ($tokens[$index - 2]->equals(';')) {
if (!$tokens[$index - 1]->equals(' ')) {
$tokens[$index - 1]->setContent(' ');
}
} elseif (!$tokens[$index - 2]->isComment()) {
$tokens[$index - 1]->clear();
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Single-line whitespace before closing semicolon are prohibited.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class SpacesCastFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
static $insideCastSpaceReplaceMap = array(
' ' => '',
"\t" => '',
"\n" => '',
"\r" => '',
"\0" => '',
"\x0B" => '',
);
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isCast()) {
$token->setContent(strtr($token->getContent(), $insideCastSpaceReplaceMap));
if ($tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t"))) {
$tokens[$index + 1]->setContent(' ');
} elseif (!$tokens[$index + 1]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
}
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'A single space should be between cast and variable.';
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class StandardizeNotEqualFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_IS_NOT_EQUAL)) {
$tokens[$index]->setContent('!=');
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Replace all <> with !=.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class TernarySpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$ternaryLevel = 0;
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if ($token->isArray()) {
continue;
}
if ($token->equals('?')) {
++$ternaryLevel;
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index);
$nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];
if ($nextNonWhitespaceToken->equals(':')) {
if ($tokens[$index + 1]->isWhitespace()) {
$tokens[$index + 1]->clear();
}
} else {
$this->ensureWhitespaceExistence($tokens, $index + 1, true);
}
$this->ensureWhitespaceExistence($tokens, $index - 1, false);
continue;
}
if ($ternaryLevel && $token->equals(':')) {
$this->ensureWhitespaceExistence($tokens, $index + 1, true);
$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
if (!$prevNonWhitespaceToken->equals('?')) {
$this->ensureWhitespaceExistence($tokens, $index - 1, false);
}
--$ternaryLevel;
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Standardize spaces around ternary operator.';
}
private function ensureWhitespaceExistence(Tokens $tokens, $index, $after)
{
if ($tokens[$index]->isWhitespace()) {
if (false === strpos($tokens[$index]->getContent(), "\n")) {
if (!$tokens[$index - 1]->isComment() || false === strpos($tokens[$index - 1]->getContent(), "\n")) {
$tokens[$index]->setContent(' ');
}
}
return;
}
$indexChange = $after ? 0 : 1;
$tokens->insertAt($index + $indexChange, new Token(array(T_WHITESPACE, ' ', $tokens[$index]->getLine())));
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class TrimArraySpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) {
if ($tokens->isArray($index)) {
self::fixArray($tokens, $index);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Arrays should be formatted like function/method arguments, without leading or trailing single line space.';
}
private static function fixArray(Tokens $tokens, $index)
{
static $whitespaceOptions = array('whitespaces' => " \t");
$startIndex = $index;
if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
$startIndex = $tokens->getNextMeaningfulToken($startIndex);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
} else {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
}
$nextToken = $tokens[$startIndex + 1];
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex);
$nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];
$prevToken = $tokens[$endIndex - 1];
$prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex);
$prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex];
if (
$nextToken->isWhitespace($whitespaceOptions)
&& (
!$nextNonWhitespaceToken->isComment()
|| $nextNonWhitespaceIndex === $prevNonWhitespaceIndex
|| false === strpos($nextNonWhitespaceToken->getContent(), "\n")
)
) {
$nextToken->clear();
}
if (
$prevToken->isWhitespace($whitespaceOptions)
&& !$prevNonWhitespaceToken->equals(',')
&& !($prevNonWhitespaceToken->isComment() && $prevNonWhitespaceToken->getContent() !== rtrim($prevNonWhitespaceToken->getContent()))
) {
$prevToken->clear();
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class UnalignDoubleArrowFixer extends AbstractFixer
{
public function getDescription()
{
return 'Unalign double arrow symbols.';
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOUBLE_ARROW)) {
continue;
}
$this->fixWhitespace($tokens[$index - 1]);
$this->fixWhitespace($tokens[$index + 1]);
}
return $tokens->generateCode();
}
private function fixWhitespace(Token $token)
{
if ($token->isWhitespace(array('whitespaces' => " \t"))) {
$token->setContent(' ');
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
class UnalignEqualsFixer extends AbstractFixer
{
public function getDescription()
{
return 'Unalign equals symbols.';
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->equals('=')) {
continue;
}
$this->fixWhitespace($tokens[$index - 1]);
$this->fixWhitespace($tokens[$index + 1]);
}
return $tokens->generateCode();
}
private function fixWhitespace(Token $token)
{
if ($token->isWhitespace(array('whitespaces' => " \t"))) {
$token->setContent(' ');
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class UnaryOperatorsSpacesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if ($tokens->isUnarySuccessorOperator($index)) {
$tokens->removeLeadingWhitespace($index);
continue;
}
if ($tokens->isUnaryPredecessorOperator($index)) {
$tokens->removeTrailingWhitespace($index);
continue;
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Unary operators should be placed adjacent to their operands.';
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class UnneededControlParenthesesFixer extends AbstractFixer
{
private static $controlStatements = array(
'break',
'continue',
'clone',
'echo_print',
'return',
'switch_case',
'yield',
);
private static $loops = array(
'break' => array('lookupTokens' => T_BREAK, 'neededSuccessors' => array(';')),
'continue' => array('lookupTokens' => T_CONTINUE, 'neededSuccessors' => array(';')),
'clone' => array('lookupTokens' => T_CLONE, 'neededSuccessors' => array(';', ':', ',', ')'), 'forbiddenContents' => array('?', ':')),
'echo_print' => array('lookupTokens' => array(T_ECHO, T_PRINT), 'neededSuccessors' => array(';', array(T_CLOSE_TAG))),
'return' => array('lookupTokens' => T_RETURN, 'neededSuccessors' => array(';', array(T_CLOSE_TAG))),
'switch_case' => array('lookupTokens' => T_CASE, 'neededSuccessors' => array(';', ':')),
);
public function __construct()
{
if (defined('T_YIELD')) {
self::$loops['yield'] = array('lookupTokens' => T_YIELD, 'neededSuccessors' => array(';', ')'));
}
}
public static function configure(array $controlStatements)
{
self::$controlStatements = $controlStatements;
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$loops = array_intersect_key(self::$loops, array_flip(self::$controlStatements));
foreach ($tokens as $index => $token) {
if (!$token->equals('(')) {
continue;
}
$blockStartIndex = $index;
$index = $tokens->getPrevMeaningfulToken($index);
$token = $tokens[$index];
foreach ($loops as $loop) {
if (!$token->isGivenKind($loop['lookupTokens'])) {
continue;
}
$blockEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $blockStartIndex);
$blockEndNextIndex = $tokens->getNextMeaningfulToken($blockEndIndex);
if (!$tokens[$blockEndNextIndex]->equalsAny($loop['neededSuccessors'])) {
continue;
}
if (array_key_exists('forbiddenContents', $loop)) {
$forbiddenTokenIndex = $tokens->getNextTokenOfKind($blockStartIndex, $loop['forbiddenContents']);
if (null !== $forbiddenTokenIndex && $forbiddenTokenIndex < $blockEndIndex) {
continue;
}
}
if ($tokens[$blockStartIndex - 1]->isWhitespace() || $tokens[$blockStartIndex - 1]->isComment()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($blockStartIndex);
} else {
$tokens->overrideAt($blockStartIndex, array(T_WHITESPACE, ' '));
}
$tokens->clearTokenAndMergeSurroundingWhitespace($blockEndIndex);
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Removes unneeded parentheses around control statements.';
}
public function getPriority()
{
return 30;
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class UnusedUseFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
$useDeclarationsIndexes = $tokens->getImportUseIndexes();
if (0 === count($useDeclarationsIndexes)) {
return $tokens->generateCode();
}
$useDeclarations = $this->getNamespaceUseDeclarations($tokens, $useDeclarationsIndexes);
$namespaceDeclarations = $this->getNamespaceDeclarations($tokens);
$contentWithoutUseDeclarations = $this->generateCodeWithoutPartials($tokens, array_merge($namespaceDeclarations, $useDeclarations));
$useUsages = $this->detectUseUsages($contentWithoutUseDeclarations, $useDeclarations);
$this->removeUnusedUseDeclarations($tokens, $useDeclarations, $useUsages);
$this->removeUsesInSameNamespace($tokens, $useDeclarations, $namespaceDeclarations);
return $tokens->generateCode();
}
public function getDescription()
{
return 'Unused use statements must be removed.';
}
public function getPriority()
{
return -10;
}
public function supports(\SplFileInfo $file)
{
if (false !== strpos($file, DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR) &&
false === strpos($file, DIRECTORY_SEPARATOR.'CS'.DIRECTORY_SEPARATOR.'Tests'.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR)
) {
return false;
}
return true;
}
private function detectUseUsages($content, array $useDeclarations)
{
$usages = array();
foreach ($useDeclarations as $shortName => $useDeclaration) {
$usages[$shortName] = (bool) preg_match('/(?<![\$\\\\])\b'.preg_quote($shortName).'\b/i', $content);
}
return $usages;
}
private function generateCodeWithoutPartials(Tokens $tokens, array $partials)
{
$content = '';
foreach ($tokens as $index => $token) {
$allowToAppend = true;
foreach ($partials as $partial) {
if ($partial['start'] <= $index && $index <= $partial['end']) {
$allowToAppend = false;
break;
}
}
if ($allowToAppend) {
$content .= $token->getContent();
}
}
return $content;
}
private function getNamespaceDeclarations(Tokens $tokens)
{
$namespaces = array();
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_NAMESPACE)) {
continue;
}
$declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
$namespaces[] = array(
'name' => trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)),
'start' => $index,
'end' => $declarationEndIndex,
);
}
return $namespaces;
}
private function getNamespaceUseDeclarations(Tokens $tokens, array $useIndexes)
{
$uses = array();
foreach ($useIndexes as $index) {
$declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
$declarationContent = $tokens->generatePartialCode($index + 1, $declarationEndIndex - 1);
if (
false !== strpos($declarationContent, ',')
|| false !== strpos($declarationContent, '{')
) {
continue;
}
$declarationParts = preg_split('/\s+as\s+/i', $declarationContent);
if (1 === count($declarationParts)) {
$fullName = $declarationContent;
$declarationParts = explode('\\', $fullName);
$shortName = end($declarationParts);
$aliased = false;
} else {
list($fullName, $shortName) = $declarationParts;
$declarationParts = explode('\\', $fullName);
$aliased = $shortName !== end($declarationParts);
}
$shortName = trim($shortName);
$uses[$shortName] = array(
'fullName' => trim($fullName),
'shortName' => $shortName,
'aliased' => $aliased,
'start' => $index,
'end' => $declarationEndIndex,
);
}
return $uses;
}
private function removeUnusedUseDeclarations(Tokens $tokens, array $useDeclarations, array $useUsages)
{
foreach ($useDeclarations as $shortName => $useDeclaration) {
if (!$useUsages[$shortName]) {
$this->removeUseDeclaration($tokens, $useDeclaration);
}
}
}
private function removeUseDeclaration(Tokens $tokens, array $useDeclaration)
{
for ($index = $useDeclaration['end'] - 1; $index >= $useDeclaration['start']; --$index) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
if ($tokens[$useDeclaration['end']]->equals(';')) {
$tokens[$useDeclaration['end']]->clear();
}
$prevToken = $tokens[$useDeclaration['start'] - 1];
if ($prevToken->isWhitespace()) {
$prevToken->setContent(rtrim($prevToken->getContent(), " \t"));
}
if (!isset($tokens[$useDeclaration['end'] + 1])) {
return;
}
$nextIndex = $useDeclaration['end'] + 1;
$nextToken = $tokens[$nextIndex];
if ($nextToken->isWhitespace()) {
$content = ltrim($nextToken->getContent(), " \t");
if ($content && "\n" === $content[0]) {
$content = substr($content, 1);
}
$nextToken->setContent($content);
}
if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) {
$tokens->overrideAt($nextIndex, array(T_WHITESPACE, $prevToken->getContent().$nextToken->getContent(), $prevToken->getLine()));
$prevToken->clear();
}
}
private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, array $namespaceDeclarations)
{
if (1 !== count($namespaceDeclarations)) {
return;
}
$namespace = $namespaceDeclarations[0]['name'];
$nsLength = strlen($namespace.'\\');
foreach ($useDeclarations as $useDeclaration) {
if ($useDeclaration['aliased']) {
continue;
}
if (0 !== strpos($useDeclaration['fullName'], $namespace.'\\')) {
continue;
}
$partName = substr($useDeclaration['fullName'], $nsLength);
if (false === strpos($partName, '\\')) {
$this->removeUseDeclaration($tokens, $useDeclaration);
}
}
}
}
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
class WhitespacyLinesFixer extends AbstractFixer
{
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $index => $token) {
if (!$token->isWhitespace()) {
continue;
}
$content = $token->getContent();
$lines = preg_split("/([\r\n])/", $content);
if (
count($lines) > 2
|| (count($lines) > 1 && !isset($tokens[$index + 1]))
) {
$lMax = count($lines) - 1;
if (!isset($tokens[$index + 1])) {
++$lMax;
}
$lStart = 1;
if (isset($tokens[$index - 1]) && $tokens[$index - 1]->isGivenKind(T_OPEN_TAG) && "\n" === substr($tokens[$index - 1]->getContent(), -1)) {
$lStart = 0;
}
for ($l = $lStart; $l < $lMax; ++$l) {
$lines[$l] = preg_replace('/^\h+$/', '', $lines[$l]);
}
$token->setContent(implode("\n", $lines));
}
}
return $tokens->generateCode();
}
public function getDescription()
{
return 'Remove trailing whitespace at the end of blank lines.';
}
public function getPriority()
{
return -19;
}
}
#!/usr/bin/env php
<?php
if (defined('HHVM_VERSION_ID')) {
if (HHVM_VERSION_ID < 30900) {
fwrite(STDERR, "HHVM needs to be a minimum version of HHVM 3.9.0\n");
exit(1);
}
} elseif (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50306 || PHP_VERSION_ID >= 70200) {
fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.3.6 and maximum version of PHP 7.1.*\n");
exit(1);
}
set_error_handler(function ($severity, $message, $file, $line) {
if ($severity & error_reporting()) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
});
Phar::mapPhar('php-cs-fixer.phar');
require_once 'phar://php-cs-fixer.phar/vendor/autoload.php';
use Symfony\CS\Console\Application;
$application = new Application();
$application->run();
__HALT_COMPILER();
<?php
namespace Symfony\CS\Tokenizer\Transformer;
use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;
class ArrayTypehint extends AbstractTransformer
{
public function process(Tokens $tokens)
{
foreach ($tokens->findGivenKind(T_ARRAY) as $index => $token) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
if (!$nextToken->equals('(')) {
$token->override(array(CT_ARRAY_TYPEHINT, $token->getContent(), $token->getLine()));
}
}
}
public function getCustomTokenNames()
{
return array('CT_ARRAY_TYPEHINT');
}
}
<?php
namespace Symfony\CS\Tokenizer\Transformer;
use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;
class ClassConstant extends AbstractTransformer
{
public function process(Tokens $tokens)
{
foreach ($tokens as $index => $token) {
if (!$token->equalsAny(array(
array(T_CLASS, 'class'),
array(T_STRING, 'class'),
), false)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind(T_DOUBLE_COLON)) {
$token->override(array(CT_CLASS_CONSTANT, $token->getContent(), $token->getLine()));
}
}
}
public function getCustomTokenNames()
{
return array('CT_CLASS_CONSTANT');
}
}
<?php
namespace Symfony\CS\Tokenizer\Transformer;
use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;
class CurlyClose extends AbstractTransformer
{
public function process(Tokens $tokens)
{
foreach ($tokens->findGivenKind(T_CURLY_OPEN) as $index => $token) {
$level = 1;
$nestIndex = $index;
while (0 < $level) {
++$nestIndex;
if ('{' === $tokens[$nestIndex]->getContent()) {
++$level;
continue;
}
if ('}' === $tokens[$nestIndex]->getContent()) {
--$level;
}
}
$tokens[$nestIndex]->override(array(CT_CURLY_CLOSE, '}', $tokens[$nestIndex]->getLine()));
}
}
public function getCustomTokenNames()
{
return array('CT_CURLY_CLOSE');
}
}
<?php
namespace Symfony\CS\Tokenizer\Transformer;
use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;
class DollarCloseCurlyBraces extends AbstractTransformer
{
public function process(Tokens $tokens)
{
foreach ($tokens->findGivenKind(T_DOLLAR_OPEN_CURLY_BRACES) as $index => $token) {
$nextIndex = $tokens->getNextTokenOfKind($index, array('}'));
$tokens[$nextIndex]->override(array(CT_DOLLAR_CLOSE_CURLY_BRACES, '}', $tokens[$nextIndex]->getLine()));
}
}
public function getCustomTokenNames()
{
return array('CT_DOLLAR_CLOSE_CURLY_BRACES');
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Tokenizer\Transformer;
use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;
class DynamicPropBrace extends AbstractTransformer
{
public function process(Tokens $tokens)
{
foreach ($tokens->findGivenKind(T_OBJECT_OPERATOR) as $index => $token) {
if (!$tokens[$index + 1]->equals('{')) {
continue;
}
$openIndex = $index + 1;
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);
$tokens[$openIndex]->override(array(CT_DYNAMIC_PROP_BRACE_OPEN, '{', $tokens[$openIndex]->getLine()));
$tokens[$closeIndex]->override(array(CT_DYNAMIC_PROP_BRACE_CLOSE, '}', $tokens[$closeIndex]->getLine()));
}
}
public function getCustomTokenNames()
{
return array('CT_DYNAMIC_PROP_BRACE_OPEN', 'CT_DYNAMIC_PROP_BRACE_CLOSE');
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Tokenizer\Transformer;
use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;
class DynamicVarBrace extends AbstractTransformer
{
public function process(Tokens $tokens)
{
foreach ($tokens as $index => $token) {
if (!$token->equals('$')) {
continue;
}
$openIndex = $tokens->getNextMeaningfulToken($index);
if (null === $openIndex) {
continue;
}
$openToken = $tokens[$openIndex];
if (!$openToken->equals('{')) {
continue;
}
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);
$closeToken = $tokens[$closeIndex];
$openToken->override(array(CT_DYNAMIC_VAR_BRACE_OPEN, '{', $openToken->getLine()));
$closeToken->override(array(CT_DYNAMIC_VAR_BRACE_CLOSE, '}', $closeToken->getLine()));
}
}
public function getCustomTokenNames()
{
return array('CT_DYNAMIC_VAR_BRACE_OPEN', 'CT_DYNAMIC_VAR_BRACE_CLOSE');
}
public function getPriority()
{
return -10;
}
}
<?php
namespace Symfony\CS\Tokenizer;
use Symfony\CS\Utils;
abstract class AbstractTransformer implements TransformerInterface
{
private static $lastGeneratedCustomTokenValue = 10000;
public function getName()
{
$nameParts = explode('\\', get_called_class());
$name = end($nameParts);
return Utils::camelCaseToUnderscore($name);
}
public function getPriority()
{
return 0;
}
public function registerCustomTokens()
{
foreach ($this->getCustomTokenNames() as $name) {
if (!defined($name)) {
define($name, ++self::$lastGeneratedCustomTokenValue);
}
}
}
}
<?php
namespace Symfony\CS\Tokenizer;
use Symfony\CS\Utils;
class Token
{
private $content;
private $id;
private $isArray;
private $line;
public function __construct($token)
{
if (is_array($token)) {
$this->isArray = true;
$this->id = $token[0];
$this->content = $token[1];
$this->line = isset($token[2]) ? $token[2] : null;
} else {
$this->isArray = false;
$this->content = $token;
}
}
public function clear()
{
$this->override('');
}
public function equals($other, $caseSensitive = true)
{
$otherPrototype = $other instanceof self ? $other->getPrototype() : $other;
if ($this->isArray() !== is_array($otherPrototype)) {
return false;
}
if (!$this->isArray()) {
return $this->content === $otherPrototype;
}
$selfPrototype = $this->getPrototype();
foreach ($otherPrototype as $key => $val) {
if (!isset($selfPrototype[$key])) {
return false;
}
if (1 === $key && !$caseSensitive) {
if (0 !== strcasecmp($val, $selfPrototype[1])) {
return false;
}
} else {
if ($selfPrototype[$key] !== $val) {
return false;
}
}
}
return true;
}
public function equalsAny(array $others, $caseSensitive = true)
{
foreach ($others as $key => $other) {
$cs = self::isKeyCaseSensitive($caseSensitive, $key);
if ($this->equals($other, $cs)) {
return true;
}
}
return false;
}
public static function isKeyCaseSensitive($caseSensitive, $key)
{
if (is_array($caseSensitive)) {
return isset($caseSensitive[$key]) ? $caseSensitive[$key] : true;
}
return $caseSensitive;
}
public function getPrototype()
{
if (!$this->isArray) {
return $this->content;
}
return array(
$this->id,
$this->content,
$this->line,
);
}
public function getContent()
{
return $this->content;
}
public function getId()
{
return $this->id;
}
public function getLine()
{
return $this->line;
}
public function getName()
{
if (!isset($this->id)) {
return;
}
$transformers = Transformers::create();
if ($transformers->hasCustomToken($this->id)) {
return $transformers->getCustomToken($this->id);
}
return token_name($this->id);
}
public static function getKeywords()
{
static $keywords = null;
if (null === $keywords) {
$keywords = self::getTokenKindsForNames(array('T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE',
'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO',
'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH',
'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL',
'T_FINALLY', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER',
'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF',
'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
'T_NAMESPACE', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE',
'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY',
'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'CT_ARRAY_TYPEHINT', 'CT_CLASS_CONSTANT',
));
}
return $keywords;
}
public static function getMagicConstants()
{
static $magicConstants = null;
if (null === $magicConstants) {
$magicConstants = self::getTokenKindsForNames(array('T_CLASS_C', 'T_DIR', 'T_FILE', 'T_FUNC_C', 'T_LINE', 'T_METHOD_C', 'T_NS_C', 'T_TRAIT_C'));
}
return $magicConstants;
}
public function isArray()
{
return $this->isArray;
}
public function isCast()
{
static $castTokens = array(T_ARRAY_CAST, T_BOOL_CAST, T_DOUBLE_CAST, T_INT_CAST, T_OBJECT_CAST, T_STRING_CAST, T_UNSET_CAST);
return $this->isGivenKind($castTokens);
}
public function isClassy()
{
static $classTokens = null;
if (null === $classTokens) {
$classTokens = array(T_CLASS, T_INTERFACE);
if (defined('T_TRAIT')) {
$classTokens[] = constant('T_TRAIT');
}
}
return $this->isGivenKind($classTokens);
}
public function isComment()
{
static $commentTokens = array(T_COMMENT, T_DOC_COMMENT);
return $this->isGivenKind($commentTokens);
}
public function isEmpty()
{
return null === $this->id && ('' === $this->content || null === $this->content);
}
public function isGivenKind($possibleKind)
{
return $this->isArray && (is_array($possibleKind) ? in_array($this->id, $possibleKind, true) : $this->id === $possibleKind);
}
public function isKeyword()
{
$keywords = static::getKeywords();
return $this->isArray && isset($keywords[$this->id]);
}
public function isNativeConstant()
{
static $nativeConstantStrings = array('true', 'false', 'null');
return $this->isArray && in_array(strtolower($this->content), $nativeConstantStrings, true);
}
public function isMagicConstant()
{
$magicConstants = static::getMagicConstants();
return $this->isArray && isset($magicConstants[$this->id]);
}
public function isStructureAlternativeEnd()
{
static $tokens = array(T_ENDDECLARE, T_ENDFOR, T_ENDFOREACH, T_ENDIF, T_ENDSWITCH, T_ENDWHILE, T_END_HEREDOC);
return $this->isGivenKind($tokens);
}
public function isWhitespace(array $opts = array())
{
if ($this->isArray && !$this->isGivenKind(T_WHITESPACE)) {
return false;
}
$whitespaces = isset($opts['whitespaces']) ? $opts['whitespaces'] : " \t\n\r\0\x0B";
return '' === trim($this->content, $whitespaces);
}
public function override($prototype)
{
if (is_array($prototype)) {
$this->isArray = true;
$this->id = $prototype[0];
$this->content = $prototype[1];
$this->line = isset($prototype[2]) ? $prototype[2] : null;
return;
}
$this->isArray = false;
$this->id = null;
$this->content = $prototype;
$this->line = null;
}
public function setContent($content)
{
if ('' === $content) {
$this->clear();
return;
}
$this->content = $content;
}
public function toArray()
{
return array(
'id' => $this->id,
'name' => $this->getName(),
'content' => $this->content,
'line' => $this->line,
'isArray' => $this->isArray,
);
}
public function toJson()
{
static $options = null;
if (null === $options) {
$options = Utils::calculateBitmask(array('JSON_PRETTY_PRINT', 'JSON_NUMERIC_CHECK'));
}
return json_encode($this->toArray(), $options);
}
private static function getTokenKindsForNames(array $tokenNames)
{
$keywords = array();
foreach ($tokenNames as $keywordName) {
if (defined($keywordName)) {
$keyword = constant($keywordName);
$keywords[$keyword] = $keyword;
}
}
return $keywords;
}
}
<?php
namespace Symfony\CS\Tokenizer;
use Symfony\CS\Utils;
class Tokens extends \SplFixedArray
{
const BLOCK_TYPE_PARENTHESIS_BRACE = 1;
const BLOCK_TYPE_CURLY_BRACE = 2;
const BLOCK_TYPE_SQUARE_BRACE = 3;
const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 4;
const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 5;
private static $cache = array();
private $codeHash;
public function __clone()
{
foreach ($this as $key => $val) {
$this[$key] = clone $val;
}
}
public static function clearCache($key = null)
{
if (null === $key) {
self::$cache = array();
return;
}
if (self::hasCache($key)) {
unset(self::$cache[$key]);
}
}
public static function detectBlockType(Token $token)
{
foreach (self::getBlockEdgeDefinitions() as $type => $definition) {
if ($token->equals($definition['start'])) {
return array('type' => $type, 'isStart' => true);
}
if ($token->equals($definition['end'])) {
return array('type' => $type, 'isStart' => false);
}
}
}
public static function fromArray($array, $saveIndexes = null)
{
$tokens = new self(count($array));
if (null === $saveIndexes || $saveIndexes) {
foreach ($array as $key => $val) {
$tokens[$key] = $val;
}
return $tokens;
}
$index = 0;
foreach ($array as $val) {
$tokens[$index++] = $val;
}
return $tokens;
}
public static function fromCode($code)
{
$codeHash = self::calculateCodeHash($code);
if (self::hasCache($codeHash)) {
$tokens = self::getCache($codeHash);
$tokens->generateCode();
if ($codeHash === $tokens->codeHash) {
$tokens->clearEmptyTokens();
return $tokens;
}
}
$tokens = new self();
$tokens->setCode($code);
return $tokens;
}
public static function isMethodNameIsMagic($name)
{
static $magicMethods = array(
'__construct', '__destruct', '__call', '__callStatic', '__get', '__set', '__isset', '__unset',
'__sleep', '__wakeup', '__toString', '__invoke', '__set_state', '__clone',
);
return in_array($name, $magicMethods, true);
}
public function clearEmptyTokens()
{
$count = 0;
foreach ($this as $token) {
if (!$token->isEmpty()) {
$this[$count++] = $token;
}
}
$this->setSize($count);
}
public function ensureWhitespaceAtIndex($index, $indexOffset, $whitespace)
{
$removeLastCommentLine = function (Token $token, $indexOffset) {
if (1 === $indexOffset && $token->isComment()) {
$content = $token->getContent();
if ("\n" === $content[strlen($content) - 1]) {
$token->setContent(substr($content, 0, -1));
}
}
};
if ($this[$index]->isWhitespace()) {
$removeLastCommentLine($this[$index - 1], $indexOffset);
$this->overrideAt($index, array(T_WHITESPACE, $whitespace, $this[$index]->getLine()));
return false;
}
$removeLastCommentLine($this[$index], $indexOffset);
$this->insertAt(
$index + $indexOffset,
array(
new Token(array(T_WHITESPACE, $whitespace)),
)
);
return true;
}
public function findBlockEnd($type, $searchIndex, $findEnd = true)
{
$blockEdgeDefinitions = self::getBlockEdgeDefinitions();
if (!isset($blockEdgeDefinitions[$type])) {
throw new \InvalidArgumentException(sprintf('Invalid param type: %s.', $type));
}
$startEdge = $blockEdgeDefinitions[$type]['start'];
$endEdge = $blockEdgeDefinitions[$type]['end'];
$startIndex = $searchIndex;
$endIndex = $this->count() - 1;
$indexOffset = 1;
if (!$findEnd) {
list($startEdge, $endEdge) = array($endEdge, $startEdge);
$indexOffset = -1;
$endIndex = 0;
}
if (!$this[$startIndex]->equals($startEdge)) {
throw new \InvalidArgumentException(sprintf('Invalid param $startIndex - not a proper block %s.', $findEnd ? 'start' : 'end'));
}
$blockLevel = 0;
for ($index = $startIndex; $index !== $endIndex; $index += $indexOffset) {
$token = $this[$index];
if ($token->equals($startEdge)) {
++$blockLevel;
continue;
}
if ($token->equals($endEdge)) {
--$blockLevel;
if (0 === $blockLevel) {
break;
}
continue;
}
}
if (!$this[$index]->equals($endEdge)) {
throw new \UnexpectedValueException(sprintf('Missing block %s.', $findEnd ? 'end' : 'start'));
}
return $index;
}
public function findGivenKind($possibleKind, $start = 0, $end = null)
{
$this->rewind();
if (null === $end) {
$end = $this->count();
}
$elements = array();
$possibleKinds = (array) $possibleKind;
foreach ($possibleKinds as $kind) {
$elements[$kind] = array();
}
for ($i = $start; $i < $end; ++$i) {
$token = $this[$i];
if ($token->isGivenKind($possibleKinds)) {
$elements[$token->getId()][$i] = $token;
}
}
return is_array($possibleKind) ? $elements : $elements[$possibleKind];
}
public function generateCode()
{
$code = $this->generatePartialCode(0, count($this) - 1);
$this->changeCodeHash(self::calculateCodeHash($code));
return $code;
}
public function generatePartialCode($start, $end)
{
$code = '';
for ($i = $start; $i <= $end; ++$i) {
$code .= $this[$i]->getContent();
}
return $code;
}
public function getClassyElements()
{
$this->rewind();
$elements = array();
$inClass = false;
$curlyBracesLevel = 0;
$bracesLevel = 0;
foreach ($this as $index => $token) {
if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) {
continue;
}
if (!$inClass) {
$inClass = $token->isClassy();
continue;
}
if ($token->equals('(')) {
++$bracesLevel;
continue;
}
if ($token->equals(')')) {
--$bracesLevel;
continue;
}
if ($token->equals('{')) {
++$curlyBracesLevel;
continue;
}
if ($token->equals('}')) {
--$curlyBracesLevel;
if (0 === $curlyBracesLevel) {
$inClass = false;
}
continue;
}
if (1 !== $curlyBracesLevel || !$token->isArray()) {
continue;
}
if (0 === $bracesLevel && $token->isGivenKind(T_VARIABLE)) {
$elements[$index] = array('token' => $token, 'type' => 'property');
continue;
}
if ($token->isGivenKind(T_FUNCTION)) {
$elements[$index] = array('token' => $token, 'type' => 'method');
}
}
return $elements;
}
public function getImportUseIndexes($perNamespace = false)
{
$this->rewind();
$uses = array();
$namespaceIndex = 0;
for ($index = 0, $limit = $this->count(); $index < $limit; ++$index) {
$token = $this[$index];
if ($token->isGivenKind(T_NAMESPACE)) {
$nextTokenIndex = $this->getNextTokenOfKind($index, array(';', '{'));
$nextToken = $this[$nextTokenIndex];
if ($nextToken->equals('{')) {
$index = $nextTokenIndex;
}
if ($perNamespace) {
++$namespaceIndex;
}
continue;
}
if ($token->equals('{')) {
$index = $this->findBlockEnd(self::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if (!$token->isGivenKind(T_USE)) {
continue;
}
$nextToken = $this[$this->getNextMeaningfulToken($index)];
if ($nextToken->equals('(')) {
continue;
}
$uses[$namespaceIndex][] = $index;
}
if (!$perNamespace && isset($uses[$namespaceIndex])) {
return $uses[$namespaceIndex];
}
return $uses;
}
public function getNextNonWhitespace($index, array $opts = array())
{
return $this->getNonWhitespaceSibling($index, 1, $opts);
}
public function getNextTokenOfKind($index, array $tokens = array(), $caseSensitive = true)
{
return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive);
}
public function getNonWhitespaceSibling($index, $direction, array $opts = array())
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return;
}
$token = $this[$index];
if (!$token->isWhitespace($opts)) {
return $index;
}
}
}
public function getNonEmptySibling($index, $direction)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return;
}
if (!$this[$index]->isEmpty()) {
return $index;
}
}
}
public function getPrevNonWhitespace($index, array $opts = array())
{
return $this->getNonWhitespaceSibling($index, -1, $opts);
}
public function getPrevTokenOfKind($index, array $tokens = array(), $caseSensitive = true)
{
return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive);
}
public function getTokenOfKindSibling($index, $direction, array $tokens = array(), $caseSensitive = true)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return;
}
$token = $this[$index];
if ($token->equalsAny($tokens, $caseSensitive)) {
return $index;
}
}
}
public function getTokenNotOfKindSibling($index, $direction, array $tokens = array())
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return;
}
$token = $this[$index];
if ($token->isEmpty()) {
continue;
}
if ($token->equalsAny($tokens)) {
continue;
}
return $index;
}
}
public function getMeaningfulTokenSibling($index, $direction)
{
return $this->getTokenNotOfKindSibling(
$index,
$direction,
array(array(T_WHITESPACE), array(T_COMMENT), array(T_DOC_COMMENT))
);
}
public function getNextMeaningfulToken($index)
{
return $this->getMeaningfulTokenSibling($index, 1);
}
public function getPrevMeaningfulToken($index)
{
return $this->getMeaningfulTokenSibling($index, -1);
}
public function findSequence(array $sequence, $start = 0, $end = null, $caseSensitive = true)
{
if (null === $end) {
$end = count($this) - 1;
}
if (!count($sequence)) {
throw new \InvalidArgumentException('Invalid sequence.');
}
foreach ($sequence as $key => $token) {
if (!$token instanceof Token) {
if (is_array($token) && !isset($token[1])) {
$token[1] = '';
}
$token = new Token($token);
}
if ($token->isWhitespace() || $token->isComment() || $token->isEmpty()) {
throw new \InvalidArgumentException(sprintf('Non-meaningful token at position: %s.', $key));
}
}
$key = key($sequence);
$firstCs = Token::isKeyCaseSensitive($caseSensitive, $key);
$firstToken = $sequence[$key];
unset($sequence[$key]);
$index = $start - 1;
while (null !== $index && $index <= $end) {
$index = $this->getNextTokenOfKind($index, array($firstToken), $firstCs);
if (null === $index || $index > $end) {
return;
}
$result = array($index => $this[$index]);
$currIdx = $index;
foreach ($sequence as $key => $token) {
$currIdx = $this->getNextMeaningfulToken($currIdx);
if (null === $currIdx || $currIdx > $end) {
return;
}
if (!$this[$currIdx]->equals($token, Token::isKeyCaseSensitive($caseSensitive, $key))) {
continue 2;
}
$result[$currIdx] = $this[$currIdx];
}
if (count($sequence) < count($result)) {
return $result;
}
}
}
public function insertAt($index, $items)
{
$items = is_array($items) || $items instanceof self ? $items : array($items);
$itemsCnt = count($items);
$oldSize = count($this);
$this->setSize($oldSize + $itemsCnt);
for ($i = $oldSize + $itemsCnt - 1; $i >= $index; --$i) {
$this[$i] = isset($this[$i - $itemsCnt]) ? $this[$i - $itemsCnt] : new Token('');
}
for ($i = 0; $i < $itemsCnt; ++$i) {
$this[$i + $index] = $items[$i];
}
}
public function isArray($index)
{
return $this[$index]->isGivenKind(T_ARRAY) || $this->isShortArray($index);
}
public function isArrayMultiLine($index)
{
if (!$this->isArray($index)) {
throw new \InvalidArgumentException(sprintf('Not an array at given index "%d".', $index));
}
if ($this[$index]->isGivenKind(T_ARRAY)) {
$index = $this->getNextMeaningfulToken($index);
}
$endIndex = $this[$index]->equals('(')
? $this->findBlockEnd(self::BLOCK_TYPE_PARENTHESIS_BRACE, $index)
: $this->findBlockEnd(self::BLOCK_TYPE_SQUARE_BRACE, $index)
;
for (++$index; $index < $endIndex; ++$index) {
$token = $this[$index];
$blockType = static::detectBlockType($token);
if ($blockType && $blockType['isStart']) {
$index = $this->findBlockEnd($blockType['type'], $index);
continue;
}
if (
$token->isGivenKind(T_WHITESPACE) &&
!$this[$index - 1]->isGivenKind(T_END_HEREDOC) &&
false !== strpos($token->getContent(), "\n")
) {
return true;
}
}
return false;
}
public function isAnonymousClass($index)
{
$token = $this[$index];
if (!$token->isClassy()) {
throw new \LogicException('No classy token at given index');
}
if (!$token->isGivenKind(T_CLASS)) {
return false;
}
return $this[$this->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW);
}
public function isLambda($index)
{
$token = $this[$index];
if (!$token->isGivenKind(T_FUNCTION)) {
throw new \LogicException(sprintf('No T_FUNCTION at given index "%d".', $index));
}
$nextIndex = $this->getNextMeaningfulToken($index);
$nextToken = $this[$nextIndex];
if ($nextToken->equals('&')) {
$nextIndex = $this->getNextMeaningfulToken($nextIndex);
$nextToken = $this[$nextIndex];
}
return $nextToken->equals('(');
}
public function isPartialCodeMultiline($start, $end)
{
for ($i = $start; $i <= $end; ++$i) {
if (false !== strpos($this[$i]->getContent(), "\n")) {
return true;
}
}
return false;
}
public function isShortArray($index)
{
static $disallowedPrevTokens = array(
']',
'}',
')',
'"',
array(T_CONSTANT_ENCAPSED_STRING),
array(T_STRING),
array(T_STRING_VARNAME),
array(T_VARIABLE),
array(CT_DYNAMIC_PROP_BRACE_CLOSE),
array(CT_DYNAMIC_VAR_BRACE_CLOSE),
);
$token = $this[$index];
if (!$token->equals('[')) {
return false;
}
$prevToken = $this[$this->getPrevMeaningfulToken($index)];
if (!$prevToken->equalsAny($disallowedPrevTokens)) {
return true;
}
return false;
}
public function isUnarySuccessorOperator($index)
{
static $allowedPrevToken = array(
']',
array(T_STRING),
array(T_VARIABLE),
array(CT_DYNAMIC_PROP_BRACE_CLOSE),
array(CT_DYNAMIC_VAR_BRACE_CLOSE),
);
$token = $this[$index];
if (!$token->isGivenKind(array(T_INC, T_DEC))) {
return false;
}
$prevToken = $this[$this->getPrevMeaningfulToken($index)];
return $prevToken->equalsAny($allowedPrevToken);
}
public function isUnaryPredecessorOperator($index)
{
static $potentialSuccessorOperator = array(T_INC, T_DEC);
static $potentialBinaryOperator = array('+', '-', '&');
static $otherOperators;
if (null === $otherOperators) {
$otherOperators = array('!', '~', '@');
if (defined('T_ELLIPSIS')) {
$otherOperators[] = array(T_ELLIPSIS);
}
}
static $disallowedPrevTokens;
if (null === $disallowedPrevTokens) {
$disallowedPrevTokens = array(
']',
'}',
')',
'"',
'`',
array(CT_DYNAMIC_PROP_BRACE_CLOSE),
array(CT_DYNAMIC_VAR_BRACE_CLOSE),
array(T_CLASS_C),
array(T_CONSTANT_ENCAPSED_STRING),
array(T_DEC),
array(T_DIR),
array(T_DNUMBER),
array(T_FILE),
array(T_FUNC_C),
array(T_INC),
array(T_LINE),
array(T_LNUMBER),
array(T_METHOD_C),
array(T_NS_C),
array(T_STRING),
array(T_VARIABLE),
);
if (defined('T_TRAIT_C')) {
$disallowedPrevTokens[] = array(T_TRAIT_C);
}
}
$token = $this[$index];
if ($token->isGivenKind($potentialSuccessorOperator)) {
return !$this->isUnarySuccessorOperator($index);
}
if ($token->equalsAny($otherOperators)) {
return true;
}
if (!$token->equalsAny($potentialBinaryOperator)) {
return false;
}
$prevToken = $this[$this->getPrevMeaningfulToken($index)];
if (!$prevToken->equalsAny($disallowedPrevTokens)) {
return true;
}
if (!$token->equals('&') || !$prevToken->isGivenKind(T_STRING)) {
return false;
}
static $searchTokens = array(
';',
'{',
'}',
array(T_FUNCTION),
array(T_OPEN_TAG),
array(T_OPEN_TAG_WITH_ECHO),
);
$prevToken = $this[$this->getPrevTokenOfKind($index, $searchTokens)];
return $prevToken->isGivenKind(T_FUNCTION);
}
public function isBinaryOperator($index)
{
static $nonArrayOperators = array(
'=' => true,
'*' => true,
'/' => true,
'%' => true,
'<' => true,
'>' => true,
'|' => true,
'^' => true,
);
static $potentialUnaryNonArrayOperators = array(
'+' => true,
'-' => true,
'&' => true,
);
static $arrayOperators;
if (null === $arrayOperators) {
$arrayOperators = array(
T_AND_EQUAL => true,
T_BOOLEAN_AND => true,
T_BOOLEAN_OR => true,
T_CONCAT_EQUAL => true,
T_DIV_EQUAL => true,
T_DOUBLE_ARROW => true,
T_IS_EQUAL => true,
T_IS_GREATER_OR_EQUAL => true,
T_IS_IDENTICAL => true,
T_IS_NOT_EQUAL => true,
T_IS_NOT_IDENTICAL => true,
T_IS_SMALLER_OR_EQUAL => true,
T_LOGICAL_AND => true,
T_LOGICAL_OR => true,
T_LOGICAL_XOR => true,
T_MINUS_EQUAL => true,
T_MOD_EQUAL => true,
T_MUL_EQUAL => true,
T_OR_EQUAL => true,
T_PLUS_EQUAL => true,
T_SL => true,
T_SL_EQUAL => true,
T_SR => true,
T_SR_EQUAL => true,
T_XOR_EQUAL => true,
);
if (defined('T_POW')) {
$arrayOperators[T_POW] = true;
$arrayOperators[T_POW_EQUAL] = true;
}
if (defined('T_SPACESHIP')) {
$arrayOperators[T_SPACESHIP] = true;
}
if (defined('T_COALESCE')) {
$arrayOperators[T_COALESCE] = true;
}
}
$token = $this[$index];
if ($token->isArray()) {
return isset($arrayOperators[$token->getId()]);
}
if (isset($nonArrayOperators[$token->getContent()])) {
return true;
}
if (isset($potentialUnaryNonArrayOperators[$token->getContent()])) {
return !$this->isUnaryPredecessorOperator($index);
}
return false;
}
public function overrideAt($index, $token)
{
$this[$index]->override($token);
}
public function removeLeadingWhitespace($index, array $opts = array())
{
if (isset($this[$index - 1]) && $this[$index - 1]->isWhitespace($opts)) {
$this[$index - 1]->clear();
}
}
public function removeTrailingWhitespace($index, array $opts = array())
{
if (isset($this[$index + 1]) && $this[$index + 1]->isWhitespace($opts)) {
$this[$index + 1]->clear();
}
}
public function setCode($code)
{
$this->setSize(0);
$tokens = defined('TOKEN_PARSE')
? token_get_all($code, TOKEN_PARSE)
: token_get_all($code);
$this->setSize(count($tokens));
foreach ($tokens as $index => $token) {
$this[$index] = new Token($token);
}
$transformers = Transformers::create();
$transformers->transform($this);
$this->rewind();
$this->changeCodeHash(crc32($code));
}
public function toJson()
{
static $options = null;
if (null === $options) {
$options = Utils::calculateBitmask(array('JSON_PRETTY_PRINT', 'JSON_NUMERIC_CHECK'));
}
$output = new \SplFixedArray(count($this));
foreach ($this as $index => $token) {
$output[$index] = $token->toArray();
}
$this->rewind();
return json_encode($output, $options);
}
public function clearRange($indexStart, $indexEnd)
{
for ($i = $indexStart; $i <= $indexEnd; ++$i) {
$this[$i]->clear();
}
}
public function isMonolithicPhp()
{
$size = $this->count();
if (0 === $size) {
return false;
}
if ($this[0]->isGivenKind(T_INLINE_HTML) || $this[$size - 1]->isGivenKind(T_INLINE_HTML)) {
return false;
}
for ($index = 1; $index < $size; ++$index) {
if (
$this[$index]->isGivenKind(array(T_INLINE_HTML, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO))
|| (
defined('HHVM_VERSION')
&& $this[$index]->equals(array(T_ECHO, '<?='))
)
) {
return false;
}
}
return true;
}
public function clearTokenAndMergeSurroundingWhitespace($index)
{
$count = count($this);
$this[$index]->clear();
if ($index === $count - 1) {
return;
}
$nextIndex = $this->getNonEmptySibling($index, 1);
if (null === $nextIndex || !$this[$nextIndex]->isWhitespace()) {
return;
}
$prevIndex = $this->getNonEmptySibling($index, -1);
if ($this[$prevIndex]->isWhitespace()) {
$this[$prevIndex]->setContent($this[$prevIndex]->getContent().$this[$nextIndex]->getContent());
} elseif ($this[$prevIndex + 1]->isEmpty()) {
$this[$prevIndex + 1]->override(array(T_WHITESPACE, $this[$nextIndex]->getContent(), $this[$prevIndex + 1]->getLine()));
}
$this[$nextIndex]->clear();
}
private static function getBlockEdgeDefinitions()
{
return array(
self::BLOCK_TYPE_CURLY_BRACE => array(
'start' => '{',
'end' => '}',
),
self::BLOCK_TYPE_PARENTHESIS_BRACE => array(
'start' => '(',
'end' => ')',
),
self::BLOCK_TYPE_SQUARE_BRACE => array(
'start' => '[',
'end' => ']',
),
self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => array(
'start' => array(CT_DYNAMIC_PROP_BRACE_OPEN, '{'),
'end' => array(CT_DYNAMIC_PROP_BRACE_CLOSE, '}'),
),
self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => array(
'start' => array(CT_DYNAMIC_VAR_BRACE_OPEN, '{'),
'end' => array(CT_DYNAMIC_VAR_BRACE_CLOSE, '}'),
),
);
}
private static function calculateCodeHash($code)
{
return crc32($code);
}
private static function getCache($key)
{
if (!self::hasCache($key)) {
throw new \OutOfBoundsException(sprintf('Unknown cache key: "%s".', $key));
}
return self::$cache[$key];
}
private static function hasCache($key)
{
return isset(self::$cache[$key]);
}
private static function setCache($key, Tokens $value)
{
self::$cache[$key] = $value;
}
private function changeCodeHash($codeHash)
{
if (null !== $this->codeHash) {
self::clearCache($this->codeHash);
}
$this->codeHash = $codeHash;
self::setCache($this->codeHash, $this);
}
}
<?php
namespace Symfony\CS\Tokenizer;
interface TransformerInterface
{
public function process(Tokens $tokens);
public function registerCustomTokens();
public function getCustomTokenNames();
public function getName();
public function getPriority();
}
<?php
namespace Symfony\CS\Tokenizer;
use Symfony\Component\Finder\Finder;
use Symfony\CS\Utils;
class Transformers
{
private $items = array();
private $customTokens = array();
private function __construct()
{
$this->registerBuiltInTransformers();
}
public static function create()
{
static $instance = null;
if (!$instance) {
$instance = new self();
}
return $instance;
}
public function getCustomToken($value)
{
if (!$this->hasCustomToken($value)) {
throw new \InvalidArgumentException(sprintf('No custom token was found for: %s', $value));
}
return $this->customTokens[$value];
}
public function getTransformers()
{
$this->sortTransformers();
return $this->items;
}
public function hasCustomToken($value)
{
return isset($this->customTokens[$value]);
}
public function registerTransformer(TransformerInterface $transformer)
{
$this->items[] = $transformer;
$transformer->registerCustomTokens();
foreach ($transformer->getCustomTokenNames() as $name) {
$this->addCustomToken(constant($name), $name);
}
}
public function transform(Tokens $tokens)
{
foreach ($this->getTransformers() as $transformer) {
$transformer->process($tokens);
}
}
private function addCustomToken($value, $name)
{
if ($this->hasCustomToken($value)) {
throw new \LogicException(
sprintf(
'Trying to register token %s (%s), token with this value was already defined: %s',
$name, $value, $this->getCustomToken($value)
)
);
}
$this->customTokens[$value] = $name;
}
private function registerBuiltInTransformers()
{
static $registered = false;
if ($registered) {
return;
}
$registered = true;
foreach (Finder::create()->files()->in(__DIR__.'/Transformer') as $file) {
$relativeNamespace = $file->getRelativePath();
$class = __NAMESPACE__.'\\Transformer\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
$this->registerTransformer(new $class());
}
}
private function sortTransformers()
{
usort($this->items, function (TransformerInterface $a, TransformerInterface $b) {
return Utils::cmpInt($b->getPriority(), $a->getPriority());
});
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\Tokenizer\Tokens;
abstract class AbstractAlignFixer extends AbstractFixer
{
const ALIGNABLE_PLACEHOLDER = "\x2 ALIGNABLE%d \x3";
protected function replacePlaceholder(Tokens $tokens, $deepestLevel)
{
$tmpCode = $tokens->generateCode();
for ($j = 0; $j <= $deepestLevel; ++$j) {
$placeholder = sprintf(self::ALIGNABLE_PLACEHOLDER, $j);
if (false === strpos($tmpCode, $placeholder)) {
continue;
}
$lines = explode("\n", $tmpCode);
$linesWithPlaceholder = array();
$blockSize = 0;
$linesWithPlaceholder[$blockSize] = array();
foreach ($lines as $index => $line) {
if (substr_count($line, $placeholder) > 0) {
$linesWithPlaceholder[$blockSize][] = $index;
} else {
++$blockSize;
$linesWithPlaceholder[$blockSize] = array();
}
}
foreach ($linesWithPlaceholder as $group) {
if (count($group) < 1) {
continue;
}
$rightmostSymbol = 0;
foreach ($group as $index) {
$rightmostSymbol = max($rightmostSymbol, strpos(utf8_decode($lines[$index]), $placeholder));
}
foreach ($group as $index) {
$line = $lines[$index];
$currentSymbol = strpos(utf8_decode($line), $placeholder);
$delta = abs($rightmostSymbol - $currentSymbol);
if ($delta > 0) {
$line = str_replace($placeholder, str_repeat(' ', $delta).$placeholder, $line);
$lines[$index] = $line;
}
}
}
$tmpCode = str_replace($placeholder, '', implode("\n", $lines));
}
return $tmpCode;
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
abstract class AbstractAnnotationRemovalFixer extends AbstractFixer
{
public function getPriority()
{
return 10;
}
protected function removeAnnotations(Tokens $tokens, array $type)
{
foreach ($tokens as $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotationsOfType($type);
if (empty($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
$annotation->remove();
}
$token->setContent($doc->getContent());
}
}
}
<?php
namespace Symfony\CS;
abstract class AbstractFixer implements FixerInterface
{
public function getLevel()
{
static $map = array(
'PSR0' => FixerInterface::PSR0_LEVEL,
'PSR1' => FixerInterface::PSR1_LEVEL,
'PSR2' => FixerInterface::PSR2_LEVEL,
'Symfony' => FixerInterface::SYMFONY_LEVEL,
'Contrib' => FixerInterface::CONTRIB_LEVEL,
);
$level = current(explode('\\', substr(get_called_class(), strlen(__NAMESPACE__.'\\Fixer\\'))));
if (!isset($map[$level])) {
throw new \LogicException('Can not determine Fixer level');
}
return $map[$level];
}
public function getName()
{
$nameParts = explode('\\', get_called_class());
$name = substr(end($nameParts), 0, -strlen('Fixer'));
return Utils::camelCaseToUnderscore($name);
}
public function getPriority()
{
return 0;
}
public function supports(\SplFileInfo $file)
{
return true;
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\Tokenizer\Tokens;
abstract class AbstractLinesBeforeNamespaceFixer extends AbstractFixer
{
protected function fixLinesBeforeNamespace(Tokens $tokens, $index, $expected)
{
if (isset($tokens[$index - 2])) {
$opening = $tokens[$index - 2];
if ($opening->isGivenKind(T_OPEN_TAG)) {
$expected -= substr_count($opening->getContent(), "\n");
}
}
$previous = $tokens[$index - 1];
if ($previous->isWhitespace()) {
$content = $previous->getContent();
if (substr_count($content, "\n") !== $expected) {
$previous->setContent(str_repeat("\n", $expected));
}
}
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;
abstract class AbstractPhpdocTypesFixer extends AbstractFixer
{
protected static $tags;
public function __construct()
{
if (null === static::$tags) {
static::$tags = Annotation::getTagsWithTypes();
}
}
public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
foreach ($tokens as $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotationsOfType(static::$tags);
if (empty($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
$this->fixTypes($annotation);
}
$token->setContent($doc->getContent());
}
return $tokens->generateCode();
}
abstract protected function normalize($type);
private function fixTypes(Annotation $annotation)
{
$types = $annotation->getTypes();
$new = $this->normalizeTypes($types);
if ($types !== $new) {
$annotation->setTypes($new);
}
}
private function normalizeTypes(array $types)
{
foreach ($types as $index => $type) {
$types[$index] = $this->normalizeType($type);
}
return $types;
}
private function normalizeType($type)
{
if (substr($type, -2) === '[]') {
return $this->normalize(substr($type, 0, -2)).'[]';
}
return $this->normalize($type);
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\Finder\DefaultFinder;
class Config implements ConfigInterface
{
protected $name;
protected $description;
protected $finder;
protected $level;
protected $fixers;
protected $dir;
protected $customFixers;
protected $usingCache = false;
protected $usingLinter = true;
protected $hideProgress = false;
public function __construct($name = 'default', $description = 'A default configuration')
{
$this->name = $name;
$this->description = $description;
$this->level = FixerInterface::SYMFONY_LEVEL;
$this->fixers = array();
$this->finder = new DefaultFinder();
$this->customFixers = array();
}
public static function create()
{
return new static();
}
public function setDir($dir)
{
@trigger_error(
sprintf(
'The "%s" method is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Configure finder instead.',
__METHOD__
),
E_USER_DEPRECATED
);
$this->dir = $dir;
}
public function setUsingCache($usingCache)
{
$this->usingCache = $usingCache;
return $this;
}
public function setUsingLinter($usingLinter)
{
$this->usingLinter = $usingLinter;
return $this;
}
public function getDir()
{
@trigger_error(
sprintf(
'The "%s" method is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use finder instead.',
__METHOD__
),
E_USER_DEPRECATED
);
return $this->dir;
}
public function finder(\Traversable $finder)
{
$this->finder = $finder;
return $this;
}
public function getFinder()
{
if ($this->finder instanceof FinderInterface && $this->dir !== null) {
$this->finder->setDir($this->dir);
}
return $this->finder;
}
public function level($level)
{
$this->level = $level;
return $this;
}
public function getLevel()
{
return $this->level;
}
public function fixers($fixers)
{
$this->fixers = $fixers;
return $this;
}
public function getFixers()
{
return $this->fixers;
}
public function getName()
{
return $this->name;
}
public function getDescription()
{
return $this->description;
}
public function getHideProgress()
{
return $this->hideProgress;
}
public function addCustomFixer(FixerInterface $fixer)
{
$this->customFixers[] = $fixer;
return $this;
}
public function addCustomFixers($fixers)
{
if (false === is_array($fixers) && false === $fixers instanceof \Traversable) {
throw new \InvalidArgumentException(sprintf(
'Argument must be an array or a Traversable, got "%s".',
is_object($fixers) ? get_class($fixers) : gettype($fixers)
));
}
foreach ($fixers as $fixer) {
$this->addCustomFixer($fixer);
}
return $this;
}
public function getCustomFixers()
{
return $this->customFixers;
}
public function hideProgress($hideProgress)
{
$this->hideProgress = $hideProgress;
return $this;
}
public function usingCache()
{
return $this->usingCache;
}
public function usingLinter()
{
return $this->usingLinter;
}
}
<?php
namespace Symfony\CS;
interface ConfigAwareInterface
{
public function setConfig(ConfigInterface $config);
}
<?php
namespace Symfony\CS;
interface ConfigInterface
{
public function getName();
public function getDescription();
public function getFinder();
public function getLevel();
public function getFixers();
public function setDir($dir);
public function getDir();
public function addCustomFixer(FixerInterface $fixer);
public function getCustomFixers();
}
<?php
namespace Symfony\CS\ConfigurationException;
use Symfony\CS\Console\Command\FixCommand;
class InvalidConfigurationException extends \InvalidArgumentException
{
public function __construct($message, $code = null)
{
parent::__construct($message, null === $code ? FixCommand::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG : $code);
}
}
<?php
namespace Symfony\CS\ConfigurationException;
use Symfony\CS\Console\Command\FixCommand;
class InvalidFixerConfigurationException extends InvalidConfigurationException
{
public function __construct($fixerName, $message)
{
parent::__construct(sprintf('[%s] %s', $fixerName, $message), FixCommand::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG);
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\ConfigurationException\InvalidConfigurationException;
class ConfigurationResolver
{
protected $allFixers;
protected $config;
protected $fixers = array();
protected $options = array(
'fixers' => null,
'level' => null,
'progress' => null,
);
private $format;
public function setAllFixers(array $allFixers)
{
$this->allFixers = $allFixers;
return $this;
}
public function setConfig(ConfigInterface $config)
{
$this->config = $config;
return $this;
}
public function setOption($name, $value)
{
$this->options[$name] = $value;
return $this;
}
public function setOptions(array $options)
{
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
return $this;
}
public function resolve()
{
$this->resolveByLevel();
$this->resolveByNames();
$this->resolveFormat();
return $this;
}
public function getFixers()
{
return $this->fixers;
}
public function getFormat()
{
return $this->format;
}
public function getProgress()
{
if (!method_exists($this->config, 'getHideProgress')) {
return $this->options['progress'];
}
return $this->options['progress'] && !$this->config->getHideProgress();
}
protected function resolveByLevel()
{
$level = $this->parseLevel();
if (null === $level) {
return;
}
$fixers = array();
foreach ($this->allFixers as $fixer) {
if ($fixer->getLevel() === ($fixer->getLevel() & $level)) {
$fixers[] = $fixer;
}
}
$this->fixers = $fixers;
}
protected function resolveByNames()
{
$names = $this->parseFixers();
if (null === $names) {
return;
}
$addNames = array();
$removeNames = array();
foreach ($names as $name) {
if (0 === strpos($name, '-')) {
$removeNames[ltrim($name, '-')] = true;
} else {
$addNames[$name] = true;
}
}
foreach ($this->fixers as $key => $fixer) {
if (isset($removeNames[$fixer->getName()])) {
unset($this->fixers[$key]);
}
}
foreach ($this->allFixers as $fixer) {
if (isset($addNames[$fixer->getName()]) && !in_array($fixer, $this->fixers, true)) {
$this->fixers[] = $fixer;
}
}
}
protected function resolveFormat()
{
if (array_key_exists('format', $this->options)) {
$format = $this->options['format'];
} elseif (method_exists($this->config, 'getFormat')) {
$format = $this->config->getFormat();
} else {
$format = 'txt';
}
static $formats = array('txt', 'xml', 'json');
if (!in_array($format, $formats, true)) {
throw new InvalidConfigurationException(sprintf('The format "%s" is not defined, supported are %s.', $format, implode(', ', $formats)));
}
$this->format = $format;
}
protected function parseLevel()
{
static $levelMap = array(
'none' => FixerInterface::NONE_LEVEL,
'psr0' => FixerInterface::PSR0_LEVEL,
'psr1' => FixerInterface::PSR1_LEVEL,
'psr2' => FixerInterface::PSR2_LEVEL,
'symfony' => FixerInterface::SYMFONY_LEVEL,
);
$levelOption = $this->options['level'];
if (null !== $levelOption) {
if (!isset($levelMap[$levelOption])) {
throw new InvalidConfigurationException(sprintf('The level "%s" is not defined.', $levelOption));
}
return $levelMap[$levelOption];
}
if (null === $this->options['fixers']) {
return $this->config->getLevel();
}
foreach ($this->parseFixers() as $fixer) {
if (0 === strpos($fixer, '-')) {
return $this->config->getLevel();
}
}
}
protected function parseFixers()
{
if (null !== $this->options['fixers']) {
return array_map('trim', explode(',', $this->options['fixers']));
}
if (null === $this->options['level']) {
return $this->config->getFixers();
}
}
}
<?php
namespace Symfony\CS;
class ErrorsManager
{
const ERROR_TYPE_EXCEPTION = 1;
const ERROR_TYPE_LINT = 2;
private $errors = array();
public function getErrors()
{
return $this->errors;
}
public function isEmpty()
{
return empty($this->errors);
}
public function report($type, $filepath, $message)
{
$this->errors[] = array(
'type' => $type,
'filepath' => $filepath,
'message' => $message,
);
}
}
<?php
namespace Symfony\CS;
use Symfony\Component\Filesystem\Exception\IOException;
class FileCacheManager
{
const CACHE_FILE = '.php_cs.cache';
private $dir;
private $isEnabled;
private $fixers;
private $newHashes = array();
private $oldHashes = array();
public function __construct($isEnabled, $dir, array $fixers)
{
$this->isEnabled = $isEnabled;
$this->dir = null !== $dir ? $dir.DIRECTORY_SEPARATOR : '';
$this->fixers = array_map(function (FixerInterface $f) {
return $f->getName();
}, $fixers);
sort($this->fixers);
$this->readFromFile();
}
public function __destruct()
{
$this->saveToFile();
}
public function needFixing($file, $fileContent)
{
if (!$this->isCacheAvailable()) {
return true;
}
if (!isset($this->oldHashes[$file])) {
return true;
}
if ($this->oldHashes[$file] !== $this->calcHash($fileContent)) {
return true;
}
$this->newHashes[$file] = $this->oldHashes[$file];
return false;
}
public function setFile($file, $fileContent)
{
if (!$this->isCacheAvailable()) {
return;
}
$this->newHashes[$file] = $this->calcHash($fileContent);
}
private function calcHash($content)
{
return crc32($content);
}
private function isCacheAvailable()
{
static $result;
if (null === $result) {
$result = $this->isEnabled && (ToolInfo::isInstalledAsPhar() || ToolInfo::isInstalledByComposer());
}
return $result;
}
private function isCacheStale($cacheVersion, $fixers)
{
if (!$this->isCacheAvailable()) {
return true;
}
return ToolInfo::getVersion() !== $cacheVersion || $this->fixers !== $fixers;
}
private function readFromFile()
{
if (!$this->isCacheAvailable()) {
return;
}
if (!file_exists($this->dir.self::CACHE_FILE)) {
return;
}
$content = file_get_contents($this->dir.self::CACHE_FILE);
$data = @unserialize($content);
if (!is_array($data)) {
return;
}
if (!isset($data['fixers'])) {
$data['fixers'] = null;
}
if (!$this->isCacheStale($data['version'], $data['fixers'])) {
$this->oldHashes = $data['hashes'];
}
}
private function saveToFile()
{
if (!$this->isCacheAvailable()) {
return;
}
$data = serialize(
array(
'version' => ToolInfo::getVersion(),
'fixers' => $this->fixers,
'hashes' => $this->newHashes,
)
);
if (false === @file_put_contents($this->dir.self::CACHE_FILE, $data, LOCK_EX)) {
throw new IOException(sprintf('Failed to write file "%s".', self::CACHE_FILE), 0, null, $this->dir.self::CACHE_FILE);
}
}
}
<?php
namespace Symfony\CS;
final class FileRemoval
{
private $files = array();
public function __construct()
{
register_shutdown_function(array($this, 'clean'));
}
public function observe($path)
{
$this->files[$path] = true;
}
public function delete($path)
{
if (isset($this->files[$path])) {
unset($this->files[$path]);
}
$this->unlink($path);
}
public function clean()
{
foreach ($this->files as $file => $value) {
$this->unlink($file);
}
$this->files = array();
}
private function unlink($path)
{
@unlink($path);
}
}
<?php
namespace Symfony\CS;
use Symfony\Component\Finder\Finder as BaseFinder;
class Finder extends BaseFinder
{
public function __construct()
{
parent::__construct();
$this
->files()
->name('*.php')
->name('*.twig')
->ignoreDotFiles(true)
->ignoreVCS(true)
->exclude('vendor')
;
}
}
<?php
namespace Symfony\CS;
interface FinderInterface
{
public function setDir($dir);
}
<?php
namespace Symfony\CS;
use SebastianBergmann\Diff\Differ;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Finder\Finder as SymfonyFinder;
use Symfony\Component\Finder\SplFileInfo as SymfonySplFileInfo;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\CS\Tokenizer\Tokens;
class Fixer
{
const VERSION = '1.12.2';
protected $fixers = array();
protected $configs = array();
protected $diff;
protected $eventDispatcher;
protected $errorsManager;
protected $lintManager;
protected $stopwatch;
public function __construct()
{
$this->diff = new Differ();
}
public function registerBuiltInFixers()
{
foreach (SymfonyFinder::create()->files()->in(__DIR__.'/Fixer') as $file) {
$relativeNamespace = $file->getRelativePath();
$class = 'Symfony\\CS\\Fixer\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
$this->addFixer(new $class());
}
}
public function registerCustomFixers(array $fixers)
{
foreach ($fixers as $fixer) {
$this->addFixer($fixer);
}
}
public function addFixer(FixerInterface $fixer)
{
$this->fixers[] = $fixer;
}
public function getFixers()
{
$this->fixers = $this->sortFixers($this->fixers);
return $this->fixers;
}
public function registerBuiltInConfigs()
{
foreach (SymfonyFinder::create()->files()->in(__DIR__.'/Config') as $file) {
$relativeNamespace = $file->getRelativePath();
$class = 'Symfony\\CS\\Config\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
$this->addConfig(new $class());
}
}
public function addConfig(ConfigInterface $config)
{
$this->configs[] = $config;
}
public function getConfigs()
{
return $this->configs;
}
public function fix(ConfigInterface $config, $dryRun = false, $diff = false)
{
$fixers = $this->prepareFixers($config);
$fixers = $this->sortFixers($fixers);
$changed = array();
if ($this->stopwatch) {
$this->stopwatch->openSection();
}
$fileCacheManager = new FileCacheManager($config->usingCache(), $config->getDir(), $fixers);
$finder = $config->getFinder();
$finderIterator = $finder instanceof \IteratorAggregate ? $finder->getIterator() : $finder;
foreach (new UniqueFileIterator($finderIterator) as $file) {
if ($this->stopwatch) {
$this->stopwatch->start($this->getFileRelativePathname($file));
}
if ($fixInfo = $this->fixFile($file, $fixers, $dryRun, $diff, $fileCacheManager)) {
$changed[$this->getFileRelativePathname($file)] = $fixInfo;
}
if ($this->stopwatch) {
$this->stopwatch->stop($this->getFileRelativePathname($file));
}
}
if ($this->stopwatch) {
$this->stopwatch->stopSection('fixFile');
}
return $changed;
}
public function fixFile(\SplFileInfo $file, array $fixers, $dryRun, $diff, FileCacheManager $fileCacheManager)
{
$new = $old = file_get_contents($file->getRealPath());
if (
'' === $old
|| !$fileCacheManager->needFixing($this->getFileRelativePathname($file), $old)
|| (PHP_VERSION_ID >= 50306 && PHP_VERSION_ID < 50400 && false !== stripos($old, '__halt_compiler()'))
) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_SKIPPED)
);
}
return;
}
if ($this->lintManager && !$this->lintManager->createProcessForFile($file->getRealPath())->isSuccessful()) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_INVALID)
);
}
return;
}
$appliedFixers = array();
Tokens::clearCache();
try {
foreach ($fixers as $fixer) {
if (!$fixer->supports($file)) {
continue;
}
$newest = $fixer->fix($file, $new);
if ($newest !== $new) {
$appliedFixers[] = $fixer->getName();
}
$new = $newest;
}
} catch (\ParseError $e) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_LINT)
);
}
if ($this->errorsManager) {
$this->errorsManager->report(ErrorsManager::ERROR_TYPE_LINT, $this->getFileRelativePathname($file), sprintf('Linting error at line %d: "%s".', $e->getLine(), $e->getMessage()));
}
return;
} catch (\Error $e) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_EXCEPTION)
);
}
if ($this->errorsManager) {
$this->errorsManager->report(ErrorsManager::ERROR_TYPE_EXCEPTION, $this->getFileRelativePathname($file), $e->__toString());
}
return;
} catch (\Exception $e) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_EXCEPTION)
);
}
if ($this->errorsManager) {
$this->errorsManager->report(ErrorsManager::ERROR_TYPE_EXCEPTION, $this->getFileRelativePathname($file), $e->__toString());
}
return;
}
$fixInfo = null;
if ($new !== $old) {
if ($this->lintManager) {
$lintProcess = $this->lintManager->createProcessForSource($new);
if (!$lintProcess->isSuccessful()) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_LINT)
);
}
if ($this->errorsManager) {
$this->errorsManager->report(ErrorsManager::ERROR_TYPE_LINT, $this->getFileRelativePathname($file), $lintProcess->getOutput());
}
return;
}
}
if (!$dryRun) {
file_put_contents($file->getRealPath(), $new);
}
$fixInfo = array('appliedFixers' => $appliedFixers);
if ($diff) {
$fixInfo['diff'] = $this->stringDiff($old, $new);
}
}
$fileCacheManager->setFile($this->getFileRelativePathname($file), $new);
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(
FixerFileProcessedEvent::NAME,
FixerFileProcessedEvent::create()->setStatus($fixInfo ? FixerFileProcessedEvent::STATUS_FIXED : FixerFileProcessedEvent::STATUS_NO_CHANGES)
);
}
return $fixInfo;
}
public static function getLevelAsString(FixerInterface $fixer)
{
$level = $fixer->getLevel();
if (($level & FixerInterface::NONE_LEVEL) === $level) {
return 'none';
}
if (($level & FixerInterface::PSR0_LEVEL) === $level) {
return 'PSR-0';
}
if (($level & FixerInterface::PSR1_LEVEL) === $level) {
return 'PSR-1';
}
if (($level & FixerInterface::PSR2_LEVEL) === $level) {
return 'PSR-2';
}
if (($level & FixerInterface::CONTRIB_LEVEL) === $level) {
return 'contrib';
}
return 'symfony';
}
public function setEventDispatcher(EventDispatcher $eventDispatcher = null)
{
$this->eventDispatcher = $eventDispatcher;
}
public function setErrorsManager(ErrorsManager $errorsManager = null)
{
$this->errorsManager = $errorsManager;
}
public function setLintManager(LintManager $lintManager = null)
{
$this->lintManager = $lintManager;
}
public function setStopwatch(Stopwatch $stopwatch = null)
{
$this->stopwatch = $stopwatch;
}
protected function stringDiff($old, $new)
{
return $this->diff->diff($old, $new);
}
private function getFileRelativePathname(\SplFileInfo $file)
{
if ($file instanceof SymfonySplFileInfo) {
return $file->getRelativePathname();
}
return $file->getPathname();
}
private function sortFixers(array $fixers)
{
usort($fixers, function (FixerInterface $a, FixerInterface $b) {
return Utils::cmpInt($b->getPriority(), $a->getPriority());
});
return $fixers;
}
private function prepareFixers(ConfigInterface $config)
{
$fixers = $config->getFixers();
foreach ($fixers as $fixer) {
if ($fixer instanceof ConfigAwareInterface) {
$fixer->setConfig($config);
}
}
return $fixers;
}
}
<?php
namespace Symfony\CS;
use Symfony\Component\EventDispatcher\Event;
class FixerFileProcessedEvent extends Event
{
const NAME = 'fixer.file_processed';
const STATUS_UNKNOWN = 0;
const STATUS_INVALID = 1;
const STATUS_SKIPPED = 2;
const STATUS_NO_CHANGES = 3;
const STATUS_FIXED = 4;
const STATUS_EXCEPTION = 5;
const STATUS_LINT = 6;
private static $statusMap = array(
self::STATUS_UNKNOWN => array('symbol' => '?', 'description' => 'unknown'),
self::STATUS_INVALID => array('symbol' => 'I', 'description' => 'invalid file syntax, file ignored'),
self::STATUS_SKIPPED => array('symbol' => '', 'description' => ''),
self::STATUS_NO_CHANGES => array('symbol' => '.', 'description' => 'no changes'),
self::STATUS_FIXED => array('symbol' => 'F', 'description' => 'fixed'),
self::STATUS_EXCEPTION => array('symbol' => 'E', 'description' => 'error'),
self::STATUS_LINT => array('symbol' => 'E', 'description' => 'error'),
);
private $status = self::STATUS_UNKNOWN;
public static function create()
{
return new static();
}
public static function getStatusMap()
{
return self::$statusMap;
}
public function getStatus()
{
return $this->status;
}
public function getStatusAsString()
{
return self::$statusMap[$this->status]['symbol'];
}
public function setStatus($status)
{
$this->status = $status;
return $this;
}
}
<?php
namespace Symfony\CS;
interface FixerInterface
{
const NONE_LEVEL = 0;
const PSR0_LEVEL = 1;
const PSR1_LEVEL = 3;
const PSR2_LEVEL = 7;
const SYMFONY_LEVEL = 15;
const CONTRIB_LEVEL = 32;
public function fix(\SplFileInfo $file, $content);
public function getDescription();
public function getLevel();
public function getName();
public function getPriority();
public function supports(\SplFileInfo $file);
}
<?php
namespace Symfony\CS;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessUtils;
class LintManager
{
private $temporaryFile;
private $fileRemoval;
public function __construct()
{
$this->fileRemoval = new FileRemoval();
}
public function __destruct()
{
if (null !== $this->temporaryFile) {
$this->fileRemoval->delete($this->temporaryFile);
}
}
public function createProcessForFile($path)
{
if (!is_file($path)) {
return $this->createProcessForSource(file_get_contents($path));
}
$process = new Process('php -l '.ProcessUtils::escapeArgument($path));
$process->setTimeout(null);
$process->run();
return $process;
}
public function createProcessForSource($source)
{
if (null === $this->temporaryFile) {
$this->temporaryFile = tempnam('.', 'cs_fixer_tmp_');
$this->fileRemoval->observe($this->temporaryFile);
}
file_put_contents($this->temporaryFile, $source);
return $this->createProcessForFile($this->temporaryFile);
}
}
<?php
namespace Symfony\CS;
class StdinFileInfo extends \SplFileInfo
{
public function __construct()
{
}
public function __toString()
{
return $this->getContents();
}
public function getRealpath()
{
return 'php://stdin';
}
public function getContents()
{
return file_get_contents($this->getRealpath());
}
public function getATime()
{
return 0;
}
public function getBasename($suffix = null)
{
return $this->getFilename();
}
public function getCTime()
{
return 0;
}
public function getExtension()
{
return '.php';
}
public function getFileInfo($class_name = null)
{
throw new \RuntimeException('Not implemented');
}
public function getFilename()
{
return 'stdin.php';
}
public function getGroup()
{
return 0;
}
public function getInode()
{
return 0;
}
public function getLinkTarget()
{
return '';
}
public function getMTime()
{
return 0;
}
public function getOwner()
{
return 0;
}
public function getPath()
{
return '';
}
public function getPathInfo($class_name = null)
{
throw new \RuntimeException('Not implemented');
}
public function getPathname()
{
return $this->getFilename();
}
public function getPerms()
{
return 0;
}
public function getSize()
{
return 0;
}
public function getType()
{
return 'file';
}
public function isDir()
{
return false;
}
public function isExecutable()
{
return false;
}
public function isFile()
{
return true;
}
public function isLink()
{
return false;
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return false;
}
public function openFile($open_mode = 'r', $use_include_path = false, $context = null)
{
throw new \RuntimeException('Not implemented');
}
public function setFileClass($class_name = null)
{
}
public function setInfoClass($class_name = null)
{
}
}
<?php
namespace Symfony\CS\Test;
use Symfony\CS\FixerInterface;
final class IntegrationCase
{
private $expectedCode;
private $fileName;
private $fixers = array();
private $inputCode;
private $requirements = array();
private $settings = array();
private $title;
public static function create()
{
return new self();
}
public function hasInputCode()
{
return null !== $this->inputCode;
}
public function getExpectedCode()
{
return $this->expectedCode;
}
public function getFileName()
{
return $this->fileName;
}
public function getFixers()
{
return $this->fixers;
}
public function getInputCode()
{
return $this->inputCode;
}
public function getRequirement($name)
{
return $this->requirements[$name];
}
public function getRequirements()
{
return $this->requirements;
}
public function getSettings()
{
return $this->settings;
}
public function getTitle()
{
return $this->title;
}
public function setExpectedCode($expectedCode)
{
$this->expectedCode = $expectedCode;
return $this;
}
public function setFileName($fileName)
{
$this->fileName = $fileName;
return $this;
}
public function setFixers(array $fixers)
{
$this->fixers = $fixers;
return $this;
}
public function setInputCode($inputCode)
{
$this->inputCode = $inputCode;
return $this;
}
public function setRequirements(array $requirements)
{
$this->requirements = $requirements;
return $this;
}
public function setSettings($settings)
{
$this->settings = $settings;
return $this;
}
public function setTitle($title)
{
$this->title = $title;
return $this;
}
public function shouldCheckPriority()
{
return $this->settings['checkPriority'];
}
}
<?php
namespace Symfony\CS\Test;
use Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;
final class IntegrationCaseFactory
{
private static $builtInFixers;
public function create($fileName, $content)
{
try {
if (!preg_match('/--TEST--\n(?<title>.*?)\s--CONFIG--\n(?<config>.*?)(\s--SETTINGS--\n(?<settings>.*?))?(\s--REQUIREMENTS--\n(?<requirements>.*?))?\s--EXPECT--\n(?<expect>.*?\n*)(?:\n--INPUT--\s(?<input>.*)|$)/s', $content, $match)) {
throw new \InvalidArgumentException('File format is invalid.');
}
return IntegrationCase::create()
->setFileName($fileName)
->setTitle($match['title'])
->setFixers($this->determineFixers($match['config']))
->setRequirements($this->determineRequirements($match['requirements']))
->setSettings($this->determineSettings($match['settings']))
->setExpectedCode($match['expect'])
->setInputCode(isset($match['input']) ? $match['input'] : null)
;
} catch (\InvalidArgumentException $e) {
throw new \InvalidArgumentException(
sprintf('%s Test file: "%s".', $e->getMessage(), $fileName),
$e->getCode(),
$e
);
}
}
protected function determineFixers($config)
{
static $levelMap = array(
'none' => FixerInterface::NONE_LEVEL,
'psr1' => FixerInterface::PSR1_LEVEL,
'psr2' => FixerInterface::PSR2_LEVEL,
'symfony' => FixerInterface::SYMFONY_LEVEL,
);
$lines = explode("\n", $config);
if (empty($lines)) {
throw new \InvalidArgumentException('No lines found in CONFIG section.');
}
$config = array('level' => null, 'fixers' => array(), '--fixers' => array());
foreach ($lines as $line) {
$labelValuePair = explode('=', $line);
if (2 !== count($labelValuePair)) {
throw new \InvalidArgumentException(sprintf('Invalid CONFIG line: "%d".', $line));
}
$label = strtolower(trim($labelValuePair[0]));
$value = trim($labelValuePair[1]);
switch ($label) {
case 'level':
if (!array_key_exists($value, $levelMap)) {
throw new \InvalidArgumentException(sprintf('Unknown level "%s" set in CONFIG, expected any of "%s".', $value, implode(', ', array_keys($levelMap))));
}
if (null !== $config['level']) {
throw new \InvalidArgumentException('Cannot use multiple levels in configuration.');
}
$config['level'] = $value;
break;
case 'fixers':
case '--fixers':
foreach (explode(',', $value) as $fixer) {
$config[$label][] = strtolower(trim($fixer));
}
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown CONFIG line: "%d".', $line));
}
}
if (null === $config['level']) {
throw new \InvalidArgumentException('Level not set in CONFIG section.');
}
if (null === self::$builtInFixers) {
$fixer = new Fixer();
$fixer->registerBuiltInFixers();
self::$builtInFixers = $fixer->getFixers();
}
$fixers = array();
for ($i = 0, $limit = count(self::$builtInFixers); $i < $limit; ++$i) {
$fixer = self::$builtInFixers[$i];
$fixerName = $fixer->getName();
if ('psr0' === $fixer->getName()) {
continue;
}
if ($fixer->getLevel() !== ($fixer->getLevel() & $levelMap[$config['level']])) {
if (false !== $key = array_search($fixerName, $config['fixers'], true)) {
$fixers[] = $fixer;
unset($config['fixers'][$key]);
}
continue;
}
if (false !== $key = array_search($fixerName, $config['--fixers'], true)) {
unset($config['--fixers'][$key]);
continue;
}
if (in_array($fixerName, $config['fixers'], true)) {
throw new \InvalidArgumentException(sprintf('Additional fixer "%s" configured, but is already part of the level.', $fixerName));
}
$fixers[] = $fixer;
}
if (!empty($config['fixers']) || !empty($config['--fixers'])) {
throw new \InvalidArgumentException(sprintf('Unknown fixers in CONFIG section: "%s".', implode(',', empty($config['fixers']) ? $config['--fixers'] : $config['fixers'])));
}
return $fixers;
}
protected function determineRequirements($config)
{
$requirements = array('hhvm' => true, 'php' => PHP_VERSION);
if ('' === $config) {
return $requirements;
}
$lines = explode("\n", $config);
if (empty($lines)) {
return $requirements;
}
foreach ($lines as $line) {
$labelValuePair = explode('=', $line);
if (2 !== count($labelValuePair)) {
throw new \InvalidArgumentException(sprintf('Invalid REQUIREMENTS line: "%d".', $line));
}
$label = strtolower(trim($labelValuePair[0]));
$value = trim($labelValuePair[1]);
switch ($label) {
case 'hhvm':
$requirements['hhvm'] = 'false' !== $value;
break;
case 'php':
$requirements['php'] = $value;
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown REQUIREMENTS line: "%d".', $line));
}
}
return $requirements;
}
protected function determineSettings($config)
{
$settings = array('checkPriority' => true);
if ('' === $config) {
return $settings;
}
$lines = explode("\n", $config);
if (empty($lines)) {
return $settings;
}
foreach ($lines as $line) {
$labelValuePair = explode('=', $line);
if (2 !== count($labelValuePair)) {
throw new \InvalidArgumentException(sprintf('Invalid SETTINGS line: "%d".', $line));
}
$label = trim($labelValuePair[0]);
$value = trim($labelValuePair[1]);
switch ($label) {
case 'checkPriority':
$settings['checkPriority'] = 'false' !== $value;
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown SETTINGS line: "%d".', $line));
}
}
return $settings;
}
}
<?php
namespace Symfony\CS;
class ToolInfo
{
const COMPOSER_INSTALLED_FILE = '/../../composer/installed.json';
const COMPOSER_PACKAGE_NAME = 'friendsofphp/php-cs-fixer';
public static function getComposerVersion()
{
static $result;
if (!self::isInstalledByComposer()) {
throw new \LogicException('Can not get composer version for tool not installed by composer.');
}
if (null === $result) {
$composerInstalled = json_decode(file_get_contents(self::getScriptDir().self::COMPOSER_INSTALLED_FILE), true);
foreach ($composerInstalled as $package) {
if (self::COMPOSER_PACKAGE_NAME === $package['name']) {
$result = $package['version'].'#'.$package['dist']['reference'];
break;
}
}
}
return $result;
}
public static function getVersion()
{
if (self::isInstalledByComposer()) {
return Fixer::VERSION.':'.self::getComposerVersion();
}
return Fixer::VERSION;
}
public static function isInstalledAsPhar()
{
static $result;
if (null === $result) {
$result = 'phar://' === substr(__DIR__, 0, 7);
}
return $result;
}
public static function isInstalledByComposer()
{
static $result;
if (null === $result) {
$result = !self::isInstalledAsPhar() && file_exists(self::getScriptDir().self::COMPOSER_INSTALLED_FILE);
}
return $result;
}
private static function getScriptDir()
{
static $result;
if (null === $result) {
$script = $_SERVER['SCRIPT_NAME'];
if (is_link($script)) {
$linkTarget = readlink($script);
if (false === realpath($linkTarget)) {
$linkTarget = dirname($script).'/'.$linkTarget;
}
$script = $linkTarget;
}
$result = dirname($script);
}
return $result;
}
}
<?php
namespace Symfony\CS;
use Symfony\Component\Finder\SplFileInfo;
final class UniqueFileIterator extends \FilterIterator
{
private $visitedElements = array();
public function accept()
{
$file = $this->current();
$path = $file->getRealPath();
if (isset($this->visitedElements[$path])) {
return false;
}
$this->visitedElements[$path] = true;
return !$file->isDir() && !$file->isLink();
}
}
<?php
namespace Symfony\CS;
use Symfony\CS\Tokenizer\Token;
class Utils
{
public static function calculateBitmask(array $options)
{
$bitmask = 0;
foreach ($options as $optionName) {
if (defined($optionName)) {
$bitmask |= constant($optionName);
}
}
return $bitmask;
}
public static function camelCaseToUnderscore($string)
{
return preg_replace_callback(
'/(^|[a-z0-9])([A-Z])/',
function (array $matches) {
return strtolower(strlen($matches[1]) ? $matches[1].'_'.$matches[2] : $matches[2]);
},
$string
);
}
public static function cmpInt($a, $b)
{
if ($a === $b) {
return 0;
}
return $a < $b ? -1 : 1;
}
public static function splitLines($content)
{
preg_match_all("/[^\n\r]+[\r\n]*/", $content, $matches);
return $matches[0];
}
public static function calculateTrailingWhitespaceIndent(Token $token)
{
if (!$token->isWhitespace()) {
throw new \InvalidArgumentException(sprintf('The given token must be whitespace, got "%s".', $token->getName()));
}
return ltrim(strrchr(str_replace(array("\r\n", "\r"), "\n", $token->getContent()), 10), "\n");
}
}
Copyright (c) 2012-2016 Fabien Potencier
Dariusz Rumiński
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.
 Ry+dÉã¸ÜZõqaGBMB