#!/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 (version_compare(phpversion(), '5.3.6', '<')) {
    fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.3.6\n");
    exit(1);
}

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/psr/log/Psr/Log/AbstractLogger.php3   vU3  s K¶      3   vendor/psr/log/Psr/Log/InvalidArgumentException.php`    vU`    ˆX1¶      #   vendor/psr/log/Psr/Log/LogLevel.phpû    vUû   jðñ8¶      /   vendor/psr/log/Psr/Log/LoggerAwareInterface.php{    vU{   (»‚@¶      +   vendor/psr/log/Psr/Log/LoggerAwareTrait.php£    vU£   ñºeÿ¶      *   vendor/psr/log/Psr/Log/LoggerInterface.php½   vU½  ø
ä}¶      &   vendor/psr/log/Psr/Log/LoggerTrait.php`   vU`  �òC¶      %   vendor/psr/log/Psr/Log/NullLogger.php�    vU�   ¥=‡¶      3   vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.phpÙ
   vUÙ
  Çû›»¶      '   vendor/composer/autoload_namespaces.php   vU  :�Ì¶      !   vendor/composer/autoload_psr4.php˜    vU˜   Õ±"¤¶      %   vendor/composer/autoload_classmap.php³J  vU³J ÙnÔ¶      !   vendor/composer/autoload_real.php_   vU_  “é=¶         vendor/composer/ClassLoader.phpB   vUB  é”í¶      c   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php   vU  ô¡ã±¶      d   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php±   vU±  ƒa¾¶      m   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcherInterface.php3   vU3  ç€[
¶      [   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Debug/WrappedListener.phpÕ   vUÕ  Wnü¶      o   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php1   vU1  ©ú¡¢¶      K   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Event.php”   vU”  G‰äº¶      U   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcher.phpy   vUy  â$ª¶      ^   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcherInterface.phpR   vUR  ¨Èý3¶      ^   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventSubscriberInterface.php´    vU´   Ÿo “¶      R   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/GenericEvent.phpŒ   vUŒ  üçrð¶      ^   vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/ImmutableEventDispatcher.phpò   vUò  ñC=	¶      @   vendor/symfony/stopwatch/Symfony/Component/Stopwatch/Section.php(   vU(  ”åL¶¶      B   vendor/symfony/stopwatch/Symfony/Component/Stopwatch/Stopwatch.phpn   vUn  E"¶      G   vendor/symfony/stopwatch/Symfony/Component/Stopwatch/StopwatchEvent.php�   vU�  ÑV(¶      H   vendor/symfony/stopwatch/Symfony/Component/Stopwatch/StopwatchPeriod.php   vU  hí�À¶      W   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/ExceptionInterface.phpk    vUk   €Ûèà¶      Z   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/FileNotFoundException.php¼   vU¼  pí\¶¶      P   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/IOException.php‰   vU‰  Ö0ÿn¶      Y   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php¦    vU¦   jÙwM¶      E   vendor/symfony/filesystem/Symfony/Component/Filesystem/Filesystem.php<&   vU<&  ªpeˆ¶      F   vendor/symfony/filesystem/Symfony/Component/Filesystem/LockHandler.phpÊ   vUÊ  ¤¸X¿¶      >   vendor/symfony/config/Symfony/Component/Config/ConfigCache.phpa   vUa  %–c¶      G   vendor/symfony/config/Symfony/Component/Config/Definition/ArrayNode.php›   vU›  ^S',¶      F   vendor/symfony/config/Symfony/Component/Config/Definition/BaseNode.phpu   vUu  î=�6¶      I   vendor/symfony/config/Symfony/Component/Config/Definition/BooleanNode.phpî   vUî  ·Ùsä¶      Y   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php*   vU*  ÷—üý¶      [   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/BooleanNodeDefinition.phpµ   vUµ  E)vu¶      X   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/EnumNodeDefinition.php¢   vU¢  ûu^¶      Q   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/ExprBuilder.phpA	   vUA	  Ä®²¶      Y   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/FloatNodeDefinition.php5   vU5  ,¹O¥¶      [   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/IntegerNodeDefinition.php;   vU;  Ì1ìR¶      R   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/MergeBuilder.phpý   vUý  uºØl¶      Q   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/NodeBuilder.php	   vU	  Ü„Ý¶      T   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/NodeDefinition.php™   vU™  Á¼„=¶      Y   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/NodeParentInterface.phpo    vUo   évr¶      Z   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/NormalizationBuilder.phpS   vUS  à¦òö¶      [   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/NumericNodeDefinition.php¡   vU¡  JX„¶      c   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php÷    vU÷   >ç#?¶      Z   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/ScalarNodeDefinition.php!   vU!  z«Æ¶      Q   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/TreeBuilder.php­   vU­  `1³¶      W   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/ValidationBuilder.php›   vU›  v¶      \   vendor/symfony/config/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.phpë   vUë  è;˜¶      T   vendor/symfony/config/Symfony/Component/Config/Definition/ConfigurationInterface.php—    vU—   <@Pä¶      W   vendor/symfony/config/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php±   vU±  õ{K¶      X   vendor/symfony/config/Symfony/Component/Config/Definition/Dumper/YamlReferenceDumper.php»   vU»  FrÑ6¶      F   vendor/symfony/config/Symfony/Component/Config/Definition/EnumNode.phpØ   vUØ  Ç,ë¶      ]   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/DuplicateKeyException.php–    vU–   §‰Úa¶      Q   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/Exception.php}    vU}   ¢ÃÃú¶      c   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/ForbiddenOverwriteException.phpœ    vUœ   òÛ™Z¶      e   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/InvalidConfigurationException.phpÕ   vUÕ  kÆ¶      b   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/InvalidDefinitionException.php†    vU†   ï¡1¶      \   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/InvalidTypeException.php”    vU”   ø—¶      Y   vendor/symfony/config/Symfony/Component/Config/Definition/Exception/UnsetKeyException.php~    vU~   ŒÞî_¶      G   vendor/symfony/config/Symfony/Component/Config/Definition/FloatNode.php   vU  QTÿ³¶      I   vendor/symfony/config/Symfony/Component/Config/Definition/IntegerNode.phpè   vUè  T¶      K   vendor/symfony/config/Symfony/Component/Config/Definition/NodeInterface.php©   vU©  `ÃP ¶      I   vendor/symfony/config/Symfony/Component/Config/Definition/NumericNode.phpù   vUù  ÷áé¶      G   vendor/symfony/config/Symfony/Component/Config/Definition/Processor.php­   vU­  ›ÅÍv¶      T   vendor/symfony/config/Symfony/Component/Config/Definition/PrototypeNodeInterface.php¥    vU¥   ²*/×¶      Q   vendor/symfony/config/Symfony/Component/Config/Definition/PrototypedArrayNode.php¢   vU¢  »YB¶      M   vendor/symfony/config/Symfony/Component/Config/Definition/ReferenceDumper.php¾    vU¾   9K¶      H   vendor/symfony/config/Symfony/Component/Config/Definition/ScalarNode.php
   vU
  £ó¶      J   vendor/symfony/config/Symfony/Component/Config/Definition/VariableNode.php6   vU6  ¯¿R¶      g   vendor/symfony/config/Symfony/Component/Config/Exception/FileLoaderImportCircularReferenceException.php»   vU»  i~‹|¶      T   vendor/symfony/config/Symfony/Component/Config/Exception/FileLoaderLoadException.php6   vU6  ÔÉ+ÿ¶      >   vendor/symfony/config/Symfony/Component/Config/FileLocator.phpš   vUš  H®´!¶      G   vendor/symfony/config/Symfony/Component/Config/FileLocatorInterface.php©    vU©   3Ë5>¶      J   vendor/symfony/config/Symfony/Component/Config/Loader/DelegatingLoader.php`   vU`   åˆÞ¶      D   vendor/symfony/config/Symfony/Component/Config/Loader/FileLoader.php¡   vU¡  g#àÔ¶      @   vendor/symfony/config/Symfony/Component/Config/Loader/Loader.php   vU  ÂÇ(¶      I   vendor/symfony/config/Symfony/Component/Config/Loader/LoaderInterface.php=   vU=  ‰n+�¶      H   vendor/symfony/config/Symfony/Component/Config/Loader/LoaderResolver.php}   vU}  èpÝ¶      Q   vendor/symfony/config/Symfony/Component/Config/Loader/LoaderResolverInterface.php¡    vU¡   ˜Kjï¶      M   vendor/symfony/config/Symfony/Component/Config/Resource/DirectoryResource.phpÛ   vUÛ  yÈ¨¶      H   vendor/symfony/config/Symfony/Component/Config/Resource/FileResource.phpÈ   vUÈ  »º4¶      M   vendor/symfony/config/Symfony/Component/Config/Resource/ResourceInterface.phpØ    vUØ   ¤ƒ‡y¶      @   vendor/symfony/config/Symfony/Component/Config/Util/XmlUtils.phpï   vUï  ‘½Ù¶      @   vendor/symfony/console/Symfony/Component/Console/Application.php¶R   vU¶R  ”.ö(¶      D   vendor/symfony/console/Symfony/Component/Console/Command/Command.phpð   vUð  pÅ¶      H   vendor/symfony/console/Symfony/Component/Console/Command/HelpCommand.php6   vU6  #¯¾}¶      H   vendor/symfony/console/Symfony/Component/Console/Command/ListCommand.php³   vU³  VÓé¶      B   vendor/symfony/console/Symfony/Component/Console/ConsoleEvents.phpï    vUï   ÕH¸¶      V   vendor/symfony/console/Symfony/Component/Console/Descriptor/ApplicationDescription.phpù   vUù  ‰>O¶      J   vendor/symfony/console/Symfony/Component/Console/Descriptor/Descriptor.php\   vU\  WJ[í¶      S   vendor/symfony/console/Symfony/Component/Console/Descriptor/DescriptorInterface.phpü    vUü   ±Qµ¶      N   vendor/symfony/console/Symfony/Component/Console/Descriptor/JsonDescriptor.php2   vU2  †ca¶      R   vendor/symfony/console/Symfony/Component/Console/Descriptor/MarkdownDescriptor.php
   vU
   LÛ*¶      N   vendor/symfony/console/Symfony/Component/Console/Descriptor/TextDescriptor.php6   vU6  ªàí;¶      M   vendor/symfony/console/Symfony/Component/Console/Descriptor/XmlDescriptor.php    vU   …{îm¶      N   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleCommandEvent.php²   vU²  Zk‰2¶      G   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleEvent.phpÅ   vUÅ  ÒxÛ\¶      P   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleExceptionEvent.php   vU  á2é¶      P   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleTerminateEvent.phpz   vUz  ³,îL¶      N   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatter.phpf   vUf  Kdÿ-¶      W   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterInterface.php˜   vU˜  3l~´¶      S   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyle.php·   vU·  Ç ÅK¶      \   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleInterface.phpŽ   vUŽ  öëÄ=¶      X   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleStack.php   vU  yI'¶      P   vendor/symfony/console/Symfony/Component/Console/Helper/DebugFormatterHelper.phpm   vUm  ò¯s>¶      L   vendor/symfony/console/Symfony/Component/Console/Helper/DescriptorHelper.php9   vU9  ûùäð¶      H   vendor/symfony/console/Symfony/Component/Console/Helper/DialogHelper.phpÊ   vUÊ  lÕHl¶      K   vendor/symfony/console/Symfony/Component/Console/Helper/FormatterHelper.phpc   vUc  “ý«N¶      B   vendor/symfony/console/Symfony/Component/Console/Helper/Helper.phpß   vUß  o¾ã¶      K   vendor/symfony/console/Symfony/Component/Console/Helper/HelperInterface.phpï    vUï   =e¶      E   vendor/symfony/console/Symfony/Component/Console/Helper/HelperSet.php/   vU/  âw d¶      L   vendor/symfony/console/Symfony/Component/Console/Helper/InputAwareHelper.phpc   vUc  ñø�|¶      I   vendor/symfony/console/Symfony/Component/Console/Helper/ProcessHelper.phpâ   vUâ  |Ì¼¶      G   vendor/symfony/console/Symfony/Component/Console/Helper/ProgressBar.php$   vU$  2Œ5J¶      J   vendor/symfony/console/Symfony/Component/Console/Helper/ProgressHelper.phpƒ   vUƒ  “h™¶      J   vendor/symfony/console/Symfony/Component/Console/Helper/QuestionHelper.php   vU  RŠ¶      A   vendor/symfony/console/Symfony/Component/Console/Helper/Table.php   vU  {ŸV‚¶      G   vendor/symfony/console/Symfony/Component/Console/Helper/TableHelper.phpØ
   vUØ
  , ¶      J   vendor/symfony/console/Symfony/Component/Console/Helper/TableSeparator.php[    vU[   LV¡¶      F   vendor/symfony/console/Symfony/Component/Console/Helper/TableStyle.phpÕ   vUÕ  æ"ðù¶      D   vendor/symfony/console/Symfony/Component/Console/Input/ArgvInput.phpÙ   vUÙ  ËkE¶      E   vendor/symfony/console/Symfony/Component/Console/Input/ArrayInput.phpû	   vUû	  âö¥p¶      @   vendor/symfony/console/Symfony/Component/Console/Input/Input.php
   vU
  ÇýT¶      H   vendor/symfony/console/Symfony/Component/Console/Input/InputArgument.phpž   vUž  K]ìi¶      N   vendor/symfony/console/Symfony/Component/Console/Input/InputAwareInterface.phpš    vUš   ‡jTŸ¶      J   vendor/symfony/console/Symfony/Component/Console/Input/InputDefinition.php   vU  ˜£JM¶      I   vendor/symfony/console/Symfony/Component/Console/Input/InputInterface.php    vU   9”øÇ¶      F   vendor/symfony/console/Symfony/Component/Console/Input/InputOption.php«   vU«  ê†®½¶      F   vendor/symfony/console/Symfony/Component/Console/Input/StringInput.php‹   vU‹  †uný¶      I   vendor/symfony/console/Symfony/Component/Console/Logger/ConsoleLogger.php;	   vU;	  #ØB~¶      J   vendor/symfony/console/Symfony/Component/Console/Output/BufferedOutput.php_   vU_  ûBÍ·¶      I   vendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutput.php   vU  jå¬¶      R   vendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutputInterface.phpå    vUå   rNô ¶      F   vendor/symfony/console/Symfony/Component/Console/Output/NullOutput.php¿   vU¿  `5EË¶      B   vendor/symfony/console/Symfony/Component/Console/Output/Output.php§   vU§  Ú _¶      K   vendor/symfony/console/Symfony/Component/Console/Output/OutputInterface.phpI   vUI  ÈâãB¶      H   vendor/symfony/console/Symfony/Component/Console/Output/StreamOutput.php¢   vU¢  ü0¶      L   vendor/symfony/console/Symfony/Component/Console/Question/ChoiceQuestion.phpf   vUf  Ôh¶      R   vendor/symfony/console/Symfony/Component/Console/Question/ConfirmationQuestion.phpK   vUK  õÃTÈ¶      F   vendor/symfony/console/Symfony/Component/Console/Question/Question.php®   vU®  .e8Ö¶      :   vendor/symfony/console/Symfony/Component/Console/Shell.php.   vU.  þÉŽ‡¶      M   vendor/symfony/console/Symfony/Component/Console/Tester/ApplicationTester.phpÔ   vUÔ  ¬ì¤d¶      I   vendor/symfony/console/Symfony/Component/Console/Tester/CommandTester.php�   vU�  H»â`¶      5   vendor/symfony/yaml/Symfony/Component/Yaml/Dumper.php	   vU	  �ÿÇ¶      6   vendor/symfony/yaml/Symfony/Component/Yaml/Escaper.phpR   vUR  Ñlö6¶      F   vendor/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.phpu    vUu   e*n¶      K   vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.phpe    vUe   Îcº¶      G   vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.phpŸ   vUŸ  PˆA=¶      I   vendor/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php—    vU—   ‡õ�¶      5   vendor/symfony/yaml/Symfony/Component/Yaml/Inline.phpî&   vUî&  VE0	¶      5   vendor/symfony/yaml/Symfony/Component/Yaml/Parser.php77   vU77  ÿ×ýÏ¶      8   vendor/symfony/yaml/Symfony/Component/Yaml/Unescaper.phpž   vUž  �:ø'¶      3   vendor/symfony/yaml/Symfony/Component/Yaml/Yaml.phpË   vUË  äó¶      J   vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractAdapter.php¤
   vU¤
  ¢)z9¶      N   vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractFindAdapter.phpÛ   vUÛ  SõT´¶      K   vendor/symfony/finder/Symfony/Component/Finder/Adapter/AdapterInterface.php¯   vU¯  ‹éÈ¶      I   vendor/symfony/finder/Symfony/Component/Finder/Adapter/BsdFindAdapter.php{   vU{  Q,D2¶      I   vendor/symfony/finder/Symfony/Component/Finder/Adapter/GnuFindAdapter.php^   vU^  ßz˜r¶      E   vendor/symfony/finder/Symfony/Component/Finder/Adapter/PhpAdapter.php+   vU+  &˜îÒ¶      H   vendor/symfony/finder/Symfony/Component/Finder/Comparator/Comparator.phpŒ   vUŒ  wþT¶      L   vendor/symfony/finder/Symfony/Component/Finder/Comparator/DateComparator.php%   vU%  L¿EÇ¶      N   vendor/symfony/finder/Symfony/Component/Finder/Comparator/NumberComparator.phpx   vUx  ½™5¶      R   vendor/symfony/finder/Symfony/Component/Finder/Exception/AccessDeniedException.php„    vU„   ½¾sœ¶      T   vendor/symfony/finder/Symfony/Component/Finder/Exception/AdapterFailureException.php   vU  mŒ_,¶      O   vendor/symfony/finder/Symfony/Component/Finder/Exception/ExceptionInterface.php„    vU„   Gz-¶      Z   vendor/symfony/finder/Symfony/Component/Finder/Exception/OperationNotPermitedException.phpŠ    vUŠ   U88¶      Y   vendor/symfony/finder/Symfony/Component/Finder/Exception/ShellCommandFailureException.php$   vU$  C”sÓ¶      H   vendor/symfony/finder/Symfony/Component/Finder/Expression/Expression.php}   vU}  /·cð¶      B   vendor/symfony/finder/Symfony/Component/Finder/Expression/Glob.php¡   vU¡    V¿¶      C   vendor/symfony/finder/Symfony/Component/Finder/Expression/Regex.php�   vU�  S7Pæ¶      L   vendor/symfony/finder/Symfony/Component/Finder/Expression/ValueInterface.php;   vU;  îãÓ¶      9   vendor/symfony/finder/Symfony/Component/Finder/Finder.phpú"   vUú"  gƒ¶      7   vendor/symfony/finder/Symfony/Component/Finder/Glob.php   vU  z�ø
¶      P   vendor/symfony/finder/Symfony/Component/Finder/Iterator/CustomFilterIterator.php]   vU]  tà±µ¶      S   vendor/symfony/finder/Symfony/Component/Finder/Iterator/DateRangeFilterIterator.phpz   vUz  }¢¶      T   vendor/symfony/finder/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.phpð   vUð  ß0™¶      Z   vendor/symfony/finder/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php”   vU”  "ÖóÁ¶      M   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilePathsIterator.php�   vU�  ýòäQ¶      R   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FileTypeFilterIterator.php\   vU\  p‘'˜¶      U   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilecontentFilterIterator.php#   vU#  Ú_VÇ¶      R   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilenameFilterIterator.php‡   vU‡  F ’¶      J   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilterIterator.php†   vU†  0£¾Ô¶      V   vendor/symfony/finder/Symfony/Component/Finder/Iterator/MultiplePcreFilterIterator.phpØ   vUØ  Òù“¶      N   vendor/symfony/finder/Symfony/Component/Finder/Iterator/PathFilterIterator.php¸   vU¸  E*E¶      V   vendor/symfony/finder/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.phpY   vUY  êÓÊÜ¶      S   vendor/symfony/finder/Symfony/Component/Finder/Iterator/SizeRangeFilterIterator.phpg   vUg  !Ô—é¶      L   vendor/symfony/finder/Symfony/Component/Finder/Iterator/SortableIterator.phpÞ   vUÞ  ö³%¶      @   vendor/symfony/finder/Symfony/Component/Finder/Shell/Command.php£
   vU£
  Ö<ÊT¶      >   vendor/symfony/finder/Symfony/Component/Finder/Shell/Shell.phpé   vUé  ¿ëÛ•¶      >   vendor/symfony/finder/Symfony/Component/Finder/SplFileInfo.phpû   vUû  ‘†6¶      Q   vendor/symfony/process/Symfony/Component/Process/Exception/ExceptionInterface.phpf    vUf   ]ö>T¶      W   vendor/symfony/process/Symfony/Component/Process/Exception/InvalidArgumentException.php¨    vU¨   ÐÀ+_¶      M   vendor/symfony/process/Symfony/Component/Process/Exception/LogicException.php”    vU”    ³ãñ¶      U   vendor/symfony/process/Symfony/Component/Process/Exception/ProcessFailedException.php<   vU<  "wÛn¶      W   vendor/symfony/process/Symfony/Component/Process/Exception/ProcessTimedOutException.php   vU  .	Ãá¶      O   vendor/symfony/process/Symfony/Component/Process/Exception/RuntimeException.php˜    vU˜   ¢Ø:¶      E   vendor/symfony/process/Symfony/Component/Process/ExecutableFinder.php~   vU~  +…¶      H   vendor/symfony/process/Symfony/Component/Process/PhpExecutableFinder.php   vU  ûÔM>¶      ?   vendor/symfony/process/Symfony/Component/Process/PhpProcess.php×   vU×  Š€«¶      H   vendor/symfony/process/Symfony/Component/Process/Pipes/AbstractPipes.php    vU   ˜|¥¾¶      I   vendor/symfony/process/Symfony/Component/Process/Pipes/PipesInterface.phpD   vUD  vØî¡¶      D   vendor/symfony/process/Symfony/Component/Process/Pipes/UnixPipes.php¤   vU¤  øUt¶      G   vendor/symfony/process/Symfony/Component/Process/Pipes/WindowsPipes.php½   vU½   .X£¶      <   vendor/symfony/process/Symfony/Component/Process/Process.phpÜN   vUÜN  …4AÔ¶      C   vendor/symfony/process/Symfony/Component/Process/ProcessBuilder.php   vU  �ïy¶      A   vendor/symfony/process/Symfony/Component/Process/ProcessUtils.phpŒ   vUŒ  ÈbÝv¶      "   vendor/guzzle/guzzle/phar-stub.phpA   vUA  ¤Þ‰G¶      5   vendor/guzzle/guzzle/phing/tasks/ComposerLintTask.php9   vU9  ¸ƒ;u¶      >   vendor/guzzle/guzzle/phing/tasks/GuzzlePearPharPackageTask.php4"   vU4"  @ÜÇ¶      7   vendor/guzzle/guzzle/phing/tasks/GuzzleSubSplitTask.phpë   vUë  ]H¶      @   vendor/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php*   vU*  àÂýG¶      /   vendor/guzzle/guzzle/src/Guzzle/Batch/Batch.phpð   vUð  ü4 ¶      6   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.phpè   vUè  ¬é5ß¶      =   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php   vU  Sfæ¡¶      >   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php*   vU*  È›É¶      >   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php”   vU”  v¯8Z¶      ?   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php    vU   n+‰£¶      8   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchInterface.php£    vU£   PØ½¶      >   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchRequestTransfer.phpi   vUi  ]«	»¶      :   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php®   vU®  ö6-j¶      @   vendor/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.phpu    vUu   ™Õ…¶      J   vendor/guzzle/guzzle/src/Guzzle/Batch/Exception/BatchTransferException.phpš   vUš  I—$ö¶      A   vendor/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php�   vU�  ; ^h¶      7   vendor/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php‰   vU‰  ùš¶      6   vendor/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.phpd   vUd  ¸ŽÛM¶      8   vendor/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php)   vU)  nÐ¹¶      >   vendor/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php¾    vU¾   nÇŒÀ¶      =   vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php¦	   vU¦	  "5)¶      ?   vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.phpY   vUY  ¶„W¤¶      =   vendor/guzzle/guzzle/src/Guzzle/Cache/ClosureCacheAdapter.phpÔ   vUÔ  k®é¶      >   vendor/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.phpw   vUw  C# '¶      :   vendor/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php«   vU«  Š�8¶      9   vendor/guzzle/guzzle/src/Guzzle/Cache/Zf1CacheAdapter.phpº   vUº  »µã`¶      9   vendor/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.phph   vUh  !ÄP¶      @   vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.phpÂ   vUÂ  B»vÜ¶      5   vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php[   vU[  u'Û;¶      0   vendor/guzzle/guzzle/src/Guzzle/Common/Event.php   vU  <4&x¶      K   vendor/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php†    vU†   ‚qS”¶      H   vendor/guzzle/guzzle/src/Guzzle/Common/Exception/ExceptionCollection.php¬   vU¬  d–ÓN¶      D   vendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.phpK    vUK   ¹ññ¶      M   vendor/guzzle/guzzle/src/Guzzle/Common/Exception/InvalidArgumentException.phpŠ    vUŠ   ùVÇ¶      E   vendor/guzzle/guzzle/src/Guzzle/Common/Exception/RuntimeException.phpz    vUz   h^Üw¶      M   vendor/guzzle/guzzle/src/Guzzle/Common/Exception/UnexpectedValueException.phpŠ    vUŠ   ¢eˆ£¶      >   vendor/guzzle/guzzle/src/Guzzle/Common/FromConfigInterface.php€    vU€   ï"­}¶      A   vendor/guzzle/guzzle/src/Guzzle/Common/HasDispatcherInterface.php   vU  ¦?J¶      ;   vendor/guzzle/guzzle/src/Guzzle/Common/ToArrayInterface.phpc    vUc   `¦ˆ÷¶      2   vendor/guzzle/guzzle/src/Guzzle/Common/Version.php   vU  ý„A¶      D   vendor/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.phpÿ   vUÿ  úúÝí¶      :   vendor/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.phpF   vUF  Å�™¶      /   vendor/guzzle/guzzle/src/Guzzle/Http/Client.php`)   vU`)  R'ä¶      8   vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php�   vU�  ©¬vz¶      8   vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlHandle.php;   vU;  !9Ö¾¶      7   vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php4    vU4   \õcD¶      @   vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.phpÃ   vUÃ  ÷_½¶      <   vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiProxy.php6	   vU6	  7öô¶      9   vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php    vU   ä	ñ‡¶      =   vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.phpž   vUž  îèÉ¶      3   vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php©   vU©  åù.=¶      <   vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php   vU  H—ƒ–¶      G   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/BadResponseException.php   vU  %öå€¶      O   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.phpo    vUo   Ò'‰ó¶      P   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/CouldNotRewindStreamException.php±    vU±   „n—ð¶      @   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/CurlException.php   vU  3‡ô¶      @   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php�    vU�   	n8­¶      I   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/MultiTransferException.php¬   vU¬  Äc¶      C   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php‘   vU‘  »LXò¶      O   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.phpo    vUo   ¥ˆ¶      L   vendor/guzzle/guzzle/src/Guzzle/Http/Exception/TooManyRedirectsException.phpi    vUi   Ç¸–¶      =   vendor/guzzle/guzzle/src/Guzzle/Http/IoEmittingEntityBody.phpË   vUË  ‘Ÿ�¶      @   vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.phpñ   vUñ  SJ0¼¶      G   vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.phpF   vUF  òB`¶      P   vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php   vU  dâ¶      7   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php
   vU
  Õm’x¶      D   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.phpÌ   vUÌ  IÇcu¶      H   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.phpW   vUW  <šÀ:¶      E   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.phpî   vUî  ¼	¶      N   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php”    vU”   ÍïÀã¶      G   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderInterface.php   vU  ƒ²gÖ¶      <   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/Link.php   vU  
�˜´¶      A   vendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php7   vU7  ®ª£f¶      9   vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFile.php”   vU”  €žÂ¶      B   vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.phpó   vUó  �3\¶      8   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Request.phpZ.   vUZ.  À¹¶      ?   vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.phpK!   vUK!  M§‹Ò¶      H   vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php©   vU©  ,êtÞ¶      A   vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestInterface.php…   vU…  ž‹%4¶      9   vendor/guzzle/guzzle/src/Guzzle/Http/Message/Response.phpZ.   vUZ.  ½(Î‘¶      2   vendor/guzzle/guzzle/src/Guzzle/Http/Mimetypes.phpl…   vUl…  Ð~‚¶      H   vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.phpŽ   vUŽ  3"¶      L   vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.phpx   vUx  kgB€¶      F   vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php´   vU´  —’¹¶      Q   vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php½    vU½   ±×E¶      4   vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.phpz   vUz  fDåQ¶      <   vendor/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.phpF   vUF  Gÿã¶      7   vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php�   vU�  îî�Ï¶      5   vendor/guzzle/guzzle/src/Guzzle/Http/StaticClient.phpÑ   vUÑ  E„g›¶      ,   vendor/guzzle/guzzle/src/Guzzle/Http/Url.php    vU   *øR¶      8   vendor/guzzle/guzzle/src/Guzzle/Inflection/Inflector.phpï   vUï  *üŒé¶      A   vendor/guzzle/guzzle/src/Guzzle/Inflection/InflectorInterface.php”    vU”   ¦Å*‰¶      A   vendor/guzzle/guzzle/src/Guzzle/Inflection/MemoizingInflector.php   vU  šõð¶      C   vendor/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.phpo   vUo  FK†B¶      ;   vendor/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.phpº    vUº   «{Ø¶      <   vendor/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php   vU  óXË¶      ;   vendor/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.phpè   vUè  ÆØEŸ¶      8   vendor/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.phpê   vUê  ¹Ìå¶      @   vendor/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php2   vU2  @!L1¶      :   vendor/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php­    vU­   À-k¶      7   vendor/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php�   vU�  �91f¶      9   vendor/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php†   vU†  ã½1Ñ¶      ;   vendor/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php’    vU’   6/Ãƒ¶      8   vendor/guzzle/guzzle/src/Guzzle/Log/MessageFormatter.phpý   vUý  šð‰Î¶      9   vendor/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php   vU  ÛîZ¶      5   vendor/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.phpG   vUG  Âè¼¶      5   vendor/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.phpi   vUi  ¾7cã¶      5   vendor/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php1   vU1  «¿å¶      >   vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php²   vU²  mzïÕ¶      G   vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php¸    vU¸   øð¡!¶      H   vendor/guzzle/guzzle/src/Guzzle/Parser/Message/AbstractMessageParser.phpÛ   vUÛ  {^"X¶      @   vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php   vU  óc¹¶      I   vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php±    vU±   
sú³¶      H   vendor/guzzle/guzzle/src/Guzzle/Parser/Message/PeclHttpMessageParser.phpN   vUN  ^¿#¶      9   vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.phpà   vUà  ß5&d¶      F   vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php²   vU²  ídŸ¶      B   vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplate.phpz   vUz  ß>Ék¶      K   vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php’    vU’   'JÜŒ¶      8   vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParser.php   vU  (yËá¶      A   vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.phpq    vUq   V³ý:¶      <   vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php'   vU'  MA"¶      J   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.phpü   vUü  m]<Î¶      S   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php   vU  ðîÍy¶      @   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.phps   vUs  T©.Ã¶      @   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php²	   vU²	  ±gí¶      K   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.phpP   vUP  J=,—¶      J   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.phpj   vUj  B}}2¶      J   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.phpü   vUü  ¤…ÿ8¶      F   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php   vU  åÃJ™¶      M   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php´   vU´  x¬&9¶      F   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php7   vU7  ú¥NG¶      H   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php   vU  SºÞ¶      N   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.phpü   vUü  žÌ¶      K   vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.phpW   vUW  ,ÙR{¶      J   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php´    vU´   =Ú8Ö¶      <   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CachePlugin.phpŸ   vUŸ  ³3®¶      F   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php}   vU}  
‚²ï¶      I   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.phpC   vUC  ‹íç-¶      J   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php    vU   ýââv¶      H   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.phpË   vUË  ZÊ‰É¶      D   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.phpf   vUf  ªÓÀ¶      H   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php|   vU|  €‰¼ô¶      D   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.phpW   vUW  €Ú<:¶      A   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php,   vU,  -NLÝ¶      F   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/RevalidationInterface.phpH   vUH  &!z¨¶      A   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/SkipRevalidation.php+   vU+  ¾$ô¶      8   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.phpÖ   vUÖ  F3¯¶      J   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php¨   vU¨  —i8n¶      N   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.phpå   vUå  Wï�ò¶      I   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php÷   vU÷  }²4Û¶      >   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.phpt   vUt  ^¡_®¶      R   vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.phpª    vUª   !m|€¶      B   vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.phpM   vUM  8^ÿ¶      X   vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php   vU  ÁIF¶      L   vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.php   vU  	@f¶      Y   vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php¡    vU¡   «ÔÒ™¶      @   vendor/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.phpó   vUó  uïñ¶      8   vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.phpR   vUR   ÄÉ¶      F   vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php¨   vU¨  ¢­0¶      A   vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.phpÇ   vUÇ  ~Ï�¶      :   vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.phpA   vUA  °—Q¶      <   vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.phpÎ   vUÎ  òt™Á¶      @   vendor/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php@   vU@  <ðJ¶      B   vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.phpH   vUH  µ‹ç¶      K   vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.phpú    vUú   2ÍÈ•¶      H   vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderLoader.php.   vU.  xÊÜÝ¶      ?   vendor/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php�   vU�  d¯¶      2   vendor/guzzle/guzzle/src/Guzzle/Service/Client.phpØ   vUØ  È¾-¶      ;   vendor/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php:   vU:  ÜîÇm¶      C   vendor/guzzle/guzzle/src/Guzzle/Service/Command/AbstractCommand.php   vU  �+6J¶      B   vendor/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php«   vU«  Ñé›Ü¶      D   vendor/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.phpè   vUè  :wª¶      L   vendor/guzzle/guzzle/src/Guzzle/Service/Command/CreateResponseClassEvent.php   vU  ‹€Ì�¶      L   vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.phpÞ   vUÞ  F< 
¶      I   vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.phpÈ   vUÈ  ˆ2�x¶      H   vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.phpM   vUM  ³�¬¶      L   vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.phpŠ   vUŠ  ‹ÊáT¶      P   vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php“   vU“  ?æE¶      L   vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.phpÁ    vUÁ   ‚ÏTO¶      F   vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/MapFactory.phpL   vUL  ód=I¶      U   vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.phpJ   vUJ  ÅÚH'¶      b   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.phpØ   vUØ  Šÿ´²¶      W   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php¹   vU¹  ›eÌ9¶      Y   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php   vU  �Æs¶¶      W   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php�   vU�  lÎ×Á¶      \   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php¿   vU¿  Þ†uª¶      [   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.phpA   vUA  ã¶*£¶      X   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php¾   vU¾  Ô§!¶      c   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php°   vU°  c`7Æ¶      _   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.php‘   vU‘  ü…¶      V   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php%   vU%  ßò¶      d   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php   vU  çXþ¶      X   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php¯   vU¯  &È¶      Z   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php    vU   ²¬2¶      X   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php‚   vU‚  êÓN¬¶      `   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php¯   vU¯  ùMµÁ¶      e   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.phpç   vUç  bZ!Ø¶      ^   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.php«   vU«  V÷N¶      W   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php›
   vU›
  $�‚¶      T   vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.phpú
   vUú
  LÕå•¶      D   vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php-   vU-  ç¨Äw¶      K   vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.phpÃ   vUÃ  íã�$¶      N   vendor/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.phpé    vUé   ãœ‡¶      J   vendor/guzzle/guzzle/src/Guzzle/Service/Command/ResponseClassInterface.php˜    vU˜   XsÆM¶      K   vendor/guzzle/guzzle/src/Guzzle/Service/Command/ResponseParserInterface.phpŒ    vUŒ   Öo¥¶      A   vendor/guzzle/guzzle/src/Guzzle/Service/ConfigLoaderInterface.php�    vU�   Vqq¶      A   vendor/guzzle/guzzle/src/Guzzle/Service/Description/Operation.php”   vU”  k¹É¶      J   vendor/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php3   vU3  ÒŠA9¶      A   vendor/guzzle/guzzle/src/Guzzle/Service/Description/Parameter.phpý"   vUý"  ¡M¹­¶      G   vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.phpR   vUR  «�”¶      G   vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php$   vU$  Cïn£¶      J   vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php=   vU=  us�°¶      S   vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.phpM   vUM  4rÏ¶      P   vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionLoader.phpÇ   vUÇ  $æî¶      J   vendor/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php´    vU´   ÎA0¶      F   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/CommandException.phpŽ    vUŽ   �£Õ¯¶      N   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/CommandTransferException.phpF   vUF  Â,¶      Q   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php™    vU™   Æ£Ñï¶      Y   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/InconsistentClientTransferException.php0   vU0  ¢
Ò´¶      L   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php•    vU•   #ìíN¶      M   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceBuilderException.php•    vU•   ïèNÎ¶      N   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceNotFoundException.phpn    vUn   ¼S¬h¶      I   vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ValidationException.php7   vU7  !ù3¶      T   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.phpÉ   vUÉ  k4‹¶      U   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.phpù   vUù  œ\åÎ¶      O   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.phpí   vUí  õÂ´·¶      :   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php_   vU_  58Ô¶      E   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php    vU   ß¾¶¶      Q   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php×   vU×  8¥6¶      Q   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php¯   vU¯  Ä“e¹¶      U   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php   vU  .½—×¶      N   vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorInterface.phpÀ   vUÀ  QíÝ-¶      B   vendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.phpö   vUö  ð3B¶      1   vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.phpN   vUN  ÁrÁ3¶      :   vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.phpl   vUl  Û§‚Z¶      H   vendor/guzzle/guzzle/src/Guzzle/Stream/StreamRequestFactoryInterface.phpë    vUë   Ü÷Ý¶      Y   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Console/Application.php,   vU,  `&ë?¶      U   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/CoverallsBundle.php‘    vU‘   OˆÉä¶      ]   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsBundle/Entity/ArrayConvertable.php}    vU}   ƒ€59¶      X   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/CoverallsApi.phpQ   vUQ  g”ûœ¶      P   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Api/Jobs.phpÿ   vUÿ  �$vJ¶      d   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CiEnvVarsCollector.phpð
   vUð
  k4ôj¶      l   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/CloverXmlCoverageCollector.php©   vU©  j(iO¶      b   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Collector/GitInfoCollector.phpÕ   vUÕ  �búÕ¶      f   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Command/CoverallsV1JobsCommand.php�
   vU�
  ñ®*B¶      \   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configuration.php„
   vU„
  ÿ@sÄ¶      [   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/Configurator.php   vU  ‰ê§Û¶      e   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Config/CoverallsConfiguration.phpƒ   vUƒ  Þ‡?b¶      Y   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/CoverallsV1Bundle.php•    vU•   ~˜Èõ¶      X   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Coveralls.php   vU  ú	 ¶      z   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Exception/RequirementsNotSatisfiedException.php   vU  ®»¯º¶      Y   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Commit.php`   vU`  öžÖ“¶      V   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Git.php.   vU.  ‚Nè¶      Y   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Git/Remote.phpŒ   vUŒ  ’«añ¶      W   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/JsonFile.phpë   vUë  &®hé¶      V   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/Metrics.phpw   vUw  ã!5¶      Y   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Entity/SourceFile.phpW   vUW  šâ$¶      a   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Repository/JobsRepository.php¸   vU¸  ]mŸ“¶      O   vendor/satooshi/php-coveralls/src/Satooshi/Bundle/CoverallsV1Bundle/Version.phps    vUs   €š
¶      B   vendor/satooshi/php-coveralls/src/Satooshi/Component/File/Path.php÷   vU÷  ‹J4¶      J   vendor/satooshi/php-coveralls/src/Satooshi/Component/Log/ConsoleLogger.phpŽ   vUŽ  n{W¶      N   vendor/satooshi/php-coveralls/src/Satooshi/Component/System/Git/GitCommand.phpZ   vUZ  kxcf¶      M   vendor/satooshi/php-coveralls/src/Satooshi/Component/System/SystemCommand.php   vU  ˜4Æ#¶      #   vendor/sebastian/diff/src/Chunk.phpK   vUK  ¦{¶      "   vendor/sebastian/diff/src/Diff.php   vU  ŸÊÝk¶      $   vendor/sebastian/diff/src/Differ.phpô   vUô  Ô²S¶      :   vendor/sebastian/diff/src/LCS/LongestCommonSubsequence.phpÃ    vUÃ   î8Å¶      W   vendor/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php+   vU+  [U�‡¶      U   vendor/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.phpx   vUx  íô'®¶      "   vendor/sebastian/diff/src/Line.php¼   vU¼  ŽE:¶      $   vendor/sebastian/diff/src/Parser.php2   vU2  à¸¶         vendor/autoload.php‘    vU‘   £­+Ü¶      !   Symfony/CS/AbstractAlignFixer.phpw   vUw  —’š¶         Symfony/CS/AbstractFixer.phpb   vUb  Œúb¶      0   Symfony/CS/AbstractLinesBeforeNamespaceFixer.phpr   vUr  2êæq¶         Symfony/CS/Config/Config.php”   vU”  S£e¶      #   Symfony/CS/Config/MagentoConfig.phpj   vUj  ;äL¶      %   Symfony/CS/Config/Symfony23Config.phpo   vUo  9Æ7µ¶      #   Symfony/CS/ConfigAwareInterface.php†    vU†   —¿ ¶         Symfony/CS/ConfigInterface.php¦   vU¦  G��Á¶      $   Symfony/CS/ConfigurationResolver.php•
   vU•
  £†þ½¶      "   Symfony/CS/Console/Application.php&   vU&  óPä¶      )   Symfony/CS/Console/Command/FixCommand.php¹A   vU¹A  î*D[¶      ,   Symfony/CS/Console/Command/ReadmeCommand.php¥   vU¥  —!¢õ¶      0   Symfony/CS/Console/Command/SelfUpdateCommand.phpÖ   vUÖ  {iÔm¶      "   Symfony/CS/DocBlock/Annotation.phpú   vUú  £vE„¶          Symfony/CS/DocBlock/DocBlock.phpI   vUI  ¬&}§¶         Symfony/CS/DocBlock/Line.phpÐ   vUÐ  .ûh¶         Symfony/CS/DocBlock/Tag.phpê   vUê  ‡–6¶      %   Symfony/CS/DocBlock/TagComparator.phpD   vUD  ™\¶         Symfony/CS/ErrorsManager.php¹   vU¹  òÂ³¶         Symfony/CS/FileCacheManager.phpk   vUk  & ¶}¶      #   Symfony/CS/Finder/DefaultFinder.phpç   vUç  ‰–Œ¶      #   Symfony/CS/Finder/MagentoFinder.phpz   vUz  {ç@…¶      %   Symfony/CS/Finder/Symfony23Finder.phpc   vUc  ,2Ýs¶         Symfony/CS/FinderInterface.phpf    vUf   «0¶      2   Symfony/CS/Fixer/Contrib/AlignDoubleArrowFixer.php�	   vU�	  Eðž¶      -   Symfony/CS/Fixer/Contrib/AlignEqualsFixer.php‹   vU‹  @‡X…¶      2   Symfony/CS/Fixer/Contrib/ConcatWithSpacesFixer.phpP   vUP  çŠ?¶      ,   Symfony/CS/Fixer/Contrib/EregToPregFixer.phpÑ	   vUÑ	  Û•ºS¶      /   Symfony/CS/Fixer/Contrib/HeaderCommentFixer.phpÞ   vUÞ  +¦úE¶      @   Symfony/CS/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixer.phpŽ   vUŽ  v¹ëØ¶      =   Symfony/CS/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixer.phpP   vUP  ¨„Àd¶      1   Symfony/CS/Fixer/Contrib/Php4ConstructorFixer.phpÉ   vUÉ  im†à¶      -   Symfony/CS/Fixer/Contrib/PhpdocOrderFixer.phpc   vUc  ÀÆ½¶      1   Symfony/CS/Fixer/Contrib/PhpdocVarToTypeFixer.php8   vU8  øm Œ¶      2   Symfony/CS/Fixer/Contrib/ShortArraySyntaxFixer.phpÉ   vUÉ  Aºÿ¶      (   Symfony/CS/Fixer/Contrib/StrictFixer.php5   vU5  rmp"¶      -   Symfony/CS/Fixer/Contrib/StrictParamFixer.php’
   vU’
  —Œëž¶      1   Symfony/CS/Fixer/Contrib/LongArraySyntaxFixer.phpí   vUí  ž§‹¶      5   Symfony/CS/Fixer/Contrib/NewlineAfterOpenTagFixer.php&   vU&  úQky¶      ,   Symfony/CS/Fixer/Contrib/OrderedUseFixer.phpj	   vUj	  ž> Œ¶      #   Symfony/CS/Fixer/PSR0/Psr0Fixer.phpâ   vUâ  ÏRDù¶      '   Symfony/CS/Fixer/PSR1/EncodingFixer.php   vU  å¤ˆ¶      '   Symfony/CS/Fixer/PSR1/ShortTagFixer.phph   vUh  Þ½9¶      %   Symfony/CS/Fixer/PSR2/BracesFixer.phpÔ3   vUÔ3  cÒ°=¶      %   Symfony/CS/Fixer/PSR2/ElseifFixer.php‹   vU‹  XÒŽ\¶      (   Symfony/CS/Fixer/PSR2/EofEndingFixer.php´   vU´  ”Hòw¶      0   Symfony/CS/Fixer/PSR2/FunctionCallSpaceFixer.php	   vU	  4( î¶      2   Symfony/CS/Fixer/PSR2/FunctionDeclarationFixer.phpW	   vUW	  g_ºä¶      *   Symfony/CS/Fixer/PSR2/IndentationFixer.php˜   vU˜  P;L¶      1   Symfony/CS/Fixer/PSR2/LineAfterNamespaceFixer.phpý   vUý  hü+î¶      '   Symfony/CS/Fixer/PSR2/LinefeedFixer.phpŠ   vUŠ  ?–-¶      1   Symfony/CS/Fixer/PSR2/LowercaseConstantsFixer.php&   vU&  ¶çéU¶      0   Symfony/CS/Fixer/PSR2/LowercaseKeywordsFixer.phpb   vUb  ”riE¶      2   Symfony/CS/Fixer/PSR2/MethodArgumentSpaceFixer.php   vU  Ó�«¶      *   Symfony/CS/Fixer/PSR2/MultipleUseFixer.php¦   vU¦  àÏ¶      *   Symfony/CS/Fixer/PSR2/ParenthesisFixer.php¤   vU¤  ”Âx¶      ,   Symfony/CS/Fixer/PSR2/PhpClosingTagFixer.php–   vU–  bY°¶      5   Symfony/CS/Fixer/PSR2/SingleLineAfterImportsFixer.php‘   vU‘  žƒÂb¶      -   Symfony/CS/Fixer/PSR2/TrailingSpacesFixer.php›   vU›  †q±¶      )   Symfony/CS/Fixer/PSR2/VisibilityFixer.phpe   vUe  I�ä¶      5   Symfony/CS/Fixer/Symfony/ConcatWithoutSpacesFixer.php   vU  6	.p¶      A   Symfony/CS/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixer.phpŽ   vUŽ  óOö¶      4   Symfony/CS/Fixer/Symfony/DuplicateSemicolonFixer.php›   vU›  Éƒ<¶      -   Symfony/CS/Fixer/Symfony/EmptyReturnFixer.php/   vU/  y‚�Õ¶      1   Symfony/CS/Fixer/Symfony/ExtraEmptyLinesFixer.php    vU   ¹5k¬¶      )   Symfony/CS/Fixer/Symfony/IncludeFixer.php`	   vU`	  °&¶      .   Symfony/CS/Fixer/Symfony/JoinFunctionFixer.phpx   vUx  Â›Z´¶      =   Symfony/CS/Fixer/Symfony/MultilineArrayTrailingCommaFixer.php–   vU–  z^ƒû¶      >   Symfony/CS/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixer.php>   vU>  l±ƒ¼¶      /   Symfony/CS/Fixer/Symfony/NewWithBracesFixer.phpÀ   vUÀ  åD¶      ?   Symfony/CS/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixer.php¿   vU¿  Xx�¶      :   Symfony/CS/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixer.phpC   vUC  Éþ»¶      0   Symfony/CS/Fixer/Symfony/ObjectOperatorFixer.php   vU  BžW¶      1   Symfony/CS/Fixer/Symfony/OperatorsSpacesFixer.php{   vU{  4L3¶      .   Symfony/CS/Fixer/Symfony/PhpdocIndentFixer.php¦   vU¦  GÀMä¶      5   Symfony/CS/Fixer/Symfony/PhpdocNoEmptyReturnFixer.phpD   vUD  ™õ„¶      1   Symfony/CS/Fixer/Symfony/PhpdocNoPackageFixer.phpD   vUD  §·äø¶      .   Symfony/CS/Fixer/Symfony/PhpdocParamsFixer.phpŠ   vUŠ  xÐ¯E¶      2   Symfony/CS/Fixer/Symfony/PhpdocSeparationFixer.phpW   vUW  ‡x¶      8   Symfony/CS/Fixer/Symfony/PhpdocShortDescriptionFixer.phpƒ   vUƒ  ÿ&s‘¶      1   Symfony/CS/Fixer/Symfony/PhpdocToCommentFixer.phpç   vUç  ·ü„&¶      ,   Symfony/CS/Fixer/Symfony/PhpdocTrimFixer.phpk   vUk  uhën¶      1   Symfony/CS/Fixer/Symfony/PhpdocTypeToVarFixer.php9   vU9  cFL¼¶      6   Symfony/CS/Fixer/Symfony/PhpdocVarWithoutNameFixer.phpx   vUx  ýb\¶      7   Symfony/CS/Fixer/Symfony/RemoveLeadingSlashUseFixer.phps   vUs  ‡$T‰¶      8   Symfony/CS/Fixer/Symfony/RemoveLinesBetweenUsesFixer.php$   vU$  Ïº)¶      (   Symfony/CS/Fixer/Symfony/ReturnFixer.phpŒ   vUŒ  ”MÀV¶      <   Symfony/CS/Fixer/Symfony/SingleArrayNoTrailingCommaFixer.phpµ   vUµ  ÖvME¶      @   Symfony/CS/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixer.php[   vU[  Ä»ÖÓ¶      7   Symfony/CS/Fixer/Symfony/SpacesBeforeSemicolonFixer.php•   vU•  V­Q¶      ,   Symfony/CS/Fixer/Symfony/SpacesCastFixer.php‘   vU‘  
Jt¶      5   Symfony/CS/Fixer/Symfony/StandardizeNotEqualFixer.php÷   vU÷  JþAv¶      /   Symfony/CS/Fixer/Symfony/TernarySpacesFixer.php   vU  ¾¾€p¶      +   Symfony/CS/Fixer/Symfony/UnusedUseFixer.phpÉ   vUÉ  ¯üï¶      1   Symfony/CS/Fixer/Symfony/WhitespacyLinesFixer.php]   vU]  žœ~¶      7   Symfony/CS/Fixer/Symfony/BlanklineAfterOpenTagFixer.php   vU  é
s�¶      ,   Symfony/CS/Fixer/Symfony/ListCommasFixer.phpã   vUã  Ëö7¶      .   Symfony/CS/Fixer/Symfony/PhpdocScalarFixer.phpÞ   vUÞ  Èö÷ÿ¶      -   Symfony/CS/Fixer/Symfony/SingleQuoteFixer.php¹   vU¹  #(¹¹¶      1   Symfony/CS/Fixer/Symfony/TrimArraySpacesFixer.phpí   vUí  ˜~öq¶      &   Symfony/CS/FixerFileProcessedEvent.phpa   vUa  ÖbM¶         Symfony/CS/FixerInterface.phpÞ   vUÞ  ¬Ö]¶         Symfony/CS/LintManager.php5   vU5  Õc´O¶      "   Symfony/CS/Resources/phar-stub.phpy   vUy  ã'>¶      ,   Symfony/CS/Tokenizer/AbstractTransformer.phpM   vUM  ­�©¶         Symfony/CS/Tokenizer/Token.php–   vU–  ¶aS‘¶      2   Symfony/CS/Tokenizer/Transformer/ArrayTypehint.phpX   vUX  ê˜H¶      2   Symfony/CS/Tokenizer/Transformer/ClassConstant.phpg   vUg  ³¢ÏË¶      /   Symfony/CS/Tokenizer/Transformer/CurlyClose.php´   vU´  $‡Ê¶      ;   Symfony/CS/Tokenizer/Transformer/DollarCloseCurlyBraces.phpŠ   vUŠ  ËÒE~¶      5   Symfony/CS/Tokenizer/Transformer/DynamicPropBrace.phpc   vUc  1‘zc¶      4   Symfony/CS/Tokenizer/Transformer/DynamicVarBrace.phpÅ   vUÅ  /èE[¶      -   Symfony/CS/Tokenizer/TransformerInterface.php/   vU/  
åÿc¶      %   Symfony/CS/Tokenizer/Transformers.php+   vU+  y>®É¶         Symfony/CS/Tokenizer/Tokens.php£<   vU£<  ¨À(©¶         Symfony/CS/ToolInfo.phpÑ   vUÑ  œÖÖ¶         Symfony/CS/Fixer.php˜   vU˜  m¶         Symfony/CS/StdinFileInfo.phpñ   vUñ  o¶Uf¶         Symfony/CS/Utils.php9   vU9  3BÆu¶         LICENSE)   vU)  m·
¶      <?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\LogLevel;






abstract class LoggerInterfaceTest extends \PHPUnit_Framework_TestCase
{



abstract function getLogger();








abstract 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()
{
$dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString'));
$dummy->expects($this->once())
->method('__toString')
->will($this->returnValue('DUMMY'));

$this->getLogger()->warning($dummy);
}

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);
}

public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$this->getLogger()->warning('Random message', array('exception' => 'oops'));
$this->getLogger()->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
}
}

class DummyTest
{
}<?php



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

return array(
'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'),
'Satooshi\\Component' => array($vendorDir . '/satooshi/php-coveralls/src'),
'Satooshi\\Bundle' => array($vendorDir . '/satooshi/php-coveralls/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log'),
'Guzzle\\Tests' => array($vendorDir . '/guzzle/guzzle/tests'),
'Guzzle' => array($vendorDir . '/guzzle/guzzle/src'),
);
<?php



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

return array(
'Symfony\\CS\\' => array($baseDir . '/Symfony/CS'),
);
<?php



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

return array(
'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\\GuzzleTestCase' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/GuzzleTestCase.php',
'Guzzle\\Tests\\Http\\Message\\HeaderComparison' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php',
'Guzzle\\Tests\\Http\\Server' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.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\\Message\\MessageParserProvider' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.php',
'Guzzle\\Tests\\Service\\Command\\LocationVisitor\\Request\\AbstractVisitorTestCase' => $vendorDir . '/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.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',
'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',
'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\\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',
'Symfony\\CS\\AbstractAlignFixer' => $baseDir . '/Symfony/CS/AbstractAlignFixer.php',
'Symfony\\CS\\AbstractFixer' => $baseDir . '/Symfony/CS/AbstractFixer.php',
'Symfony\\CS\\AbstractLinesBeforeNamespaceFixer' => $baseDir . '/Symfony/CS/AbstractLinesBeforeNamespaceFixer.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\\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\\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\\ConcatWithSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/ConcatWithSpacesFixer.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\\LongArraySyntaxFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/LongArraySyntaxFixer.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\\OrderedUseFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/OrderedUseFixer.php',
'Symfony\\CS\\Fixer\\Contrib\\Php4ConstructorFixer' => $baseDir . '/Symfony/CS/Fixer/Contrib/Php4ConstructorFixer.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\\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\\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\\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\\TrailingSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/TrailingSpacesFixer.php',
'Symfony\\CS\\Fixer\\PSR2\\VisibilityFixer' => $baseDir . '/Symfony/CS/Fixer/PSR2/VisibilityFixer.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\\DoubleArrowMultilineWhitespacesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\DuplicateSemicolonFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/DuplicateSemicolonFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\EmptyReturnFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/EmptyReturnFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\ExtraEmptyLinesFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/ExtraEmptyLinesFixer.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\\MultilineArrayTrailingCommaFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/MultilineArrayTrailingCommaFixer.php',
'Symfony\\CS\\Fixer\\Symfony\\NamespaceNoLeadingWhitespaceFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixer.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\\NoEmptyLinesAfterPhpdocsFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixer.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\\PhpdocIndentFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocIndentFixer.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\\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\\PhpdocVarWithoutNameFixer' => $baseDir . '/Symfony/CS/Fixer/Symfony/PhpdocVarWithoutNameFixer.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\\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\\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\\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\\Tests\\Fixer\\AbstractFixerTestBase' => $baseDir . '/Symfony/CS/Tests/Fixer/AbstractFixerTestBase.php',
'Symfony\\CS\\Tests\\Tokenizer\\AbstractTransformerTestBase' => $baseDir . '/Symfony/CS/Tests/Tokenizer/AbstractTransformerTestBase.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\\Utils' => $baseDir . '/Symfony/CS/Utils.php',
'Symfony\\Component\\Config\\ConfigCache' => $vendorDir . '/symfony/config/Symfony/Component/Config/ConfigCache.php',
'Symfony\\Component\\Config\\Definition\\ArrayNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/ArrayNode.php',
'Symfony\\Component\\Config\\Definition\\BaseNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/BaseNode.php',
'Symfony\\Component\\Config\\Definition\\BooleanNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/BooleanNode.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ArrayNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\BooleanNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/BooleanNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\EnumNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/EnumNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ExprBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/ExprBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\FloatNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/FloatNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\IntegerNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/IntegerNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\MergeBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/MergeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/NodeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/NodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NodeParentInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/NodeParentInterface.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NormalizationBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/NormalizationBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\NumericNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/NumericNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ParentNodeDefinitionInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/ParentNodeDefinitionInterface.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ScalarNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/ScalarNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\Builder\\TreeBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/TreeBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\ValidationBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/ValidationBuilder.php',
'Symfony\\Component\\Config\\Definition\\Builder\\VariableNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Builder/VariableNodeDefinition.php',
'Symfony\\Component\\Config\\Definition\\ConfigurationInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/ConfigurationInterface.php',
'Symfony\\Component\\Config\\Definition\\Dumper\\XmlReferenceDumper' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\Dumper\\YamlReferenceDumper' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Dumper/YamlReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\EnumNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/EnumNode.php',
'Symfony\\Component\\Config\\Definition\\Exception\\DuplicateKeyException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/DuplicateKeyException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\Exception' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/Exception.php',
'Symfony\\Component\\Config\\Definition\\Exception\\ForbiddenOverwriteException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/ForbiddenOverwriteException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidConfigurationException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/InvalidConfigurationException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidDefinitionException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/InvalidDefinitionException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\InvalidTypeException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/InvalidTypeException.php',
'Symfony\\Component\\Config\\Definition\\Exception\\UnsetKeyException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Exception/UnsetKeyException.php',
'Symfony\\Component\\Config\\Definition\\FloatNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/FloatNode.php',
'Symfony\\Component\\Config\\Definition\\IntegerNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/IntegerNode.php',
'Symfony\\Component\\Config\\Definition\\NodeInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/NodeInterface.php',
'Symfony\\Component\\Config\\Definition\\NumericNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/NumericNode.php',
'Symfony\\Component\\Config\\Definition\\Processor' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/Processor.php',
'Symfony\\Component\\Config\\Definition\\PrototypeNodeInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/PrototypeNodeInterface.php',
'Symfony\\Component\\Config\\Definition\\PrototypedArrayNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/PrototypedArrayNode.php',
'Symfony\\Component\\Config\\Definition\\ReferenceDumper' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/ReferenceDumper.php',
'Symfony\\Component\\Config\\Definition\\ScalarNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/ScalarNode.php',
'Symfony\\Component\\Config\\Definition\\VariableNode' => $vendorDir . '/symfony/config/Symfony/Component/Config/Definition/VariableNode.php',
'Symfony\\Component\\Config\\Exception\\FileLoaderImportCircularReferenceException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Exception/FileLoaderImportCircularReferenceException.php',
'Symfony\\Component\\Config\\Exception\\FileLoaderLoadException' => $vendorDir . '/symfony/config/Symfony/Component/Config/Exception/FileLoaderLoadException.php',
'Symfony\\Component\\Config\\FileLocator' => $vendorDir . '/symfony/config/Symfony/Component/Config/FileLocator.php',
'Symfony\\Component\\Config\\FileLocatorInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/FileLocatorInterface.php',
'Symfony\\Component\\Config\\Loader\\DelegatingLoader' => $vendorDir . '/symfony/config/Symfony/Component/Config/Loader/DelegatingLoader.php',
'Symfony\\Component\\Config\\Loader\\FileLoader' => $vendorDir . '/symfony/config/Symfony/Component/Config/Loader/FileLoader.php',
'Symfony\\Component\\Config\\Loader\\Loader' => $vendorDir . '/symfony/config/Symfony/Component/Config/Loader/Loader.php',
'Symfony\\Component\\Config\\Loader\\LoaderInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Loader/LoaderInterface.php',
'Symfony\\Component\\Config\\Loader\\LoaderResolver' => $vendorDir . '/symfony/config/Symfony/Component/Config/Loader/LoaderResolver.php',
'Symfony\\Component\\Config\\Loader\\LoaderResolverInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Loader/LoaderResolverInterface.php',
'Symfony\\Component\\Config\\Resource\\DirectoryResource' => $vendorDir . '/symfony/config/Symfony/Component/Config/Resource/DirectoryResource.php',
'Symfony\\Component\\Config\\Resource\\FileResource' => $vendorDir . '/symfony/config/Symfony/Component/Config/Resource/FileResource.php',
'Symfony\\Component\\Config\\Resource\\ResourceInterface' => $vendorDir . '/symfony/config/Symfony/Component/Config/Resource/ResourceInterface.php',
'Symfony\\Component\\Config\\Tests\\Definition\\Builder\\BarNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Tests/Fixtures/Builder/BarNodeDefinition.php',
'Symfony\\Component\\Config\\Tests\\Definition\\Builder\\NodeBuilder' => $vendorDir . '/symfony/config/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.php',
'Symfony\\Component\\Config\\Tests\\Definition\\Builder\\VariableNodeDefinition' => $vendorDir . '/symfony/config/Symfony/Component/Config/Tests/Fixtures/Builder/VariableNodeDefinition.php',
'Symfony\\Component\\Config\\Tests\\Fixtures\\Configuration\\ExampleConfiguration' => $vendorDir . '/symfony/config/Symfony/Component/Config/Tests/Fixtures/Configuration/ExampleConfiguration.php',
'Symfony\\Component\\Config\\Util\\XmlUtils' => $vendorDir . '/symfony/config/Symfony/Component/Config/Util/XmlUtils.php',
'Symfony\\Component\\Console\\Application' => $vendorDir . '/symfony/console/Symfony/Component/Console/Application.php',
'Symfony\\Component\\Console\\Command\\Command' => $vendorDir . '/symfony/console/Symfony/Component/Console/Command/Command.php',
'Symfony\\Component\\Console\\Command\\HelpCommand' => $vendorDir . '/symfony/console/Symfony/Component/Console/Command/HelpCommand.php',
'Symfony\\Component\\Console\\Command\\ListCommand' => $vendorDir . '/symfony/console/Symfony/Component/Console/Command/ListCommand.php',
'Symfony\\Component\\Console\\ConsoleEvents' => $vendorDir . '/symfony/console/Symfony/Component/Console/ConsoleEvents.php',
'Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/ApplicationDescription.php',
'Symfony\\Component\\Console\\Descriptor\\Descriptor' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/Descriptor.php',
'Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/DescriptorInterface.php',
'Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/JsonDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/MarkdownDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/TextDescriptor.php',
'Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => $vendorDir . '/symfony/console/Symfony/Component/Console/Descriptor/XmlDescriptor.php',
'Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => $vendorDir . '/symfony/console/Symfony/Component/Console/Event/ConsoleCommandEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleEvent' => $vendorDir . '/symfony/console/Symfony/Component/Console/Event/ConsoleEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleExceptionEvent' => $vendorDir . '/symfony/console/Symfony/Component/Console/Event/ConsoleExceptionEvent.php',
'Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => $vendorDir . '/symfony/console/Symfony/Component/Console/Event/ConsoleTerminateEvent.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatter' => $vendorDir . '/symfony/console/Symfony/Component/Console/Formatter/OutputFormatter.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => $vendorDir . '/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyle.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleInterface.php',
'Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => $vendorDir . '/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleStack.php',
'Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/DebugFormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\DescriptorHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/DescriptorHelper.php',
'Symfony\\Component\\Console\\Helper\\DialogHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/DialogHelper.php',
'Symfony\\Component\\Console\\Helper\\FormatterHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/FormatterHelper.php',
'Symfony\\Component\\Console\\Helper\\Helper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/Helper.php',
'Symfony\\Component\\Console\\Helper\\HelperInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/HelperInterface.php',
'Symfony\\Component\\Console\\Helper\\HelperSet' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/HelperSet.php',
'Symfony\\Component\\Console\\Helper\\InputAwareHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/InputAwareHelper.php',
'Symfony\\Component\\Console\\Helper\\ProcessHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/ProcessHelper.php',
'Symfony\\Component\\Console\\Helper\\ProgressBar' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/ProgressBar.php',
'Symfony\\Component\\Console\\Helper\\ProgressHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/ProgressHelper.php',
'Symfony\\Component\\Console\\Helper\\QuestionHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/QuestionHelper.php',
'Symfony\\Component\\Console\\Helper\\Table' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/Table.php',
'Symfony\\Component\\Console\\Helper\\TableHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/TableHelper.php',
'Symfony\\Component\\Console\\Helper\\TableSeparator' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/TableSeparator.php',
'Symfony\\Component\\Console\\Helper\\TableStyle' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/TableStyle.php',
'Symfony\\Component\\Console\\Input\\ArgvInput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/ArgvInput.php',
'Symfony\\Component\\Console\\Input\\ArrayInput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/ArrayInput.php',
'Symfony\\Component\\Console\\Input\\Input' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/Input.php',
'Symfony\\Component\\Console\\Input\\InputArgument' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/InputArgument.php',
'Symfony\\Component\\Console\\Input\\InputAwareInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/InputAwareInterface.php',
'Symfony\\Component\\Console\\Input\\InputDefinition' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/InputDefinition.php',
'Symfony\\Component\\Console\\Input\\InputInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/InputInterface.php',
'Symfony\\Component\\Console\\Input\\InputOption' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/InputOption.php',
'Symfony\\Component\\Console\\Input\\StringInput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Input/StringInput.php',
'Symfony\\Component\\Console\\Logger\\ConsoleLogger' => $vendorDir . '/symfony/console/Symfony/Component/Console/Logger/ConsoleLogger.php',
'Symfony\\Component\\Console\\Output\\BufferedOutput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/BufferedOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/ConsoleOutput.php',
'Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/ConsoleOutputInterface.php',
'Symfony\\Component\\Console\\Output\\NullOutput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/NullOutput.php',
'Symfony\\Component\\Console\\Output\\Output' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/Output.php',
'Symfony\\Component\\Console\\Output\\OutputInterface' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/OutputInterface.php',
'Symfony\\Component\\Console\\Output\\StreamOutput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Output/StreamOutput.php',
'Symfony\\Component\\Console\\Question\\ChoiceQuestion' => $vendorDir . '/symfony/console/Symfony/Component/Console/Question/ChoiceQuestion.php',
'Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => $vendorDir . '/symfony/console/Symfony/Component/Console/Question/ConfirmationQuestion.php',
'Symfony\\Component\\Console\\Question\\Question' => $vendorDir . '/symfony/console/Symfony/Component/Console/Question/Question.php',
'Symfony\\Component\\Console\\Shell' => $vendorDir . '/symfony/console/Symfony/Component/Console/Shell.php',
'Symfony\\Component\\Console\\Tester\\ApplicationTester' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tester/ApplicationTester.php',
'Symfony\\Component\\Console\\Tester\\CommandTester' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tester/CommandTester.php',
'Symfony\\Component\\Console\\Tests\\Descriptor\\ObjectsProvider' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.php',
'Symfony\\Component\\Console\\Tests\\Fixtures\\DescriptorApplication1' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tests/Fixtures/DescriptorApplication1.php',
'Symfony\\Component\\Console\\Tests\\Fixtures\\DescriptorApplication2' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tests/Fixtures/DescriptorApplication2.php',
'Symfony\\Component\\Console\\Tests\\Fixtures\\DescriptorCommand1' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tests/Fixtures/DescriptorCommand1.php',
'Symfony\\Component\\Console\\Tests\\Fixtures\\DescriptorCommand2' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tests/Fixtures/DescriptorCommand2.php',
'Symfony\\Component\\Console\\Tests\\Fixtures\\DummyOutput' => $vendorDir . '/symfony/console/Symfony/Component/Console/Tests/Fixtures/DummyOutput.php',
'Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcherInterface' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Debug/WrappedListener.php',
'Symfony\\Component\\EventDispatcher\\DependencyInjection\\RegisterListenersPass' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php',
'Symfony\\Component\\EventDispatcher\\Event' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Event.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcher' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcher.php',
'Symfony\\Component\\EventDispatcher\\EventDispatcherInterface' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcherInterface.php',
'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventSubscriberInterface.php',
'Symfony\\Component\\EventDispatcher\\GenericEvent' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/GenericEvent.php',
'Symfony\\Component\\EventDispatcher\\ImmutableEventDispatcher' => $vendorDir . '/symfony/event-dispatcher/Symfony/Component/EventDispatcher/ImmutableEventDispatcher.php',
'Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/Exception/ExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/Exception/FileNotFoundException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOException' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/Exception/IOException.php',
'Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php',
'Symfony\\Component\\Filesystem\\Filesystem' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/Filesystem.php',
'Symfony\\Component\\Filesystem\\LockHandler' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/LockHandler.php',
'Symfony\\Component\\Filesystem\\Tests\\FilesystemTestCase' => $vendorDir . '/symfony/filesystem/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php',
'Symfony\\Component\\Finder\\Adapter\\AbstractAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Adapter/AbstractAdapter.php',
'Symfony\\Component\\Finder\\Adapter\\AbstractFindAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Adapter/AbstractFindAdapter.php',
'Symfony\\Component\\Finder\\Adapter\\AdapterInterface' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Adapter/AdapterInterface.php',
'Symfony\\Component\\Finder\\Adapter\\BsdFindAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Adapter/BsdFindAdapter.php',
'Symfony\\Component\\Finder\\Adapter\\GnuFindAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Adapter/GnuFindAdapter.php',
'Symfony\\Component\\Finder\\Adapter\\PhpAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Adapter/PhpAdapter.php',
'Symfony\\Component\\Finder\\Comparator\\Comparator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Comparator/Comparator.php',
'Symfony\\Component\\Finder\\Comparator\\DateComparator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Comparator/DateComparator.php',
'Symfony\\Component\\Finder\\Comparator\\NumberComparator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Comparator/NumberComparator.php',
'Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Exception/AccessDeniedException.php',
'Symfony\\Component\\Finder\\Exception\\AdapterFailureException' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Exception/AdapterFailureException.php',
'Symfony\\Component\\Finder\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Exception/ExceptionInterface.php',
'Symfony\\Component\\Finder\\Exception\\OperationNotPermitedException' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Exception/OperationNotPermitedException.php',
'Symfony\\Component\\Finder\\Exception\\ShellCommandFailureException' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Exception/ShellCommandFailureException.php',
'Symfony\\Component\\Finder\\Expression\\Expression' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Expression/Expression.php',
'Symfony\\Component\\Finder\\Expression\\Glob' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Expression/Glob.php',
'Symfony\\Component\\Finder\\Expression\\Regex' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Expression/Regex.php',
'Symfony\\Component\\Finder\\Expression\\ValueInterface' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Expression/ValueInterface.php',
'Symfony\\Component\\Finder\\Finder' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Finder.php',
'Symfony\\Component\\Finder\\Glob' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Glob.php',
'Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/CustomFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/DateRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilePathsIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/FilePathsIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/FileTypeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/FilecontentFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/FilenameFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\FilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/FilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/MultiplePcreFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/PathFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/SizeRangeFilterIterator.php',
'Symfony\\Component\\Finder\\Iterator\\SortableIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Iterator/SortableIterator.php',
'Symfony\\Component\\Finder\\Shell\\Command' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Shell/Command.php',
'Symfony\\Component\\Finder\\Shell\\Shell' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Shell/Shell.php',
'Symfony\\Component\\Finder\\SplFileInfo' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/SplFileInfo.php',
'Symfony\\Component\\Finder\\Tests\\FakeAdapter\\DummyAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/FakeAdapter/DummyAdapter.php',
'Symfony\\Component\\Finder\\Tests\\FakeAdapter\\FailingAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/FakeAdapter/FailingAdapter.php',
'Symfony\\Component\\Finder\\Tests\\FakeAdapter\\NamedAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/FakeAdapter/NamedAdapter.php',
'Symfony\\Component\\Finder\\Tests\\FakeAdapter\\UnsupportedAdapter' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/FakeAdapter/UnsupportedAdapter.php',
'Symfony\\Component\\Finder\\Tests\\Iterator\\Iterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/Iterator/Iterator.php',
'Symfony\\Component\\Finder\\Tests\\Iterator\\IteratorTestCase' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/Iterator/IteratorTestCase.php',
'Symfony\\Component\\Finder\\Tests\\Iterator\\MockFileListIterator' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/Iterator/MockFileListIterator.php',
'Symfony\\Component\\Finder\\Tests\\Iterator\\MockSplFileInfo' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php',
'Symfony\\Component\\Finder\\Tests\\Iterator\\RealIteratorTestCase' => $vendorDir . '/symfony/finder/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.php',
'Symfony\\Component\\Process\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/process/Symfony/Component/Process/Exception/ExceptionInterface.php',
'Symfony\\Component\\Process\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/process/Symfony/Component/Process/Exception/InvalidArgumentException.php',
'Symfony\\Component\\Process\\Exception\\LogicException' => $vendorDir . '/symfony/process/Symfony/Component/Process/Exception/LogicException.php',
'Symfony\\Component\\Process\\Exception\\ProcessFailedException' => $vendorDir . '/symfony/process/Symfony/Component/Process/Exception/ProcessFailedException.php',
'Symfony\\Component\\Process\\Exception\\ProcessTimedOutException' => $vendorDir . '/symfony/process/Symfony/Component/Process/Exception/ProcessTimedOutException.php',
'Symfony\\Component\\Process\\Exception\\RuntimeException' => $vendorDir . '/symfony/process/Symfony/Component/Process/Exception/RuntimeException.php',
'Symfony\\Component\\Process\\ExecutableFinder' => $vendorDir . '/symfony/process/Symfony/Component/Process/ExecutableFinder.php',
'Symfony\\Component\\Process\\PhpExecutableFinder' => $vendorDir . '/symfony/process/Symfony/Component/Process/PhpExecutableFinder.php',
'Symfony\\Component\\Process\\PhpProcess' => $vendorDir . '/symfony/process/Symfony/Component/Process/PhpProcess.php',
'Symfony\\Component\\Process\\Pipes\\AbstractPipes' => $vendorDir . '/symfony/process/Symfony/Component/Process/Pipes/AbstractPipes.php',
'Symfony\\Component\\Process\\Pipes\\PipesInterface' => $vendorDir . '/symfony/process/Symfony/Component/Process/Pipes/PipesInterface.php',
'Symfony\\Component\\Process\\Pipes\\UnixPipes' => $vendorDir . '/symfony/process/Symfony/Component/Process/Pipes/UnixPipes.php',
'Symfony\\Component\\Process\\Pipes\\WindowsPipes' => $vendorDir . '/symfony/process/Symfony/Component/Process/Pipes/WindowsPipes.php',
'Symfony\\Component\\Process\\Process' => $vendorDir . '/symfony/process/Symfony/Component/Process/Process.php',
'Symfony\\Component\\Process\\ProcessBuilder' => $vendorDir . '/symfony/process/Symfony/Component/Process/ProcessBuilder.php',
'Symfony\\Component\\Process\\ProcessUtils' => $vendorDir . '/symfony/process/Symfony/Component/Process/ProcessUtils.php',
'Symfony\\Component\\Process\\Tests\\ProcessInSigchildEnvironment' => $vendorDir . '/symfony/process/Symfony/Component/Process/Tests/ProcessInSigchildEnvironment.php',
'Symfony\\Component\\Stopwatch\\Section' => $vendorDir . '/symfony/stopwatch/Symfony/Component/Stopwatch/Section.php',
'Symfony\\Component\\Stopwatch\\Stopwatch' => $vendorDir . '/symfony/stopwatch/Symfony/Component/Stopwatch/Stopwatch.php',
'Symfony\\Component\\Stopwatch\\StopwatchEvent' => $vendorDir . '/symfony/stopwatch/Symfony/Component/Stopwatch/StopwatchEvent.php',
'Symfony\\Component\\Stopwatch\\StopwatchPeriod' => $vendorDir . '/symfony/stopwatch/Symfony/Component/Stopwatch/StopwatchPeriod.php',
'Symfony\\Component\\Yaml\\Dumper' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Dumper.php',
'Symfony\\Component\\Yaml\\Escaper' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Escaper.php',
'Symfony\\Component\\Yaml\\Exception\\DumpException' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.php',
'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.php',
'Symfony\\Component\\Yaml\\Exception\\ParseException' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.php',
'Symfony\\Component\\Yaml\\Exception\\RuntimeException' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php',
'Symfony\\Component\\Yaml\\Inline' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Inline.php',
'Symfony\\Component\\Yaml\\Parser' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Parser.php',
'Symfony\\Component\\Yaml\\Unescaper' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Unescaper.php',
'Symfony\\Component\\Yaml\\Yaml' => $vendorDir . '/symfony/yaml/Symfony/Component/Yaml/Yaml.php',
);
<?php



class ComposerAutoloaderInitc6248fbec04c2ab212eb18aa1bad6c1b
{
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('ComposerAutoloaderInitc6248fbec04c2ab212eb18aa1bad6c1b', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitc6248fbec04c2ab212eb18aa1bad6c1b', 'loadClassLoader'));

$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);

return $loader;
}
}

function composerRequirec6248fbec04c2ab212eb18aa1bad6c1b($file)
{
require $file;
}
<?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;

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) {
return false;
}

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


 if ($file === null && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}

if ($file === null) {

 return $this->classMap[$class] = false;
}

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;
}
}
}






function includeFile($file)
{
include $file;
}
<?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 => $args) {
list($serviceId, $method, $priority) = $args;
$key = $serviceId.'.'.$method;
if (isset($this->listeners[$eventName][$key]) && $listener === array($this->listeners[$eventName][$key], $method)) {
unset($this->listeners[$eventName][$key]);
if (empty($this->listeners[$eventName])) {
unset($this->listeners[$eventName]);
}
unset($this->listenerIds[$eventName][$i]);
if (empty($this->listenerIds[$eventName])) {
unset($this->listenerIds[$eventName]);
}
}
}
}

parent::removeListener($eventName, $listener);
}




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 (array_keys($this->listenerIds) as $serviceEventName) {
$this->lazyLoad($serviceEventName);
}
} else {
$this->lazyLoad($eventName);
}

return parent::getListeners($eventName);
}







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 dispatch($eventName, Event $event = null)
{
$this->lazyLoad($eventName);

return parent::dispatch($eventName, $event);
}

public function getContainer()
{
return $this->container;
}









protected function lazyLoad($eventName)
{
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as $args) {
list($serviceId, $method, $priority) = $args;
$listener = $this->container->get($serviceId);

$key = $serviceId.'.'.$method;
if (!isset($this->listeners[$eventName][$key])) {
$this->addListener($eventName, array($listener, $method), $priority);
} elseif ($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;








public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null)
{
$this->dispatcher = $dispatcher;
$this->stopwatch = $stopwatch;
$this->logger = $logger;
$this->called = 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)
{
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 hasListeners($eventName = null)
{
return $this->dispatcher->hasListeners($eventName);
}




public function dispatch($eventName, Event $event = null)
{
if (null === $event) {
$event = new Event();
}

$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(sprintf('An exception was thrown while getting the uncalled listeners (%s)', $e->getMessage()), 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;
}
}
}

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) {
$this->dispatcher->removeListener($eventName, $listener);
$info = $this->getListenerInfo($listener, $eventName);
$name = isset($info['class']) ? $info['class'] : $info['type'];
$this->dispatcher->addListener($eventName, new WrappedListener($listener, $name, $this->stopwatch, $this));
}
}

private function postProcess($eventName)
{
$skipped = false;
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
if (!$listener instanceof WrappedListener) { 
 continue;
}

 $this->dispatcher->removeListener($eventName, $listener);
$this->dispatcher->addListener($eventName, $listener->getWrappedListener());

$info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
if ($listener->wasCalled()) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Notified event "%s" to listener "%s".', $eventName, $info['pretty']));
}

if (!isset($this->called[$eventName])) {
$this->called[$eventName] = new \SplObjectStorage();
}

$this->called[$eventName]->attach($listener);
}

if (null !== $this->logger && $skipped) {
$this->logger->debug(sprintf('Listener "%s" was not called for event "%s".', $info['pretty'], $eventName));
}

if ($listener->stoppedPropagation()) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Listener "%s" stopped propagation of the event "%s".', $info['pretty'], $eventName));
}

$skipped = true;
}
}
}









private function getListenerInfo($listener, $eventName)
{
$info = array(
'event' => $eventName,
);
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;
}
}
<?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());

$refClass = new \ReflectionClass($class);
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
if (!$refClass->implementsInterface($interface)) {
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;




private $dispatcher;




private $name;










public function isPropagationStopped()
{
return $this->propagationStopped;
}










public function stopPropagation()
{
$this->propagationStopped = true;
}










public function setDispatcher(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}










public function getDispatcher()
{
return $this->dispatcher;
}










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










public function setName($name)
{
$this->name = $name;
}
}
<?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();
}

$event->setDispatcher($this);
$event->setName($eventName);

if (!isset($this->listeners[$eventName])) {
return $event;
}

$this->doDispatch($this->getListeners($eventName), $eventName, $event);

return $event;
}




public function getListeners($eventName = null)
{
if (null !== $eventName) {
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}

return $this->sorted[$eventName];
}

foreach (array_keys($this->listeners) as $eventName) {
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
}

return array_filter($this->sorted);
}




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) {
call_user_func($listener, $event, $eventName, $this);
if ($event->isPropagationStopped()) {
break;
}
}
}






private function sortListeners($eventName)
{
$this->sorted[$eventName] = array();

if (isset($this->listeners[$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 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('%s not found in %s', $key, $this->getName()));
}









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 hasListeners($eventName = null)
{
return $this->dispatcher->hasListeners($eventName);
}
}
<?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);
}
}
<?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\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, $override = 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));

if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
$doCopy = filemtime($originFile) > filemtime($targetFile);
} else {
$doCopy = true;
}

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);
}

if (stream_is_local($originFile) && $bytesCopied !== filesize($originFile)) {
throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s %g bytes copied".', $originFile, $targetFile, $bytesCopied), 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 (!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)
{
$files = iterator_to_array($this->toIterator($files));
$files = array_reverse($files);
foreach ($files as $file) {
if (!file_exists($file) && !is_link($file)) {
continue;
}

if (is_dir($file) && !is_link($file)) {
$this->remove(new \FilesystemIterator($file));

if (true !== @rmdir($file)) {
throw new IOException(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
}
} else {

 if ('\\' === DIRECTORY_SEPARATOR && is_dir($file)) {
if (true !== @rmdir($file)) {
throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
}
} else {
if (true !== @unlink($file)) {
throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
}
}
}
}
}











public function chmod($files, $mode, $umask = 0000, $recursive = false)
{
foreach ($this->toIterator($files) as $file) {
if ($recursive && is_dir($file) && !is_link($file)) {
$this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
}
if (true !== @chmod($file, $mode & ~$umask)) {
throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
}
}
}










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)) {
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 && is_readable($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);
}
}










public function symlink($originDir, $targetDir, $copyOnWindows = false)
{
if ('\\' === DIRECTORY_SEPARATOR && $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) {
if (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?');
}
}
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 = strtr($endPath, '\\', '/');
$startPath = strtr($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;


 $traverser = str_repeat('../', $depth);

$endPathRemainder = implode('/', array_slice($endPathArr, $index));


 $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');

return (strlen($relativePath) === 0) ? './' : $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_link($file) || 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->getRealPath(), $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)
{
if (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)
) {
return true;
}

return false;
}











public function dumpFile($filename, $content, $mode = 0666)
{
$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 = tempnam($dir, basename($filename));

if (false === @file_put_contents($tmpFile, $content)) {
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
}

$this->rename($tmpFile, $filename, true);
if (null !== $mode) {
$this->chmod($filename, $mode);
}
}






private function toIterator($files)
{
if (!$files instanceof \Traversable) {
$files = new \ArrayObject(is_array($files) ? $files : array($files));
}

return $files;
}
}
<?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;
}


 $errorLevel = error_reporting(0);
set_error_handler('var_dump', 0);

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();
error_reporting($errorLevel);

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\ResourceInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;









class ConfigCache
{
private $debug;
private $file;







public function __construct($file, $debug)
{
$this->file = $file;
$this->debug = (bool) $debug;
}






public function __toString()
{
return $this->file;
}









public function isFresh()
{
if (!is_file($this->file)) {
return false;
}

if (!$this->debug) {
return true;
}

$metadata = $this->getMetaFile();
if (!is_file($metadata)) {
return false;
}

$time = filemtime($this->file);
$meta = unserialize(file_get_contents($metadata));
foreach ($meta as $resource) {
if (!$resource->isFresh($time)) {
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 && true === $this->debug) {
$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\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 $normalizeKeys = true;

public function setNormalizeKeys($normalizeKeys)
{
$this->normalizeKeys = (bool) $normalizeKeys;
}














protected function preNormalize($value)
{
if (!$this->normalizeKeys || !is_array($value)) {
return $value;
}

foreach ($value as $k => $v) {
if (false !== strpos($k, '-') && false === strpos($k, '_') && !array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) {
$value[$normalizedKey] = $v;
unset($value[$k]);
}
}

return $value;
}






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)
{
$this->ignoreExtraKeys = (bool) $boolean;
}






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 $unset) {
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]);
}
}


 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 $transformation) {
list($singular, $plural) = $transformation;

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 $correctEx) {
throw $correctEx;
} catch (\Exception $invalid) {
throw new InvalidConfigurationException(sprintf(
'Invalid configuration for path "%s": %s',
$this->getPath(),
$invalid->getMessage()
), $invalid->getCode(), $invalid);
}
}

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;
}
}
}
<?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 $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()
{
$this->ignoreExtraKeys = true;

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);
$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;






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);
}
}
<?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 (count($values) <= 1) {
throw new \InvalidArgumentException('->values() must be called with at least two distinct values.');
}

$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 ExprBuilder) {
$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;






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;
}
}
<?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) {
array_unshift($rootComments, 'prototype');

if ($key = $node->getKeyAttribute()) {
$rootAttributes[$key] = str_replace('-', ' ', $rootName).' '.$key;
}

$prototype = $node->getPrototype();

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)."\n";
}








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);
$keyNode->setInfo('Prototype');


 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 = '~';
} 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 (count($values) <= 1) {
throw new \InvalidArgumentException('$values must contain at least two distinct elements.');
}

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;
}
}
<?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 $unset) {
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\Dumper\YamlReferenceDumper;




class ReferenceDumper extends YamlReferenceDumper
{
}
<?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;
}
}
}
<?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 && empty($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;
}
}
<?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);
}

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;
}

$filepaths = array();
if (null !== $currentPath && file_exists($file = $currentPath.DIRECTORY_SEPARATOR.$name)) {
if (true === $first) {
return $file;
}
$filepaths[] = $file;
}

foreach ($this->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%s).', $name, null !== $currentPath ? $currentPath.', ' : '', implode(', ', $this->paths)));
}

return array_values(array_unique($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 FileLoader && null !== $this->currentDir) {

 
 
 $locator = $loader->getLocator() ?: $this->locator;
$resource = $locator->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;

$ret = $loader->load($resource, $type);

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 ResourceInterface, \Serializable
{
private $resource;
private $pattern;







public function __construct($resource, $pattern = null)
{
$this->resource = $resource;
$this->pattern = $pattern;
}




public function __toString()
{
return (string) $this->resource;
}




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 FileResource implements ResourceInterface, \Serializable
{



private $resource;






public function __construct($resource)
{
$this->resource = realpath($resource);
}




public function __toString()
{
return (string) $this->resource;
}




public function getResource()
{
return $this->resource;
}




public function isFresh($timestamp)
{
if (false === $this->resource || !file_exists($this->resource)) {
return false;
}

return 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();








public function isFresh($timestamp);






public function getResource();
}
<?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 = intval($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('/^(-|\+)?[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\Console;

use Symfony\Component\Console\Descriptor\TextDescriptor;
use Symfony\Component\Console\Descriptor\XmlDescriptor;
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\BufferedOutput;
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\Helper\DialogHelper;
use Symfony\Component\Console\Helper\ProgressHelper;
use Symfony\Component\Console\Helper\TableHelper;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
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'))) {
$output->writeln($this->getLongVersion());

return 0;
}

$name = $this->getCommandName($input);
if (true === $input->hasParameterOption(array('--help', '-h'))) {
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 setCatchExceptions($boolean)
{
$this->catchExceptions = (bool) $boolean;
}








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() && 'UNKNOWN' !== $this->getVersion()) {
return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
}

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 \InvalidArgumentException(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->commands 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, array())) {
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 \InvalidArgumentException($message);
}

$exact = in_array($namespace, $namespaces, true);
if (count($namespaces) > 1 && !$exact) {
throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(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, array())) {
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 \InvalidArgumentException($message);
}


 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 \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
}

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 asText($namespace = null, $raw = false)
{
$descriptor = new TextDescriptor();
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, !$raw);
$descriptor->describe($output, $this, array('namespace' => $namespace, 'raw_output' => true));

return $output->fetch();
}











public function asXml($namespace = null, $asDom = false)
{
$descriptor = new XmlDescriptor();

if ($asDom) {
return $descriptor->getApplicationDocument($this, $namespace);
}

$output = new BufferedOutput();
$descriptor->describe($output, $this, array('namespace' => $namespace));

return $output->fetch();
}







public function renderException($e, $output)
{
do {
$title = sprintf('  [%s]  ', get_class($e));

$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[] = '';
$messages[] = '';

$output->writeln($messages, OutputInterface::OUTPUT_RAW);

if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$output->writeln('<comment>Exception trace:</comment>');


 $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));
}

$output->writeln("");
$output->writeln("");
}
} while ($e = $e->getPrevious());

if (null !== $this->runningCommand) {
$output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
$output->writeln("");
$output->writeln("");
}
}






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'))) {
$output->setDecorated(true);
} elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
$output->setDecorated(false);
}

if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
$input->setInteractive(false);
} elseif (function_exists('posix_isatty') && $this->getHelperSet()->has('question')) {
$inputStream = $this->getHelperSet()->get('question')->getInputStream();
if (!@posix_isatty($inputStream)) {
$input->setInteractive(false);
}
}

if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
} else {
if ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') || $input->getParameterOption('--verbose') === 3) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
} elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') || $input->getParameterOption('--verbose') === 2) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
} elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') || $input->hasParameterOption('--verbose') || $input->getParameterOption('--verbose')) {
$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);
}

$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 ConsoleTerminateEvent($command, $input, $output, $e->getCode());
$this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);

$event = new ConsoleExceptionEvent($command, $input, $output, $e, $event->getExitCode());
$this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);

throw $event->getException();
}
} 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 DialogHelper(),
new ProgressHelper(),
new TableHelper(),
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 (!function_exists('mb_strwidth')) {
return strlen($string);
}

if (false === $encoding = mb_detect_encoding($string)) {
return strlen($string);
}

return mb_strwidth($string, $encoding);
}

private function splitStringByWidth($string, $width)
{

 
 

if (!function_exists('mb_strwidth')) {
return str_split($string, $width);
}

if (false === $encoding = mb_detect_encoding($string)) {
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 (strlen($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\Descriptor\TextDescriptor;
use Symfony\Component\Console\Descriptor\XmlDescriptor;
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\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;








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;
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();


 $this->mergeApplicationDefinition();


 try {
$input->bind($this->definition);
} catch (\Exception $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);
}

$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($code)
{
if (!is_callable($code)) {
throw new \InvalidArgumentException('Invalid callable provided to Command::setCode.');
}

$this->code = $code;

return $this;
}








public function mergeApplicationDefinition($mergeArgs = true)
{
if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
return;
}

if ($mergeArgs) {
$currentArguments = $this->definition->getArguments();
$this->definition->setArguments($this->application->getDefinition()->getArguments());
$this->definition->addArguments($currentArguments);
}

$this->definition->addOptions($this->application->getDefinition()->getOptions());

$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());
}












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()
{
if (null === $this->synopsis) {
$this->synopsis = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis()));
}

return $this->synopsis;
}












public function getHelper($name)
{
return $this->helperSet->get($name);
}








public function asText()
{
$descriptor = new TextDescriptor();
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
$descriptor->describe($output, $this, array('raw_output' => true));

return $output->fetch();
}










public function asXml($asDom = false)
{
$descriptor = new XmlDescriptor();

if ($asDom) {
return $descriptor->getCommandDocument($this);
}

$output = new BufferedOutput();
$descriptor->describe($output, $this);

return $output->fetch();
}










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('xml', null, InputOption::VALUE_NONE, 'To output help as XML'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'To output help in other formats', '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'));
}

if ($input->getOption('xml')) {
$input->setOption('format', 'xml');
}

$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)
{
if ($input->getOption('xml')) {
$input->setOption('format', 'xml');
}

$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('xml', null, InputOption::VALUE_NONE, 'To output list as XML'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'To output list in other formats', '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;






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 \InvalidArgumentException(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();
foreach ($commands as $name => $command) {
$key = $this->application->extractNamespace($name, 1);
if (!$key) {
$key = '_global';
}

$namespacedCommands[$key][$name] = $command;
}
ksort($namespacedCommands);

foreach ($namespacedCommands as &$commands) {
ksort($commands);
}

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;






abstract class Descriptor implements DescriptorInterface
{



private $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' => $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' => $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' => $command->getSynopsis(),
'description' => $command->getDescription(),
'help' => $command->getProcessedHelp(),
'aliases' => $command->getAliases(),
'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: '.($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: '.($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: `'.$command->getSynopsis().'`'."\n"
.'* Aliases: '.(count($command->getAliases()) ? '`'.implode('`, `', $command->getAliases()).'`' : '<none>')
);

if ($help = $command->getProcessedHelp()) {
$this->write("\n\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 = '';
}

$nameWidth = isset($options['name_width']) ? $options['name_width'] : strlen($argument->getName());

$this->writeText(sprintf(" <info>%-${nameWidth}s</info> %s%s",
$argument->getName(),
str_replace("\n", "\n".str_repeat(' ', $nameWidth + 2), $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 = '';
}

$nameWidth = isset($options['name_width']) ? $options['name_width'] : strlen($option->getName());
$nameWithShortcutWidth = $nameWidth - strlen($option->getName()) - 2;

$this->writeText(sprintf(" <info>%s</info> %-${nameWithShortcutWidth}s%s%s%s",
'--'.$option->getName(),
$option->getShortcut() ? sprintf('(-%s) ', $option->getShortcut()) : '',
str_replace("\n", "\n".str_repeat(' ', $nameWidth + 2), $option->getDescription()),
$default,
$option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
), $options);
}




protected function describeInputDefinition(InputDefinition $definition, array $options = array())
{
$nameWidth = 0;
foreach ($definition->getOptions() as $option) {
$nameLength = strlen($option->getName()) + 2;
if ($option->getShortcut()) {
$nameLength += strlen($option->getShortcut()) + 3;
}
$nameWidth = max($nameWidth, $nameLength);
}
foreach ($definition->getArguments() as $argument) {
$nameWidth = max($nameWidth, strlen($argument->getName()));
}
++$nameWidth;

if ($definition->getArguments()) {
$this->writeText('<comment>Arguments:</comment>', $options);
$this->writeText("\n");
foreach ($definition->getArguments() as $argument) {
$this->describeInputArgument($argument, array_merge($options, array('name_width' => $nameWidth)));
$this->writeText("\n");
}
}

if ($definition->getArguments() && $definition->getOptions()) {
$this->writeText("\n");
}

if ($definition->getOptions()) {
$this->writeText('<comment>Options:</comment>', $options);
$this->writeText("\n");
foreach ($definition->getOptions() as $option) {
$this->describeInputOption($option, array_merge($options, array('name_width' => $nameWidth)));
$this->writeText("\n");
}
}
}




protected function describeCommand(Command $command, array $options = array())
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);

$this->writeText('<comment>Usage:</comment>', $options);
$this->writeText("\n");
$this->writeText(' '.$command->getSynopsis(), $options);
$this->writeText("\n");

if (count($command->getAliases()) > 0) {
$this->writeText("\n");
$this->writeText('<comment>Aliases:</comment> <info>'.implode(', ', $command->getAliases()).'</info>', $options);
}

if ($definition = $command->getNativeDefinition()) {
$this->writeText("\n");
$this->describeInputDefinition($definition, $options);
}

$this->writeText("\n");

if ($help = $command->getProcessedHelp()) {
$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->writeText('<comment>Options:</comment>', $options);

$inputOptions = $application->getDefinition()->getOptions();

$width = 0;
foreach ($inputOptions as $option) {
$nameLength = strlen($option->getName()) + 2;
if ($option->getShortcut()) {
$nameLength += strlen($option->getShortcut()) + 3;
}
$width = max($width, $nameLength);
}
++$width;

foreach ($inputOptions as $option) {
$this->writeText("\n", $options);
$this->describeInputOption($option, array_merge($options, array('name_width' => $width)));
}

$this->writeText("\n\n", $options);

$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");
$this->writeText(sprintf(" <info>%-${width}s</info> %s", $name, $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)
{
if (PHP_VERSION_ID < 50400) {
return str_replace('\/', '/', json_encode($default));
}

return json_encode($default, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}






private function getColumnWidth(array $commands)
{
$width = 0;
foreach ($commands as $command) {
$width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
}

return $width + 2;
}
}
<?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($usageXML = $dom->createElement('usage'));
$usageXML->appendChild($dom->createTextNode(sprintf($command->getSynopsis(), '')));

$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())));

$commandXML->appendChild($aliasesXML = $dom->createElement('aliases'));
foreach ($command->getAliases() as $alias) {
$aliasesXML->appendChild($aliasXML = $dom->createElement('alias'));
$aliasXML->appendChild($dom->createTextNode($alias));
}

$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\Formatter;








class OutputFormatter implements OutputFormatterInterface
{
private $decorated;
private $styles = array();
private $styleStack;








public static function escape($text)
{
return preg_replace('/([^\\\\]?)</is', '$1\\<', $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)
{
$offset = 0;
$output = '';
$tagRegex = '[a-z][a-z0-9_=;-]*';
preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#isx", $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));

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;








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),
);
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),
);
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;




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');
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;






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\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;









class DialogHelper extends InputAwareHelper
{
private $inputStream;
private static $shell;
private static $stty;
















public function select(OutputInterface $output, $question, $choices, $default = null, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
{
$width = max(array_map('strlen', array_keys($choices)));

$messages = (array) $question;
foreach ($choices as $key => $value) {
$messages[] = sprintf("  [<info>%-${width}s</info>] %s", $key, $value);
}

$output->writeln($messages);

$result = $this->askAndValidate($output, '> ', function ($picked) use ($choices, $errorMessage, $multiselect) {

 $selectedChoices = str_replace(" ", "", $picked);

if ($multiselect) {

 if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
throw new \InvalidArgumentException(sprintf($errorMessage, $picked));
}
$selectedChoices = explode(",", $selectedChoices);
} else {
$selectedChoices = array($picked);
}

$multiselectChoices = array();

foreach ($selectedChoices as $value) {
if (empty($choices[$value])) {
throw new \InvalidArgumentException(sprintf($errorMessage, $value));
}
array_push($multiselectChoices, $value);
}

if ($multiselect) {
return $multiselectChoices;
}

return $picked;
}, $attempts, $default);

return $result;
}













public function ask(OutputInterface $output, $question, $default = null, array $autocomplete = null)
{
if ($this->input && !$this->input->isInteractive()) {
return $default;
}

$output->write($question);

$inputStream = $this->inputStream ?: STDIN;

if (null === $autocomplete || !$this->hasSttyAvailable()) {
$ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new \RuntimeException('Aborted');
}
$ret = trim($ret);
} else {
$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 strlen($ret) > 0 ? $ret : $default;
}












public function askConfirmation(OutputInterface $output, $question, $default = true)
{
$answer = 'z';
while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
$answer = $this->ask($output, $question);
}

if (false === $default) {
return $answer && 'y' == strtolower($answer[0]);
}

return !$answer || 'y' == strtolower($answer[0]);
}












public function askHiddenResponse(OutputInterface $output, $question, $fallback = true)
{
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;
}

$output->write($question);
$value = rtrim(shell_exec($exe));
$output->writeln('');

if (isset($tmpExe)) {
unlink($tmpExe);
}

return $value;
}

if ($this->hasSttyAvailable()) {
$output->write($question);

$sttyMode = shell_exec('stty -g');

shell_exec('stty -echo');
$value = fgets($this->inputStream ?: STDIN, 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()) {
$output->write($question);
$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;
}

if ($fallback) {
return $this->ask($output, $question);
}

throw new \RuntimeException('Unable to hide the response');
}



















public function askAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $default = null, array $autocomplete = null)
{
$that = $this;

$interviewer = function () use ($output, $question, $default, $autocomplete, $that) {
return $that->ask($output, $question, $default, $autocomplete);
};

return $this->validateAttempts($interviewer, $output, $validator, $attempts);
}



















public function askHiddenResponseAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $fallback = true)
{
$that = $this;

$interviewer = function () use ($output, $question, $fallback, $that) {
return $that->askHiddenResponse($output, $question, $fallback);
};

return $this->validateAttempts($interviewer, $output, $validator, $attempts);
}








public function setInputStream($stream)
{
$this->inputStream = $stream;
}






public function getInputStream()
{
return $this->inputStream;
}




public function getName()
{
return 'dialog';
}






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;
}













private function validateAttempts($interviewer, OutputInterface $output, $validator, $attempts)
{
$error = null;
while (false === $attempts || $attempts--) {
if (null !== $error) {
$output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'));
}

try {
return call_user_func($validator, $interviewer());
} catch (\Exception $error) {
}
}

throw $error;
}
}
<?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 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 (!function_exists('mb_strwidth')) {
return strlen($string);
}

if (false === $encoding = mb_detect_encoding($string)) {
return strlen($string);
}

return mb_strwidth($string, $encoding);
}

public static function formatTime($secs)
{
static $timeFormats = array(
array(0, '< 1 sec'),
array(2, '1 sec'),
array(59, 'secs', 1),
array(60, '1 min'),
array(3600, 'mins', 60),
array(5400, '1 hr'),
array(86400, 'hrs', 3600),
array(129600, '1 day'),
array(604800, 'days', 86400),
);

foreach ($timeFormats as $format) {
if ($secs >= $format[0]) {
continue;
}

if (2 == count($format)) {
return $format[1];
}

return ceil($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;






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\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, $callback = null, $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE)
{
$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, $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, $callback = null)
{
$formatter = $this->getHelperSet()->get('debug_formatter');

$that = $this;

return function ($type, $buffer) use ($output, $process, $callback, $formatter, $that) {
$output->write($formatter->progress(spl_object_hash($process), $that->escapeString($buffer), Process::ERR === $type));

if (null !== $callback) {
call_user_func($callback, $type, $buffer);
}
};
}






public function escapeString($str)
{
return str_replace('<', '\\<', $str);
}




public function getName()
{
return 'process';
}
}
<?php










namespace Symfony\Component\Console\Helper;

use Symfony\Component\Console\Output\OutputInterface;







class ProgressBar
{

 private $barWidth = 28;
private $barChar;
private $emptyBarChar = '-';
private $progressChar = '>';
private $format = null;
private $redrawFreq = 1;




private $output;
private $step = 0;
private $max;
private $startTime;
private $stepWidth;
private $percent = 0.0;
private $lastMessagesLength = 0;
private $formatLineCount;
private $messages;
private $overwrite = true;

private static $formatters;
private static $formats;







public function __construct(OutputInterface $output, $max = 0)
{
$this->output = $output;
$this->setMaxSteps($max);

if (!$this->output->isDecorated()) {

 $this->overwrite = false;

if ($this->max > 10) {

 $this->setRedrawFrequency($max / 10);
}
}

$this->setFormat($this->determineBestFormat());

$this->startTime = time();
}









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;
}









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 getStep()
{
return $this->getProgress();
}






public function getProgress()
{
return $this->step;
}








public 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)
{

 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");
}






public function setRedrawFrequency($freq)
{
$this->redrawFreq = (int) $freq;
}






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 setCurrent($step)
{
$this->setProgress($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 = intval($this->step / $this->redrawFreq);
$currPeriod = intval($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;
}


 $self = $this;
$output = $this->output;
$messages = $this->messages;
$this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) use ($self, $output, $messages) {
if ($formatter = $self::getPlaceholderFormatterDefinition($matches[1])) {
$text = call_user_func($formatter, $self, $output);
} elseif (isset($messages[$matches[1]])) {
$text = $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;
}

$this->overwrite(str_repeat("\n", $this->formatLineCount));
}






private function setMaxSteps($max)
{
$this->max = max(0, (int) $max);
$this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
}






private function overwrite($message)
{
$lines = explode("\n", $message);


 if (null !== $this->lastMessagesLength) {
foreach ($lines as $i => $line) {
if ($this->lastMessagesLength > Helper::strlenWithoutDecoration($this->output->getFormatter(), $line)) {
$lines[$i] = str_pad($line, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
}
}
}

if ($this->overwrite) {

 $this->output->write("\x0D");
} elseif ($this->step > 0) {

 $this->output->writeln('');
}

if ($this->formatLineCount) {
$this->output->write(sprintf("\033[%dA", $this->formatLineCount));
}
$this->output->write(implode("\n", $lines));

$this->lastMessagesLength = 0;
foreach ($lines as $line) {
$len = Helper::strlenWithoutDecoration($this->output->getFormatter(), $line);
if ($len > $this->lastMessagesLength) {
$this->lastMessagesLength = $len;
}
}
}

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\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;









class ProgressHelper extends Helper
{
const FORMAT_QUIET = ' %percent%%';
const FORMAT_NORMAL = ' %current%/%max% [%bar%] %percent%%';
const FORMAT_VERBOSE = ' %current%/%max% [%bar%] %percent%% Elapsed: %elapsed%';
const FORMAT_QUIET_NOMAX = ' %current%';
const FORMAT_NORMAL_NOMAX = ' %current% [%bar%]';
const FORMAT_VERBOSE_NOMAX = ' %current% [%bar%] Elapsed: %elapsed%';


 private $barWidth = 28;
private $barChar = '=';
private $emptyBarChar = '-';
private $progressChar = '>';
private $format = null;
private $redrawFreq = 1;

private $lastMessagesLength;
private $barCharOriginal;




private $output;






private $current;






private $max;






private $startTime;






private $defaultFormatVars = array(
'current',
'max',
'bar',
'percent',
'elapsed',
);






private $formatVars;






private $widths = array(
'current' => 4,
'max' => 4,
'percent' => 3,
'elapsed' => 6,
);






private $timeFormats = array(
array(0, '???'),
array(2, '1 sec'),
array(59, 'secs', 1),
array(60, '1 min'),
array(3600, 'mins', 60),
array(5400, '1 hr'),
array(86400, 'hrs', 3600),
array(129600, '1 day'),
array(604800, 'days', 86400),
);






public function setBarWidth($size)
{
$this->barWidth = (int) $size;
}






public function setBarCharacter($char)
{
$this->barChar = $char;
}






public function setEmptyBarCharacter($char)
{
$this->emptyBarChar = $char;
}






public function setProgressCharacter($char)
{
$this->progressChar = $char;
}






public function setFormat($format)
{
$this->format = $format;
}






public function setRedrawFrequency($freq)
{
$this->redrawFreq = (int) $freq;
}







public function start(OutputInterface $output, $max = null)
{
$this->startTime = time();
$this->current = 0;
$this->max = (int) $max;


 $this->output = $output->isDecorated() ? $output : new NullOutput();
$this->lastMessagesLength = 0;
$this->barCharOriginal = '';

if (null === $this->format) {
switch ($output->getVerbosity()) {
case OutputInterface::VERBOSITY_QUIET:
$this->format = self::FORMAT_QUIET_NOMAX;
if ($this->max > 0) {
$this->format = self::FORMAT_QUIET;
}
break;
case OutputInterface::VERBOSITY_VERBOSE:
case OutputInterface::VERBOSITY_VERY_VERBOSE:
case OutputInterface::VERBOSITY_DEBUG:
$this->format = self::FORMAT_VERBOSE_NOMAX;
if ($this->max > 0) {
$this->format = self::FORMAT_VERBOSE;
}
break;
default:
$this->format = self::FORMAT_NORMAL_NOMAX;
if ($this->max > 0) {
$this->format = self::FORMAT_NORMAL;
}
break;
}
}

$this->initialize();
}









public function advance($step = 1, $redraw = false)
{
$this->setCurrent($this->current + $step, $redraw);
}









public function setCurrent($current, $redraw = false)
{
if (null === $this->startTime) {
throw new \LogicException('You must start the progress bar before calling setCurrent().');
}

$current = (int) $current;

if ($current < $this->current) {
throw new \LogicException('You can\'t regress the progress bar');
}

if (0 === $this->current) {
$redraw = true;
}

$prevPeriod = (int) ($this->current / $this->redrawFreq);

$this->current = $current;

$currPeriod = (int) ($this->current / $this->redrawFreq);
if ($redraw || $prevPeriod !== $currPeriod || $this->max === $this->current) {
$this->display();
}
}








public function display($finish = false)
{
if (null === $this->startTime) {
throw new \LogicException('You must start the progress bar before calling display().');
}

$message = $this->format;
foreach ($this->generate($finish) as $name => $value) {
$message = str_replace("%{$name}%", $value, $message);
}
$this->overwrite($this->output, $message);
}








public function clear()
{
$this->overwrite($this->output, '');
}




public function finish()
{
if (null === $this->startTime) {
throw new \LogicException('You must start the progress bar before calling finish().');
}

if (null !== $this->startTime) {
if (!$this->max) {
$this->barChar = $this->barCharOriginal;
$this->display(true);
}
$this->startTime = null;
$this->output->writeln('');
$this->output = null;
}
}




private function initialize()
{
$this->formatVars = array();
foreach ($this->defaultFormatVars as $var) {
if (false !== strpos($this->format, "%{$var}%")) {
$this->formatVars[$var] = true;
}
}

if ($this->max > 0) {
$this->widths['max'] = $this->strlen($this->max);
$this->widths['current'] = $this->widths['max'];
} else {
$this->barCharOriginal = $this->barChar;
$this->barChar = $this->emptyBarChar;
}
}








private function generate($finish = false)
{
$vars = array();
$percent = 0;
if ($this->max > 0) {
$percent = (float) $this->current / $this->max;
}

if (isset($this->formatVars['bar'])) {
$completeBars = 0;

if ($this->max > 0) {
$completeBars = floor($percent * $this->barWidth);
} else {
if (!$finish) {
$completeBars = floor($this->current % $this->barWidth);
} else {
$completeBars = $this->barWidth;
}
}

$emptyBars = $this->barWidth - $completeBars - $this->strlen($this->progressChar);
$bar = str_repeat($this->barChar, $completeBars);
if ($completeBars < $this->barWidth) {
$bar .= $this->progressChar;
$bar .= str_repeat($this->emptyBarChar, $emptyBars);
}

$vars['bar'] = $bar;
}

if (isset($this->formatVars['elapsed'])) {
$elapsed = time() - $this->startTime;
$vars['elapsed'] = str_pad($this->humaneTime($elapsed), $this->widths['elapsed'], ' ', STR_PAD_LEFT);
}

if (isset($this->formatVars['current'])) {
$vars['current'] = str_pad($this->current, $this->widths['current'], ' ', STR_PAD_LEFT);
}

if (isset($this->formatVars['max'])) {
$vars['max'] = $this->max;
}

if (isset($this->formatVars['percent'])) {
$vars['percent'] = str_pad(floor($percent * 100), $this->widths['percent'], ' ', STR_PAD_LEFT);
}

return $vars;
}








private function humaneTime($secs)
{
$text = '';
foreach ($this->timeFormats as $format) {
if ($secs < $format[0]) {
if (count($format) == 2) {
$text = $format[1];
break;
} else {
$text = ceil($secs / $format[2]).' '.$format[1];
break;
}
}
}

return $text;
}







private function overwrite(OutputInterface $output, $message)
{
$length = $this->strlen($message);


 if (null !== $this->lastMessagesLength && $this->lastMessagesLength > $length) {
$message = str_pad($message, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
}


 $output->write("\x0D");
$output->write($message);

$this->lastMessagesLength = $this->strlen($message);
}




public function getName()
{
return 'progress';
}
}
<?php










namespace Symfony\Component\Console\Helper;

use Symfony\Component\Console\Input\InputInterface;
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 (!$input->isInteractive()) {
return $question->getDefault();
}

if (!$question->getValidator()) {
return $this->doAsk($output, $question);
}

$that = $this;

$interviewer = function () use ($output, $question, $that) {
return $that->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';
}














public function doAsk(OutputInterface $output, Question $question)
{
$inputStream = $this->inputStream ?: STDIN;

$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$width = max(array_map('strlen', array_keys($question->getChoices())));

$messages = (array) $question->getQuestion();
foreach ($question->getChoices() as $key => $value) {
$messages[] = sprintf("  [<info>%-${width}s</info>] %s", $key, $value);
}

$output->writeln($messages);

$message = $question->getPrompt();
}

$output->write($message);

$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;
}









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($interviewer, OutputInterface $output, Question $question)
{
$error = null;
$attempts = $question->getMaxAttempts();
while (null === $attempts || $attempts--) {
if (null !== $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);
}

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\Output\OutputInterface;







class Table
{





private $headers = array();






private $rows = array();






private $columnWidths = array();






private $numberOfColumns;




private $output;




private $style;

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 (!self::$styles[$name]) {
throw new \InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}

return self::$styles[$name];
}








public function setStyle($name)
{
if ($name instanceof TableStyle) {
$this->style = $name;
} elseif (isset(self::$styles[$name])) {
$this->style = self::$styles[$name];
} else {
throw new \InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}

return $this;
}






public function getStyle()
{
return $this->style;
}

public function setHeaders(array $headers)
{
$this->headers = array_values($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;
}

if (!is_array($row)) {
throw new \InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}

$this->rows[] = array_values($row);

end($this->rows);
$rowKey = key($this->rows);
reset($this->rows);

foreach ($row as $key => $cellValue) {
if (!strstr($cellValue, "\n")) {
continue;
}

$lines = explode("\n", $cellValue);
$this->rows[$rowKey][$key] = $lines[0];
unset($lines[0]);

foreach ($lines as $lineKey => $line) {
$nextRowKey = $rowKey + $lineKey + 1;

if (isset($this->rows[$nextRowKey])) {
$this->rows[$nextRowKey][$key] = $line;
} else {
$this->rows[$nextRowKey] = array($key => $line);
}
}
}

return $this;
}

public function setRow($column, array $row)
{
$this->rows[$column] = $row;

return $this;
}













public function render()
{
$this->renderRowSeparator();
$this->renderRow($this->headers, $this->style->getCellHeaderFormat());
if (!empty($this->headers)) {
$this->renderRowSeparator();
}
foreach ($this->rows as $row) {
if ($row instanceof TableSeparator) {
$this->renderRowSeparator();
} else {
$this->renderRow($row, $this->style->getCellRowFormat());
}
}
if (!empty($this->rows)) {
$this->renderRowSeparator();
}

$this->cleanup();
}






private function renderRowSeparator()
{
if (0 === $count = $this->getNumberOfColumns()) {
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->getColumnWidth($column)).$this->style->getCrossingChar();
}

$this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
}




private function renderColumnSeparator()
{
$this->output->write(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
}









private function renderRow(array $row, $cellFormat)
{
if (empty($row)) {
return;
}

$this->renderColumnSeparator();
for ($column = 0, $count = $this->getNumberOfColumns(); $column < $count; $column++) {
$this->renderCell($row, $column, $cellFormat);
$this->renderColumnSeparator();
}
$this->output->writeln('');
}








private function renderCell(array $row, $column, $cellFormat)
{
$cell = isset($row[$column]) ? $row[$column] : '';
$width = $this->getColumnWidth($column);


 if (function_exists('mb_strwidth') && false !== $encoding = mb_detect_encoding($cell)) {
$width += strlen($cell) - mb_strwidth($cell, $encoding);
}

$width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);

$content = sprintf($this->style->getCellRowContentFormat(), $cell);

$this->output->write(sprintf($cellFormat, str_pad($content, $width, $this->style->getPaddingChar(), $this->style->getPadType())));
}






private function getNumberOfColumns()
{
if (null !== $this->numberOfColumns) {
return $this->numberOfColumns;
}

$columns = array(count($this->headers));
foreach ($this->rows as $row) {
$columns[] = count($row);
}

return $this->numberOfColumns = max($columns);
}








private function getColumnWidth($column)
{
if (isset($this->columnWidths[$column])) {
return $this->columnWidths[$column];
}

$lengths = array($this->getCellWidth($this->headers, $column));
foreach ($this->rows as $row) {
if ($row instanceof TableSeparator) {
continue;
}

$lengths[] = $this->getCellWidth($row, $column);
}

return $this->columnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
}









private function getCellWidth(array $row, $column)
{
return isset($row[$column]) ? Helper::strlenWithoutDecoration($this->output->getFormatter(), $row[$column]) : 0;
}




private function cleanup()
{
$this->columnWidths = array();
$this->numberOfColumns = null;
}

private static function initStyles()
{
$borderless = new TableStyle();
$borderless
->setHorizontalBorderChar('=')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
;

$compact = new TableStyle();
$compact
->setHorizontalBorderChar('')
->setVerticalBorderChar(' ')
->setCrossingChar('')
->setCellRowContentFormat('%s')
;

return array(
'default' => new TableStyle(),
'borderless' => $borderless,
'compact' => $compact,
);
}
}
<?php










namespace Symfony\Component\Console\Helper;

use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\NullOutput;









class TableHelper extends Helper
{
const LAYOUT_DEFAULT = 0;
const LAYOUT_BORDERLESS = 1;
const LAYOUT_COMPACT = 2;




private $table;

public function __construct()
{
$this->table = new Table(new NullOutput());
}










public function setLayout($layout)
{
switch ($layout) {
case self::LAYOUT_BORDERLESS:
$this->table->setStyle('borderless');
break;

case self::LAYOUT_COMPACT:
$this->table->setStyle('compact');
break;

case self::LAYOUT_DEFAULT:
$this->table->setStyle('default');
break;

default:
throw new \InvalidArgumentException(sprintf('Invalid table layout "%s".', $layout));
};

return $this;
}

public function setHeaders(array $headers)
{
$this->table->setHeaders($headers);

return $this;
}

public function setRows(array $rows)
{
$this->table->setRows($rows);

return $this;
}

public function addRows(array $rows)
{
$this->table->addRows($rows);

return $this;
}

public function addRow(array $row)
{
$this->table->addRow($row);

return $this;
}

public function setRow($column, array $row)
{
$this->table->setRow($column, $row);

return $this;
}








public function setPaddingChar($paddingChar)
{
$this->table->getStyle()->setPaddingChar($paddingChar);

return $this;
}








public function setHorizontalBorderChar($horizontalBorderChar)
{
$this->table->getStyle()->setHorizontalBorderChar($horizontalBorderChar);

return $this;
}








public function setVerticalBorderChar($verticalBorderChar)
{
$this->table->getStyle()->setVerticalBorderChar($verticalBorderChar);

return $this;
}








public function setCrossingChar($crossingChar)
{
$this->table->getStyle()->setCrossingChar($crossingChar);

return $this;
}








public function setCellHeaderFormat($cellHeaderFormat)
{
$this->table->getStyle()->setCellHeaderFormat($cellHeaderFormat);

return $this;
}








public function setCellRowFormat($cellRowFormat)
{
$this->table->getStyle()->setCellHeaderFormat($cellRowFormat);

return $this;
}








public function setCellRowContentFormat($cellRowContentFormat)
{
$this->table->getStyle()->setCellRowContentFormat($cellRowContentFormat);

return $this;
}








public function setBorderFormat($borderFormat)
{
$this->table->getStyle()->setBorderFormat($borderFormat);

return $this;
}








public function setPadType($padType)
{
$this->table->getStyle()->setPadType($padType);

return $this;
}















public function render(OutputInterface $output)
{
$p = new \ReflectionProperty($this->table, 'output');
$p->setAccessible(true);
$p->setValue($this->table, $output);

$this->table->render();
}




public function getName()
{
return 'table';
}
}
<?php










namespace Symfony\Component\Console\Helper;






class TableSeparator
{
}
<?php










namespace Symfony\Component\Console\Helper;







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)
{
$this->padType = $padType;

return $this;
}






public function getPadType()
{
return $this->padType;
}
}
<?php










namespace Symfony\Component\Console\Input;




























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 {
throw new \RuntimeException('Too many arguments.');
}
}









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 (false === $value) {
$value = null;
}

if (null !== $value && !$option->acceptValue()) {
throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name, $value));
}

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)
{
$values = (array) $values;

foreach ($this->tokens as $token) {
foreach ($values as $value) {
if ($token === $value || 0 === strpos($token, $value.'=')) {
return true;
}
}
}

return false;
}












public function getParameterOption($values, $default = false)
{
$values = (array) $values;
$tokens = $this->tokens;

while (0 < count($tokens)) {
$token = array_shift($tokens);

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()
{
$self = $this;
$tokens = array_map(function ($token) use ($self) {
if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
return $match[1].$self->escapeToken($match[2]);
}

if ($token && $token[0] !== '-') {
return $self->escapeToken($token);
}

return $token;
}, $this->tokens);

return implode(' ', $tokens);
}
}
<?php










namespace Symfony\Component\Console\Input;












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)
{
$values = (array) $values;

foreach ($this->parameters as $k => $v) {
if (!is_int($k)) {
$v = $k;
}

if (in_array($v, $values)) {
return true;
}
}

return false;
}












public function getParameterOption($values, $default = false)
{
$values = (array) $values;

foreach ($this->parameters as $k => $v) {
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 (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 \InvalidArgumentException(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 \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
}

$option = $this->definition->getOption($name);

if (null === $value) {
if ($option->isValueRequired()) {
throw new \InvalidArgumentException(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;












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()
{
if (count($this->arguments) < $this->definition->getArgumentRequiredCount()) {
throw new \RuntimeException('Not enough arguments.');
}
}






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;








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\Descriptor\TextDescriptor;
use Symfony\Component\Console\Descriptor\XmlDescriptor;
use Symfony\Component\Console\Output\BufferedOutput;















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()
{
$elements = array();
foreach ($this->getOptions() as $option) {
$shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
$elements[] = sprintf('['.($option->isValueRequired() ? '%s--%s="..."' : ($option->isValueOptional() ? '%s--%s[="..."]' : '%s--%s')).']', $shortcut, $option->getName());
}

foreach ($this->getArguments() as $argument) {
$elements[] = sprintf($argument->isRequired() ? '%s' : '[%s]', $argument->getName().($argument->isArray() ? '1' : ''));

if ($argument->isArray()) {
$elements[] = sprintf('... [%sN]', $argument->getName());
}
}

return implode(' ', $elements);
}








public function asText()
{
$descriptor = new TextDescriptor();
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
$descriptor->describe($output, $this, array('raw_output' => true));

return $output->fetch();
}










public function asXml($asDom = false)
{
$descriptor = new XmlDescriptor();

if ($asDom) {
return $descriptor->getInputDefinitionDocument($this);
}

$output = new BufferedOutput();
$descriptor->describe($output, $this);

return $output->fetch();
}
}
<?php










namespace Symfony\Component\Console\Input;






interface InputInterface
{





public function getFirstArgument();











public function hasParameterOption($values);












public function getParameterOption($values, $default = 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;








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;












class StringInput extends ArgvInput
{
const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';











public function __construct($input, InputDefinition $definition = null)
{
parent::__construct(array(), null);

$this->setTokens($this->tokenize($input));

if (null !== $definition) {
$this->bind($definition);
}
}










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)
{
$outputStream = 'php://stdout';
if (!$this->hasStdoutSupport()) {
$outputStream = 'php://output';
}

parent::__construct(fopen($outputStream, 'w'), $verbosity, $decorated, $formatter);

$this->stderr = new StreamOutput(fopen('php://stderr', 'w'), $verbosity, $decorated, $this->getFormatter());
}




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 ('OS400' != php_uname('s'));
}
}
<?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, $type = self::OUTPUT_NORMAL)
{

 }




public function write($messages, $newline = false, $type = 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, $type = self::OUTPUT_NORMAL)
{
$this->write($messages, true, $type);
}




public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
if (self::VERBOSITY_QUIET === $this->verbosity) {
return;
}

$messages = (array) $messages;

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;
default:
throw new \InvalidArgumentException(sprintf('Unknown output type given (%s)', $type));
}

$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 = 0;
const VERBOSITY_NORMAL = 1;
const VERBOSITY_VERBOSE = 2;
const VERBOSITY_VERY_VERBOSE = 3;
const VERBOSITY_DEBUG = 4;

const OUTPUT_NORMAL = 0;
const OUTPUT_RAW = 1;
const OUTPUT_PLAIN = 2;












public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL);











public function writeln($messages, $type = self::OUTPUT_NORMAL);








public function setVerbosity($level);








public function getVerbosity();








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\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 ? PHP_EOL : ''))) {

 throw new \RuntimeException('Unable to write output.');
}

fflush($this->stream);
}











protected function hasColorSupport()
{
if (DIRECTORY_SEPARATOR == '\\') {
return false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI');
}

return function_exists('posix_isatty') && @posix_isatty($this->stream);
}
}
<?php










namespace Symfony\Component\Console\Question;






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(array_keys($choices));
}






public function getChoices()
{
return $this->choices;
}










public function setMultiselect($multiselect)
{
$this->multiselect = $multiselect;
$this->setValidator($this->getDefaultValidator());

return $this;
}






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;

return function ($selected) use ($choices, $errorMessage, $multiselect) {

 $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) {
if (empty($choices[$value])) {
throw new \InvalidArgumentException(sprintf($errorMessage, $value));
}
array_push($multiselectChoices, $choices[$value]);
}

if ($multiselect) {
return $multiselectChoices;
}

return $choices[$selected];
};
}
}
<?php










namespace Symfony\Component\Console\Question;






class ConfirmationQuestion extends Question
{






public function __construct($question, $default = true)
{
parent::__construct($question, (bool) $default);

$this->setNormalizer($this->getDefaultNormalizer());
}






private function getDefaultNormalizer()
{
$default = $this->getDefault();

return function ($answer) use ($default) {
if (is_bool($answer)) {
return $answer;
}

if (false === $default) {
return $answer && 'y' === strtolower($answer[0]);
}

return !$answer || 'y' === strtolower($answer[0]);
};
}
}
<?php










namespace Symfony\Component\Console\Question;






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 (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($validator)
{
$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($normalizer)
{
$this->normalizer = $normalizer;

return $this;
}








public function getNormalizer()
{
return $this->normalizer;
}
}
<?php










namespace Symfony\Component\Console;

use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Process\ProcessBuilder;
use Symfony\Component\Process\PhpExecutableFinder;










class Shell
{
private $application;
private $history;
private $output;
private $hasReadline;
private $processIsolation = false;









public function __construct(Application $application)
{
$this->hasReadline = function_exists('readline');
$this->application = $application;
$this->history = getenv('HOME').'/.history_'.$application->getName();
$this->output = new ConsoleOutput();
}




public function run()
{
$this->application->setAutoExit(false);
$this->application->setCatchExceptions(true);

if ($this->hasReadline) {
readline_read_history($this->history);
readline_completion_function(array($this, 'autocompleter'));
}

$this->output->writeln($this->getHeader());
$php = null;
if ($this->processIsolation) {
$finder = new PhpExecutableFinder();
$php = $finder->find();
$this->output->writeln(<<<EOF
<info>Running with process isolation, you should consider this:</info>
  * each command is executed as separate process,
  * commands don't support interactivity, all params must be passed explicitly,
  * commands output is not colorized.

EOF
);
}

while (true) {
$command = $this->readline();

if (false === $command) {
$this->output->writeln("\n");

break;
}

if ($this->hasReadline) {
readline_add_history($command);
readline_write_history($this->history);
}

if ($this->processIsolation) {
$pb = new ProcessBuilder();

$process = $pb
->add($php)
->add($_SERVER['argv'][0])
->add($command)
->inheritEnvironmentVariables(true)
->getProcess()
;

$output = $this->output;
$process->run(function ($type, $data) use ($output) {
$output->writeln($data);
});

$ret = $process->getExitCode();
} else {
$ret = $this->application->run(new StringInput($command), $this->output);
}

if (0 !== $ret) {
$this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
}
}
}






protected function getHeader()
{
return <<<EOF

Welcome to the <info>{$this->application->getName()}</info> shell (<comment>{$this->application->getVersion()}</comment>).

At the prompt, type <comment>help</comment> for some help,
or <comment>list</comment> to get a list of available commands.

To exit the shell, type <comment>^D</comment>.

EOF;
}






protected function getPrompt()
{

 return $this->output->getFormatter()->format($this->application->getName().' > ');
}

protected function getOutput()
{
return $this->output;
}

protected function getApplication()
{
return $this->application;
}








private function autocompleter($text)
{
$info = readline_info();
$text = substr($info['line_buffer'], 0, $info['end']);

if ($info['point'] !== $info['end']) {
return true;
}


 if (false === strpos($text, ' ') || !$text) {
return array_keys($this->application->all());
}


 try {
$command = $this->application->find(substr($text, 0, strpos($text, ' ')));
} catch (\Exception $e) {
return true;
}

$list = array('--help');
foreach ($command->getDefinition()->getOptions() as $option) {
$list[] = '--'.$option->getName();
}

return $list;
}






private function readline()
{
if ($this->hasReadline) {
$line = readline($this->getPrompt());
} else {
$this->output->write($this->getPrompt());
$line = fgets(STDIN, 1024);
$line = (!$line && strlen($line) == 0) ? false : rtrim($line);
}

return $line;
}

public function getProcessIsolation()
{
return $this->processIsolation;
}

public function setProcessIsolation($processIsolation)
{
$this->processIsolation = (bool) $processIsolation;

if ($this->processIsolation && !class_exists('Symfony\\Component\\Process\\Process')) {
throw new \RuntimeException('Unable to isolate processes as the Symfony Process Component is not installed.');
}
}
}
<?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\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;











class ApplicationTester
{
private $application;
private $input;
private $output;
private $statusCode;






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->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->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 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['command'] = $this->command->getName();
}

$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\Yaml;






class Dumper
{





protected $indentation = 4;






public function setIndentation($num)
{
$this->indentation = (int) $num;
}












public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false)
{
$output = '';
$prefix = $indent ? str_repeat(' ', $indent) : '';

if ($inline <= 0 || !is_array($input) || empty($input)) {
$output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
} else {
$isAHash = array_keys($input) !== range(0, count($input) - 1);

foreach ($input as $key => $value) {
$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);

$output .= sprintf('%s%s%s%s',
$prefix,
$isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-',
$willBeInlined ? ' ' : "\n",
$this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)
).($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) {
if (PHP_VERSION_ID >= 50400) {
$jsonOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
} else {
$jsonOptions = 0;
}
$this->message .= sprintf(' in %s', json_encode($this->parsedFile, $jsonOptions));
}

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, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false, $references = array())
{
self::$exceptionOnInvalidType = $exceptionOnInvalidType;
self::$objectSupport = $objectSupport;
self::$objectForMap = $objectForMap;

$value = trim($value);

if (0 == strlen($value)) {
return '';
}

if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
}

$i = 0;
switch ($value[0]) {
case '[':
$result = self::parseSequence($value, $i, $references);
++$i;
break;
case '{':
$result = self::parseMapping($value, $i, $references);
++$i;
break;
default:
$result = self::parseScalar($value, 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, $exceptionOnInvalidType = false, $objectSupport = false)
{
switch (true) {
case is_resource($value):
if ($exceptionOnInvalidType) {
throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
}

return 'null';
case is_object($value):
if ($objectSupport) {
return '!!php/object:'.serialize($value);
}

if ($exceptionOnInvalidType) {
throw new DumpException('Object support when dumping a YAML file has been disabled.');
}

return 'null';
case is_array($value):
return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport);
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 Escaper::requiresDoubleQuoting($value):
return Escaper::escapeWithDoubleQuotes($value);
case Escaper::requiresSingleQuoting($value):
case preg_match(self::getTimestampRegex(), $value):
return Escaper::escapeWithSingleQuotes($value);
default:
return $value;
}
}










private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
{

 $keys = array_keys($value);
$keysCount = count($keys);
if ((1 === $keysCount && '0' == $keys[0])
|| ($keysCount > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) === $keysCount * ($keysCount - 1) / 2)
) {
$output = array();
foreach ($value as $val) {
$output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
}

return sprintf('[%s]', implode(', ', $output));
}


 $output = array();
foreach ($value as $key => $val) {
$output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));
}

return sprintf('{ %s }', implode(', ', $output));
}















public static function parseScalar($scalar, $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 (false !== $strpos = strpos($output, ' #')) {
$output = rtrim(substr($output, 0, $strpos));
}
} 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 ($evaluate) {
$output = self::evaluateScalar($output, $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, &$i = 0, $references = array())
{
$output = array();
$len = strlen($sequence);
++$i;


 while ($i < $len) {
switch ($sequence[$i]) {
case '[':

 $output[] = self::parseSequence($sequence, $i, $references);
break;
case '{':

 $output[] = self::parseMapping($sequence, $i, $references);
break;
case ']':
return $output;
case ',':
case ' ':
break;
default:
$isQuoted = in_array($sequence[$i], array('"', "'"));
$value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);


 if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {

 try {
$pos = 0;
$value = self::parseMapping('{'.$value.'}', $pos, $references);
} catch (\InvalidArgumentException $e) {

 }
}

$output[] = $value;

--$i;
}

++$i;
}

throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
}












private static function parseMapping($mapping, &$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, array(':', ' '), array('"', "'"), $i, false);


 $done = false;

while ($i < $len) {
switch ($mapping[$i]) {
case '[':

 $value = self::parseSequence($mapping, $i, $references);

 
 
 if (!isset($output[$key])) {
$output[$key] = $value;
}
$done = true;
break;
case '{':

 $value = self::parseMapping($mapping, $i, $references);

 
 
 if (!isset($output[$key])) {
$output[$key] = $value;
}
$done = true;
break;
case ':':
case ' ':
break;
default:
$value = self::parseScalar($mapping, 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, $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));
case 0 === strpos($scalar, '!!php/object:'):
if (self::$objectSupport) {
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):
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 preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
return (float) str_replace(',', '', $scalar);
case preg_match(self::getTimestampRegex(), $scalar):
return strtotime($scalar);
}
default:
return (string) $scalar;
}
}








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;
}
}
<?php










namespace Symfony\Component\Yaml;

use Symfony\Component\Yaml\Exception\ParseException;






class Parser
{
const FOLDED_SCALAR_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';

private $offset = 0;
private $lines = array();
private $currentLineNb = -1;
private $currentLine = '';
private $refs = array();






public function __construct($offset = 0)
{
$this->offset = $offset;
}













public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false)
{
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 (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
$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');
}
$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'], ' '), '#')) {
$c = $this->getRealCurrentLineNb() + 1;
$parser = new Parser($c);
$parser->refs = & $this->refs;
$data[] = $parser->parse($this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap);
} else {
if (isset($values['leadspaces'])
&& preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
) {

 $c = $this->getRealCurrentLineNb();
$parser = new Parser($c);
$parser->refs = & $this->refs;

$block = $values['value'];
if ($this->isNextLineIndented()) {
$block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1);
}

$data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap);
} else {
$data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
}
}
} 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');
}
$context = 'mapping';


 Inline::parse(null, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
try {
$key = Inline::parseScalar($values['key']);
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);

throw $e;
}

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();
}
$c = $this->getRealCurrentLineNb() + 1;
$parser = new Parser($c);
$parser->refs = & $this->refs;
$parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap);

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 {
$c = $this->getRealCurrentLineNb() + 1;
$parser = new Parser($c);
$parser->refs = & $this->refs;
$value = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap);

 
 if ($allowOverwrite || !isset($data[$key])) {
$data[$key] = $value;
}
}
} else {
$value = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);

 
 if ($allowOverwrite || !isset($data[$key])) {
$data[$key] = $value;
}
}
} else {

 if ('---' === $this->currentLine) {
throw new ParseException('Multiple documents are not supported.');
}


 if ($this->lines[0] === trim($value)) {
try {
$value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);

throw $e;
}

if (is_array($value)) {
$first = reset($value);
if (is_string($first) && 0 === strpos($first, '*')) {
$data = array();
foreach ($value as $alias) {
$data[] = $this->refs[substr($alias, 1)];
}
$value = $data;
}
}

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 ($isRef) {
$this->refs[$isRef] = end($data);
}
}

if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}

return empty($data) ? null : $data;
}






private function getRealCurrentLineNb()
{
return $this->currentLineNb + $this->offset;
}






private function getCurrentLineIndentation()
{
return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
}











private function getNextEmbedBlock($indentation = null, $inSequence = false)
{
$oldLineIndentation = $this->getCurrentLineIndentation();

if (!$this->moveToNextLine()) {
return;
}

if (null === $indentation) {
$newIndent = $this->getCurrentLineIndentation();

$unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem($this->currentLine);

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 && '-' === $data[0][0]) {

 
 $this->moveToPreviousLine();

return;
}

$isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine);


 $removeCommentsPattern = '~'.self::FOLDED_SCALAR_PATTERN.'$~';
$removeComments = !preg_match($removeCommentsPattern, $this->currentLine);

while ($this->moveToNextLine()) {
$indent = $this->getCurrentLineIndentation();

if ($indent === $newIndent) {
$removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
}

if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem($this->currentLine) && $newIndent === $indent) {
$this->moveToPreviousLine();
break;
}

if ($this->isCurrentLineBlank()) {
$data[] = substr($this->currentLine, $newIndent);
continue;
}

if ($removeComments && $this->isCurrentLineComment()) {
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()
{
$this->currentLine = $this->lines[--$this->currentLineNb];
}













private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap)
{
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->currentLine);
}

return $this->refs[$value];
}

if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';

return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
}

try {
return Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);

throw $e;
}
}










private function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
{
$notEOF = $this->moveToNextLine();
if (!$notEOF) {
return '';
}

$isCurrentLineBlank = $this->isCurrentLineBlank();
$text = '';


 while ($notEOF && $isCurrentLineBlank) {

 if ($notEOF = $this->moveToNextLine()) {
$text .= "\n";
$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) {
$text .= substr($this->currentLine, $indentation);
} else {
$text .= $matches[1];
}


 if ($notEOF = $this->moveToNextLine()) {
$text .= "\n";
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
} elseif ($notEOF) {
$text .= "\n";
}

if ($notEOF) {
$this->moveToPreviousLine();
}


 if ('>' === $separator) {
preg_match('/(\n*)$/', $text, $matches);
$text = preg_replace('/(?<!\n)\n(?!\n)/', ' ', rtrim($text, "\n"));
$text .= $matches[1];
}


 if ('' === $indicator) {
$text = preg_replace('/\n+$/s', "\n", $text);
} elseif ('-' === $indicator) {
$text = preg_replace('/\n+$/s', '', $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[0] === '#';
}








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*$#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($this->currentLine)
) {
$ret = true;
}

$this->moveToPreviousLine();

return $ret;
}






private function isStringUnIndentedCollectionItem()
{
return (0 === strpos($this->currentLine, '- '));
}
}
<?php










namespace Symfony\Component\Yaml;







class Unescaper
{

 
 
 const ENCODING = 'UTF-8';


 
 const REGEX_ESCAPED_CHARACTER = "\\\\([0abt\tnvfre \\\"\\/\\\\N_LP]|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)
{
$self = $this;
$callback = function ($match) use ($self) {
return $self->unescapeCharacter($match[0]);
};


 return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value);
}








public 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)));
}
}








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
{


























public static function parse($input, $exceptionOnInvalidType = false, $objectSupport = false)
{

 $file = '';
if (strpos($input, "\n") === false && is_file($input)) {
if (false === is_readable($input)) {
throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input));
}

$file = $input;
$input = file_get_contents($file);
}

$yaml = new Parser();

try {
return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport);
} catch (ParseException $e) {
if ($file) {
$e->setParsedFile($file);
}

throw $e;
}
}

















public static function dump($array, $inline = 2, $indent = 4, $exceptionOnInvalidType = false, $objectSupport = false)
{
$yaml = new Dumper();
$yaml->setIndentation($indent);

return $yaml->dump($array, $inline, 0, $exceptionOnInvalidType, $objectSupport);
}
}
<?php










namespace Symfony\Component\Finder\Adapter;






abstract class AbstractAdapter implements AdapterInterface
{
protected $followLinks = false;
protected $mode = 0;
protected $minDepth = 0;
protected $maxDepth = PHP_INT_MAX;
protected $exclude = array();
protected $names = array();
protected $notNames = array();
protected $contains = array();
protected $notContains = array();
protected $sizes = array();
protected $dates = array();
protected $filters = array();
protected $sort = false;
protected $paths = array();
protected $notPaths = array();
protected $ignoreUnreadableDirs = false;

private static $areSupported = array();




public function isSupported()
{
$name = $this->getName();

if (!array_key_exists($name, self::$areSupported)) {
self::$areSupported[$name] = $this->canBeUsed();
}

return self::$areSupported[$name];
}




public function setFollowLinks($followLinks)
{
$this->followLinks = $followLinks;

return $this;
}




public function setMode($mode)
{
$this->mode = $mode;

return $this;
}




public function setDepths(array $depths)
{
$this->minDepth = 0;
$this->maxDepth = PHP_INT_MAX;

foreach ($depths as $comparator) {
switch ($comparator->getOperator()) {
case '>':
$this->minDepth = $comparator->getTarget() + 1;
break;
case '>=':
$this->minDepth = $comparator->getTarget();
break;
case '<':
$this->maxDepth = $comparator->getTarget() - 1;
break;
case '<=':
$this->maxDepth = $comparator->getTarget();
break;
default:
$this->minDepth = $this->maxDepth = $comparator->getTarget();
}
}

return $this;
}




public function setExclude(array $exclude)
{
$this->exclude = $exclude;

return $this;
}




public function setNames(array $names)
{
$this->names = $names;

return $this;
}




public function setNotNames(array $notNames)
{
$this->notNames = $notNames;

return $this;
}




public function setContains(array $contains)
{
$this->contains = $contains;

return $this;
}




public function setNotContains(array $notContains)
{
$this->notContains = $notContains;

return $this;
}




public function setSizes(array $sizes)
{
$this->sizes = $sizes;

return $this;
}




public function setDates(array $dates)
{
$this->dates = $dates;

return $this;
}




public function setFilters(array $filters)
{
$this->filters = $filters;

return $this;
}




public function setSort($sort)
{
$this->sort = $sort;

return $this;
}




public function setPath(array $paths)
{
$this->paths = $paths;

return $this;
}




public function setNotPath(array $notPaths)
{
$this->notPaths = $notPaths;

return $this;
}




public function ignoreUnreadableDirs($ignore = true)
{
$this->ignoreUnreadableDirs = (bool) $ignore;

return $this;
}












abstract protected function canBeUsed();
}
<?php










namespace Symfony\Component\Finder\Adapter;

use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Shell\Shell;
use Symfony\Component\Finder\Expression\Expression;
use Symfony\Component\Finder\Shell\Command;
use Symfony\Component\Finder\Comparator\NumberComparator;
use Symfony\Component\Finder\Comparator\DateComparator;






abstract class AbstractFindAdapter extends AbstractAdapter
{



protected $shell;




public function __construct()
{
$this->shell = new Shell();
}




public function searchInDirectory($dir)
{

 $dir = realpath($dir);


 if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode && ($this->contains || $this->notContains)) {
return new Iterator\FilePathsIterator(array(), $dir);
}

$command = Command::create();
$find = $this->buildFindCommand($command, $dir);

if ($this->followLinks) {
$find->add('-follow');
}

$find->add('-mindepth')->add($this->minDepth + 1);

if (PHP_INT_MAX !== $this->maxDepth) {
$find->add('-maxdepth')->add($this->maxDepth + 1);
}

if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode) {
$find->add('-type d');
} elseif (Iterator\FileTypeFilterIterator::ONLY_FILES === $this->mode) {
$find->add('-type f');
}

$this->buildNamesFiltering($find, $this->names);
$this->buildNamesFiltering($find, $this->notNames, true);
$this->buildPathsFiltering($find, $dir, $this->paths);
$this->buildPathsFiltering($find, $dir, $this->notPaths, true);
$this->buildSizesFiltering($find, $this->sizes);
$this->buildDatesFiltering($find, $this->dates);

$useGrep = $this->shell->testCommand('grep') && $this->shell->testCommand('xargs');
$useSort = is_int($this->sort) && $this->shell->testCommand('sort') && $this->shell->testCommand('cut');

if ($useGrep && ($this->contains || $this->notContains)) {
$grep = $command->ins('grep');
$this->buildContentFiltering($grep, $this->contains);
$this->buildContentFiltering($grep, $this->notContains, true);
}

if ($useSort) {
$this->buildSorting($command, $this->sort);
}

$command->setErrorHandler(
$this->ignoreUnreadableDirs

 ? function ($stderr) { return; }
: function ($stderr) { throw new AccessDeniedException($stderr); }
);

$paths = $this->shell->testCommand('uniq') ? $command->add('| uniq')->execute() : array_unique($command->execute());
$iterator = new Iterator\FilePathsIterator($paths, $dir);

if ($this->exclude) {
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
}

if (!$useGrep && ($this->contains || $this->notContains)) {
$iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
}

if ($this->filters) {
$iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
}

if (!$useSort && $this->sort) {
$iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
$iterator = $iteratorAggregate->getIterator();
}

return $iterator;
}




protected function canBeUsed()
{
return $this->shell->testCommand('find');
}







protected function buildFindCommand(Command $command, $dir)
{
return $command
->ins('find')
->add('find ')
->arg($dir)
->add('-noleaf'); 
 }






private function buildNamesFiltering(Command $command, array $names, $not = false)
{
if (0 === count($names)) {
return;
}

$command->add($not ? '-not' : null)->cmd('(');

foreach ($names as $i => $name) {
$expr = Expression::create($name);


 if ($expr->isGlob() && $expr->getGlob()->isExpandable()) {
$expr = Expression::create($expr->getGlob()->toRegex(false));
}


 
 
 if ($expr->isRegex()) {
$regex = $expr->getRegex();
$regex->prepend($regex->hasStartFlag() ? '/' : '/[^/]*')
->setStartFlag(false)
->setStartJoker(true)
->replaceJokers('[^/]');
if (!$regex->hasEndFlag() || $regex->hasEndJoker()) {
$regex->setEndJoker(false)->append('[^/]*');
}
}

$command
->add($i > 0 ? '-or' : null)
->add($expr->isRegex()
? ($expr->isCaseSensitive() ? '-regex' : '-iregex')
: ($expr->isCaseSensitive() ? '-name' : '-iname')
)
->arg($expr->renderPattern());
}

$command->cmd(')');
}







private function buildPathsFiltering(Command $command, $dir, array $paths, $not = false)
{
if (0 === count($paths)) {
return;
}

$command->add($not ? '-not' : null)->cmd('(');

foreach ($paths as $i => $path) {
$expr = Expression::create($path);


 if ($expr->isGlob() && $expr->getGlob()->isExpandable()) {
$expr = Expression::create($expr->getGlob()->toRegex(false));
}


 if ($expr->isRegex()) {
$regex = $expr->getRegex();
$regex->prepend($regex->hasStartFlag() ? preg_quote($dir).DIRECTORY_SEPARATOR : '.*')->setEndJoker(!$regex->hasEndFlag());
} else {
$expr->prepend('*')->append('*');
}

$command
->add($i > 0 ? '-or' : null)
->add($expr->isRegex()
? ($expr->isCaseSensitive() ? '-regex' : '-iregex')
: ($expr->isCaseSensitive() ? '-path' : '-ipath')
)
->arg($expr->renderPattern());
}

$command->cmd(')');
}





private function buildSizesFiltering(Command $command, array $sizes)
{
foreach ($sizes as $i => $size) {
$command->add($i > 0 ? '-and' : null);

switch ($size->getOperator()) {
case '<=':
$command->add('-size -'.($size->getTarget() + 1).'c');
break;
case '>=':
$command->add('-size +'.($size->getTarget() - 1).'c');
break;
case '>':
$command->add('-size +'.$size->getTarget().'c');
break;
case '!=':
$command->add('-size -'.$size->getTarget().'c');
$command->add('-size +'.$size->getTarget().'c');
break;
case '<':
default:
$command->add('-size -'.$size->getTarget().'c');
}
}
}





private function buildDatesFiltering(Command $command, array $dates)
{
foreach ($dates as $i => $date) {
$command->add($i > 0 ? '-and' : null);

$mins = (int) round((time()-$date->getTarget()) / 60);

if (0 > $mins) {

 $command->add(' -mmin -0');

 return;
}

switch ($date->getOperator()) {
case '<=':
$command->add('-mmin +'.($mins - 1));
break;
case '>=':
$command->add('-mmin -'.($mins + 1));
break;
case '>':
$command->add('-mmin -'.$mins);
break;
case '!=':
$command->add('-mmin +'.$mins.' -or -mmin -'.$mins);
break;
case '<':
default:
$command->add('-mmin +'.$mins);
}
}
}







private function buildSorting(Command $command, $sort)
{
$this->buildFormatSorting($command, $sort);
}





abstract protected function buildFormatSorting(Command $command, $sort);






abstract protected function buildContentFiltering(Command $command, array $contains, $not = false);
}
<?php










namespace Symfony\Component\Finder\Adapter;




interface AdapterInterface
{





public function setFollowLinks($followLinks);






public function setMode($mode);






public function setExclude(array $exclude);






public function setDepths(array $depths);






public function setNames(array $names);






public function setNotNames(array $notNames);






public function setContains(array $contains);






public function setNotContains(array $notContains);






public function setSizes(array $sizes);






public function setDates(array $dates);






public function setFilters(array $filters);






public function setSort($sort);






public function setPath(array $paths);






public function setNotPath(array $notPaths);






public function ignoreUnreadableDirs($ignore = true);






public function searchInDirectory($dir);






public function isSupported();






public function getName();
}
<?php










namespace Symfony\Component\Finder\Adapter;

use Symfony\Component\Finder\Shell\Shell;
use Symfony\Component\Finder\Shell\Command;
use Symfony\Component\Finder\Iterator\SortableIterator;
use Symfony\Component\Finder\Expression\Expression;






class BsdFindAdapter extends AbstractFindAdapter
{



public function getName()
{
return 'bsd_find';
}




protected function canBeUsed()
{
return in_array($this->shell->getType(), array(Shell::TYPE_BSD, Shell::TYPE_DARWIN)) && parent::canBeUsed();
}




protected function buildFormatSorting(Command $command, $sort)
{
switch ($sort) {
case SortableIterator::SORT_BY_NAME:
$command->ins('sort')->add('| sort');

return;
case SortableIterator::SORT_BY_TYPE:
$format = '%HT';
break;
case SortableIterator::SORT_BY_ACCESSED_TIME:
$format = '%a';
break;
case SortableIterator::SORT_BY_CHANGED_TIME:
$format = '%c';
break;
case SortableIterator::SORT_BY_MODIFIED_TIME:
$format = '%m';
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort));
}

$command
->add('-print0 | xargs -0 stat -f')
->arg($format.'%t%N')
->add('| sort | cut -f 2');
}




protected function buildFindCommand(Command $command, $dir)
{
parent::buildFindCommand($command, $dir)->addAtIndex('-E', 1);

return $command;
}




protected function buildContentFiltering(Command $command, array $contains, $not = false)
{
foreach ($contains as $contain) {
$expr = Expression::create($contain);


 $command
->add('| grep -v \'^$\'')
->add('| xargs -I{} grep -I')
->add($expr->isCaseSensitive() ? null : '-i')
->add($not ? '-L' : '-l')
->add('-Ee')->arg($expr->renderPattern())
->add('{}')
;
}
}
}
<?php










namespace Symfony\Component\Finder\Adapter;

use Symfony\Component\Finder\Shell\Shell;
use Symfony\Component\Finder\Shell\Command;
use Symfony\Component\Finder\Iterator\SortableIterator;
use Symfony\Component\Finder\Expression\Expression;






class GnuFindAdapter extends AbstractFindAdapter
{



public function getName()
{
return 'gnu_find';
}




protected function buildFormatSorting(Command $command, $sort)
{
switch ($sort) {
case SortableIterator::SORT_BY_NAME:
$command->ins('sort')->add('| sort');

return;
case SortableIterator::SORT_BY_TYPE:
$format = '%y';
break;
case SortableIterator::SORT_BY_ACCESSED_TIME:
$format = '%A@';
break;
case SortableIterator::SORT_BY_CHANGED_TIME:
$format = '%C@';
break;
case SortableIterator::SORT_BY_MODIFIED_TIME:
$format = '%T@';
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort));
}

$command
->get('find')
->add('-printf')
->arg($format.' %h/%f\\n')
->add('| sort | cut')
->arg('-d ')
->arg('-f2-')
;
}




protected function canBeUsed()
{
return $this->shell->getType() === Shell::TYPE_UNIX && parent::canBeUsed();
}




protected function buildFindCommand(Command $command, $dir)
{
return parent::buildFindCommand($command, $dir)->add('-regextype posix-extended');
}




protected function buildContentFiltering(Command $command, array $contains, $not = false)
{
foreach ($contains as $contain) {
$expr = Expression::create($contain);


 $command
->add('| xargs -I{} -r grep -I')
->add($expr->isCaseSensitive() ? null : '-i')
->add($not ? '-L' : '-l')
->add('-Ee')->arg($expr->renderPattern())
->add('{}')
;
}
}
}
<?php










namespace Symfony\Component\Finder\Adapter;

use Symfony\Component\Finder\Iterator;






class PhpAdapter extends AbstractAdapter
{



public function searchInDirectory($dir)
{
$flags = \RecursiveDirectoryIterator::SKIP_DOTS;

if ($this->followLinks) {
$flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
}

$iterator = new \RecursiveIteratorIterator(
new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs),
\RecursiveIteratorIterator::SELF_FIRST
);

if ($this->minDepth > 0 || $this->maxDepth < PHP_INT_MAX) {
$iterator = new Iterator\DepthRangeFilterIterator($iterator, $this->minDepth, $this->maxDepth);
}

if ($this->mode) {
$iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
}

if ($this->exclude) {
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
}

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->sort) {
$iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
$iterator = $iteratorAggregate->getIterator();
}

if ($this->paths || $this->notPaths) {
$iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
}

return $iterator;
}




public function getName()
{
return 'php';
}




protected function canBeUsed()
{
return true;
}
}
<?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;

use Symfony\Component\Finder\Adapter\AdapterInterface;






class AdapterFailureException extends \RuntimeException implements ExceptionInterface
{



private $adapter;






public function __construct(AdapterInterface $adapter, $message = null, \Exception $previous = null)
{
$this->adapter = $adapter;
parent::__construct($message ?: 'Search failed with "'.$adapter->getName().'" adapter.', $previous);
}




public function getAdapter()
{
return $this->adapter;
}
}
<?php










namespace Symfony\Component\Finder\Exception;




interface ExceptionInterface
{



public function getAdapter();
}
<?php










namespace Symfony\Component\Finder\Exception;




class OperationNotPermitedException extends AdapterFailureException
{
}
<?php










namespace Symfony\Component\Finder\Exception;

use Symfony\Component\Finder\Adapter\AdapterInterface;
use Symfony\Component\Finder\Shell\Command;




class ShellCommandFailureException extends AdapterFailureException
{



private $command;






public function __construct(AdapterInterface $adapter, Command $command, \Exception $previous = null)
{
$this->command = $command;
parent::__construct($adapter, 'Shell command failed: "'.$command->join().'".', $previous);
}




public function getCommand()
{
return $this->command;
}
}
<?php










namespace Symfony\Component\Finder\Expression;




class Expression implements ValueInterface
{
const TYPE_REGEX = 1;
const TYPE_GLOB = 2;




private $value;






public static function create($expr)
{
return new self($expr);
}




public function __construct($expr)
{
try {
$this->value = Regex::create($expr);
} catch (\InvalidArgumentException $e) {
$this->value = new Glob($expr);
}
}




public function __toString()
{
return $this->render();
}




public function render()
{
return $this->value->render();
}




public function renderPattern()
{
return $this->value->renderPattern();
}




public function isCaseSensitive()
{
return $this->value->isCaseSensitive();
}




public function getType()
{
return $this->value->getType();
}




public function prepend($expr)
{
$this->value->prepend($expr);

return $this;
}




public function append($expr)
{
$this->value->append($expr);

return $this;
}




public function isRegex()
{
return self::TYPE_REGEX === $this->value->getType();
}




public function isGlob()
{
return self::TYPE_GLOB === $this->value->getType();
}






public function getGlob()
{
if (self::TYPE_GLOB !== $this->value->getType()) {
throw new \LogicException('Regex can\'t be transformed to glob.');
}

return $this->value;
}




public function getRegex()
{
return self::TYPE_REGEX === $this->value->getType() ? $this->value : $this->value->toRegex();
}
}
<?php










namespace Symfony\Component\Finder\Expression;




class Glob implements ValueInterface
{



private $pattern;




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




public function render()
{
return $this->pattern;
}




public function renderPattern()
{
return $this->pattern;
}




public function getType()
{
return Expression::TYPE_GLOB;
}




public function isCaseSensitive()
{
return true;
}




public function prepend($expr)
{
$this->pattern = $expr.$this->pattern;

return $this;
}




public function append($expr)
{
$this->pattern .= $expr;

return $this;
}






public function isExpandable()
{
return false !== strpos($this->pattern, '{')
&& false !== strpos($this->pattern, '}');
}







public function toRegex($strictLeadingDot = true, $strictWildcardSlash = true)
{
$firstByte = true;
$escaping = false;
$inCurlies = 0;
$regex = '';
$sizeGlob = strlen($this->pattern);
for ($i = 0; $i < $sizeGlob; $i++) {
$car = $this->pattern[$i];
if ($firstByte) {
if ($strictLeadingDot && '.' !== $car) {
$regex .= '(?=[^\.])';
}

$firstByte = false;
}

if ('/' === $car) {
$firstByte = true;
}

if ('.' === $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 new Regex('^'.$regex.'$');
}
}
<?php










namespace Symfony\Component\Finder\Expression;




class Regex implements ValueInterface
{
const START_FLAG = '^';
const END_FLAG = '$';
const BOUNDARY = '~';
const JOKER = '.*';
const ESCAPING = '\\';




private $pattern;




private $options;




private $startFlag;




private $endFlag;




private $startJoker;




private $endJoker;








public static function create($expr)
{
if (preg_match('/^(.{3,}?)([imsxuADU]*)$/', $expr, $m)) {
$start = substr($m[1], 0, 1);
$end = substr($m[1], -1);

if (
($start === $end && !preg_match('/[*?[:alnum:] \\\\]/', $start))
|| ($start === '{' && $end === '}')
|| ($start === '(' && $end === ')')
) {
return new self(substr($m[1], 1, -1), $m[2], $end);
}
}

throw new \InvalidArgumentException('Given expression is not a regex.');
}






public function __construct($pattern, $options = '', $delimiter = null)
{
if (null !== $delimiter) {

 $pattern = str_replace('\\'.$delimiter, $delimiter, $pattern);
}

$this->parsePattern($pattern);
$this->options = $options;
}




public function __toString()
{
return $this->render();
}




public function render()
{
return self::BOUNDARY
.$this->renderPattern()
.self::BOUNDARY
.$this->options;
}




public function renderPattern()
{
return ($this->startFlag ? self::START_FLAG : '')
.($this->startJoker ? self::JOKER : '')
.str_replace(self::BOUNDARY, '\\'.self::BOUNDARY, $this->pattern)
.($this->endJoker ? self::JOKER : '')
.($this->endFlag ? self::END_FLAG : '');
}




public function isCaseSensitive()
{
return !$this->hasOption('i');
}




public function getType()
{
return Expression::TYPE_REGEX;
}




public function prepend($expr)
{
$this->pattern = $expr.$this->pattern;

return $this;
}




public function append($expr)
{
$this->pattern .= $expr;

return $this;
}






public function hasOption($option)
{
return false !== strpos($this->options, $option);
}






public function addOption($option)
{
if (!$this->hasOption($option)) {
$this->options .= $option;
}

return $this;
}






public function removeOption($option)
{
$this->options = str_replace($option, '', $this->options);

return $this;
}






public function setStartFlag($startFlag)
{
$this->startFlag = $startFlag;

return $this;
}




public function hasStartFlag()
{
return $this->startFlag;
}






public function setEndFlag($endFlag)
{
$this->endFlag = (bool) $endFlag;

return $this;
}




public function hasEndFlag()
{
return $this->endFlag;
}






public function setStartJoker($startJoker)
{
$this->startJoker = $startJoker;

return $this;
}




public function hasStartJoker()
{
return $this->startJoker;
}






public function setEndJoker($endJoker)
{
$this->endJoker = (bool) $endJoker;

return $this;
}




public function hasEndJoker()
{
return $this->endJoker;
}






public function replaceJokers($replacement)
{
$replace = function ($subject) use ($replacement) {
$subject = $subject[0];
$replace = 0 === substr_count($subject, '\\') % 2;

return $replace ? str_replace('.', $replacement, $subject) : $subject;
};

$this->pattern = preg_replace_callback('~[\\\\]*\\.~', $replace, $this->pattern);

return $this;
}




private function parsePattern($pattern)
{
if ($this->startFlag = self::START_FLAG === substr($pattern, 0, 1)) {
$pattern = substr($pattern, 1);
}

if ($this->startJoker = self::JOKER === substr($pattern, 0, 2)) {
$pattern = substr($pattern, 2);
}

if ($this->endFlag = (self::END_FLAG === substr($pattern, -1) && self::ESCAPING !== substr($pattern, -2, -1))) {
$pattern = substr($pattern, 0, -1);
}

if ($this->endJoker = (self::JOKER === substr($pattern, -2) && self::ESCAPING !== substr($pattern, -3, -2))) {
$pattern = substr($pattern, 0, -2);
}

$this->pattern = $pattern;
}
}
<?php










namespace Symfony\Component\Finder\Expression;




interface ValueInterface
{





public function render();






public function renderPattern();






public function isCaseSensitive();






public function getType();






public function prepend($expr);






public function append($expr);
}
<?php










namespace Symfony\Component\Finder;

use Symfony\Component\Finder\Adapter\AdapterInterface;
use Symfony\Component\Finder\Adapter\GnuFindAdapter;
use Symfony\Component\Finder\Adapter\BsdFindAdapter;
use Symfony\Component\Finder\Adapter\PhpAdapter;
use Symfony\Component\Finder\Comparator\DateComparator;
use Symfony\Component\Finder\Comparator\NumberComparator;
use Symfony\Component\Finder\Exception\ExceptionInterface;
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 $adapters = 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;

$this
->addAdapter(new GnuFindAdapter())
->addAdapter(new BsdFindAdapter())
->addAdapter(new PhpAdapter(), -50)
->setAdapter('php')
;
}








public static function create()
{
return new static();
}









public function addAdapter(AdapterInterface $adapter, $priority = 0)
{
$this->adapters[$adapter->getName()] = array(
'adapter' => $adapter,
'priority' => $priority,
'selected' => false,
);

return $this->sortAdapters();
}






public function useBestAdapter()
{
$this->resetAdapterSelection();

return $this->sortAdapters();
}










public function setAdapter($name)
{
if (!isset($this->adapters[$name])) {
throw new \InvalidArgumentException(sprintf('Adapter "%s" does not exist.', $name));
}

$this->resetAdapterSelection();
$this->adapters[$name]['selected'] = true;

return $this->sortAdapters();
}






public function removeAdapters()
{
$this->adapters = array();

return $this;
}






public function getAdapters()
{
return array_values(array_map(function (array $adapter) {
return $adapter['adapter'];
}, $this->adapters));
}








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, GLOB_BRACE | 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 sortAdapters()
{
uasort($this->adapters, function (array $a, array $b) {
if ($a['selected'] || $b['selected']) {
return $a['selected'] ? -1 : 1;
}

return $a['priority'] > $b['priority'] ? -1 : 1;
});

return $this;
}








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[] = '#(^|/)\..+(/|$)#';
}

foreach ($this->adapters as $adapter) {
if ($adapter['adapter']->isSupported()) {
try {
return $this
->buildAdapter($adapter['adapter'])
->searchInDirectory($dir);
} catch (ExceptionInterface $e) {
}
}
}

throw new \RuntimeException('No supported adapter found.');
}






private function buildAdapter(AdapterInterface $adapter)
{
return $adapter
->setFollowLinks($this->followLinks)
->setDepths($this->depths)
->setMode($this->mode)
->setExclude($this->exclude)
->setNames($this->names)
->setNotNames($this->notNames)
->setContains($this->contains)
->setNotContains($this->notContains)
->setSizes($this->sizes)
->setDates($this->dates)
->setFilters($this->filters)
->setSort($this->sort)
->setPath($this->paths)
->setNotPath($this->notPaths)
->ignoreUnreadableDirs($this->ignoreUnreadableDirs);
}




private function resetAdapterSelection()
{
$this->adapters = array_map(function (array $properties) {
$properties['selected'] = false;

return $properties;
}, $this->adapters);
}
}
<?php










namespace Symfony\Component\Finder;























class Glob
{









public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true)
{
$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 ('.' === $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 '#^'.$regex.'$#';
}
}
<?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
{
private $patterns = array();







public function __construct(\Iterator $iterator, array $directories)
{
foreach ($directories as $directory) {
$this->patterns[] = '#(^|/)'.preg_quote($directory, '#').'(/|$)#';
}

parent::__construct($iterator);
}






public function accept()
{
$path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
$path = strtr($path, '\\', '/');
foreach ($this->patterns as $pattern) {
if (preg_match($pattern, $path)) {
return false;
}
}

return true;
}
}
<?php










namespace Symfony\Component\Finder\Iterator;

use Symfony\Component\Finder\SplFileInfo;






class FilePathsIterator extends \ArrayIterator
{



private $baseDir;




private $baseDirLength;




private $subPath;




private $subPathname;




private $current;





public function __construct(array $paths, $baseDir)
{
$this->baseDir = $baseDir;
$this->baseDirLength = strlen($baseDir);

parent::__construct($paths);
}







public function __call($name, array $arguments)
{
return call_user_func_array(array($this->current(), $name), $arguments);
}






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




public function key()
{
return $this->current->getPathname();
}

public function next()
{
parent::next();
$this->buildProperties();
}

public function rewind()
{
parent::rewind();
$this->buildProperties();
}




public function getSubPath()
{
return $this->subPath;
}




public function getSubPathname()
{
return $this->subPathname;
}

private function buildProperties()
{
$absolutePath = parent::current();

if ($this->baseDir === substr($absolutePath, 0, $this->baseDirLength)) {
$this->subPathname = ltrim(substr($absolutePath, $this->baseDirLength), '/\\');
$dir = dirname($this->subPathname);
$this->subPath = '.' === $dir ? '' : $dir;
} else {
$this->subPath = $this->subPathname = '';
}

$this->current = new SplFileInfo(parent::current(), $this->subPath, $this->subPathname);
}
}
<?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;
}


 foreach ($this->noMatchRegexps as $regex) {
if (preg_match($regex, $content)) {
return false;
}
}


 $match = true;
if ($this->matchRegexps) {
$match = false;
foreach ($this->matchRegexps as $regex) {
if (preg_match($regex, $content)) {
return true;
}
}
}

return $match;
}








protected function toRegex($str)
{
return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
}
}
<?php










namespace Symfony\Component\Finder\Iterator;

use Symfony\Component\Finder\Expression\Expression;






class FilenameFilterIterator extends MultiplePcreFilterIterator
{





public function accept()
{
$filename = $this->current()->getFilename();


 foreach ($this->noMatchRegexps as $regex) {
if (preg_match($regex, $filename)) {
return false;
}
}


 $match = true;
if ($this->matchRegexps) {
$match = false;
foreach ($this->matchRegexps as $regex) {
if (preg_match($regex, $filename)) {
return true;
}
}
}

return $match;
}











protected function toRegex($str)
{
return Expression::create($str)->getRegex()->render();
}
}
<?php










namespace Symfony\Component\Finder\Iterator;








abstract class FilterIterator extends \FilterIterator
{






public function rewind()
{
$iterator = $this;
while ($iterator instanceof \OuterIterator) {
$innerIterator = $iterator->getInnerIterator();

if ($innerIterator instanceof RecursiveDirectoryIterator) {
if ($innerIterator->isRewindable()) {
$innerIterator->next();
$innerIterator->rewind();
}
} elseif ($iterator->getInnerIterator() instanceof \FilesystemIterator) {
$iterator->getInnerIterator()->next();
$iterator->getInnerIterator()->rewind();
}
$iterator = $iterator->getInnerIterator();
}

parent::rewind();
}
}
<?php










namespace Symfony\Component\Finder\Iterator;

use Symfony\Component\Finder\Expression\Expression;






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 isRegex($str)
{
return Expression::create($str)->isRegex();
}








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 = strtr($filename, '\\', '/');
}


 foreach ($this->noMatchRegexps as $regex) {
if (preg_match($regex, $filename)) {
return false;
}
}


 $match = true;
if ($this->matchRegexps) {
$match = false;
foreach ($this->matchRegexps as $regex) {
if (preg_match($regex, $filename)) {
return true;
}
}
}

return $match;
}















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;










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;
}






public function current()
{
return new SplFileInfo(parent::current()->getPathname(), $this->getSubPath(), $this->getSubPathname());
}






public function getChildren()
{
try {
$children = parent::getChildren();

if ($children instanceof self) {

 $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
}

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;
}


 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\Shell;




class Command
{



private $parent;




private $bits = array();




private $labels = array();




private $errorHandler;






public function __construct(Command $parent = null)
{
$this->parent = $parent;
}






public function __toString()
{
return $this->join();
}








public static function create(Command $parent = null)
{
return new self($parent);
}








public static function escape($input)
{
return escapeshellcmd($input);
}








public static function quote($input)
{
return escapeshellarg($input);
}








public function add($bit)
{
$this->bits[] = $bit;

return $this;
}








public function top($bit)
{
array_unshift($this->bits, $bit);

foreach ($this->labels as $label => $index) {
$this->labels[$label] += 1;
}

return $this;
}








public function arg($arg)
{
$this->bits[] = self::quote($arg);

return $this;
}








public function cmd($esc)
{
$this->bits[] = self::escape($esc);

return $this;
}










public function ins($label)
{
if (isset($this->labels[$label])) {
throw new \RuntimeException(sprintf('Label "%s" already exists.', $label));
}

$this->bits[] = self::create($this);
$this->labels[$label] = count($this->bits)-1;

return $this->bits[$this->labels[$label]];
}










public function get($label)
{
if (!isset($this->labels[$label])) {
throw new \RuntimeException(sprintf('Label "%s" does not exist.', $label));
}

return $this->bits[$this->labels[$label]];
}








public function end()
{
if (null === $this->parent) {
throw new \RuntimeException('Calling end on root command doesn\'t make sense.');
}

return $this->parent;
}






public function length()
{
return count($this->bits);
}






public function setErrorHandler(\Closure $errorHandler)
{
$this->errorHandler = $errorHandler;

return $this;
}




public function getErrorHandler()
{
return $this->errorHandler;
}








public function execute()
{
if (null === $errorHandler = $this->errorHandler) {
exec($this->join(), $output);
} else {
$process = proc_open($this->join(), array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes);
$output = preg_split('~(\r\n|\r|\n)~', stream_get_contents($pipes[1]), -1, PREG_SPLIT_NO_EMPTY);

if ($error = stream_get_contents($pipes[2])) {
$errorHandler($error);
}

proc_close($process);
}

return $output ?: array();
}






public function join()
{
return implode(' ', array_filter(
array_map(function ($bit) {
return $bit instanceof Command ? $bit->join() : ($bit ?: null);
}, $this->bits),
function ($bit) { return null !== $bit; }
));
}









public function addAtIndex($bit, $index)
{
array_splice($this->bits, $index, 0, $bit);

return $this;
}
}
<?php










namespace Symfony\Component\Finder\Shell;




class Shell
{
const TYPE_UNIX = 1;
const TYPE_DARWIN = 2;
const TYPE_CYGWIN = 3;
const TYPE_WINDOWS = 4;
const TYPE_BSD = 5;




private $type;






public function getType()
{
if (null === $this->type) {
$this->type = $this->guessType();
}

return $this->type;
}








public function testCommand($command)
{
if (!function_exists('exec')) {
return false;
}


 $testCommand = 'which ';
if (self::TYPE_WINDOWS === $this->type) {
$testCommand = 'where ';
}

$command = escapeshellcmd($command);

exec($testCommand.$command, $output, $code);

return 0 === $code && count($output) > 0;
}






private function guessType()
{
$os = strtolower(PHP_OS);

if (false !== strpos($os, 'cygwin')) {
return self::TYPE_CYGWIN;
}

if (false !== strpos($os, 'darwin')) {
return self::TYPE_DARWIN;
}

if (false !== strpos($os, 'bsd')) {
return self::TYPE_BSD;
}

if (0 === strpos($os, 'win')) {
return self::TYPE_WINDOWS;
}

return self::TYPE_UNIX;
}
}
<?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.'."\nExit Code: %s(%s)",
$process->getCommandLine(),
$process->getExitCode(),
$process->getExitCodeText()
);

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;







class PhpExecutableFinder
{
private $executableFinder;

public function __construct()
{
$this->executableFinder = new ExecutableFinder();
}








public function find($includeArgs = true)
{

 if (defined('HHVM_VERSION')) {
return (false !== ($hhvm = getenv('PHP_BINARY')) ? $hhvm : PHP_BINARY).($includeArgs ? ' '.implode(' ', $this->findArguments()) : '');
}


 if (defined('PHP_BINARY') && PHP_BINARY && in_array(PHP_SAPI, array('cli', 'cli-server')) && is_file(PHP_BINARY)) {
return PHP_BINARY;
}

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';
}

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 = array(), $timeout = 60, array $options = array())
{
$executableFinder = new PhpExecutableFinder();
if (false === $php = $executableFinder->find()) {
$php = null;
}

parent::__construct($php, $cwd, $env, $script, $timeout, $options);
}






public function setPhpBinary($php)
{
$this->setCommandLine($php);
}




public function start($callback = null)
{
if (null === $this->getCommandLine()) {
throw new RuntimeException('Unable to find the PHP executable.');
}

parent::start($callback);
}
}
<?php










namespace Symfony\Component\Process\Pipes;






abstract class AbstractPipes implements PipesInterface
{

public $pipes = array();


protected $inputBuffer = '';

protected $input;


private $blocked = true;




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 (null !== $this->input) {
stream_set_blocking($this->input, 0);
}

$this->blocked = false;
}
}
<?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 close();
}
<?php










namespace Symfony\Component\Process\Pipes;

use Symfony\Component\Process\Process;








class UnixPipes extends AbstractPipes
{

private $ttyMode;

private $ptyMode;

private $disableOutput;

public function __construct($ttyMode, $ptyMode, $input, $disableOutput)
{
$this->ttyMode = (bool) $ttyMode;
$this->ptyMode = (bool) $ptyMode;
$this->disableOutput = (bool) $disableOutput;

if (is_resource($input)) {
$this->input = $input;
} else {
$this->inputBuffer = (string) $input;
}
}

public function __destruct()
{
$this->close();
}




public function getDescriptors()
{
if ($this->disableOutput) {
$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)
{

 
 if (1 === count($this->pipes) && array(0) === array_keys($this->pipes)) {
fclose($this->pipes[0]);
unset($this->pipes[0]);
}

if (empty($this->pipes)) {
return array();
}

$this->unblock();

$read = array();

if (null !== $this->input) {

 
 $r = array_merge($this->pipes, array('input' => $this->input));
} else {
$r = $this->pipes;
}

 unset($r[0]);

$w = isset($this->pipes[0]) ? array($this->pipes[0]) : null;
$e = null;


 if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {

 
 if (!$this->hasSystemCallBeenInterrupted()) {
$this->pipes = array();
}

return $read;
}


 if (0 === $n) {
return $read;
}

foreach ($r as $pipe) {

 
 $type = (false !== $found = array_search($pipe, $this->pipes)) ? $found : 'input';
$data = '';
while ('' !== $dataread = (string) fread($pipe, self::CHUNK_SIZE)) {
$data .= $dataread;
}

if ('' !== $data) {
if ($type === 'input') {
$this->inputBuffer .= $data;
} else {
$read[$type] = $data;
}
}

if (false === $data || (true === $close && feof($pipe) && '' === $data)) {
if ($type === 'input') {

 
 $this->input = null;
} else {
fclose($this->pipes[$type]);
unset($this->pipes[$type]);
}
}
}

if (null !== $w && 0 < count($w)) {
while (strlen($this->inputBuffer)) {
$written = fwrite($w[0], $this->inputBuffer, 2 << 18); 
 if ($written > 0) {
$this->inputBuffer = (string) substr($this->inputBuffer, $written);
} else {
break;
}
}
}


 if ('' === $this->inputBuffer && null === $this->input && isset($this->pipes[0])) {
fclose($this->pipes[0]);
unset($this->pipes[0]);
}

return $read;
}




public function areOpen()
{
return (bool) $this->pipes;
}









public static function create(Process $process, $input)
{
return new static($process->isTty(), $process->isPty(), $input, $process->isOutputDisabled());
}
}
<?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 $disableOutput;

public function __construct($disableOutput, $input)
{
$this->disableOutput = (bool) $disableOutput;

if (!$this->disableOutput) {

 
 
 
 $this->files = array(
Process::STDOUT => tempnam(sys_get_temp_dir(), 'sf_proc_stdout'),
Process::STDERR => tempnam(sys_get_temp_dir(), 'sf_proc_stderr'),
);
foreach ($this->files as $offset => $file) {
$this->fileHandles[$offset] = fopen($this->files[$offset], 'rb');
if (false === $this->fileHandles[$offset]) {
throw new RuntimeException('A temporary file could not be opened to write the process output to, verify that your TEMP environment variable is writable');
}
}
}

if (is_resource($input)) {
$this->input = $input;
} else {
$this->inputBuffer = $input;
}
}

public function __destruct()
{
$this->close();
$this->removeFiles();
}




public function getDescriptors()
{
if ($this->disableOutput) {
$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->write($blocking, $close);

$read = array();
$fh = $this->fileHandles;
foreach ($fh as $type => $fileHandle) {
if (0 !== fseek($fileHandle, $this->readBytes[$type])) {
continue;
}
$data = '';
$dataread = null;
while (!feof($fileHandle)) {
if (false !== $dataread = fread($fileHandle, self::CHUNK_SIZE)) {
$data .= $dataread;
}
}
if (0 < $length = strlen($data)) {
$this->readBytes[$type] += $length;
$read[$type] = $data;
}

if (false === $dataread || (true === $close && feof($fileHandle) && '' === $data)) {
fclose($this->fileHandles[$type]);
unset($this->fileHandles[$type]);
}
}

return $read;
}




public function areOpen()
{
return (bool) $this->pipes && (bool) $this->fileHandles;
}




public function close()
{
parent::close();
foreach ($this->fileHandles as $handle) {
fclose($handle);
}
$this->fileHandles = array();
}









public static function create(Process $process, $input)
{
return new static($process->isOutputDisabled(), $input);
}




private function removeFiles()
{
foreach ($this->files as $filename) {
if (file_exists($filename)) {
@unlink($filename);
}
}
$this->files = array();
}







private function write($blocking, $close)
{
if (empty($this->pipes)) {
return;
}

$this->unblock();

$r = null !== $this->input ? array('input' => $this->input) : null;
$w = isset($this->pipes[0]) ? array($this->pipes[0]) : null;
$e = null;


 if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {

 
 if (!$this->hasSystemCallBeenInterrupted()) {
$this->pipes = array();
}

return;
}


 if (0 === $n) {
return;
}

if (null !== $w && 0 < count($r)) {
$data = '';
while ($dataread = fread($r['input'], self::CHUNK_SIZE)) {
$data .= $dataread;
}

$this->inputBuffer .= $data;

if (false === $data || (true === $close && feof($r['input']) && '' === $data)) {

 
 $this->input = null;
}
}

if (null !== $w && 0 < count($w)) {
while (strlen($this->inputBuffer)) {
$written = fwrite($w[0], $this->inputBuffer, 2 << 18);
if ($written > 0) {
$this->inputBuffer = (string) substr($this->inputBuffer, $written);
} else {
break;
}
}
}


 if ('' === $this->inputBuffer && null === $this->input && isset($this->pipes[0])) {
fclose($this->pipes[0]);
unset($this->pipes[0]);
}
}
}
<?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
{
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;

private $callback;
private $commandline;
private $cwd;
private $env;
private $input;
private $starttime;
private $lastOutputTime;
private $timeout;
private $idleTimeout;
private $options;
private $exitcode;
private $fallbackExitcode;
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->input = $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();
}

public function __clone()
{
$this->resetProcessData();
}






















public function run($callback = null)
{
$this->start($callback);

return $this->wait();
}














public function mustRun($callback = null)
{
if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
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($callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}
if ($this->outputDisabled && null !== $callback) {
throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
}

$this->resetProcessData();
$this->starttime = $this->lastOutputTime = microtime(true);
$this->callback = $this->buildCallback($callback);
$descriptors = $this->getDescriptors();

$commandline = $this->commandline;

if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
$commandline = 'cmd /V:ON /E:ON /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;
}
}

$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 ($this->tty) {
return;
}

$this->updateStatus(false);
$this->checkTimeout();
}
















public function restart($callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}

$process = clone $this;
$process->start($callback);

return $process;
}
















public function wait($callback = null)
{
$this->requireProcessIsStarted(__FUNCTION__);

$this->updateStatus(false);
if (null !== $callback) {
$this->callback = $this->buildCallback($callback);
}

do {
$this->checkTimeout();
$running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$close = '\\' !== DIRECTORY_SEPARATOR || !$running;
$this->readPipes(true, $close);
} 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()
{
if ($this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
}

$this->updateStatus(false);

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()
{
if ($this->outputDisabled) {
throw new LogicException('Output has been disabled.');
}

$this->requireProcessIsStarted(__FUNCTION__);

$this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);

return $this->stdout;
}












public function getIncrementalOutput()
{
$this->requireProcessIsStarted(__FUNCTION__);

$data = $this->getOutput();

$latest = substr($data, $this->incrementalOutputOffset);

if (false === $latest) {
return '';
}

$this->incrementalOutputOffset = strlen($data);

return $latest;
}






public function clearOutput()
{
$this->stdout = '';
$this->incrementalOutputOffset = 0;

return $this;
}











public function getErrorOutput()
{
if ($this->outputDisabled) {
throw new LogicException('Output has been disabled.');
}

$this->requireProcessIsStarted(__FUNCTION__);

$this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);

return $this->stderr;
}













public function getIncrementalErrorOutput()
{
$this->requireProcessIsStarted(__FUNCTION__);

$data = $this->getErrorOutput();

$latest = substr($data, $this->incrementalErrorOutputOffset);

if (false === $latest) {
return '';
}

$this->incrementalErrorOutputOffset = strlen($data);

return $latest;
}






public function clearErrorOutput()
{
$this->stderr = '';
$this->incrementalErrorOutputOffset = 0;

return $this;
}










public function getExitCode()
{
if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
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->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}

$this->updateStatus(false);

return $this->processInformation['signaled'];
}













public function getTermSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);

if ($this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}

$this->updateStatus(false);

return $this->processInformation['termsig'];
}












public function hasBeenStopped()
{
$this->requireProcessIsTerminated(__FUNCTION__);

$this->updateStatus(false);

return $this->processInformation['stopped'];
}












public function getStopSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);

$this->updateStatus(false);

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()) {
if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) {
exec(sprintf("taskkill /F /T /PID %d 2>&1", $this->getPid()), $output, $exitCode);
if ($exitCode > 0) {
throw new RuntimeException('Unable to kill the process');
}
}

 $this->doSignal(15, false);
do {
usleep(1000);
} while ($this->isRunning() && microtime(true) < $timeoutMicro);

if ($this->isRunning() && !$this->isSigchildEnabled()) {
if (null !== $signal || defined('SIGKILL')) {

 
 
 
 $this->doSignal($signal ?: SIGKILL, false);
}
}
}

$this->updateStatus(false);
if ($this->processInformation['running']) {
$this->close();
}

return $this->exitcode;
}






public function addOutput($line)
{
$this->lastOutputTime = microtime(true);
$this->stdout .= $line;
}






public function addErrorOutput($line)
{
$this->lastOutputTime = microtime(true);
$this->stderr .= $line;
}






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[(binary) $key] = (binary) $value;
}

return $this;
}









public function getStdin()
{
return $this->getInput();
}






public function getInput()
{
return $this->input;
}














public function setStdin($stdin)
{
return $this->setInput($stdin);
}












public function setInput($input)
{
if ($this->isRunning()) {
throw new LogicException('Input can not be set while the process is running.');
}

$this->input = ProcessUtils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $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;
}

$proc = @proc_open('echo 1', array(array('pty'), array('pty'), array('pty')), $pipes);
if (is_resource($proc)) {
proc_close($proc);

return $result = true;
}

return $result = false;
}






private function getDescriptors()
{
if ('\\' === DIRECTORY_SEPARATOR) {
$this->processPipes = WindowsPipes::create($this, $this->input);
} else {
$this->processPipes = UnixPipes::create($this, $this->input);
}
$descriptors = $this->processPipes->getDescriptors($this->outputDisabled);

if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {

 $descriptors = array_merge($descriptors, array(array('pipe', 'w')));

$this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
}

return $descriptors;
}











protected function buildCallback($callback)
{
$that = $this;
$out = self::OUT;
$callback = function ($type, $data) use ($that, $callback, $out) {
if ($out == $type) {
$that->addOutput($data);
} else {
$that->addErrorOutput($data);
}

if (null !== $callback) {
call_user_func($callback, $type, $data);
}
};

return $callback;
}






protected function updateStatus($blocking)
{
if (self::STATUS_STARTED !== $this->status) {
return;
}

$this->processInformation = proc_get_status($this->process);
$this->captureExitCode();

$this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);

if (!$this->processInformation['running']) {
$this->close();
}
}






protected function isSigchildEnabled()
{
if (null !== self::$sigchild) {
return self::$sigchild;
}

if (!function_exists('phpinfo')) {
return self::$sigchild = false;
}

ob_start();
phpinfo(INFO_GENERAL);

return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
}










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) {
$this->fallbackExitcode = (int) $data;
} else {
$callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
}
}
}




private function captureExitCode()
{
if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
$this->exitcode = $this->processInformation['exitcode'];
}
}






private function close()
{
$this->processPipes->close();
if (is_resource($this->process)) {
$exitcode = proc_close($this->process);
} else {
$exitcode = -1;
}

$this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
$this->status = self::STATUS_TERMINATED;

if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
$this->exitcode = $this->fallbackExitcode;
} elseif (-1 === $this->exitcode && $this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {

 $this->exitcode = 128 + $this->processInformation['termsig'];
}

return $this->exitcode;
}




private function resetProcessData()
{
$this->starttime = null;
$this->callback = null;
$this->exitcode = null;
$this->fallbackExitcode = null;
$this->processInformation = null;
$this->stdout = null;
$this->stderr = null;
$this->process = null;
$this->latestSignal = null;
$this->status = self::STATUS_READY;
$this->incrementalOutputOffset = 0;
$this->incrementalErrorOutputOffset = 0;
}













private function doSignal($signal, $throwException)
{
if (!$this->isRunning()) {
if ($throwException) {
throw new LogicException('Can not send signal on a non running process.');
}

return false;
}

if ($this->isSigchildEnabled()) {
if ($throwException) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
}

return false;
}

if (true !== @proc_terminate($this->process, $signal)) {
if ($throwException) {
throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
}

return false;
}

$this->latestSignal = $signal;

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(sprintf('%s::%s', __CLASS__, __FUNCTION__), $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('/(")/i', $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_scalar($input)) {
return (string) $input;
}

 if (is_object($input) && method_exists($input, '__toString')) {
return (string) $input;
}

throw new InvalidArgumentException(sprintf('%s only accepts strings 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

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 !== false ? $lifeTime : 0);
}
}
<?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.9.3';





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;
const DEFAULT_SELECT_TIMEOUT = 1.0;
const MAX_HANDLES = 3;


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 (strpos($uri, '://')) {

 $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(
self::MAX_HANDLES,
$this->getConfig('select_timeout') ?: self::DEFAULT_SELECT_TIMEOUT
);
}

return $this->curlMulti;
}

public function setRequestFactory(RequestFactoryInterface $factory)
{
$this->requestFactory = $factory;

return $this;
}








public function setUriTemplate(UriTemplateInterface $uriTemplate)
{
$this->uriTemplate = $uriTemplate;

return $this;
}









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()
{
$authority = $this->config[self::SSL_CERT_AUTHORITY];

if ($authority === 'system') {
return;
}

if ($authority === null) {
$authority = true;
}

if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') {
$authority = self::extractPharCacert(__DIR__ . '/Resources/cacert.pem');
}

$this->setSslVerification($authority);
}




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;
}




public function preparePharCacert($md5Check = true)
{
return sys_get_temp_dir() . '/guzzle-cacert.pem';
}











public static function extractPharCacert($pharCacertPath)
{

 
 $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem';

if (!file_exists($pharCacertPath)) {
throw new \RuntimeException("Could not find $pharCacertPath");
}

if (!file_exists($certFile) ||
filesize($certFile) != filesize($pharCacertPath)
) {
if (!copy($pharCacertPath, $certFile)) {
throw new \RuntimeException(
"Could not copy {$pharCacertPath} to {$certFile}: "
. var_export(error_get_last(), true)
);
}
}

return $certFile;
}
}
<?php

namespace Guzzle\Http;

use Guzzle\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 (null !== $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;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Exception\RequestException;




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!')
);


protected $selectTimeout;

public function __construct($selectTimeout = 1.0)
{
$this->selectTimeout = $selectTimeout;
$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) {
$this->addHandle($request);
} else {

 
 $this->remove($request);
if ($state == RequestInterface::STATE_COMPLETE) {
$this->successful[] = $request;
}
}
} catch (\Exception $e) {

 $this->removeErroredRequest($request, $e);
}
}

private function addHandle(RequestInterface $request)
{
$handle = $this->createCurlHandle($request)->getHandle();
$this->checkCurlResult(
curl_multi_add_handle($this->multiHandle, $handle)
);
}








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 = $this->selectTimeout;
} 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) {
if ($this->validateResponseWasSet($request)) {
$state = $request->setState(
RequestInterface::STATE_COMPLETE,
array('handle' => $handle)
);

 
 if ($state != RequestInterface::STATE_TRANSFER) {
$this->remove($request);
}
}
return;
}


 $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
);
}
}




private function validateResponseWasSet(RequestInterface $request)
{
if ($request->getResponse()) {
return true;
}

$body = $request instanceof EntityEnclosingRequestInterface
? $request->getBody()
: null;

if (!$body) {
$rex = new RequestException(
'No response was received for a request with no body. This'
. ' could mean that you are saturating your network.'
);
$rex->setRequest($request);
$this->removeErroredRequest($request, $rex);
} elseif (!$body->isSeekable() || !$body->seek(0)) {

 $rex = new RequestException(
'The connection was unexpectedly closed. The request would'
. ' have been retried, but attempting to rewind the'
. ' request body failed.'
);
$rex->setRequest($request);
$this->removeErroredRequest($request, $rex);
} else {
$this->remove($request);

 $this->requests[] = $request;
$this->addHandle($request);
}

return false;
}
}
<?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;
protected $selectTimeout;





public function __construct($maxHandles = 3, $selectTimeout = 1.0)
{
$this->maxHandles = $maxHandles;
$this->selectTimeout = $selectTimeout;

 
 
 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($this->selectTimeout);
$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 ($port && (($scheme == 'http' && $port != 80) || ($scheme == 'https' && $port != 443))) {
$this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost() . ':' . $port);
} else {
$this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost());
}

return $this;
}

public function getUsername()
{
return $this->username;
}

public function getPassword()
{
return $this->password;
}

public function setAuth($user, $password = '', $scheme = CURLAUTH_BASIC)
{
static $authMap = array(
'basic' => CURLAUTH_BASIC,
'digest' => CURLAUTH_DIGEST,
'ntlm' => CURLAUTH_NTLM,
'any' => CURLAUTH_ANY
);


 if (!$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') {

 $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\Common\Exception\RuntimeException;
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, false);
}
}


 if ($foundDuplicates && !$foundPhpStyle) {
$q->setAggregator(new DuplicateAggregator());
}

return $q;
}







public function __toString()
{
if (!$this->data) {
return '';
}

$queryList = array();
foreach ($this->prepareData($this->data) as $name => $value) {
$queryList[] = $this->convertKvp($name, $value);
}

return implode($this->fieldSeparator, $queryList);
}






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 ($value === false || $value === null) {

 $temp[$this->encodeValue($key)] = $value;
} elseif (is_array($value)) {
$temp = array_merge($temp, $this->aggregator->aggregate($key, $value, $this));
} else {
$temp[$this->encodeValue($key)] = $this->encodeValue($value);
}
}

return $temp;
}









private function convertKvp($name, $value)
{
if ($value === self::BLANK || $value === null || $value === false) {
return $name;
} elseif (!is_array($value)) {
return $name . $this->valueSeparator . $value;
}

$result = '';
foreach ($value as $v) {
$result .= $this->convertKvp($name, $v) . $this->fieldSeparator;
}

return rtrim($result, $this->fieldSeparator);
}
}
<?php

namespace Guzzle\Http;

use Guzzle\Stream\StreamInterface;




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()
{
if (!$this->body->isReadable() ||
(!$this->body->isSeekable() && $this->body->isConsumed())
) {
return '';
}

$originalPos = $this->body->ftell();
$this->body->seek($this->offset);
$data = '';
while (!$this->feof()) {
$data .= $this->read(1048576);
}
$this->body->seek($originalPos);

return (string) $data ?: '';
}

public function isConsumed()
{
return $this->body->isConsumed() ||
($this->body->ftell() >= $this->offset + $this->limit);
}





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)
{
if ($this->scheme == 'http' && $this->port == 80) {
$this->port = null;
} elseif ($this->scheme == 'https' && $this->port == 443) {
$this->port = null;
}

$this->scheme = $scheme;

return $this;
}






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 != '/' && is_string($relativePath) && strlen($relativePath) > 0) {

 if ($relativePath[0] != '/') {
$relativePath = '/' . $relativePath;
}
$this->setPath(str_replace('//', '/', $this->path . $relativePath));
}

return $this;
}






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, $extras);
}
}
<?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' => null,
'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'];
}


 
 
 
 
 
 if (!$data['path'] || substr($data['path'], 0, 1) !== '/') {
$data['path'] = $this->getDefaultPath($path);
}

return $data;
}









protected function getDefaultPath($path) {

 


 
 if (empty($path) || substr($path, 0, 1) !== '/') {
return '/';
}


 
 if ($path === "/") {
return $path;
}

$rightSlashPos = strrpos($path, '/');
if ($rightSlashPos === 0) {
return "/";
}


 
 return substr($path, 0, $rightSlashPos);

}
}
<?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(isset($parts['start_line'][1]) ? $parts['start_line'][1] : '' , $parsed);

return $parsed;
}

public function parseResponse($message)
{
if (!$message) {
return false;
}

$parts = $this->parseMessage($message);
list($protocol, $version) = explode('/', trim($parts['start_line'][0]));

return array(
'protocol' => $protocol,
'version' => $version,
'code' => $parts['start_line'][1],
'reason_phrase' => isset($parts['start_line'][2]) ? $parts['start_line'][2] : '',
'headers' => $parts['headers'],
'body' => $parts['body']
);
}








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();

$overrideTtl = $request->getParams()->get('cache.override_ttl');
if ($overrideTtl) {
$ttl = $overrideTtl;
} else {
$maxAge = $response->getMaxAge();
if ($maxAge !== null) {
$ttl = $maxAge;
} else {
$ttl = $this->defaultTtl;
}
}

if ($cacheControl = $response->getHeader('Cache-Control')) {
$stale = $cacheControl->getDirective('stale-if-error');
if ($stale === true) {
$ttl += $ttl;
} else if (is_numeric($stale)) {
$ttl += $stale;
}
}


 $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');

if ($response->getLastModified()) {
$revalidate->setHeader('If-Modified-Since', $response->getLastModified());
}

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)
{

 
 


 if ($path == $this->getPath()) {
return true;
}

$pos = stripos($path, $this->getPath());
if ($pos === 0) {

 
 if (substr($this->getPath(), -1, 1) === "/") {
return true;
}


 
 
 if (substr($path, strlen($this->getPath()), 1) === "/") {
return true;
}
}

return false;
}








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 {
$this->removeCookieIfEmpty($cookie);
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;
}







private function removeCookieIfEmpty(Cookie $cookie)
{
$cookieValue = $cookie->getValue();
if ($cookieValue === null || $cookieValue === '') {
$this->remove($cookie->getDomain(), $cookie->getPath(), $cookie->getName());
}
}
}
<?php

namespace Guzzle\Plugin\Cookie\CookieJar;

use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;




interface 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 (!(in_array($errorClassInterface, class_implements($className)))) {
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) {
throw new \OutOfBoundsException('Mock queue is empty');
}

$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 = clone $request->getQuery();
$parameterString->replace($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();
uksort($params, 'strcmp');

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 ($this->getCommandFactory() && $this->getCommandFactory() instanceof CompositeFactory) {
$this->commandFactory->add(new Command\Factory\ServiceDescriptionFactory($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);
} elseif ($type == 'string' && gettype($value) == 'array') {
$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 {

 foreach ($diff as $prop) {
$this->errors[] = sprintf('%s[%s] is not an allowed property', $path, $prop);
}
}
}
}


 
 
 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)
{
$errors = null;
set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
$errors[] = array(
'message' => $msg,
'file' => $file,
'line' => $line
);
return true;
});
$resource = call_user_func($callback);
restore_error_handler();

if (!$resource) {
$message = 'Error creating resource. ';
foreach ($errors as $err) {
foreach ($err as $key => $value) {
$message .= "[$key] $value" . PHP_EOL;
}
}
throw new RuntimeException(trim($message));
}

return $resource;
}
}
<?php

namespace Guzzle\Stream;

use Guzzle\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 (!$stream->feof()) {
hash_update($ctx, $stream->read(8192));
}

$out = hash_final($ctx, (bool) $rawOutput);
$stream->seek($pos);

return $out;
}

public function getMetaData($key = null)
{
$meta = stream_get_meta_data($this->stream);

return !$key ? $meta : (array_key_exists($key, $meta) ? $meta[$key] : null);
}

public function getStream()
{
return $this->stream;
}

public function setStream($stream, $size = null)
{
if (!is_resource($stream)) {
throw new InvalidArgumentException('Stream must be a resource');
}

$this->size = $size;
$this->stream = $stream;
$this->rebuildCache();

return $this;
}

public function detachStream()
{
$this->stream = null;

return $this;
}

public function getWrapper()
{
return $this->cache[self::WRAPPER_TYPE];
}

public function getWrapperData()
{
return $this->getMetaData('wrapper_data') ?: array();
}

public function getStreamType()
{
return $this->cache[self::STREAM_TYPE];
}

public function getUri()
{
return $this->cache['uri'];
}

public function getSize()
{
if ($this->size !== null) {
return $this->size;
}


 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 null;
}
}
<?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 = (string) ($file['path'] ?: $file['name']);

if (false === strpos($absolutePath, $root)) {
return null;
}

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 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'
);
}






protected function execute(InputInterface $input, OutputInterface $output)
{
$stopwatch = new Stopwatch();
$stopwatch->start(__CLASS__);

$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)
->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 $srcDir;






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 setSrcDir($srcDir)
{
$this->srcDir = $srcDir;

return $this;
}






public function getSrcDir()
{
return $this->srcDir;
}

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\Yaml\Yaml;






class Configurator
{












public function load($coverallsYmlPath, $rootDir)
{
$yml = $this->parse($coverallsYmlPath);
$options = $this->process($yml);

return $this->createConfiguration($options, $rootDir);
}












protected function parse($coverallsYmlPath)
{
$file = new Path();
$path = realpath($coverallsYmlPath);

if ($file->isRealFileReadable($path)) {
$yml = Yaml::parse($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)
{
$configuration = new Configuration();
$file = new Path();

$repoToken = $options['repo_token'];
$repoSecretToken = $options['repo_secret_token'];

return $configuration
->setRepoToken($repoToken !== null ? $repoToken : $repoSecretToken)
->setServiceName($options['service_name'])

 ->setSrcDir($this->ensureSrcDir($options['src_dir'], $rootDir, $file))
->setRootDir($rootDir)
->setCloverXmlPaths($this->ensureCloverXmlPaths($options['coverage_clover'], $rootDir, $file))
->setJsonPath($this->ensureJsonPath($options['json_path'], $rootDir, $file))
->setExcludeNoStatements($options['exclude_no_stmt']);
}












protected function ensureSrcDir($option, $rootDir, Path $file)
{

 $realpath = $file->getRealPath($option, $rootDir);


 if (!$file->isRealDirExist($realpath)) {
throw new InvalidConfigurationException(sprintf('src directory %s is not found', $realpath));
}

return $realpath;
}












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()


 ->scalarNode('src_dir')
->defaultValue('src')
->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;






public function getHelpMessage()
{
$message = $this->message . "\n";

if (isset($this->readEnv) && is_array($this->readEnv)) {
foreach ($this->readEnv as $envVarName => $value) {
$message .= sprintf("  - %s=%s\n", $envVarName, var_export($value, true));
}
}

$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 null;
}








public function setAuthorName($authorName)
{
$this->authorName = $authorName;

return $this;
}






public function getAuthorName()
{
if (isset($this->authorName)) {
return $this->authorName;
}

return null;
}








public function setAuthorEmail($authorEmail)
{
$this->authorEmail = $authorEmail;

return $this;
}






public function getAuthorEmail()
{
if (isset($this->authorEmail)) {
return $this->authorEmail;
}

return null;
}








public function setCommitterName($committerName)
{
$this->committerName = $committerName;

return $this;
}






public function getCommitterName()
{
if (isset($this->committerName)) {
return $this->committerName;
}

return null;
}








public function setCommitterEmail($committerEmail)
{
$this->committerEmail = $committerEmail;

return $this;
}






public function getCommitterEmail()
{
if (isset($this->committerEmail)) {
return $this->committerEmail;
}

return null;
}








public function setMessage($message)
{
$this->message = $message;

return $this;
}






public function getMessage()
{
if (isset($this->message)) {
return $this->message;
}

return null;
}
}
<?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 null;
}








public function setUrl($url)
{
$this->url = $url;

return $this;
}






public function getUrl()
{
if (isset($this->url)) {
return $this->url;
}

return null;
}
}
<?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 null;
}








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 null;
}








public function setRepoToken($repoToken)
{
$this->repoToken = $repoToken;

return $this;
}






public function getRepoToken()
{
if (isset($this->repoToken)) {
return $this->repoToken;
}

return null;
}








public function setServiceJobId($serviceJobId)
{
$this->serviceJobId = $serviceJobId;

return $this;
}






public function getServiceJobId()
{
if (isset($this->serviceJobId)) {
return $this->serviceJobId;
}

return null;
}






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 null;
}








public function setRunAt($runAt)
{
$this->runAt = $runAt;

return $this;
}






public function getRunAt()
{
if (isset($this->runAt)) {
return $this->runAt;
}

return null;
}






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)
{
try {
$body = $response->json();

if (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']));
}
}
} catch (\Guzzle\Common\Exception\RuntimeException $e) {

 $body = $response->getBody(true);

if ($body) {
$this->logger->error($body);
}
}
}










public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle;






final class Version
{





const VERSION = '0.7.0-dev';
}
<?php
namespace Satooshi\Component\File;






class Path
{







public function isRelativePath($path)
{
return strlen($path) === 0 || 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











































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;




public function __construct($header = "--- Original\n+++ New\n")
{
$this->header = $header;
}









public function diff($from, $to, LongestCommonSubsequence $lcs = null)
{
$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) {
$buffer .= "@@ @@\n";
$newChunk = false;
}

if ($diff[$i][1] === 1 ) {
$buffer .= '+' . $diff[$i][0] . "\n";
} elseif ($diff[$i][1] === 2 ) {
$buffer .= '-' . $diff[$i][0] . "\n";
} else {
$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();
$matrix = array();
$fromLength = count($from);
$toLength = count($to);

for ($i = 0; $i <= $fromLength; ++$i) {
$matrix[$i][0] = 0;
}

for ($j = 0; $j <= $toLength; ++$j) {
$matrix[0][$j] = 0;
}

for ($i = 1; $i <= $fromLength; ++$i) {
for ($j = 1; $j <= $toLength; ++$j) {
$matrix[$i][$j] = max(
$matrix[$i-1][$j],
$matrix[$i][$j-1],
$from[$i-1] === $to[$j-1] ? $matrix[$i-1][$j-1] + 1 : 0
);
}
}

$i = $fromLength;
$j = $toLength;

while ($i > 0 && $j > 0) {
if ($from[$i-1] === $to[$j-1]) {
array_unshift($common, $from[$i-1]);
--$i;
--$j;
} elseif ($matrix[$i][$j-1] > $matrix[$i-1][$j]) {
--$j;
} else {
--$i;
}
}

return $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 {
$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();

while (count($lines)) {
while (!preg_match('(^@@\\s+-(?P<start>\\d+)(?:,\\s*(?P<startrange>\\d+))?\\s+\\+(?P<end>\\d+)(?:,\\s*(?P<endrange>\\d+))?\\s+@@)', $last = array_shift($lines), $match)) {
if ($last === null) {
break 2;
}
}

$chunk = new Chunk(
$match['start'],
isset($match['startrange']) ? max(1, $match['startrange']) : 1,
$match['end'],
isset($match['endrange']) ? max(1, $match['endrange']) : 1
);

$diffLines = array();
$last = null;

while (count($lines) &&
(preg_match('(^(?P<type>[+ -])?(?P<line>.*))', $last = array_shift($lines), $match) ||
(strpos($last, '\\ No newline at end of file') === 0))) {
if (count($match)) {
$type = Line::UNCHANGED;

if ($match['type'] == '+') {
$type = Line::ADDED;
} elseif ($match['type'] == '-') {
$type = Line::REMOVED;
}

$diffLines[] = new Line($type, $match['line']);
}
}

$chunk->setLines($diffLines);

$chunks[] = $chunk;

if ($last !== null) {
array_unshift($lines, $last);
}
}

$diff->setChunks($chunks);
}
}
<?php



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

return ComposerAutoloaderInitc6248fbec04c2ab212eb18aa1bad6c1b::getLoader();
<?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();
}
}

$i = 0;
foreach ($linesWithPlaceholder as $group) {
if (1 === count($group)) {
continue;
}
++$i;
$rightmostSymbol = 0;

foreach ($group as $index) {
$rightmostSymbol = max($rightmostSymbol, strpos($lines[$index], $placeholder));
}

foreach ($group as $index) {
$line = $lines[$index];
$currentSymbol = strpos($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;




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\Config;

use Symfony\CS\ConfigInterface;
use Symfony\CS\Finder\DefaultFinder;
use Symfony\CS\FinderInterface;
use Symfony\CS\FixerInterface;





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)
{
$this->dir = $dir;
}

public function setUsingCache($usingCache)
{
$this->usingCache = $usingCache;

return $this;
}

public function setUsingLinter($usingLinter)
{
$this->usingLinter = $usingLinter;

return $this;
}

public function getDir()
{
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 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\Config;

use Symfony\CS\Finder\MagentoFinder;




class MagentoConfig extends Config
{
public function __construct()
{
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()
{
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;




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;








class ConfigurationResolver
{
protected $allFixers;
protected $config;
protected $fixers = array();
protected $options = array(
'fixers' => null,
'level' => null,
'progress' => null,
);

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();

return $this;
}






public function getFixers()
{
return $this->fixers;
}

public function getProgress()
{
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 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 \InvalidArgumentException(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();
}
}

return;
}

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();
}

return;
}
}
<?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>';
$commit = '81a46f8a0f92f1ba64587b384a275d0766cf2c70';

if ('@'.'git-commit@' !== $commit) {
$version .= ' ('.substr($commit, 0, 7).')';
}

return $version;
}
}
<?php










namespace Symfony\CS\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
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\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
{





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 directory:

    <info>php %command.full_name% /path/to/dir</info>
    <info>php %command.full_name% /path/to/file</info>

The <comment>--verbose</comment> option show applied fixers. When using ``txt`` format (default one) it will also displays progress notification.

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\DefaultFinder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('strict_param', 'short_array_syntax'))
        ->finder(\$finder)
    ;

    ?>

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\DefaultFinder::create()
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\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\DefaultFinder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\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\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\Config::create()
        ->setUsingCache(true)
    ;

    ?>
EOF
);
}




protected function execute(InputInterface $input, OutputInterface $output)
{
$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) {
if (is_file($path) && $dirName = pathinfo($path, PATHINFO_DIRNAME)) {
$configDir = $dirName;
} elseif ($stdin || null === $path) {
$configDir = getcwd();

 } else {
$configDir = $path;
}
$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 \InvalidArgumentException(sprintf('The configuration "%s" is not defined', $input->getOption('config')));
}
} elseif (file_exists($configFile)) {
$config = include $configFile;

 if (!$config instanceof Config) {
throw new \UnexpectedValueException(sprintf('The config file "%s" does not return an instance of Symfony\CS\Config\Config', $configFile));
}

if ('txt' === $input->getOption('format')) {
$output->writeln(sprintf('Loaded config from "%s"', $configFile));
}
} else {
$config = $this->defaultConfig;
}

if ($config->usingLinter()) {
$this->fixer->setLintManager(new LintManager());
}

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);
}


 $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' => $output->isVerbose() && 'txt' === $input->getOption('format'),
))
->resolve();

$config->fixers($resolver->getFixers());
$showProgress = $resolver->getProgress();

if ($showProgress) {
$fileProcessedEventListener = function (FixerFileProcessedEvent $event) use ($output) {
$output->write($event->getStatusAsString());
};

$this->fixer->setEventDispatcher($this->eventDispatcher);
$this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
}

$this->stopwatch->start('fixFiles');
$changed = $this->fixer->fix($config, $input->getOption('dry-run'), $input->getOption('diff'));
$this->stopwatch->stop('fixFiles');

if ($showProgress) {
$this->fixer->setEventDispatcher(null);
$this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
$output->writeln('');

$legend = array();
foreach (FixerFileProcessedEvent::getStatusMap() as $status) {
if ($status['symbol'] && $status['description']) {
$legend[] = $status['symbol'].'-'.$status['description'];
}
}

$output->writeln('Legend: '.implode(', ', array_unique($legend)));
}

$verbosity = $output->getVerbosity();
$i = 1;

switch ($input->getOption('format')) {
case 'txt':
foreach ($changed as $file => $fixResult) {
$output->write(sprintf('%4d) %s', $i++, $file));

if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$output->write(sprintf(' (<comment>%s</comment>)', implode(', ', $fixResult['appliedFixers'])));
}

if ($input->getOption('diff')) {
$output->writeln('');
$output->writeln('<comment>      ---------- begin diff ----------</comment>');
$output->writeln($fixResult['diff']);
$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('Fixed all files in %.3f seconds, %.3f MB memory used', $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 ($input->getOption('diff')) {
$diffXML = $dom->createElement('diff');
$diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
$fileXML->appendChild($diffXML);
}
}

$fixEvent = $this->stopwatch->getEvent('fixFiles');

$timeXML = $dom->createElement('time');
$memoryXML = $dom->createElement('memory');
$dom->appendChild($timeXML);
$dom->appendChild($memoryXML);

$memoryXML->setAttribute('value', round($fixEvent->getMemory() / 1024 / 1024, 3));
$memoryXML->setAttribute('unit', 'MB');

$timeXML->setAttribute('unit', 's');
$timeTotalXML = $dom->createElement('total');
$timeTotalXML->setAttribute('value', round($fixEvent->getDuration() / 1000, 3));
$timeXML->appendChild($timeTotalXML);

if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
$timeFilesXML = $dom->createElement('files');
$timeXML->appendChild($timeFilesXML);
$eventCounter = 1;

foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
if ('__section__' === $file) {
continue;
}

$timeFileXML = $dom->createElement('file');
$timeFilesXML->appendChild($timeFileXML);
$timeFileXML->setAttribute('id', $eventCounter++);
$timeFileXML->setAttribute('name', $file);
$timeFileXML->setAttribute('value', round($event->getDuration() / 1000, 3));
}
}

$dom->formatOutput = true;
$output->write($dom->saveXML());
break;
case 'json':
$jFiles = array();

foreach ($changed as $file => $fixResult) {
$jfile = array('name' => $file);

if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$jfile['appliedFixers'] = $fixResult['appliedFixers'];
}

if ($input->getOption('diff')) {
$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));
break;
default:
throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
}

if (!$this->errorsManager->isEmpty()) {
$output->writeLn('');
$output->writeLn('Files that were not fixed due to internal error:');

foreach ($this->errorsManager->getErrors() as $i => $error) {
$output->writeLn(sprintf('%4d) %s', $i + 1, $error['filepath']));
}
}

return empty($changed) ? 0 : 1;
}

protected function getFixersHelp()
{
$help = '';
$maxName = 0;
$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());
}
);

foreach ($fixers as $fixer) {
if (strlen($fixer->getName()) > $maxName) {
$maxName = strlen($fixer->getName());
}
}

$count = count($fixers) - 1;
foreach ($fixers as $i => $fixer) {
$chunks = explode("\n", wordwrap(sprintf("[%s]\n%s", $this->fixer->getLevelAsString($fixer), $fixer->getDescription()), 72 - $maxName, "\n"));
$help .= sprintf(" * <comment>%s</comment>%s %s\n", $fixer->getName(), str_repeat(' ', $maxName - strlen($fixer->getName())), array_shift($chunks));
while ($c = array_shift($chunks)) {
$help .= str_repeat(' ', $maxName + 4).$c."\n";
}

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.

If you are already using ``PHP_CodeSniffer`` to identify coding standards
problems in your code, you know that fixing them by hand is tedious, especially
on large projects. This tool does the job 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 http://get.sensiolabs.org/php-cs-fixer.phar -O php-cs-fixer

or with curl:

.. code-block:: bash

    \$ curl http://get.sensiolabs.org/php-cs-fixer.phar -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 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 fabpot/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:

* `Vim`_
* `Sublime Text`_
* `NetBeans`_
* `PhpStorm`_

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: http://get.sensiolabs.org/php-cs-fixer.phar
.. _Vim:               https://github.com/stephpy/vim-php-cs-fixer
.. _Sublime Text:      https://github.com/benmatselby/sublime-phpcs
.. _NetBeans:          http://plugins.netbeans.org/plugin/49042/php-cs-fixer
.. _PhpStorm:          http://arnolog.net/post/92715936483/use-fabpots-php-cs-fixer-tool-in-phpstorm-in-2-steps
.. _contribute:        https://github.com/FriendsOfPhp/php-cs-fixer/blob/master/CONTRIBUTING.md

EOF;

$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( +<\?php)#m", ".. code-block:: php\n\n$1", $help);
$help = preg_replace_callback(
"#<\?php.*?\?>#s",
function ($matches) {
return preg_replace("#\n\n +\?>#", '', preg_replace("#^\.\. code-block:: bash\n\n#m", '', $matches[0]));
},
$help
);
$help = preg_replace('#^                        #m', '  ', $help);
$help = preg_replace('#\*\* +\[#', '** [', $help);

$output->write($header."\n".$help."\n".$footer);
}
}
<?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 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;
}

if (false !== $remoteVersion = @file_get_contents('http://get.sensiolabs.org/php-cs-fixer.version')) {
if ($this->getApplication()->getVersion() === $remoteVersion) {
$output->writeln('<info>php-cs-fixer is already up to date.</info>');

return;
}
}

$remoteFilename = 'http://get.sensiolabs.org/php-cs-fixer.phar';
$localFilename = $_SERVER['argv'][0];
$tempFilename = basename($localFilename, '.phar').'-tmp.phar';

if (false === @file_get_contents($remoteFilename)) {
$output->writeln('<error>Unable to download new versions from the server.</error>');

return 1;
}

try {
copy($remoteFilename, $tempFilename);
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;
}
}
}
<?php










namespace Symfony\CS\DocBlock;






class Annotation
{







private $lines;






private $tag;






public function __construct(array $lines)
{
$this->lines = $lines;
}






public function getStart()
{
$keys = array_keys($this->lines);

return $keys[0];
}






public function getEnd()
{
$keys = array_keys($this->lines);

return end($keys);
}






public function getTag()
{
if (null === $this->tag) {
$values = array_values($this->lines);
$this->tag = new Tag($values[0]->getContent());
}

return $this->tag;
}




public function remove()
{
foreach ($this->lines as $line) {
$line->remove();
}
}






public function getContent()
{
return implode($this->lines);
}






public function __toString()
{
return $this->getContent();
}
}
<?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 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;
}

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;
}








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);
}






public function __toString()
{
return $this->getContent();
}
}
<?php










namespace Symfony\CS\DocBlock;






class Line
{





private $content;






public function __construct($content)
{
$this->content = $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";
}






public function __toString()
{
return $this->content;
}
}
<?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', 'return', 'see', 'since', 'struct', 'subpackage', 'throws',
'todo', 'typedef', 'uses', 'var', 'version',
);






private $name;






public function __construct($content)
{
preg_match_all('/@[a-zA-Z0-9_]+/', $content, $matches);

if (isset($matches[0][0])) {
$this->name = strtolower(ltrim($matches[0][0], '@'));
} else {
$this->name = 'other';
}
}








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('package', 'subpackage'),
);









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;






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;















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 (!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,
)
);

file_put_contents($this->dir.self::CACHE_FILE, $data, LOCK_EX);
}
}
<?php










namespace Symfony\CS\Finder;

use Symfony\Component\Finder\Finder;
use Symfony\CS\FinderInterface;




class DefaultFinder extends Finder implements FinderInterface
{
public function __construct()
{
parent::__construct();

$files = $this->getFilesToExclude();

$this
->files()
->name('*.php')
->name('*.twig')
->name('*.xml')
->name('*.yml')
->ignoreDotFiles(true)
->ignoreVCS(true)
->exclude('vendor')
->filter(
function (\SplFileInfo $file) use ($files) {
return !in_array($file->getRelativePathname(), $files, true);
}
)
;
}

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 MagentoFinder extends DefaultFinder
{
public function __construct()
{
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
{
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;




interface FinderInterface
{
public function setDir($dir);
}
<?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);

return $this->replacePlaceholder($tokens, $this->deepestLevel);
}




public function getDescription()
{
return 'Align double arrow symbols in consecutive lines.';
}










private function injectAlignmentPlaceholders(Tokens $tokens, $startAt = null, $endAt = null)
{
if (empty($startAt)) {
$startAt = 0;
}

if (empty($endAt)) {
$endAt = count($tokens);
}

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->deepestLevel;
++$this->currentLevel;
$this->injectAlignmentPlaceholders($tokens, $from, $until);
--$this->currentLevel;
continue;
}

if ($token->equals('[')) {
$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->deepestLevel;
++$this->currentLevel;
$this->injectAlignmentPlaceholders($tokens, $from + 1, $until - 1);
--$this->currentLevel;
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(',')) {
do {
++$index;
$token = $tokens[$index];
} while (false === strpos($token->getContent(), "\n"));
}
}
}
}
<?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)
{
list($tokens, $deepestLevel) = $this->injectAlignmentPlaceholders($content);

return $this->replacePlaceholder($tokens, $deepestLevel);
}




public function getDescription()
{
return 'Align equals symbols in consecutive lines.';
}








private function injectAlignmentPlaceholders($content)
{
$deepestLevel = 0;
$parenCount = 0;
$bracketCount = 0;
$tokens = Tokens::fromCode($content);

foreach ($tokens as $token) {
$tokenContent = $token->getContent();

if ($token->equals('=') && 0 === $parenCount && 0 === $bracketCount) {
$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, $deepestLevel);
}
}
<?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) {
$token = $tokens[$index];

if ($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 'Concatenation should be used with at least one whitespace around.';
}




public function getPriority()
{

 return -10;
}
}
<?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\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;




class HeaderCommentFixer extends AbstractFixer
{
private static $header = '';
private static $headerComment = '';










public static function setHeader($header)
{
self::$header = trim((string) $header);

if (strlen(self::$header)) {
self::$headerComment = self::encloseTextInComment(self::$header);
} else {
self::$headerComment = '';
}
}




public static function getHeader()
{
return self::$header;
}




public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);

if (!$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 .= " */\n";

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 = Tokens::fromArray(
array(
new Token(array(T_WHITESPACE, "\n")),
new Token(array(T_COMMENT, self::$headerComment)),
new Token(array(T_WHITESPACE, strlen(self::$headerComment) ? "\n" : '')),
)
);

$tokens->insertAt($index, $headCommentTokens);
}
}
<?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\AbstractLinesBeforeNamespaceFixer;
use Symfony\CS\Tokenizer\Tokens;




class NoBlankLinesBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{



public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);

foreach (array_keys($tokens->findGivenKind(T_NAMESPACE)) as $index) {
$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\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];


 $nspIndex = $tokens->getPrevTokenOfKind($index, array(array(T_NAMESPACE, 'namespace')));
if (null !== $nspIndex) {
$nspIndex = $tokens->getNextMeaningfulToken($nspIndex);


 if (!$tokens[$nspIndex]->equals('{')) {

 $nspIndex = $tokens->getNextMeaningfulToken($nspIndex);

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\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);

$token->clear();
$tokens[$openIndex]->setContent('[');
$tokens[$closeIndex]->setContent(']');
}

return $tokens->generateCode();
}




public function getDescription()
{
return 'PHP arrays should use the PHP 5.4 short-syntax.';
}
}
<?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 $token) {
$tokenId = $token->getId();

if (isset($map[$tokenId])) {
$token->override(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.';
}




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 StrictParamFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{
static $map = null;

if (null === $map) {
$token = array(
'true' => new Token(array(T_STRING, 'true')),
'null' => new Token(array(T_STRING, 'null')),
);

$map = array(
'in_array' => array(null, null, $token['true']),
'base64_decode' => array(null, $token['true']),
'array_search' => array(null, null, $token['true']),
'array_keys' => array(null, null, $token['true']),
'mb_detect_encoding' => array(null, array(new Token(array(T_STRING, 'mb_detect_order')), new Token('('), new Token(')')), $token['true']),
);
}

$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\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[$index]->setContent('(');
$tokens[$closeIndex]->setContent(')');
$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;




class NewlineAfterOpenTagFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);


 if (!$tokens->isMonolithicPhp()) {
return $content;
}


 if (!$tokens[0]->isGivenKind(T_OPEN_TAG)) {
return $content;
}

$newlineFound = false;
foreach ($tokens as $token) {
if ($token->isWhitespace(array('whitespaces' => "\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\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;





class OrderedUseFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);

$namespacesImports = $tokens->getImportUseIndexes(true);
$usesOrder = array();

if (!count($namespacesImports)) {
return $content;
}

foreach ($namespacesImports as $uses) {
$uses = array_reverse($uses);
$usesOrder = array_replace($usesOrder, $this->getNewOrder($uses, $tokens));
}


 
 foreach ($usesOrder as $use) {
$tokens->clearRange($use[1], $use[2]);
}

$usesOrder = array_reverse($usesOrder, true);


 foreach ($usesOrder as $index => $use) {
$declarationTokens = Tokens::fromCode('<?php use '.$use[0].';');
$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 -10;
}









public static function sortingCallBack(array $first, array $second)
{
$a = trim(preg_replace('%/\*(.*)\*/%s', '', $first[0]));
$b = trim(preg_replace('%/\*(.*)\*/%s', '', $second[0]));


 $a = str_replace('\\', ' ', $a);
$b = str_replace('\\', ' ', $b);

return strcasecmp($a, $b);
}

private function getNewOrder(array $uses, Tokens $tokens)
{
$uses = array_reverse($uses);

$indexes = array();
$originalIndexes = array();

foreach ($uses as $index) {
$endIndex = $tokens->getNextTokenOfKind($index, array(';'));
$startIndex = $tokens->getTokenNotOfKindSibling($index + 1, 1, array(array(T_WHITESPACE)));

$namespace = '';
$index = $startIndex;

while ($index <= $endIndex) {
$token = $tokens[$index];
if ($token->equals(',') || $index === $endIndex) {
$indexes[$startIndex] = array($namespace, $startIndex, $index - 1);
$originalIndexes[] = $startIndex;

$namespace = '';
$nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, array(array(','), array(T_WHITESPACE)));
$startIndex = $nextPartIndex;
$index = $nextPartIndex;

continue;
}

$namespace .= $token->getContent();
++$index;
}
}

uasort($indexes, 'self::sortingCallBack');

$i = -1;

$usesOrder = array();


 foreach ($indexes as $v) {
$usesOrder[$originalIndexes[++$i]] = $v;
}

return $usesOrder;
}
}
<?php










namespace Symfony\CS\Fixer\PSR0;

use Symfony\CS\AbstractFixer;
use Symfony\CS\ConfigAwareInterface;
use Symfony\CS\ConfigInterface;
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->getNextNonWhitespace($index);
$namespaceEndIndex = $tokens->getNextTokenOfKind($index, array(';'));

$namespace = trim($tokens->generatePartialCode($namespaceIndex, $namespaceEndIndex - 1));
} elseif ($token->isClassy()) {
if (null !== $classyName) {
return $content;
}

$classyIndex = $tokens->getNextNonWhitespace($index);
$classyName = $tokens[$classyIndex]->getContent();
}
}

if (null === $classyName) {
return $content;
}

if (false !== $namespace) {
$normNamespace = strtr($namespace, '\\', '/');
$path = strtr($file->getRealPath(), '\\', '/');
$dir = dirname($path);

if ($this->config) {
$dir = substr($dir, strlen(realpath($this->config->getDir())) + 1);
if (strlen($normNamespace) > strlen($dir)) {
if (strlen($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)).strtr($dir, '/', '\\');

$newNamespace = Tokens::fromCode('<?php namespace '.$namespace.';');
$newNamespace[0]->clear();
$newNamespace[1]->clear();
$newNamespace[2]->clear();

$tokens->insertAt($namespaceIndex, $newNamespace);
}
} else {
$normClass = strtr($classyName, '_', '/');
$path = strtr($file->getRealPath(), '\\', '/');
$filename = substr($path, -strlen($normClass) - 4, -4);

if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) {
$tokens[$classyIndex]->setContent(strtr($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)
{
$filenameParts = explode('.', $file->getBasename(), 2);

if (!isset($filenameParts[1]) || 'php' !== $filenameParts[1]) {
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 (!$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.';
}
}
<?php










namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;






class BracesFixer extends AbstractFixer
{



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);
$this->fixLambdas($tokens);

return $tokens->generateCode();
}




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)) {
continue;
}

$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
$afterParenthesisIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
$afterParenthesisToken = $tokens[$afterParenthesisIndex];

if (!$afterParenthesisToken->isComment()) {
continue;
}

$afterCommentIndex = $tokens->getNextMeaningfulToken($afterParenthesisIndex);
$afterCommentToken = $tokens[$afterCommentIndex];

if (!$afterCommentToken->equals('{')) {
continue;
}

$tokenTmp = $tokens[$afterCommentIndex];
$tokens[$afterCommentIndex - 1]->setContent(rtrim($tokens[$afterCommentIndex - 1]->getContent()));

for ($i = $afterCommentIndex; $i > $afterParenthesisIndex; --$i) {
$tokens[$i] = $tokens[$i - 1];
}

$tokens[$afterParenthesisIndex] = $tokenTmp;
}
}

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->isLambda($index)) {
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('}') && $tokens[$nestIndex - 1]->equalsAny(array('"', "'", array(T_CONSTANT_ENCAPSED_STRING))))
) {
if ($nextNonWhitespaceNestToken->isGivenKind($this->getControlContinuationTokens())) {
$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);
} elseif (!$tokens[$index]->isClassy()) {
$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.'    ');
}
} else {
$nextToken = $tokens[$startBraceIndex + 1];
if ($nextToken->isWhitespace(array('whitespaces' => " \t")) || !$nextToken->isWhitespace()) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, "\n".$indent.'    ');
}
}

if ($token->isGivenKind($classyTokens)) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, "\n".$indent);
} elseif ($token->isGivenKind(T_FUNCTION)) {
$closingParenthesisIndex = $tokens->getPrevTokenOfKind($startBraceIndex, array(')'));
$prevToken = $tokens[$closingParenthesisIndex - 1];

if ($prevToken->isWhitespace() && false !== strpos($prevToken->getContent(), "\n")) {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
} else {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, "\n".$indent);
}
} else {
$tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
}


 $limit = count($tokens);
}
}

private function fixLambdas(Tokens $tokens)
{
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];

if (!$token->isGivenKind(T_FUNCTION) || !$tokens->isLambda($index)) {
continue;
}

$nextIndex = $tokens->getNextTokenOfKind($index, array('{'));

$tokens->ensureWhitespaceAtIndex($nextIndex - 1, 1, ' ');
}
}

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->removeTrailingWhitespace($parenthesisEndIndex);
$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($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)
{
static $goBackTokens = array(T_ABSTRACT, T_FINAL, T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC);

$token = $tokens[$index];

if ($token->isGivenKind($goBackTokens) || $token->isClassy() || $token->isGivenKind(T_FUNCTION)) {
$prevIndex = $tokens->getPrevNonWhitespace($index);
$prevToken = $tokens[$prevIndex];

if ($prevToken->isGivenKind($goBackTokens)) {
return $this->detectIndent($tokens, $prevIndex);
}
}

$prevIndex = $index - 1;
$prevToken = $tokens[$prevIndex];

if ($prevToken->equals('}')) {
return $this->detectIndent($tokens, $prevIndex);
}


 if (!$prevToken->isWhitespace()) {
return '';
}

$explodedContent = explode("\n", $prevToken->getContent());


 if (1 === count($explodedContent)) {
if ($tokens[$index - 2]->equals('}')) {
return $this->detectIndent($tokens, $index - 2);
}
}

return end($explodedContent);
}

private function findParenthesisEnd(Tokens $tokens, $structureTokenIndex)
{
$nextIndex = $tokens->getNextNonWhitespace($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->getNextNonWhitespace($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->getNextNonWhitespace($endIndex);
$nextToken = $tokens[$nextIndex];
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();
}
}
<?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->findGivenKind(T_ELSE) as $index => $token) {
$nextIndex = $tokens->getNextNonWhitespace($index);
$nextToken = $tokens[$nextIndex];


 if (!$nextToken->isGivenKind(T_IF)) {
continue;
}


 
 $tokens[$index + 1]->clear();


 $token->override(array(T_ELSEIF, 'elseif', $token->getLine()));


 $nextToken->clear();
}


 
 if (defined('HHVM_VERSION')) {
foreach ($tokens->findGivenKind(T_ELSEIF) as $token) {
$token->setContent('elseif');
}
}

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;




class EofEndingFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{


$content = rtrim($content);

if (strlen($content)) {
return $content."\n";
}

return $content;
}




public function getDescription()
{
return 'A file must always end with an empty line feed.';
}




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 FunctionCallSpaceFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);

$functionyTokens = $this->getFunctionyTokens();

foreach ($tokens as $index => $token) {

 if (!$token->equals('(')) {
continue;
}


 $lastTokenIndex = $tokens->getPrevNonWhitespace($index);

if (null === $lastTokenIndex) {
continue;
}


 if ($tokens[$lastTokenIndex]->isGivenKind($functionyTokens)) {
$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 getFunctionyTokens()
{
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_STRING, 
 T_UNSET,
);
}

return $tokens;
}
}
<?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('('));
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, array(';', '{'));
$startBraceToken = $tokens[$startBraceIndex];

if ($startBraceToken->equals('{')) {

 
 
 if (
!$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);

for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];

if (T_NAMESPACE === $token->getId()) {
$semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
$semicolonToken = $tokens[$semicolonIndex];

if (!$semicolonToken->equals(';') || !isset($tokens[$semicolonIndex + 1])) {
continue;
}

$nextToken = $tokens[$semicolonIndex + 1];

if (!$nextToken->isWhitespace()) {
$tokens->insertAt($semicolonIndex + 1, new Token(array(T_WHITESPACE, "\n\n")));
} else {
$nextToken->setContent("\n\n".ltrim($nextToken->getContent()));
}
}
}

return $tokens->generateCode();
}




public function getDescription()
{
return 'There MUST be one blank line after the namespace declaration.';
}
}
<?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->getPrevNonWhitespace($index))
&&
$this->isNeighbourAccepted($tokens, $tokens->getNextNonWhitespace($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;
}
}

if (null === $index) {
return true;
}

$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(';'));
$declarationContent = $tokens->generatePartialCode($index + 1, $endIndex - 1);

$declarationParts = explode(',', $declarationContent);

if (1 === count($declarationParts)) {
continue;
}

$declarationContent = array();

foreach ($declarationParts as $declarationPart) {
$declarationContent[] = 'use '.trim($declarationPart).';';
}

$declarationContent = implode("\n".$this->detectIndent($tokens, $index), $declarationContent);

for ($i = $index; $i <= $endIndex; ++$i) {
$tokens[$i]->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\Token;
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);

foreach (array_reverse($closeTags, true) as $index => $token) {
$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 getPriority()
{

 return 5;
}




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) {

 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]);
} else {
$indent = '';
}

$newline = "\n";


 $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
$insertIndex = $semicolonIndex + 1;
if ($tokens[$insertIndex]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$insertIndex + 1]->isComment()) {
++$insertIndex;
}


 if ($tokens[$insertIndex]->isGivenKind(T_COMMENT)) {
$newline = '';
}


 if ($tokens[$insertIndex]->isComment()) {
++$insertIndex;
}

$afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
if (!$tokens[$afterSemicolon]->isGivenKind(T_USE)) {
$newline .= "\n";
}

if ($tokens[$insertIndex]->isWhitespace()) {
$nextToken = $tokens[$insertIndex];
$nextToken->setContent($newline.$indent.ltrim($nextToken->getContent()));
} else {
$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;






class TrailingSpacesFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{

 return preg_replace('/(?<=\S)[ \t]+$/m', '', $content);
}




public function getDescription()
{
return 'Remove trailing whitespace at the end of non-blank lines.';
}




public function getPriority()
{
return 20;
}
}
<?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;




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('.')) {
if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isGivenKind(T_LNUMBER)) {
$tokens->removeLeadingWhitespace($index, $whitespaces);
}

if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind(T_LNUMBER)) {
$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\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 arounded 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);
$limit = $tokens->count();

for ($index = 0; $index < $limit; ++$index) {
$token = $tokens[$index];


 if ($token->isGivenKind(T_FOR)) {
$index = $tokens->getNextMeaningfulToken($index);
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}

if (!$token->equals(';')) {
continue;
}

$prevIndex = $tokens->getPrevNonWhitespace($index);

if (!$tokens[$prevIndex]->equals(';')) {
continue;
}

$tokens->removeLeadingWhitespace($index);
$token->clear();
}

return $tokens->generateCode();
}




public function getDescription()
{
return 'Remove duplicated semicolons.';
}




public function getPriority()
{

 return 10;
}
}
<?php










namespace Symfony\CS\Fixer\Symfony;

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".';
}









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' === $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\Symfony;

use Symfony\CS\AbstractFixer;
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 $token) {
$content = '';
$count = 0;
$parts = explode("\n", $token->getContent());

for ($i = 0, $last = count($parts) - 1; $i <= $last; ++$i) {
if ('' === $parts[$i]) {

 ++$count;
} else {
$count = 0;
$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 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 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->equals(';')) {
$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->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(';')),
);

$nextTokenIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextTokenIndex];

if ($nextToken->equals('(')) {

 
 $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextTokenIndex);

if ($tokens[$tokens->getNextMeaningfulToken($braceCloseIndex)]->equals(';')) {
$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\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->setContent('');
} 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)
{
return strlen($str) > 0 && ctype_space(substr($str, -1));
}
}
<?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)
{
$tokens = Tokens::fromCode($content);

for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];

if (!$token->isGivenKind(T_NEW)) {
continue;
}

$nextIndex = $tokens->getNextTokenOfKind($index, array(';', ',', '(', ')', '[', ']', ':'));
$nextToken = $tokens[$nextIndex];


 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;
}

$meaningBeforeNextIndex = $tokens->getPrevNonWhitespace($nextIndex);

$tokens->insertAt($meaningBeforeNextIndex + 1, array(new Token('('), new Token(')')));
}

return $tokens->generateCode();
}




public function getDescription()
{
return 'All instances created with new keyword must be followed by braces.';
}
}
<?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();
}






private function fixWhitespace(Token $token)
{
$content = $token->getContent();

 if (substr_count($content, "\n") > 1) {

 $lines = Utils::splitLines($content);
$token->setContent("\n".end($lines));
}
}




public function getDescription()
{
return 'There should be no empty lines after class opening brace.';
}
}
<?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;





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() - 1; $index >= 0; --$index) {
$token = $tokens[$index];

if (!$this->isOperator($token)) {
continue;
}

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 'Operators should be arounded by at least one space.';
}

private function isOperator(Token $token)
{
static $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, 
 );

static $nonArrayOperators = array(
'=' => true,
);

return $token->isArray() ? isset($arrayOperators[$token->getId()]) : isset($nonArrayOperators[$token->getContent()]);
}
}
<?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->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\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\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;




class PhpdocNoPackageFixer 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(array('package', 'subpackage'));


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

foreach ($annotations as $annotation) {
$annotation->remove();
}

$token->setContent($doc->getContent());
}

return $tokens->generateCode();
}




public function getDescription()
{
return '@package and @subpackage annotations should be omitted from phpdocs.';
}




public function getPriority()
{

 return 10;
}
}
<?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 = '/^ {5}\* @(?:'.$paramTag.'|'.$otherTags.')'.$desc.'$/';
$this->regexCommentLine = '/^ {5}\*(?:\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 -10;
}






private function fixDocBlock($content)
{
$lines = Utils::splitLines($content);

$l = count($lines);

for ($i = 0; $i < $l; ++$i) {
$items = array();

if ($matches = $this->getMatches($lines[$i])) {
$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['desc']."\n";
continue;
}
$line =
'     *  '
.str_repeat(' ', ($tagMax + $hintMax + $varMax + ('param' === $currTag ? 3 : 2)))
.$item['desc']."\n";

$lines[$current + $j] = $line;

continue;
}

$currTag = $item['tag'];

$line =
'     * @'
.$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\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 < $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 < $final; ++$pos) {
$doc->getLine($pos)->remove();
}
}
}
<?php










namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
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, '.!?Â¡Â¿');
}
}
<?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('}')) {
$token->override(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(T_OPEN_TAG)) {
continue;
}

$token->override(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);

if (!$tokens[$nextIndex]->equals('=')) {
return false;
}

return false !== strpos($docsToken->getContent(), $tokens[$variableIndex]->getContent());
}










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 fist 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 ($line->containsUsefulContent() || $total - $index < 3) {
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 ($line->containsUsefulContent() || $total - $index < 3) {
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->findGivenKind(T_DOC_COMMENT) as $token) {
$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.';
}
}
<?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('var', 'type'));

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

foreach ($annotations as $annotation) {
$this->fixLine($doc->getLine($annotation->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 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(';'));
$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.';
}
}
<?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 (array_keys($tokens->findGivenKind(T_NAMESPACE)) as $index) {
$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 SpacesBeforeSemicolonFixer 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(array('whitespaces' => " \t")) && !$tokens[$index - 2]->isComment()) {
$previous->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(' '));
}
}
}

return $tokens->generateCode();
}




public function getDescription()
{
return 'A single space should be between cast and variable.';
}
}
<?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->ensureWhitespaceExistance($tokens, $index + 1, true);
}


 $this->ensureWhitespaceExistance($tokens, $index - 1, false);

continue;
}

if ($ternaryLevel && $token->equals(':')) {

 $this->ensureWhitespaceExistance($tokens, $index + 1, true);

$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];

if (!$prevNonWhitespaceToken->equals('?')) {

 $this->ensureWhitespaceExistance($tokens, $index - 1, false);
}

--$ternaryLevel;
}
}

return $tokens->generateCode();
}




public function getDescription()
{
return 'Standardize spaces around ternary operator.';
}

private function ensureWhitespaceExistance(Tokens $tokens, $index, $after)
{
$indexChange = $after ? 0 : 1;
$token = $tokens[$index];

if ($token->isWhitespace()) {
return;
}

$tokens->insertAt($index + $indexChange, new Token(array(T_WHITESPACE, ' ', $token->getLine())));
}
}
<?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);

$namespaceDeclarations = $this->getNamespaceDeclarations($tokens);
$useDeclarationsIndexes = $tokens->getImportUseIndexes();
$useDeclarations = $this->getNamespaceUseDeclarations($tokens, $useDeclarationsIndexes);
$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 getPriority()
{

 return -10;
}




public function supports(\SplFileInfo $file)
{

 if (false !== strpos($file, DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR)) {
return false;
}

return true;
}




public function getDescription()
{
return 'Unused use statements must be removed.';
}

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 (T_NAMESPACE !== $token->getId()) {
continue;
}

$declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));

$namespaces[] = array(
'end' => $declarationEndIndex,
'name' => trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)),
'start' => $index,
);
}

return $namespaces;
}

private function getNamespaceUseDeclarations(Tokens $tokens, array $useIndexes)
{
$uses = array();

foreach ($useIndexes as $index) {
$declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';'));
$declarationContent = $tokens->generatePartialCode($index + 1, $declarationEndIndex - 1);


 
 if (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 {
$fullName = $declarationParts[0];
$shortName = $declarationParts[1];
$declarationParts = explode('\\', $fullName);
$aliased = $shortName !== end($declarationParts);
}

$shortName = trim($shortName);

$uses[$shortName] = array(
'aliased' => $aliased,
'end' => $declarationEndIndex,
'fullName' => trim($fullName),
'shortName' => $shortName,
'start' => $index,
);
}

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['start']; $index <= $useDeclaration['end']; ++$index) {
$tokens[$index]->clear();
}

$token = $tokens[$useDeclaration['start'] - 1];

if ($token->isWhitespace()) {
$token->setContent(rtrim($token->getContent(), " \t"));
}

if (!isset($tokens[$useDeclaration['end'] + 1])) {
return;
}

$token = $tokens[$useDeclaration['end'] + 1];

if ($token->isWhitespace()) {
$content = ltrim($token->getContent(), " \t");

if ($content && "\n" === $content[0]) {
$content = substr($content, 1);
}

$token->setContent($content);
}
}

private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, array $namespaceDeclarations)
{
if (empty($namespaceDeclarations)) {
return;
}


 if (count($namespaceDeclarations) > 1) {
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;




class WhitespacyLinesFixer extends AbstractFixer
{



public function fix(\SplFileInfo $file, $content)
{
return preg_replace('/^\h+$/m', '', $content);
}




public function getDescription()
{
return 'Remove trailing whitespace at the end of blank lines.';
}
}
<?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->isMonolithicPhp()) {
return $content;
}


 if (!$tokens[0]->isGivenKind(T_OPEN_TAG)) {
return $content;
}

$newlineFound = false;
foreach ($tokens as $token) {
if ($token->isWhitespace(array('whitespaces' => "\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(array('whitespaces' => "\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.';
}
}
<?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\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;
use Symfony\CS\Tokenizer\Tokens;




class PhpdocScalarFixer extends AbstractFixer
{





private static $tags = array('param', 'return', 'type', 'var');






private static $types = array(
'integer' => 'int',
'boolean' => 'bool',
'real' => 'float',
'double' => '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 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(self::$tags);

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

foreach ($annotations as $annotation) {
$this->fixScalars($doc->getLine($annotation->getStart()), $annotation->getTag()->getName());
}

$token->setContent($doc->getContent());
}

return $tokens->generateCode();
}









private function fixScalars(Line $line, $tag)
{
$content = $line->getContent();
$tagSplit = preg_split('/\s*\@'.$tag.'\s*/', $content);
$spaceSplit = preg_split('/\s/', $tagSplit[1]);
$usefulContent = $spaceSplit[0];

if (strpos($usefulContent, '|') !== false) {
$newContent = implode('|', self::normalizeTypes(explode('|', $usefulContent)));
} else {
$newContent = self::normalizeType($usefulContent);
}

if ($newContent !== $usefulContent) {

 
 
 $line->setContent(preg_replace('/'.preg_quote($usefulContent).'/', $newContent, $content, 1));
}
}








private static function normalizeTypes(array $types)
{
foreach ($types as $index => $type) {
$types[$index] = self::normalizeType($type);
}

return $types;
}








private static function normalizeType($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\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, "'") &&
false === strpos($content, '\\')
) {
$token->setContent("'".substr($content, 1, -1)."'");
}
}

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\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];

if ($nextToken->isWhitespace($whitespaceOptions)) {
$nextToken->clear();
}

$prevToken = $tokens[$endIndex - 1];
$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($endIndex)];

if (
$prevToken->isWhitespace($whitespaceOptions)
&& !$prevNonWhitespaceToken->equals(',')

 && !($prevNonWhitespaceToken->isComment() && $prevNonWhitespaceToken->getContent() !== rtrim($prevNonWhitespaceToken->getContent()))
) {
$prevToken->clear();
}
}
}
<?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;

public function __destruct()
{
if ($this->temporaryFile) {
unlink($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 (!$this->temporaryFile) {
$this->temporaryFile = tempnam('.', 'tmp');
}

file_put_contents($this->temporaryFile, $source);
$process = $this->createProcessForFile($this->temporaryFile);

return $process;
}
}
#!/usr/bin/env php
<?php










if (version_compare(phpversion(), '5.3.6', '<')) {
fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.3.6\n");
exit(1);
}

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;

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 Token ? $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 = array();
$keywordsStrings = 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',
);

foreach ($keywordsStrings as $keywordName) {
if (defined($keywordName)) {
$keyword = constant($keywordName);
$keywords[$keyword] = $keyword;
}
}
}

return $keywords;
}






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 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())
{
$whitespaces = isset($opts['whitespaces']) ? $opts['whitespaces'] : " \t\n\r\0\x0B";

if ($this->isArray && !$this->isGivenKind(T_WHITESPACE)) {
return false;
}

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)
{
$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);
}
}
<?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->findGivenKind(T_CLASS) as $index => $token) {
$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;











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("No custom token was found for $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("Trying to register token $name ($value), token with this value was already defined: ".$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\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;






private static $cache = array();






private $codeHash;






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);
}
}

return;
}









public static function fromArray($array, $saveIndexes = null)
{
$tokens = new Tokens(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 = crc32($code);

if (self::hasCache($codeHash)) {
$tokens = self::getCache($codeHash);


 $tokens->generateCode();

if ($codeHash === $tokens->codeHash) {
$tokens->clearEmptyTokens();

return $tokens;
}
}

$tokens = token_get_all($code);

foreach ($tokens as $index => $tokenPrototype) {
$tokens[$index] = new Token($tokenPrototype);
}

$collection = self::fromArray($tokens);
$transformers = Transformers::create();
$transformers->transform($collection);
$collection->changeCodeHash($codeHash);

return $collection;
}






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, '}'),
),
);
}








private static function getCache($key)
{
if (!self::hasCache($key)) {
throw new \OutOfBoundsException('Unknown cache key: '.$key);
}

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








private static function hasCache($key)
{
return isset(self::$cache[$key]);
}








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);
}







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);
}






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->isGivenKind(array(T_COMMENT, T_DOC_COMMENT))) {
$content = $token->getContent();

if ("\n" === $content[strlen($content) - 1]) {
$token->setContent(substr($content, 0, -1));
}
}
};

$token = $this[$index];

if ($token->isWhitespace()) {
$removeLastCommentLine($this[$index - 1], $indexOffset);
$token->override(array(T_WHITESPACE, $whitespace, $token->getLine()));

return false;
}

$removeLastCommentLine($token, $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('Invalid param $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('Invalid param $startIndex - not a proper block start');
}

$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('Missing block end');
}

return $index;
}








public function findGivenKind($possibleKind)
{
$this->rewind();

$elements = array();
$possibleKinds = is_array($possibleKind) ? $possibleKind : array($possibleKind);

foreach ($possibleKinds as $kind) {
$elements[$kind] = array();
}

foreach ($this as $index => $token) {
if ($token->isGivenKind($possibleKinds)) {
$elements[$token->getId()][$index] = $token;
}
}

return is_array($possibleKind) ? $elements : $elements[$possibleKind];
}






public function generateCode()
{
$code = $this->generatePartialCode(0, count($this) - 1);
$this->changeCodeHash(crc32($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 (T_VARIABLE === $token->getId() && 0 === $bracesLevel) {
$elements[$index] = array('token' => $token, 'type' => 'property');
continue;
}

if (T_FUNCTION === $token->getId()) {
$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 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('Non-meaningful token at position: '.$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[$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) &&
false !== strpos($token->getContent(), "\n") &&
!$this[$index - 1]->isGivenKind(T_END_HEREDOC)
) {
return true;
}
}

return false;
}








public function isLambda($index)
{
$token = $this[$index];

if (!$token->isGivenKind(T_FUNCTION)) {
throw new \LogicException('No T_FUNCTION at given index');
}

$nextIndex = $this->getNextMeaningfulToken($index);
$nextToken = $this[$nextIndex];


 if ($nextToken->equals('&')) {
$nextIndex = $this->getNextMeaningfulToken($nextIndex);
$nextToken = $this[$nextIndex];
}

if (!$nextToken->equals('(')) {
return false;
}

$endParenthesisIndex = $this->findBlockEnd(self::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);

$nextIndex = $this->getNextMeaningfulToken($endParenthesisIndex);
$nextToken = $this[$nextIndex];

if (!$nextToken->equalsAny(array('{', array(T_USE)))) {
return false;
}

return true;
}








public function isShortArray($index)
{
static $disallowedPrevTokens = array(
']',
'}',
')',
'"',
array(T_CONSTANT_ENCAPSED_STRING),
array(T_STRING),
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 offsetExists($index)
{
return $index >= 0 && parent::offsetExists($index);
}







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 = 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 __clone()
{
foreach ($this as $key => $val) {
$this[$key] = clone $val;
}
}







public function clearRange($indexStart, $indexEnd)
{
for ($i = $indexStart; $i <= $indexEnd; ++$i) {
$this[$i]->clear();
}
}









public function isMonolithicPhp()
{
$kinds = $this->findGivenKind(array(T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_INLINE_HTML));




$hhvmOpenTagsWithEcho = array();
$hhvmHashBangs = array();

if (defined('HHVM_VERSION')) {





$hhvmEchoes = $this->findGivenKind(T_ECHO);
foreach ($hhvmEchoes as $token) {
if (0 === strpos($token->getContent(), '<?=')) {
$hhvmOpenTagsWithEcho[] = $token;
}
}








$tokens = Tokens::fromCode("#!/usr/bin/env php\n");
if (!$tokens[0]->isGivenKind(T_INLINE_HTML)) {
$hashBangId = $tokens[0]->getId();
$hhvmHashBangs = $this->findGivenKind($hashBangId);
}
}

return 0 === count($kinds[T_INLINE_HTML]) + count($hhvmHashBangs) && 1 === count($kinds[T_OPEN_TAG]) + count($kinds[T_OPEN_TAG_WITH_ECHO]) + count($hhvmOpenTagsWithEcho);
}
}
<?php










namespace Symfony\CS;






class ToolInfo
{
const COMPOSER_INSTALLED_FILE = '/../../composer/installed.json';
const COMPOSER_PACKAGE_NAME = 'fabpot/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;
}

private static function getScriptDir()
{
static $result;

if (null === $result) {
$script = $_SERVER['SCRIPT_NAME'];

if (is_link($script)) {
$script = dirname($script).'/'.readlink($script);
}

$result = dirname($script);
}

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;
}
}
<?php










namespace Symfony\CS;

use SebastianBergmann\Diff\Differ;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo as FinderSplFileInfo;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\CS\Tokenizer\Tokens;





class Fixer
{
const VERSION = '1.6';

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 (Finder::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($fixers)
{
foreach ($fixers as $fixer) {
$this->addFixer($fixer);
}
}

public function addFixer(FixerInterface $fixer)
{
$this->fixers[] = $fixer;
}

public function getFixers()
{
$this->sortFixers();

return $this->fixers;
}

public function registerBuiltInConfigs()
{
foreach (Finder::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);
$changed = array();

if ($this->stopwatch) {
$this->stopwatch->openSection();
}

$fileCacheManager = new FileCacheManager($config->usingCache(), $config->getDir(), $config->getFixers());

foreach ($config->getFinder() as $file) {
if ($file->isDir() || $file->isLink()) {
continue;
}

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 (\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;
}

private function getFileRelativePathname(\SplFileInfo $file)
{
if ($file instanceof FinderSplFileInfo) {
return $file->getRelativePathname();
}

return $file->getPathname();
}

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';
}

protected function stringDiff($old, $new)
{
$diff = $this->diff->diff($old, $new);

$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, $diff)
)
);

return $diff;
}

private function sortFixers()
{
usort($this->fixers, function (FixerInterface $a, FixerInterface $b) {
return Utils::cmpInt($b->getPriority(), $a->getPriority());
});
}

private function prepareFixers(ConfigInterface $config)
{
$fixers = $config->getFixers();

foreach ($fixers as $fixer) {
if ($fixer instanceof ConfigAwareInterface) {
$fixer->setConfig($config);
}
}

return $fixers;
}






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;
}
}
<?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;

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('The given token must be whitespace.');
}

return ltrim(strrchr(str_replace(array("\r\n", "\r"), "\n", $token->getContent()), 10), "\n");
}
}
Copyright (c) 2012-2015 Fabien Potencier

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
˜íÊŒ‹3ˆà
h~ØTC—?O	   GBMB