#!/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.
 */

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(); ?>
S0  ‰               #   vendor/sebastian/diff/src/Chunk.php&  ÛÂÚR&  JS­8¶      "   vendor/sebastian/diff/src/Diff.phpý  ÛÂÚRý  Z�û†¶      $   vendor/sebastian/diff/src/Differ.phpÔ  ÛÂÚRÔ  @áõÃ¶      "   vendor/sebastian/diff/src/Line.php­  ÛÂÚR­  pÎQ÷¶      $   vendor/sebastian/diff/src/Parser.php+  ÛÂÚR+  Þ&¶      &   vendor/sebastian/diff/src/autoload.phpÒ  ÛÂÚRÒ  ¨
$ý¶      '   vendor/composer/autoload_namespaces.phpq  ÛÂÚRq  }�è¬¶      !   vendor/composer/autoload_psr4.phpd   ÛÂÚRd   Z¡¦H¶      %   vendor/composer/autoload_classmap.php+K  ÛÂÚR+K  	õÑÒ¶      !   vendor/composer/autoload_real.phpK  ÛÂÚRK  Ãgb¶         vendor/composer/ClassLoader.php—  ÛÂÚR—  B§†0¶      H   vendor/symfony/console/Symfony/Component/Console/Command/HelpCommand.php1  ÛÂÚR1  ý€”¶      H   vendor/symfony/console/Symfony/Component/Console/Command/ListCommand.php³  ÛÂÚR³  VÓé¶      D   vendor/symfony/console/Symfony/Component/Console/Command/Command.php  ÛÂÚR  OÝ‚¶      B   vendor/symfony/console/Symfony/Component/Console/ConsoleEvents.phpé   ÛÂÚRé   RÛÔe¶      V   vendor/symfony/console/Symfony/Component/Console/Descriptor/ApplicationDescription.php÷  ÛÂÚR÷  )Ißð¶      J   vendor/symfony/console/Symfony/Component/Console/Descriptor/Descriptor.phpZ  ÛÂÚRZ  v;ƒö¶      S   vendor/symfony/console/Symfony/Component/Console/Descriptor/DescriptorInterface.phpü   ÛÂÚRü   ±Qµ¶      N   vendor/symfony/console/Symfony/Component/Console/Descriptor/JsonDescriptor.php0  ÛÂÚR0  FÄ`¶      R   vendor/symfony/console/Symfony/Component/Console/Descriptor/MarkdownDescriptor.php  ÛÂÚR  ?¨Ðz¶      N   vendor/symfony/console/Symfony/Component/Console/Descriptor/TextDescriptor.php›  ÛÂÚR›  õ#a‘¶      M   vendor/symfony/console/Symfony/Component/Console/Descriptor/XmlDescriptor.phpž  ÛÂÚRž  Ò‘¦j¶      N   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleCommandEvent.phpt   ÛÂÚRt   ˜J”í¶      G   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleEvent.phpÅ  ÛÂÚRÅ  ÒxÛ\¶      P   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleExceptionEvent.php  ÛÂÚR  á2é¶      P   vendor/symfony/console/Symfony/Component/Console/Event/ConsoleTerminateEvent.phpz  ÛÂÚRz  ³,îL¶      N   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatter.php   ÛÂÚR   }×í)¶      W   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterInterface.php˜  ÛÂÚR˜  3l~´¶      S   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyle.phpU  ÛÂÚRU  z¨Üí¶      \   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleInterface.phpŽ  ÛÂÚRŽ  öëÄ=¶      X   vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleStack.php  ÛÂÚR  yI'¶      L   vendor/symfony/console/Symfony/Component/Console/Helper/DescriptorHelper.php9  ÛÂÚR9  ûùäð¶      H   vendor/symfony/console/Symfony/Component/Console/Helper/DialogHelper.php¾  ÛÂÚR¾  ºï™é¶      K   vendor/symfony/console/Symfony/Component/Console/Helper/FormatterHelper.php  ÛÂÚR  žI‚�¶      B   vendor/symfony/console/Symfony/Component/Console/Helper/Helper.php"  ÛÂÚR"  ¨äU¶      K   vendor/symfony/console/Symfony/Component/Console/Helper/HelperInterface.phpï   ÛÂÚRï   =e¶      E   vendor/symfony/console/Symfony/Component/Console/Helper/HelperSet.php/  ÛÂÚR/  âw d¶      L   vendor/symfony/console/Symfony/Component/Console/Helper/InputAwareHelper.phpc  ÛÂÚRc  ñø�|¶      G   vendor/symfony/console/Symfony/Component/Console/Helper/TableHelper.php�  ÛÂÚR�  5èN©¶      J   vendor/symfony/console/Symfony/Component/Console/Helper/ProgressHelper.php"  ÛÂÚR"  ÎÍ6[¶      D   vendor/symfony/console/Symfony/Component/Console/Input/ArgvInput.phpÅ  ÛÂÚRÅ  �'ä¶      E   vendor/symfony/console/Symfony/Component/Console/Input/ArrayInput.php÷	  ÛÂÚR÷	  à"9¶      @   vendor/symfony/console/Symfony/Component/Console/Input/Input.php
  ÛÂÚR
  Û©êª¶      H   vendor/symfony/console/Symfony/Component/Console/Input/InputArgument.phpž  ÛÂÚRž  K]ìi¶      N   vendor/symfony/console/Symfony/Component/Console/Input/InputAwareInterface.phpš   ÛÂÚRš   ‡jTŸ¶      J   vendor/symfony/console/Symfony/Component/Console/Input/InputDefinition.php…  ÛÂÚR…  $~¨E¶      I   vendor/symfony/console/Symfony/Component/Console/Input/InputInterface.php   ÛÂÚR   9”øÇ¶      F   vendor/symfony/console/Symfony/Component/Console/Input/InputOption.phpª  ÛÂÚRª  âõþ1¶      F   vendor/symfony/console/Symfony/Component/Console/Input/StringInput.php�  ÛÂÚR�  Ä]th¶      J   vendor/symfony/console/Symfony/Component/Console/Output/BufferedOutput.php_  ÛÂÚR_  ûBÍ·¶      I   vendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutput.php	  ÛÂÚR	  q‚9ž¶      R   vendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutputInterface.phpå   ÛÂÚRå   rNô ¶      F   vendor/symfony/console/Symfony/Component/Console/Output/NullOutput.php  ÛÂÚR  ³(Š÷¶      B   vendor/symfony/console/Symfony/Component/Console/Output/Output.php§  ÛÂÚR§  Ú _¶      K   vendor/symfony/console/Symfony/Component/Console/Output/OutputInterface.phpI  ÛÂÚRI  ÈâãB¶      H   vendor/symfony/console/Symfony/Component/Console/Output/StreamOutput.phpª  ÛÂÚRª  ²ø¶      :   vendor/symfony/console/Symfony/Component/Console/Shell.php1  ÛÂÚR1  ®Þ$û¶      M   vendor/symfony/console/Symfony/Component/Console/Tester/ApplicationTester.phpÔ  ÛÂÚRÔ  ¬ì¤d¶      I   vendor/symfony/console/Symfony/Component/Console/Tester/CommandTester.php�  ÛÂÚR�  H»â`¶      @   vendor/symfony/console/Symfony/Component/Console/Application.php´L  ÛÂÚR´L  ¸@ˆš¶      W   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/ExceptionInterface.phpk   ÛÂÚRk   €Ûèà¶      Z   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/FileNotFoundException.php¼  ÛÂÚR¼  pí\¶¶      P   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/IOException.php‰  ÛÂÚR‰  Ö0ÿn¶      Y   vendor/symfony/filesystem/Symfony/Component/Filesystem/Exception/IOExceptionInterface.php¦   ÛÂÚR¦   jÙwM¶      E   vendor/symfony/filesystem/Symfony/Component/Filesystem/Filesystem.php¶"  ÛÂÚR¶"  XD2K¶      J   vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractAdapter.php§
  ÛÂÚR§
  þn†¶      N   vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractFindAdapter.php  ÛÂÚR  ·YËü¶      K   vendor/symfony/finder/Symfony/Component/Finder/Adapter/AdapterInterface.php¯  ÛÂÚR¯  ‹éÈ¶      I   vendor/symfony/finder/Symfony/Component/Finder/Adapter/BsdFindAdapter.php{  ÛÂÚR{  Q,D2¶      I   vendor/symfony/finder/Symfony/Component/Finder/Adapter/GnuFindAdapter.php^  ÛÂÚR^  ßz˜r¶      E   vendor/symfony/finder/Symfony/Component/Finder/Adapter/PhpAdapter.php+  ÛÂÚR+  &˜îÒ¶      H   vendor/symfony/finder/Symfony/Component/Finder/Comparator/Comparator.phpŒ  ÛÂÚRŒ  wþT¶      L   vendor/symfony/finder/Symfony/Component/Finder/Comparator/DateComparator.php&  ÛÂÚR&  éhd±¶      N   vendor/symfony/finder/Symfony/Component/Finder/Comparator/NumberComparator.phpy  ÛÂÚRy  "`Û¶      R   vendor/symfony/finder/Symfony/Component/Finder/Exception/AccessDeniedException.php„   ÛÂÚR„   ½¾sœ¶      T   vendor/symfony/finder/Symfony/Component/Finder/Exception/AdapterFailureException.php  ÛÂÚR  mŒ_,¶      O   vendor/symfony/finder/Symfony/Component/Finder/Exception/ExceptionInterface.php„   ÛÂÚR„   Gz-¶      Z   vendor/symfony/finder/Symfony/Component/Finder/Exception/OperationNotPermitedException.phpŠ   ÛÂÚRŠ   U88¶      Y   vendor/symfony/finder/Symfony/Component/Finder/Exception/ShellCommandFailureException.php$  ÛÂÚR$  C”sÓ¶      H   vendor/symfony/finder/Symfony/Component/Finder/Expression/Expression.php}  ÛÂÚR}  /·cð¶      B   vendor/symfony/finder/Symfony/Component/Finder/Expression/Glob.php¡  ÛÂÚR¡    V¿¶      C   vendor/symfony/finder/Symfony/Component/Finder/Expression/Regex.phpZ  ÛÂÚRZ  @�²~¶      L   vendor/symfony/finder/Symfony/Component/Finder/Expression/ValueInterface.php;  ÛÂÚR;  îãÓ¶      7   vendor/symfony/finder/Symfony/Component/Finder/Glob.php  ÛÂÚR  z�ø
¶      P   vendor/symfony/finder/Symfony/Component/Finder/Iterator/CustomFilterIterator.php]  ÛÂÚR]  tà±µ¶      T   vendor/symfony/finder/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.phpð  ÛÂÚRð  ß0™¶      Z   vendor/symfony/finder/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php”  ÛÂÚR”  "ÖóÁ¶      M   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilePathsIterator.php�  ÛÂÚR�  ýòäQ¶      R   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FileTypeFilterIterator.php\  ÛÂÚR\  p‘'˜¶      U   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilecontentFilterIterator.php#  ÛÂÚR#  Ú_VÇ¶      R   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilenameFilterIterator.phpˆ  ÛÂÚRˆ  êBƒZ¶      J   vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilterIterator.php†  ÛÂÚR†  0£¾Ô¶      V   vendor/symfony/finder/Symfony/Component/Finder/Iterator/MultiplePcreFilterIterator.phpØ  ÛÂÚRØ  Òù“¶      N   vendor/symfony/finder/Symfony/Component/Finder/Iterator/PathFilterIterator.phpÁ  ÛÂÚRÁ  _ÜA¶      V   vendor/symfony/finder/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.phpÜ  ÛÂÚRÜ  ª½éú¶      S   vendor/symfony/finder/Symfony/Component/Finder/Iterator/SizeRangeFilterIterator.phpg  ÛÂÚRg  !Ô—é¶      L   vendor/symfony/finder/Symfony/Component/Finder/Iterator/SortableIterator.phpÞ  ÛÂÚRÞ  ’”Ç¶      S   vendor/symfony/finder/Symfony/Component/Finder/Iterator/DateRangeFilterIterator.phpg  ÛÂÚRg  °Ée ¶      @   vendor/symfony/finder/Symfony/Component/Finder/Shell/Command.php©
  ÛÂÚR©
  V‚„j¶      >   vendor/symfony/finder/Symfony/Component/Finder/Shell/Shell.php¢  ÛÂÚR¢  D…A
¶      >   vendor/symfony/finder/Symfony/Component/Finder/SplFileInfo.phpû  ÛÂÚRû  ‘†6¶      9   vendor/symfony/finder/Symfony/Component/Finder/Finder.phpÊ   ÛÂÚRÊ   Œþéˆ¶         vendor/autoload.php‘   ÛÂÚR‘   tˆiÝ¶         Symfony/CS/Config/Config.php“  ÛÂÚR“  -Ð%À¶      #   Symfony/CS/Config/MagentoConfig.phpj  ÛÂÚRj  ;äL¶      %   Symfony/CS/Config/Symfony23Config.phpo  ÛÂÚRo  9Æ7µ¶      #   Symfony/CS/ConfigAwareInterface.php†   ÛÂÚR†   —¿ ¶         Symfony/CS/ConfigInterface.php„  ÛÂÚR„  s/W«¶      )   Symfony/CS/Console/Command/FixCommand.phpU'  ÛÂÚRU'  ¬Ee¶      ,   Symfony/CS/Console/Command/ReadmeCommand.phpî  ÛÂÚRî  ìKþÆ¶      0   Symfony/CS/Console/Command/SelfUpdateCommand.php{  ÛÂÚR{  èÐCË¶      "   Symfony/CS/Console/Application.php  ÛÂÚR  …è˜¶      #   Symfony/CS/Finder/DefaultFinder.phpÝ  ÛÂÚRÝ  ìŒ3¼¶      #   Symfony/CS/Finder/MagentoFinder.phpŸ  ÛÂÚRŸ  gùÓ­¶      %   Symfony/CS/Finder/Symfony23Finder.php‰  ÛÂÚR‰  í:£¤¶         Symfony/CS/FinderInterface.phpf   ÛÂÚRf   «0¶         Symfony/CS/Fixer.phpÖ  ÛÂÚRÖ  ëI¢¶      '   Symfony/CS/Fixer/ControlSpacesFixer.phpÚ  ÛÂÚRÚ  Ø8¶      .   Symfony/CS/Fixer/CurlyBracketsNewlineFixer.phpƒ	  ÛÂÚRƒ	  |.•¶          Symfony/CS/Fixer/ElseifFixer.phpª  ÛÂÚRª  �Ych¶      +   Symfony/CS/Fixer/EndOfFileLineFeedFixer.phpi  ÛÂÚRi  VÄ?¶      )   Symfony/CS/Fixer/ExtraEmptyLinesFixer.phpu  ÛÂÚRu  Ó¡ø9¶      4   Symfony/CS/Fixer/FunctionDeclarationSpacingFixer.phpR  ÛÂÚRR  á~o¶      !   Symfony/CS/Fixer/IncludeFixer.php  ÛÂÚR  9Ò¶      %   Symfony/CS/Fixer/IndentationFixer.phpà  ÛÂÚRà  ðYáÀ¶      "   Symfony/CS/Fixer/LineFeedFixer.php5  ÛÂÚR5  6ÿ½Ä¶      '   Symfony/CS/Fixer/PhpClosingTagFixer.phpì  ÛÂÚRì  %û¶      /   Symfony/CS/Fixer/PhpdocParamsAlignmentFixer.phpæ
  ÛÂÚRæ
  .žÐÂ¶         Symfony/CS/Fixer/Psr0Fixer.phpN  ÛÂÚRN  ±q¶      *   Symfony/CS/Fixer/ReturnStatementsFixer.php¸  ÛÂÚR¸  
¾>Ã¶      "   Symfony/CS/Fixer/ShortTagFixer.php°  ÛÂÚR°  ÁíLe¶      (   Symfony/CS/Fixer/TrailingSpacesFixer.php<  ÛÂÚR<  (ê+¶      -   Symfony/CS/Fixer/UnusedUseStatementsFixer.php¯  ÛÂÚR¯  %½~¶      $   Symfony/CS/Fixer/VisibilityFixer.phpÐ  ÛÂÚRÐ  0«Ÿâ¶         Symfony/CS/FixerInterface.php£  ÛÂÚR£  §éà¶      "   Symfony/CS/Resources/phar-stub.phpö   ÛÂÚRö   ª�°¶         LICENSE)  ÛÂÚR)  ÈfcÎ¶      <?php











































namespace SebastianBergmann\Diff;









class Chunk
{
private $start;
private $startRange;
private $end;
private $endRange;
private $lines;

public function __construct($start = null, $startRange = 1, $end = null, $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;











class Differ
{



private $header;






public function __construct($header = "--- Original\n+++ New\n")
{
$this->header = $header;
}








public function diff($from, $to)
{
$buffer = $this->header;
$diff = $this->diffToArray($from,$to);

$inOld = FALSE;
$i = 0;
$old = array();

foreach ($diff as $line) {
if ($line[1] === 0 ) {
if ($inOld === FALSE) {
$inOld = $i;
}
}

else if ($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";
}

else if ($diff[$i][1] === 2 ) {
$buffer .= '-' . $diff[$i][0] . "\n";
}

else {
$buffer .= ' ' . $diff[$i][0] . "\n";
}
}

return $buffer;
}
















public function diffToArray($from, $to)
{
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;
}
}

$common = $this->longestCommonSubsequence(
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 longestCommonSubsequence(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;
}

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



spl_autoload_register(
function($class) {
static $classes = null;
if ($classes === null) {
$classes = array(
'sebastianbergmann\\diff\\chunk' => '/Chunk.php',
'sebastianbergmann\\diff\\diff' => '/Diff.php',
'sebastianbergmann\\diff\\differ' => '/Differ.php',
'sebastianbergmann\\diff\\line' => '/Line.php',
'sebastianbergmann\\diff\\parser' => '/Parser.php'
);
}
$cn = strtolower($class);
if (isset($classes[$cn])) {
require __DIR__ . $classes[$cn];
}
}
);
<?php



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

return array(
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Symfony\\CS' => array($baseDir . '/'),
);
<?php



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

return array(
);
<?php



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

return array(
'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\\Line' => $vendorDir . '/sebastian/diff/src/Line.php',
'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.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\\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\\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\\FixerInterface' => $baseDir . '/Symfony/CS/FixerInterface.php',
'Symfony\\CS\\Fixer\\ControlSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/ControlSpacesFixer.php',
'Symfony\\CS\\Fixer\\CurlyBracketsNewlineFixer' => $baseDir . '/Symfony/CS/Fixer/CurlyBracketsNewlineFixer.php',
'Symfony\\CS\\Fixer\\ElseifFixer' => $baseDir . '/Symfony/CS/Fixer/ElseifFixer.php',
'Symfony\\CS\\Fixer\\EndOfFileLineFeedFixer' => $baseDir . '/Symfony/CS/Fixer/EndOfFileLineFeedFixer.php',
'Symfony\\CS\\Fixer\\ExtraEmptyLinesFixer' => $baseDir . '/Symfony/CS/Fixer/ExtraEmptyLinesFixer.php',
'Symfony\\CS\\Fixer\\FunctionDeclarationSpacingFixer' => $baseDir . '/Symfony/CS/Fixer/FunctionDeclarationSpacingFixer.php',
'Symfony\\CS\\Fixer\\IncludeFixer' => $baseDir . '/Symfony/CS/Fixer/IncludeFixer.php',
'Symfony\\CS\\Fixer\\IndentationFixer' => $baseDir . '/Symfony/CS/Fixer/IndentationFixer.php',
'Symfony\\CS\\Fixer\\LineFeedFixer' => $baseDir . '/Symfony/CS/Fixer/LineFeedFixer.php',
'Symfony\\CS\\Fixer\\PhpClosingTagFixer' => $baseDir . '/Symfony/CS/Fixer/PhpClosingTagFixer.php',
'Symfony\\CS\\Fixer\\PhpdocParamsAlignmentFixer' => $baseDir . '/Symfony/CS/Fixer/PhpdocParamsAlignmentFixer.php',
'Symfony\\CS\\Fixer\\Psr0Fixer' => $baseDir . '/Symfony/CS/Fixer/Psr0Fixer.php',
'Symfony\\CS\\Fixer\\ReturnStatementsFixer' => $baseDir . '/Symfony/CS/Fixer/ReturnStatementsFixer.php',
'Symfony\\CS\\Fixer\\ShortTagFixer' => $baseDir . '/Symfony/CS/Fixer/ShortTagFixer.php',
'Symfony\\CS\\Fixer\\TrailingSpacesFixer' => $baseDir . '/Symfony/CS/Fixer/TrailingSpacesFixer.php',
'Symfony\\CS\\Fixer\\UnusedUseStatementsFixer' => $baseDir . '/Symfony/CS/Fixer/UnusedUseStatementsFixer.php',
'Symfony\\CS\\Fixer\\VisibilityFixer' => $baseDir . '/Symfony/CS/Fixer/VisibilityFixer.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\\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\\ProgressHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/ProgressHelper.php',
'Symfony\\Component\\Console\\Helper\\TableHelper' => $vendorDir . '/symfony/console/Symfony/Component/Console/Helper/TableHelper.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\\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\\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\\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\\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',
);
<?php



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

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

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

public function getPrefixes()
{
return call_user_func_array('array_merge', $this->prefixesPsr0);
}

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

return true;
}
}








public function findFile($class)
{

 if ('\\' == $class[0]) {
$class = substr($class, 1);
}


 if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}


 $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . '.php';

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

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


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


 if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}


 return $this->classMap[$class] = false;
}
}
<?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' => $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\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 $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('The command name cannot be empty.');
}
}






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






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 ($definition = $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 {
$width = $this->getColumnWidth($description->getCommands());

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

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 (version_compare(PHP_VERSION, '5.4', '<')) {
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
{
}
<?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
{



const FORMAT_PATTERN = '#(\\\\?)<(/?)([a-z][a-z0-9_=;-]*)?>((?: [^<\\\\]+ | (?!<(?:/?[a-z]|/>)). | .(?<=\\\\<) )*)#isx';

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








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









public function setStyle($name, OutputFormatterStyleInterface $style)
{
$this->styles[strtolower($name)] = $style;
}










public function hasStyle($name)
{
return isset($this->styles[strtolower($name)]);
}












public function getStyle($name)
{
if (!$this->hasStyle($name)) {
throw new \InvalidArgumentException(sprintf('Undefined style: %s', $name));
}

return $this->styles[strtolower($name)];
}










public function format($message)
{
$message = preg_replace_callback(self::FORMAT_PATTERN, array($this, 'replaceStyle'), $message);

return str_replace('\\<', '<', $message);
}




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










private function replaceStyle($match)
{

 if ('\\' === $match[1]) {
return $this->applyCurrentStyle($match[0]);
}

if ('' === $match[3]) {
if ('/' === $match[2]) {

 $this->styleStack->pop();

return $this->applyCurrentStyle($match[4]);
}


 return '<>'.$this->applyCurrentStyle($match[4]);
}

if (isset($this->styles[strtolower($match[3])])) {
$style = $this->styles[strtolower($match[3])];
} else {
$style = $this->createStyleFromString($match[3]);

if (false === $style) {
return $this->applyCurrentStyle($match[0]);
}
}

if ('/' === $match[2]) {
$this->styleStack->pop($style);
} else {
$this->styleStack->push($style);
}

return $this->applyCurrentStyle($match[4]);
}








private function createStyleFromString($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 {
$style->setOption($match[1]);
}
}

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' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
);
private static $availableBackgroundColors = array(
'black' => 40,
'red' => 41,
'green' => 42,
'yellow' => 43,
'blue' => 44,
'magenta' => 45,
'cyan' => 46,
'white' => 47
);
private static $availableOptions = array(
'bold' => 1,
'underscore' => 4,
'blink' => 5,
'reverse' => 7,
'conceal' => 8
);

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 (false === array_search(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)
{
$codes = array();

if (null !== $this->foreground) {
$codes[] = $this->foreground;
}
if (null !== $this->background) {
$codes[] = $this->background;
}
if (count($this->options)) {
$codes = array_merge($codes, $this->options);
}

if (0 === count($codes)) {
return $text;
}

return sprintf("\033[%sm%s\033[0m", implode(';', $codes), $text);
}
}
<?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;

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 ('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 (defined('PHP_WINDOWS_VERSION_BUILD')) {
$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)
{
$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();
foreach ($lines as $line) {
$messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
}
if ($large) {
$messages[] = str_repeat(' ', $len);
}

foreach ($messages as &$message) {
$message = sprintf('<%s>%s</%s>', $style, $message, $style);
}

return implode("\n", $messages);
}




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










namespace Symfony\Component\Console\Helper;






abstract class Helper implements HelperInterface
{
protected $helperSet = null;






public function setHelperSet(HelperSet $helperSet = null)
{
$this->helperSet = $helperSet;
}






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








protected function strlen($string)
{
if (!function_exists('mb_strlen')) {
return strlen($string);
}

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

return mb_strlen($string, $encoding);
}
}
<?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 InvalidArgumentException;






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






private $headers = array();






private $rows = array();


 private $paddingChar;
private $horizontalBorderChar;
private $verticalBorderChar;
private $crossingChar;
private $cellHeaderFormat;
private $cellRowFormat;
private $cellRowContentFormat;
private $borderFormat;
private $padType;






private $columnWidths = array();






private $numberOfColumns;




private $output;

public function __construct()
{
$this->setLayout(self::LAYOUT_DEFAULT);
}








public function setLayout($layout)
{
switch ($layout) {
case self::LAYOUT_BORDERLESS:
$this
->setPaddingChar(' ')
->setHorizontalBorderChar('=')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
->setCellHeaderFormat('<info>%s</info>')
->setCellRowFormat('%s')
->setCellRowContentFormat(' %s ')
->setBorderFormat('%s')
->setPadType(STR_PAD_RIGHT)
;
break;

case self::LAYOUT_COMPACT:
$this
->setPaddingChar(' ')
->setHorizontalBorderChar('')
->setVerticalBorderChar(' ')
->setCrossingChar('')
->setCellHeaderFormat('<info>%s</info>')
->setCellRowFormat('%s')
->setCellRowContentFormat('%s')
->setBorderFormat('%s')
->setPadType(STR_PAD_RIGHT)
;
break;

case self::LAYOUT_DEFAULT:
$this
->setPaddingChar(' ')
->setHorizontalBorderChar('-')
->setVerticalBorderChar('|')
->setCrossingChar('+')
->setCellHeaderFormat('<info>%s</info>')
->setCellRowFormat('%s')
->setCellRowContentFormat(' %s ')
->setBorderFormat('%s')
->setPadType(STR_PAD_RIGHT)
;
break;

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

return $this;
}

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(array $row)
{
$this->rows[] = array_values($row);

$keys = array_keys($this->rows);
$rowKey = array_pop($keys);

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 setPaddingChar($paddingChar)
{
if (!$paddingChar) {
throw new \LogicException('The padding char must not be empty');
}

$this->paddingChar = $paddingChar;

return $this;
}








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

return $this;
}








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

return $this;
}








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

return $this;
}








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

return $this;
}








public function setCellRowFormat($cellRowFormat)
{
$this->cellRowFormat = $cellRowFormat;

return $this;
}








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

return $this;
}








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

return $this;
}








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

return $this;
}















public function render(OutputInterface $output)
{
$this->output = $output;

$this->renderRowSeparator();
$this->renderRow($this->headers, $this->cellHeaderFormat);
if (!empty($this->headers)) {
$this->renderRowSeparator();
}
foreach ($this->rows as $row) {
$this->renderRow($row, $this->cellRowFormat);
}
if (!empty($this->rows)) {
$this->renderRowSeparator();
}

$this->cleanup();
}






private function renderRowSeparator()
{
if (0 === $count = $this->getNumberOfColumns()) {
return;
}

if (!$this->horizontalBorderChar && !$this->crossingChar) {
return;
}

$markup = $this->crossingChar;
for ($column = 0; $column < $count; $column++) {
$markup .= str_repeat($this->horizontalBorderChar, $this->getColumnWidth($column)).$this->crossingChar;
}

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




private function renderColumnSeparator()
{
$this->output->write(sprintf($this->borderFormat, $this->verticalBorderChar));
}









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_strlen') && false !== $encoding = mb_detect_encoding($cell)) {
$width += strlen($cell) - mb_strlen($cell, $encoding);
}

$width += $this->strlen($cell) - $this->computeLengthWithoutDecoration($cell);

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

$this->output->write(sprintf($cellFormat, str_pad($content, $width, $this->paddingChar, $this->padType)));
}






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

$columns = array(0);
$columns[] = 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(0);
$lengths[] = $this->getCellWidth($this->headers, $column);
foreach ($this->rows as $row) {
$lengths[] = $this->getCellWidth($row, $column);
}

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









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




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

private function computeLengthWithoutDecoration($string)
{
$formatter = $this->output->getFormatter();
$isDecorated = $formatter->isDecorated();
$formatter->setDecorated(false);

$string = $formatter->format($string);
$formatter->setDecorated($isDecorated);

return $this->strlen($string);
}




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










namespace Symfony\Component\Console\Helper;

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;
$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 = intval($this->current / $this->redrawFreq);

$this->current = $current;

$currPeriod = intval($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 = (double) $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\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 ($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) && 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 = (Boolean) $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;

if (!defined('JSON_UNESCAPED_UNICODE')) {
define('JSON_UNESCAPED_SLASHES', 64);
define('JSON_UNESCAPED_UNICODE', 256);
}

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




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

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 = (Boolean) $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\Console;

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









public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
{
$this->name = $name;
$this->version = $version;
$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 = 'list';
$input = new ArrayInput(array('command' => 'list'));
}


 $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()
{
$messages = array(
$this->getLongVersion(),
'',
'<comment>Usage:</comment>',
'  [options] command [arguments]',
'',
'<comment>Options:</comment>',
);

foreach ($this->getDefinition()->getOptions() as $option) {
$messages[] = sprintf('  %-29s %s %s',
'<info>--'.$option->getName().'</info>',
$option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : '  ',
$option->getDescription()
);
}

return implode(PHP_EOL, $messages);
}








public function setCatchExceptions($boolean)
{
$this->catchExceptions = (Boolean) $boolean;
}








public function setAutoExit($boolean)
{
$this->autoExit = (Boolean) $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[] = $this->extractNamespace($command->getName());

foreach ($command->getAliases() as $alias) {
$namespaces[] = $this->extractNamespace($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);
}

$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)
{
$strlen = function ($string) {
if (!function_exists('mb_strlen')) {
return strlen($string);
}

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

return mb_strlen($string, $encoding);
};

do {
$title = sprintf('  [%s]  ', get_class($e));
$len = $strlen($title);
$width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
$formatter = $output->getFormatter();
$lines = array();
foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
foreach (str_split($line, $width - 4) as $line) {

 $lineLength = $strlen(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 - $strlen($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 (defined('PHP_WINDOWS_VERSION_BUILD')) {

 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('dialog')) {
$inputStream = $this->getHelperSet()->get('dialog')->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);

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

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






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

 $source = fopen($originFile, 'r');
$target = fopen($targetFile, 'w');
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);
}
}
}









public function mkdir($dirs, $mode = 0777)
{
foreach ($this->toIterator($dirs) as $dir) {
if (is_dir($dir)) {
continue;
}

if (true !== @mkdir($dir, $mode, true)) {
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 (defined('PHP_WINDOWS_VERSION_MAJOR') && 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 (!function_exists('symlink') && $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 (defined('PHP_WINDOWS_VERSION_MAJOR') && 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 (defined('PHP_WINDOWS_VERSION_MAJOR')) {
$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']) && !function_exists('symlink')) {
$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);
}

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->getLinkTarget(), $target);
} elseif (is_dir($file)) {
$this->mkdir($target);
} elseif (is_file($file)) {
$this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
} else {
throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
}
}
}
}








public function isAbsolutePath($file)
{
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);
$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\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 = (Boolean) $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\Iterator\SortableIterator;
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() ? $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');
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 === '}')) {
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;























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;






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 (defined('PHP_WINDOWS_VERSION_MAJOR')) {
$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 {
return parent::getChildren();
} 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 callback 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\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 (!$fileinfo->isFile()) {
return true;
}

$filedate = $fileinfo->getMTime();
foreach ($this->comparators as $compare) {
if (!$compare->test($filedate)) {
return false;
}
}

return true;
}
}
<?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 === $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])) {
call_user_func($this->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 (self::TYPE_WINDOWS === $this->type) {

 return false;
}

if (!function_exists('exec')) {
return false;
}


 exec('command -v '.$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\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\Exception\ExceptionInterface;
















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(Adapter\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 = $this->ignore | static::IGNORE_DOT_FILES;
} else {
$this->ignore = $this->ignore & ~static::IGNORE_DOT_FILES;
}

return $this;
}












public function ignoreVCS($ignoreVCS)
{
if ($ignoreVCS) {
$this->ignore = $this->ignore | static::IGNORE_VCS_FILES;
} else {
$this->ignore = $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 = (Boolean) $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_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



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

return ComposerAutoloaderInitd7d2a434ae84b76ac837f264a1ca5197::getLoader();
<?php










namespace Symfony\CS\Config;

use Symfony\CS\FixerInterface;
use Symfony\CS\FinderInterface;
use Symfony\CS\ConfigInterface;
use Symfony\CS\Finder\DefaultFinder;




class Config implements ConfigInterface
{
protected $name;
protected $description;
protected $finder;
protected $fixers;
protected $dir;
protected $customFixers;

public function __construct($name = 'default', $description = 'A default configuration')
{
$this->name = $name;
$this->description = $description;
$this->fixers = FixerInterface::ALL_LEVEL;
$this->finder = new DefaultFinder();
$this->customFixers = array();
}

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

public function setDir($dir)
{
$this->dir = $dir;
}

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 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 addCustomFixer(FixerInterface $fixer)
{
$this->customFixers[] = $fixer;
}

public function getCustomFixers()
{
return $this->customFixers;
}
}
<?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 getFixers();






public function setDir($dir);






public function getDir();






public function addCustomFixer(FixerInterface $fixer);






public function getCustomFixers();
}
<?php










namespace Symfony\CS\Console\Command;

use Symfony\Component\Console\Command\Command;
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\Filesystem\Filesystem;
use Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;
use Symfony\CS\Config\Config;
use Symfony\CS\ConfigInterface;




class FixCommand extends Command
{
protected $fixer;
protected $defaultConfig;





public function __construct(Fixer $fixer = null, ConfigInterface $config = null)
{
$this->fixer = $fixer ?: new Fixer();
$this->fixer->registerBuiltInFixers();
$this->fixer->registerBuiltInConfigs();
$this->defaultConfig = $config ?: new Config();

parent::__construct();
}




protected function configure()
{
$this
->setName('fix')
->setDefinition(array(
new InputArgument('path', InputArgument::REQUIRED, 'The path'),
new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The configuration name', 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 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>--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=all</info>

By default, all PSR-2 fixers and some additional ones are run.

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 if this is more convenient,
using <comment>-name</comment>:

    <info>php %command.full_name% /path/to/dir --fixers=-short_tag,-indentation</info>

A combination of <comment>--dry-run</comment>, <comment>--verbose</comment> and <comment>--diff</comment> will
display summary of proposed fixes, leaving your files unchanged.

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 files,
and directories that need to be analyzed:

    <?php

    \$finder = Symfony\CS\Finder\DefaultFinder::create()
        ->exclude('somefile')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('indentation', 'elseif'))
        ->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 Fixers but the `Psr0Fixer`.
Note the additional <comment>-</comment> in front of the Fixer name.

    <?php

    \$finder = Symfony\CS\Finder\DefaultFinder::create()
        ->exclude('somefile')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('-Psr0Fixer'))
        ->finder(\$finder)
    ;
EOF
);
}




protected function execute(InputInterface $input, OutputInterface $output)
{
$path = $input->getArgument('path');
$filesystem = new Filesystem();
if (!$filesystem->isAbsolutePath($path)) {
$path = getcwd().DIRECTORY_SEPARATOR.$path;
}

$addSuppliedPathFromCli = true;

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($file = $path.'/.php_cs')) {
$config = include $file;
$addSuppliedPathFromCli = false;
} else {
$config = $this->defaultConfig;
}

if ($addSuppliedPathFromCli) {
if (is_file($path)) {
$config->finder(new \ArrayIterator(array(new \SplFileInfo($path))));
} else {
$config->setDir($path);
}
}


 $this->fixer->registerCustomFixers($config->getCustomFixers());

$allFixers = $this->fixer->getFixers();

switch ($input->getOption('level')) {
case 'psr0':
$level = FixerInterface::PSR0_LEVEL;
break;
case 'psr1':
$level = FixerInterface::PSR1_LEVEL;
break;
case 'psr2':
$level = FixerInterface::PSR2_LEVEL;
break;
case 'all':
$level = FixerInterface::ALL_LEVEL;
break;
case null:
$fixerOption = $input->getOption('fixers');
if (empty($fixerOption) || preg_match('{(^|,)-}', $fixerOption)) {
$level = $config->getFixers();
} else {
$level = null;
}
break;
default:
throw new \InvalidArgumentException(sprintf('The level "%s" is not defined.', $input->getOption('level')));
}


 $fixers = array();
if (is_array($level)) {
foreach ($allFixers as $fixer) {
if (in_array($fixer->getName(), $level, true) || in_array($fixer, $level, true)) {
$fixers[] = $fixer;
}
}
} else {
foreach ($allFixers as $fixer) {
if ($fixer->getLevel() === ($fixer->getLevel() & $level)) {
$fixers[] = $fixer;
}
}
}


 if (preg_match('{(^|,)-}', $input->getOption('fixers'))) {
foreach ($fixers as $key => $fixer) {
if (preg_match('{(^|,)-'.preg_quote($fixer->getName()).'}', $input->getOption('fixers'))) {
unset($fixers[$key]);
}
}
} elseif ($input->getOption('fixers')) {
$names = array_map('trim', explode(',', $input->getOption('fixers')));

foreach ($allFixers as $fixer) {
if (in_array($fixer->getName(), $names) && !in_array($fixer, $fixers)) {
$fixers[] = $fixer;
}
}
}

$config->fixers($fixers);

$changed = $this->fixer->fix($config, $input->getOption('dry-run'), $input->getOption('diff'));

$i = 1;
switch ($input->getOption('format')) {
case 'txt':
foreach ($changed as $file => $fixResult) {
$output->write(sprintf('%4d) %s', $i++, $file));
if ($input->getOption('verbose')) {
$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('');
}
break;
case 'xml':
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($filesXML = $dom->createElement('files'));
foreach ($changed as $file => $fixResult) {
$filesXML->appendChild($fileXML = $dom->createElement('file'));

$fileXML->setAttribute('id', $i++);
$fileXML->setAttribute('name', $file);
if ($input->getOption('verbose')) {
$fileXML->appendChild($appliedFixersXML = $dom->createElement('applied_fixers'));
foreach ($fixResult['appliedFixers'] as $appliedFixer) {
$appliedFixersXML->appendChild($appliedFixerXML = $dom->createElement('applied_fixer'));
$appliedFixerXML->setAttribute('name', $appliedFixer);
}

if ($input->getOption('diff')) {
$fileXML->appendChild($diffXML = $dom->createElement('diff'));

$diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
}
}
}

$dom->formatOutput = true;
$output->write($dom->saveXML());
break;
default:
throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
}

return empty($changed) ? 0 : 1;
}

protected function getFixersHelp()
{
$fixers = '';
$maxName = 0;
foreach ($this->fixer->getFixers() as $fixer) {
if (strlen($fixer->getName()) > $maxName) {
$maxName = strlen($fixer->getName());
}
}

$count = count($this->fixer->getFixers()) - 1;
foreach ($this->fixer->getFixers() as $i => $fixer) {
$chunks = explode("\n", wordwrap(sprintf('[%s] %s', $this->fixer->getLevelAsString($fixer), $fixer->getDescription()), 72 - $maxName, "\n"));
$fixers .= sprintf(" * <comment>%s</comment>%s %s\n", $fixer->getName(), str_repeat(' ', $maxName - strlen($fixer->getName())), array_shift($chunks));
while ($c = array_shift($chunks)) {
$fixers .= str_repeat(' ', $maxName + 4).$c."\n";
}

if ($count != $i) {
$fixers .= "\n";
}
}

return $fixers;
}

protected function getConfigsHelp()
{
$configs = '';
$maxName = 0;
foreach ($this->fixer->getConfigs() as $config) {
if (strlen($config->getName()) > $maxName) {
$maxName = strlen($config->getName());
}
}

$count = count($this->fixer->getConfigs()) - 1;
foreach ($this->fixer->getConfigs() as $i => $config) {
$chunks = explode("\n", wordwrap($config->getDescription(), 72 - $maxName, "\n"));
$configs .= sprintf(" * <comment>%s</comment>%s %s\n", $config->getName(), str_repeat(' ', $maxName - strlen($config->getName())), array_shift($chunks));
while ($c = array_shift($chunks)) {
$configs .= str_repeat(' ', $maxName + 4).$c."\n";
}

if ($count != $i) {
$configs .= "\n";
}
}

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

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

    \$ sudo wget http://cs.sensiolabs.org/get/php-cs-fixer.phar -O /usr/local/bin/php-cs-fixer

or with curl:

.. code-block:: bash

    \$ sudo curl http://cs.sensiolabs.org/get/php-cs-fixer.phar -o /usr/local/bin/php-cs-fixer

then:

.. code-block:: bash

    \$ sudo chmod a+x /usr/local/bin/php-cs-fixer

Then, just run ``php-cs-fixer``.

Globally (homebrew)
~~~~~~~~~~~~~~~~~~~

PHP-CS-Fixer is part of the homebrew-php project:

.. code-block:: bash

    \$ brew tap josegonzalez/homebrew-php
    \$ brew install 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 (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`_

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://cs.sensiolabs.org/get/php-cs-fixer.phar
.. _Vim:               https://github.com/stephpy/vim-php-cs-fixer
.. _Sublime Text:      https://github.com/benmatselby/sublime-phpcs
.. _contribute:        https://github.com/fabpot/php-cs-fixer

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('#^                        #m', '  ', $help);
$help = preg_replace('#\*\* +\[#', '** [', $help);

$output->writeln($header);
$output->writeln($help);
$output->write($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;






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)
{
preg_match('/\((.*?)\)$/', $this->getApplication()->getLongVersion(), $match);
$localVersion = isset($match[1]) ? $match[1] : '';

if (false !== $remoteVersion = @file_get_contents('http://get.sensiolabs.org/php-cs-fixer.version')) {
if ($localVersion == $remoteVersion) {
$output->writeln('<info>php-cs-fixer is already up to date.</info>');

return;
}
}

$localFilename = $_SERVER['argv'][0];
$tempFilename = basename($localFilename, '.phar').'-tmp.phar';

if (false === @file_get_contents('http://get.sensiolabs.org/php-cs-fixer.phar')) {
$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\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>';

if ('@'.'git-commit@' !== $commit = '3cef8c3d87c002de40a59f0708e9be50ec7219ab') {
$version .= ' ('.substr($commit, 0, 7).')';
}

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

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;

use Symfony\Component\Finder\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;

use Symfony\Component\Finder\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;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo as FinderSplFileInfo;
use SebastianBergmann\Diff\Differ;




class Fixer
{
const VERSION = '0.3-DEV';

protected $fixers = array();
protected $configs = array();
protected $diff;

public function __construct()
{
$this->diff = new Differ();
}

public function registerBuiltInFixers()
{
foreach (Finder::create()->files()->in(__DIR__.'/Fixer') as $file) {
$class = 'Symfony\\CS\\Fixer\\'.basename($file, '.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) {
$class = 'Symfony\\CS\\Config\\'.basename($file, '.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)
{
$this->sortFixers();

$fixers = $this->prepareFixers($config);
$changed = array();
foreach ($config->getFinder() as $file) {
if ($file->isDir()) {
continue;
}

if ($fixInfo = $this->fixFile($file, $fixers, $dryRun, $diff)) {
if ($file instanceof FinderSplFileInfo) {
$changed[$file->getRelativePathname()] = $fixInfo;
} else {
$changed[$file->getPathname()] = $fixInfo;
}
}
}

return $changed;
}

public function fixFile(\SplFileInfo $file, array $fixers, $dryRun, $diff)
{
$new = $old = file_get_contents($file->getRealpath());
$appliedFixers = array();

foreach ($fixers as $fixer) {
if (!$fixer->supports($file)) {
continue;
}

$new1 = $fixer->fix($file, $new);
if ($new1 != $new) {
$appliedFixers[] = $fixer->getName();
}
$new = $new1;
}

if ($new != $old) {
if (!$dryRun) {
file_put_contents($file->getRealpath(), $new);
}

$fixInfo = array('appliedFixers' => $appliedFixers);

if ($diff) {
$fixInfo['diff'] = $this->stringDiff($old, $new);
}

return $fixInfo;
}
}

public static function getLevelAsString(FixerInterface $fixer)
{
if ($fixer->getLevel() === ($fixer->getLevel() & FixerInterface::PSR0_LEVEL)) {
return 'PSR-0';
}

if ($fixer->getLevel() === ($fixer->getLevel() & FixerInterface::PSR1_LEVEL)) {
return 'PSR-1';
}

if ($fixer->getLevel() === ($fixer->getLevel() & FixerInterface::PSR2_LEVEL)) {
return 'PSR-2';
}

return 'all';
}

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 ($a, $b) {
if ($a->getPriority() == $b->getPriority()) {
return 0;
}

return $a->getPriority() > $b->getPriority() ? -1 : 1;
});
}

private function prepareFixers(ConfigInterface $config)
{
$fixers = $config->getFixers();

foreach ($fixers as $fixer) {
if ($fixer instanceof ConfigAwareInterface) {
$fixer->setConfig($config);
}
}

return $fixers;
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;






class ControlSpacesFixer implements FixerInterface
{



public function fix(\SplFileInfo $file, $content)
{
$content = $this->fixControlsWithSuffixBrace($content);
$content = $this->fixControlsWithPrefixBraceAndParentheses($content);
$content = $this->fixControlsWithParenthesesAndSuffixBrace($content);
$content = $this->fixControlsWithPrefixBraceAndSuffixBrace($content);
$content = $this->fixControlsWithPrefixBraceAndParenthesesAndSuffixBrace($content);
$content = $this->fixControlsWithPrefixBraceAndParenthesesAndSuffixBraceInLambdas($content);
$content = $this->fixCasts($content);

return $content;
}




public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}




public function getPriority()
{

 return -10;
}




public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}




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




public function getDescription()
{
return 'A single space should be between: the closing brace and the control, the control and the opening parentheses, the closing parentheses and the opening brace.';
}








private function fixControlsWithSuffixBrace($content)
{
$statements = array(
'try',
'do',
);

return preg_replace(sprintf('/(%s)[^\S\n]*{/', implode('|', $statements)), '\\1 {', $content);
}








private function fixControlsWithPrefixBraceAndParentheses($content)
{
$statements = array(
'while'
);

return preg_replace(sprintf('/}[^\S\n]*(%s)[^\S\n]*\((.*)\)/', implode('|', $statements)), '} \\1 (\\2)', $content);
}








private function fixControlsWithParenthesesAndSuffixBrace($content)
{
$statements = array(
'if',
'for',
'while',
'foreach',
'switch',
);

return preg_replace(
array(

 


 sprintf(
'/(%s)  # group capture: $statements
                    [^\S\n]*
                    \(          # literal (
                        [^\S\n]*
                        (                   # group capture: start
                            [^()]*?         # not () or newline zero or more times, greedy
                            |               # OR
                            (?R)            # recursive syntax
                        )                   # group capture: end
                        [^\S\n]*
                    (\s*)
                    \)          # literal )
                    [^\S\n]*
                    {
                    /x', 
 implode('|', $statements)
),

 sprintf('/(%s)[^\S\n]*\((.*)\)[^\S\n]*{/', implode('|', $statements)),
),
array(
'\\1 (\\2\\3) {',
'\\1 (\\2) {'
),
$content
);
}








private function fixControlsWithPrefixBraceAndSuffixBrace($content)
{
$statements = array(
'else',
);

return preg_replace(sprintf('/}[^\S\n]*(%s)[^\S\n]*{/', implode('|', $statements)), '} \\1 {', $content);
}








private function fixControlsWithPrefixBraceAndParenthesesAndSuffixBrace($content)
{
$statements = array(
'elseif',
'else if',
'catch',
);

return preg_replace(sprintf('/}[^\S\n]*(%s)[^\S\n]*\((.*)\)[^\S\n]*{/', implode('|', $statements)), '} \\1 (\\2) {', $content);
}








private function fixControlsWithPrefixBraceAndParenthesesAndSuffixBraceInLambdas($content)
{
$statements = array(
'use',
);

return preg_replace(sprintf('/\)[^\S\n]*(%s)[^\S\n]*\((.*)\)[^\S\n]*{/', implode('|', $statements)), ') \\1 (\\2) {', $content);
}








private function fixCasts($content)
{
$types = implode('|', array(
'int',
'integer',
'bool',
'boolean',
'float',
'double',
'real',
'string',
'array',
'object',
'unset',
'binary',
));

return preg_replace(
array(
sprintf('/\(\s*(%s)\s*\)[^\S\n]*/', $types), 
 sprintf('/ $/m', $types), 
 sprintf('/\((%s)\)\s*\((%s)\)/', $types, $types) 
 ),
array(
'(\\1) ',
'',
'(\\1) (\\2)'
),
$content
);
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class CurlyBracketsNewlineFixer implements FixerInterface
{
const REMOVE_NEWLINE = '\\1 {\\4';


 const ADD_NEWLINE = "\\1\\2\n\\1{";

public function fix(\SplFileInfo $file, $content)
{
$content = $this->classDeclarationFix($content);
$content = $this->functionDeclarationFix($content);
$content = $this->anonymousFunctionsFix($content);
$content = $this->controlStatementsFix($content);
$content = $this->controlStatementContinuationFix($content);
$content = $this->doWhileFix($content);

return $content;
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{
return 0;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'Opening braces for classes, interfaces, traits and methods must go on the next line, and closing braces must go on the next line after the body. Opening braces for control structures must go on the same line, and closing braces must go on the next line after the body.';
}

private function classDeclarationFix($content)
{

 return preg_replace('/^([ \t]*)((?:[\w \t]+ )?(class|interface|trait) [\w, \t\\\\]+?)[ \t]*{\s*$/m', self::ADD_NEWLINE, $content);
}

private function functionDeclarationFix($content)
{

 return preg_replace('/^([ \t]*)((?:[\w \t]+ )?function [\w \t]+\(.*?\))[ \t]*{\s*$/m', self::ADD_NEWLINE, $content);
}

private function anonymousFunctionsFix($content)
{

 return preg_replace('/((^|[\s\W])function\s*\(.*\))([^\n]*?) *\n[^\S\n]*{/', self::REMOVE_NEWLINE, $content);
}

private function controlStatementsFix($content)
{
$statements = array(
'\bif\s*\(.*\)',
'\belse\s*if\s*\(.*\)',
'\b(?<!\$)else\b',
'\bfor\s*\(.*\)',
'\b(?<!\$)do\b',
'\bwhile\s*\(.*\)',
'\bforeach\s*\(.*\)',
'\bswitch\s*\(.*\)',
'\b(?<!\$)try\b',
'\bcatch\s*\(.*\)',
);


 return preg_replace('/((^|[\s\W])('.implode('|', $statements).'))([^\n]*?) *\n[^\S\n]*{/', self::REMOVE_NEWLINE, $content);
}

private function controlStatementContinuationFix($content)
{
$statements = array(
'catch',
'else',
);


 return preg_replace('/}\s*\n\s*(' . implode('|', $statements) . ')/', '} \\1', $content);
}

private function doWhileFix($content)
{

 return preg_replace('/(do {[\s\S]*)}\s*\n\s*while/', '\\1} while', $content);
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class ElseifFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 return str_replace('} else if (', '} elseif (', $content);
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{

 return -20;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

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;

use Symfony\CS\FixerInterface;




class EndOfFileLineFeedFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{


$content = rtrim($content);

if (strlen($content)) {
return $content."\n";
}

return $content;
}

public function getLevel()
{
return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{

 return -50;
}

public function supports(\SplFileInfo $file)
{
return true;
}

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

public function getDescription()
{
return 'A file must always end with an empty line feed.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;





class ExtraEmptyLinesFixer implements FixerInterface
{



public function fix(\SplFileInfo $file, $content)
{
$regex = <<<'REGEX'
(?: # heredoc/nowdoc
    <<<(?P<nowdoc_quote>'?) (?P<nowdoc_delimiter>[_[:alpha:]][_[:alnum:]]*) (?P=nowdoc_quote)
        \C*(?!(?P=nowdoc_end))
    (?P<nowdoc_end>\n(?P=nowdoc_delimiter))
)
|(?: # single quoted string
    '
        [^\\']*+
        (?:\\.[^\\']*+)*+
    '
)
|(?: # double quoted string
    "
        [^\\"]*+
        (?:\\.[^\\"]*+)*+
    "
)
|(?P<to_fix>
    \n{3,}
)
REGEX;


 return preg_replace_callback(sprintf('@%s@x', $regex), function ($matches) {
if (isset($matches['to_fix'])) {
return "\n\n";
}

return $matches[0];
}, $content);
}

public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}

public function getPriority()
{
return 0;
}




public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'Removes extra empty lines.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class FunctionDeclarationSpacingFixer implements FixerInterface
{



public function fix(\SplFileInfo $file, $content)
{
$content = $this->fixNamedFunctions($content);
$content = $this->fixAnonymousFunctions($content);
$content = $this->fixSpaceBeforeBrace($content);
return $content;
}




public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}




public function getPriority()
{
return 0;
}




public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}




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




public function getDescription()
{
return 'Spaces should be properly placed in a function declaration';
}

private function fixAnonymousFunctions($content)
{
$content = preg_replace(
$this->regex(array('params', 'end')),
'\1function (\2)\3',
$content
);
$content = preg_replace(
$this->regex(array('params', 'use', 'end')),
'\1function (\2) use (\3)\4',
$content
);
return $content;
}

private function fixNamedFunctions($content)
{
return preg_replace(
$this->regex(array('name', 'params', 'end')),
'\1function \2(\3)\4',
$content
);
}







private function fixSpaceBeforeBrace($content)
{
return preg_replace(
'/(function[^{]+\)){/',
'\1 {',
$content);
}

private function regex(array $keys)
{
$map = array(
'name' => '\s+([a-zA-Z0-9_]+)',
'params' => '
                \s*
                \(
                    \h*
                    (
                        [^)]*
                        [^)\s]
                    )?
                    \h*
                \)
            ',
'end' => '\h*((?:\v\s*)?{)',
);
$map['use'] = '\s*use'.$map['params'];

return '/(^|[^a-zA-Z0-9_\x7f-\xff\$])function' . implode('', array_map(function ($key) use ($map) {
return $map[$key];
}, $keys)).'/x';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class IncludeFixer implements FixerInterface
{



public function fix(\SplFileInfo $file, $content)
{
$statements = implode('|', array(
'include',
'include_once',
'require',
'require_once',
));

return preg_replace(
array(
sprintf('#^(\s*(?:return +)?(?:\$[a-z0-9_()>-]+ *= *)?(?:%s))\s*\(?\s*[\'"]{1}(?!\")([a-zA-Z0-9\-_.\/]*)[\'"]{1}\s*\)?#m', $statements), 
 sprintf('#^(\s*(?:return +)?(?:\$[a-z0-9_()>-]+ *= *)?(?:%s))[^\S\n]+(.*)#m', $statements), 
 ),
array(
"\\1 '\\2'",
'\\1 \\2',
),
$content
);
}




public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}




public function getPriority()
{
return 0;
}




public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}




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




public function getDescription()
{
return 'Include and file path should be divided with a single space. File path should not be placed under brackets.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class IndentationFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 return preg_replace_callback('/^([ \t]+)/m', function ($matches) use ($content) {

 return preg_replace('/(?:(?<! ) {1,3})?\t/', '    ', $matches[0]);
}, $content);
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{
return 50;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'Code must use 4 spaces for indenting, not tabs.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class LineFeedFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 return str_replace("\r\n", "\n", $content);
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{
return 50;
}

public function supports(\SplFileInfo $file)
{
return true;
}

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

public function getDescription()
{
return 'All PHP files must use the Unix LF (linefeed) line ending.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class PhpClosingTagFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 
 if (strpos($content, '<?php') === 0 && substr_count($content, '<?php') < 2) {
return preg_replace('/( *)\?>\s*$/s', '', $content);
}

return $content;
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{
return 0;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'The closing ?> tag MUST be omitted from files containing only PHP.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class PhpdocParamsAlignmentFixer implements FixerInterface
{
private $regex;
private $regexCommentLine;

public function __construct()
{

 $paramTag = '(?P<tag>param)\s+(?P<hint>[^$]+?)\s+(?P<var>&?\$[^\s]+)';

 $returnThrowsTag = '(?P<tag2>return|throws)\s+(?P<hint2>[^\s]+?)';

 $desc = '(?:\s+(?P<desc>.*)|\s*)';
$this->regex = '/^ {5}\* @(?:'.$paramTag.'|'.$returnThrowsTag.')'.$desc.'$/';
$this->regexCommentLine = '/^ {5}\*(?:\s+(?P<desc>.+))$/';
}

public function fix(\SplFileInfo $file, $content)
{
$lines = explode("\n", $content);
for ($i = 0, $l = count($lines); $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'];
continue;
}
$line =
'     *  '
.str_repeat(' ', ($tagMax + $hintMax + $varMax + ('param' === $currTag ? 3 : 2)))
.$item['desc'];

$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']
: ''
)
;
} elseif (!empty($item['desc'])) {
$line .= str_repeat(' ', $hintMax - strlen($item['hint']) + 1).$item['desc'];
}

$lines[$current + $j] = $line;
}
}
}

return implode("\n", $lines);
}

public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}

public function getPriority()
{
return 0;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'All items of the @param phpdoc tags must be aligned vertically.';
}

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;

use Symfony\CS\ConfigInterface;
use Symfony\CS\ConfigAwareInterface;
use Symfony\CS\FixerInterface;




class Psr0Fixer implements FixerInterface, ConfigAwareInterface
{
protected $config;

public function fix(\SplFileInfo $file, $content)
{
$namespace = false;
if (preg_match('{^[^\S\n]*(?:<\?php\s+)?namespace\s+(\S+)\s*;}um', $content, $match)) {
$namespace = $match[1];
if (stripos($match[0], 'namespace') > 0) {
$content = str_replace($match[0], ltrim($match[0], " \t"), $content);
}
}

if (!preg_match_all('{^((abstract\s+|final\s+)?class|interface|trait)\s+(\S+)}um', $content, $matches, PREG_SET_ORDER)) {
return $content;
}


 if (!$matches) {
return $content;
}

if (count($matches) > 1) {
return $content;
}

$match = $matches[0];

$keyword = $match[1];
$class = $match[3];

if ($namespace) {
$normNamespace = strtr($namespace, '\\', '/');
$path = strtr($file->getRealPath(), '\\', '/');
$dir = dirname($path);
$filename = basename($path, '.php');

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 ($class !== $filename) {
$content = preg_replace('{^'.$keyword.'\s+(\S+)}um', $keyword.' '.$filename, $content, 1);
}
if ($normNamespace !== $dir) {
if (strtolower($normNamespace) === strtolower($dir)) {
$namespace = substr($namespace, 0, -strlen($dir)) . strtr($dir, '/', '\\');
$content = preg_replace('{^namespace\s+(\S+)\s*;}um', 'namespace '.$namespace.';', $content, 1);
} else {
echo '! The namespace '.$namespace.' in '.$path.' does not match the file path according to PSR-0 rules'.PHP_EOL;
}
}
} else {
$normClass = strtr($class, '_', '/');
$path = strtr($file->getRealPath(), '\\', '/');
$filename = substr($path, -strlen($normClass)-4, -4);

if (!strpos($class, '_')) {
echo '! Class '.$class.' in '.$path.' should have at least a vendor namespace according to PSR-0 rules'.PHP_EOL;
}

if ($normClass !== $filename) {
if (strtolower($normClass) === strtolower($filename)) {
$content = preg_replace('{^'.$keyword.'\s+(\S+)}um', $keyword.' '.strtr($filename, '/', '_'), $content, 1);
} else {
echo '! The class '.$class.' in '.$path.' does not match the file path according to PSR-0 rules'.PHP_EOL;
}
}
}

return $content;
}

public function setConfig(ConfigInterface $config)
{
$this->config = $config;
}

public function getLevel()
{
return FixerInterface::PSR0_LEVEL;
}

public function getPriority()
{
return -10;
}

public function supports(\SplFileInfo $file)
{
if ('php' !== pathinfo($file->getFilename(), PATHINFO_EXTENSION)) {
return false;
}


 return !preg_match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath());
}

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

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










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class ReturnStatementsFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 return preg_replace_callback('/(^.*$)\n+(^ +return\b)/m', function ($match) {

 if (
preg_match('/\{$/m', $match[1]) || 
 preg_match('/\:$/m', $match[1]) || 
 preg_match('%^ *//%m', $match[1]) || 
 preg_match('/^$/m', $match[1]) || 
 preg_match('/^(?!.*\{) *(if .+|else.*)/m', $match[1]) 
 ) {
return $match[1]."\n".$match[2];
}

return $match[1]."\n\n".$match[2];
}, $content);
}

public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}

public function getPriority()
{
return 0;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'An empty line feed should precede a return statement.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class ShortTagFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 return preg_replace('/<\?(\s|$)/', '<?php$1', $content);
}

public function getLevel()
{

 return FixerInterface::PSR1_LEVEL;
}

public function getPriority()
{
return 0;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

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;

use Symfony\CS\FixerInterface;




class TrailingSpacesFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 return preg_replace('/[ \t]+$/m', '', $content);
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{
return 20;
}

public function supports(\SplFileInfo $file)
{
return true;
}

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

public function getDescription()
{
return 'Remove trailing whitespace at the end of lines.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class UnusedUseStatementsFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 if (false !== strpos($file, '/Fixtures/')) {
return $content;
}


 preg_match_all('/^use (?P<class>[^\s;]+)(?:\s+as\s+(?P<alias>[^\s;]+))?\s*;/m', $content, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (isset($match['alias'])) {
$short = $match['alias'];
} else {
$parts = explode('\\', $match['class']);
$short = array_pop($parts);
}

$removed = false;


 
 if (!isset($match['alias']) && preg_match('{^[^\S\n]*(?:<\?php\s+)?namespace\s+(\S+)\s*;}um', $content, $lmatch)) {
$namespace = $lmatch[1];

if (preg_match('{^'.str_replace('\\', '\\\\', $namespace).'\\\\[^\\\\]+$}', trim($match['class'], '\\'))) {
$removed = true;
}
}


 if (!$removed) {
preg_match_all('/\b'.preg_quote($short, '/').'\b/i', str_replace($match[0]."\n", '', $content), $m);
$removed = !count($m[0]);
}

if ($removed) {
$content = str_replace($match[0]."\n", '', $content);
}
}

return $content;
}

public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}

public function getPriority()
{

 return 5;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

public function getDescription()
{
return 'Unused use statements must be removed.';
}
}
<?php










namespace Symfony\CS\Fixer;

use Symfony\CS\FixerInterface;




class VisibilityFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{

 if (!preg_match('{\b(?<!\$)(?:class|interface|trait)\b}i', $content)) {
return $content;
}


 
 
 $content = preg_replace_callback('/^( {2,4}|\t)((?:static\s+)?)((?:(?:public|protected|private|var)\s+)+)((?:static\s+)?)\s*(\$[a-z0-9_]+)/im', function ($matches) {
$flags = explode(' ', strtolower(trim($matches[3])));
if (in_array('protected', $flags)) {
$visibility = 'protected';
} elseif (in_array('private', $flags)) {
$visibility = 'private';
} else {
$visibility = 'public';
}

return $matches[1] . $visibility
. (strlen(trim($matches[2])) > 0 || strlen(trim($matches[4])) > 0 ? ' static' : '')
. ' ' . $matches[5];
}, $content);

$content = preg_replace_callback('/^( {2,4}|\t)((?:(?:public|protected|private|static|abstract|final)\s+)*)(?:function\s+([a-z0-9_]+))/im', function ($matches) {

 $matches[2] = preg_replace('/\\s/', ' ', $matches[2]);
$flags = explode(' ', strtolower(trim($matches[2])));
if (in_array('protected', $flags)) {
$visibility = 'protected';
} elseif (in_array('private', $flags)) {
$visibility = 'private';
} else {
$visibility = 'public';
}

return $matches[1]
. (in_array('abstract', $flags) ? 'abstract ' : '')
. (in_array('final', $flags) ? 'final ' : '')
. $visibility
. (in_array('static', $flags) ? ' static' : '')
. ' function '. $matches[3];
}, $content);

return $content;
}

public function getLevel()
{

 return FixerInterface::PSR2_LEVEL;
}

public function getPriority()
{
return 0;
}

public function supports(\SplFileInfo $file)
{
return 'php' == pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}

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

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










namespace Symfony\CS;




interface FixerInterface
{
const PSR0_LEVEL = 1;
const PSR1_LEVEL = 3;
const PSR2_LEVEL = 7;
const ALL_LEVEL = 15;









public function fix(\SplFileInfo $file, $content);






public function getLevel();






public function getPriority();






public function supports(\SplFileInfo $file);








public function getName();








public function getDescription();
}
#!/usr/bin/env php
<?php










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();
Copyright (c) 2012-2013 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.
6æR1Ís`zÿüªg¥¥ËÌ�   GBMB