composer update
This commit is contained in:
+19
-6
@@ -44,6 +44,7 @@ use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use Symfony\Component\Debug\ErrorHandler;
|
||||
use Symfony\Component\Debug\Exception\FatalThrowableError;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
|
||||
|
||||
/**
|
||||
* An Application is the container for a collection of commands.
|
||||
@@ -90,9 +91,12 @@ class Application
|
||||
$this->defaultCommand = 'list';
|
||||
}
|
||||
|
||||
/**
|
||||
* @final since Symfony 4.3, the type-hint will be updated to the interface from symfony/contracts in 5.0
|
||||
*/
|
||||
public function setDispatcher(EventDispatcherInterface $dispatcher)
|
||||
{
|
||||
$this->dispatcher = $dispatcher;
|
||||
$this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
|
||||
}
|
||||
|
||||
public function setCommandLoader(CommandLoaderInterface $commandLoader)
|
||||
@@ -235,7 +239,7 @@ class Application
|
||||
if (!($e instanceof CommandNotFoundException && !$e instanceof NamespaceNotFoundException) || 1 !== \count($alternatives = $e->getAlternatives()) || !$input->isInteractive()) {
|
||||
if (null !== $this->dispatcher) {
|
||||
$event = new ConsoleErrorEvent($input, $output, $e);
|
||||
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
|
||||
$this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
|
||||
|
||||
if (0 === $event->getExitCode()) {
|
||||
return 0;
|
||||
@@ -254,7 +258,7 @@ class Application
|
||||
if (!$style->confirm(sprintf('Do you want to run "%s" instead? ', $alternative), false)) {
|
||||
if (null !== $this->dispatcher) {
|
||||
$event = new ConsoleErrorEvent($input, $output, $e);
|
||||
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
|
||||
$this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
|
||||
|
||||
return $event->getExitCode();
|
||||
}
|
||||
@@ -610,6 +614,15 @@ class Application
|
||||
$this->init();
|
||||
|
||||
$aliases = [];
|
||||
|
||||
foreach ($this->commands as $command) {
|
||||
foreach ($command->getAliases() as $alias) {
|
||||
if (!$this->has($alias)) {
|
||||
$this->commands[$alias] = $command;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
|
||||
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
|
||||
$commands = preg_grep('{^'.$expr.'}', $allCommands);
|
||||
@@ -920,7 +933,7 @@ class Application
|
||||
$e = null;
|
||||
|
||||
try {
|
||||
$this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
|
||||
$this->dispatcher->dispatch($event, ConsoleEvents::COMMAND);
|
||||
|
||||
if ($event->commandShouldRun()) {
|
||||
$exitCode = $command->run($input, $output);
|
||||
@@ -929,7 +942,7 @@ class Application
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$event = new ConsoleErrorEvent($input, $output, $e, $command);
|
||||
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
|
||||
$this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
|
||||
$e = $event->getError();
|
||||
|
||||
if (0 === $exitCode = $event->getExitCode()) {
|
||||
@@ -938,7 +951,7 @@ class Application
|
||||
}
|
||||
|
||||
$event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
|
||||
$this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
|
||||
$this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
|
||||
|
||||
if (null !== $e) {
|
||||
throw $e;
|
||||
|
||||
Vendored
+8
@@ -1,6 +1,14 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* added support for hyperlinks
|
||||
* added `ProgressBar::iterate()` method that simplify updating the progress bar when iterating
|
||||
* added `Question::setAutocompleterCallback()` to provide a callback function
|
||||
that dynamically generates suggestions as the user types
|
||||
|
||||
4.2.0
|
||||
-----
|
||||
|
||||
|
||||
@@ -24,9 +24,9 @@ class CommandNotFoundException extends \InvalidArgumentException implements Exce
|
||||
* @param string $message Exception message to throw
|
||||
* @param array $alternatives List of similar defined names
|
||||
* @param int $code Exception code
|
||||
* @param \Exception $previous Previous exception used for the exception chaining
|
||||
* @param \Throwable $previous Previous exception used for the exception chaining
|
||||
*/
|
||||
public function __construct(string $message, array $alternatives = [], int $code = 0, \Exception $previous = null)
|
||||
public function __construct(string $message, array $alternatives = [], int $code = 0, \Throwable $previous = null)
|
||||
{
|
||||
parent::__construct($message, $code, $previous);
|
||||
|
||||
|
||||
+3
-1
@@ -141,7 +141,7 @@ class OutputFormatter implements WrappableOutputFormatterInterface
|
||||
{
|
||||
$offset = 0;
|
||||
$output = '';
|
||||
$tagRegex = '[a-z][a-z0-9,_=;-]*+';
|
||||
$tagRegex = '[a-z][^<>]*+';
|
||||
$currentLineLength = 0;
|
||||
preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#ix", $message, $matches, PREG_OFFSET_CAPTURE);
|
||||
foreach ($matches[0] as $i => $match) {
|
||||
@@ -216,6 +216,8 @@ class OutputFormatter implements WrappableOutputFormatterInterface
|
||||
$style->setForeground(strtolower($match[1]));
|
||||
} elseif ('bg' == $match[0]) {
|
||||
$style->setBackground(strtolower($match[1]));
|
||||
} elseif ('href' === $match[0]) {
|
||||
$style->setHref($match[1]);
|
||||
} elseif ('options' === $match[0]) {
|
||||
preg_match_all('([^,;]+)', strtolower($match[1]), $options);
|
||||
$options = array_shift($options);
|
||||
|
||||
+19
-5
@@ -52,7 +52,9 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
|
||||
|
||||
private $foreground;
|
||||
private $background;
|
||||
private $href;
|
||||
private $options = [];
|
||||
private $handlesHrefGracefully;
|
||||
|
||||
/**
|
||||
* Initializes output formatter style.
|
||||
@@ -118,6 +120,11 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
|
||||
$this->background = static::$availableBackgroundColors[$color];
|
||||
}
|
||||
|
||||
public function setHref(string $url): void
|
||||
{
|
||||
$this->href = $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets some specific style option.
|
||||
*
|
||||
@@ -179,6 +186,10 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
|
||||
$setCodes = [];
|
||||
$unsetCodes = [];
|
||||
|
||||
if (null === $this->handlesHrefGracefully) {
|
||||
$this->handlesHrefGracefully = 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR');
|
||||
}
|
||||
|
||||
if (null !== $this->foreground) {
|
||||
$setCodes[] = $this->foreground['set'];
|
||||
$unsetCodes[] = $this->foreground['unset'];
|
||||
@@ -187,11 +198,14 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
|
||||
$setCodes[] = $this->background['set'];
|
||||
$unsetCodes[] = $this->background['unset'];
|
||||
}
|
||||
if (\count($this->options)) {
|
||||
foreach ($this->options as $option) {
|
||||
$setCodes[] = $option['set'];
|
||||
$unsetCodes[] = $option['unset'];
|
||||
}
|
||||
|
||||
foreach ($this->options as $option) {
|
||||
$setCodes[] = $option['set'];
|
||||
$unsetCodes[] = $option['unset'];
|
||||
}
|
||||
|
||||
if (null !== $this->href && $this->handlesHrefGracefully) {
|
||||
$text = "\033]8;;$this->href\033\\$text\033]8;;\033\\";
|
||||
}
|
||||
|
||||
if (0 === \count($setCodes)) {
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Helper;
|
||||
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
|
||||
use Symfony\Component\VarDumper\Cloner\VarCloner;
|
||||
use Symfony\Component\VarDumper\Dumper\CliDumper;
|
||||
|
||||
/**
|
||||
* @author Roland Franssen <franssen.roland@gmail.com>
|
||||
*/
|
||||
final class Dumper
|
||||
{
|
||||
private $output;
|
||||
private $dumper;
|
||||
private $cloner;
|
||||
private $handler;
|
||||
|
||||
public function __construct(OutputInterface $output, CliDumper $dumper = null, ClonerInterface $cloner = null)
|
||||
{
|
||||
$this->output = $output;
|
||||
$this->dumper = $dumper;
|
||||
$this->cloner = $cloner;
|
||||
|
||||
if (class_exists(CliDumper::class)) {
|
||||
$this->handler = function ($var): string {
|
||||
$dumper = $this->dumper ?? $this->dumper = new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR);
|
||||
$dumper->setColors($this->output->isDecorated());
|
||||
|
||||
return rtrim($dumper->dump(($this->cloner ?? $this->cloner = new VarCloner())->cloneVar($var)->withRefHandles(false), true));
|
||||
};
|
||||
} else {
|
||||
$this->handler = function ($var): string {
|
||||
switch (true) {
|
||||
case null === $var:
|
||||
return 'null';
|
||||
case true === $var:
|
||||
return 'true';
|
||||
case false === $var:
|
||||
return 'false';
|
||||
case \is_string($var):
|
||||
return '"'.$var.'"';
|
||||
default:
|
||||
return rtrim(print_r($var, true));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public function __invoke($var): string
|
||||
{
|
||||
return ($this->handler)($var);
|
||||
}
|
||||
}
|
||||
+18
@@ -243,6 +243,24 @@ final class ProgressBar
|
||||
$this->redrawFreq = max($freq, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator that will automatically update the progress bar when iterated.
|
||||
*
|
||||
* @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable
|
||||
*/
|
||||
public function iterate(iterable $iterable, ?int $max = null): iterable
|
||||
{
|
||||
$this->start($max ?? (\is_countable($iterable) ? \count($iterable) : 0));
|
||||
|
||||
foreach ($iterable as $key => $value) {
|
||||
yield $key => $value;
|
||||
|
||||
$this->advance();
|
||||
}
|
||||
|
||||
$this->finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the progress output.
|
||||
*
|
||||
|
||||
+50
-18
@@ -115,7 +115,7 @@ class QuestionHelper extends Helper
|
||||
$this->writePrompt($output, $question);
|
||||
|
||||
$inputStream = $this->inputStream ?: STDIN;
|
||||
$autocomplete = $question->getAutocompleterValues();
|
||||
$autocomplete = $question->getAutocompleterCallback();
|
||||
|
||||
if (null === $autocomplete || !$this->hasSttyAvailable()) {
|
||||
$ret = false;
|
||||
@@ -137,7 +137,7 @@ class QuestionHelper extends Helper
|
||||
$ret = trim($ret);
|
||||
}
|
||||
} else {
|
||||
$ret = trim($this->autocomplete($output, $question, $inputStream, \is_array($autocomplete) ? $autocomplete : iterator_to_array($autocomplete, false)));
|
||||
$ret = trim($this->autocomplete($output, $question, $inputStream, $autocomplete));
|
||||
}
|
||||
|
||||
if ($output instanceof ConsoleSectionOutput) {
|
||||
@@ -194,17 +194,16 @@ class QuestionHelper extends Helper
|
||||
/**
|
||||
* Autocompletes a question.
|
||||
*
|
||||
* @param OutputInterface $output
|
||||
* @param Question $question
|
||||
* @param resource $inputStream
|
||||
* @param resource $inputStream
|
||||
*/
|
||||
private function autocomplete(OutputInterface $output, Question $question, $inputStream, array $autocomplete): string
|
||||
private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
|
||||
{
|
||||
$fullChoice = '';
|
||||
$ret = '';
|
||||
|
||||
$i = 0;
|
||||
$ofs = -1;
|
||||
$matches = $autocomplete;
|
||||
$matches = $autocomplete($ret);
|
||||
$numMatches = \count($matches);
|
||||
|
||||
$sttyMode = shell_exec('stty -g');
|
||||
@@ -226,13 +225,14 @@ class QuestionHelper extends Helper
|
||||
} elseif ("\177" === $c) { // Backspace Character
|
||||
if (0 === $numMatches && 0 !== $i) {
|
||||
--$i;
|
||||
$fullChoice = substr($fullChoice, 0, -1);
|
||||
// Move cursor backwards
|
||||
$output->write("\033[1D");
|
||||
}
|
||||
|
||||
if (0 === $i) {
|
||||
$ofs = -1;
|
||||
$matches = $autocomplete;
|
||||
$matches = $autocomplete($ret);
|
||||
$numMatches = \count($matches);
|
||||
} else {
|
||||
$numMatches = 0;
|
||||
@@ -260,18 +260,27 @@ class QuestionHelper extends Helper
|
||||
} elseif (\ord($c) < 32) {
|
||||
if ("\t" === $c || "\n" === $c) {
|
||||
if ($numMatches > 0 && -1 !== $ofs) {
|
||||
$ret = $matches[$ofs];
|
||||
$ret = (string) $matches[$ofs];
|
||||
// Echo out remaining chars for current match
|
||||
$output->write(substr($ret, $i));
|
||||
$i = \strlen($ret);
|
||||
$remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
|
||||
$output->write($remainingCharacters);
|
||||
$fullChoice .= $remainingCharacters;
|
||||
$i = \strlen($fullChoice);
|
||||
|
||||
$matches = array_filter(
|
||||
$autocomplete($ret),
|
||||
function ($match) use ($ret) {
|
||||
return '' === $ret || 0 === strpos($match, $ret);
|
||||
}
|
||||
);
|
||||
$numMatches = \count($matches);
|
||||
$ofs = -1;
|
||||
}
|
||||
|
||||
if ("\n" === $c) {
|
||||
$output->write($c);
|
||||
break;
|
||||
}
|
||||
|
||||
$numMatches = 0;
|
||||
}
|
||||
|
||||
continue;
|
||||
@@ -282,14 +291,21 @@ class QuestionHelper extends Helper
|
||||
|
||||
$output->write($c);
|
||||
$ret .= $c;
|
||||
$fullChoice .= $c;
|
||||
++$i;
|
||||
|
||||
$tempRet = $ret;
|
||||
|
||||
if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
|
||||
$tempRet = $this->mostRecentlyEnteredValue($fullChoice);
|
||||
}
|
||||
|
||||
$numMatches = 0;
|
||||
$ofs = 0;
|
||||
|
||||
foreach ($autocomplete as $value) {
|
||||
foreach ($autocomplete($ret) as $value) {
|
||||
// If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
|
||||
if (0 === strpos($value, $ret)) {
|
||||
if (0 === strpos($value, $tempRet)) {
|
||||
$matches[$numMatches++] = $value;
|
||||
}
|
||||
}
|
||||
@@ -301,8 +317,9 @@ class QuestionHelper extends Helper
|
||||
if ($numMatches > 0 && -1 !== $ofs) {
|
||||
// Save cursor position
|
||||
$output->write("\0337");
|
||||
// Write highlighted text
|
||||
$output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $i)).'</hl>');
|
||||
// Write highlighted text, complete the partially entered response
|
||||
$charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
|
||||
$output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
|
||||
// Restore cursor position
|
||||
$output->write("\0338");
|
||||
}
|
||||
@@ -311,7 +328,22 @@ class QuestionHelper extends Helper
|
||||
// Reset stty so it behaves normally again
|
||||
shell_exec(sprintf('stty %s', $sttyMode));
|
||||
|
||||
return $ret;
|
||||
return $fullChoice;
|
||||
}
|
||||
|
||||
private function mostRecentlyEnteredValue($entered)
|
||||
{
|
||||
// Determine the most recent value that the user entered
|
||||
if (false === strpos($entered, ',')) {
|
||||
return $entered;
|
||||
}
|
||||
|
||||
$choices = explode(',', $entered);
|
||||
if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
|
||||
return $lastChoice;
|
||||
}
|
||||
|
||||
return $entered;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+38
-7
@@ -25,7 +25,7 @@ class Question
|
||||
private $attempts;
|
||||
private $hidden = false;
|
||||
private $hiddenFallback = true;
|
||||
private $autocompleterValues;
|
||||
private $autocompleterCallback;
|
||||
private $validator;
|
||||
private $default;
|
||||
private $normalizer;
|
||||
@@ -81,7 +81,7 @@ class Question
|
||||
*/
|
||||
public function setHidden($hidden)
|
||||
{
|
||||
if ($this->autocompleterValues) {
|
||||
if ($this->autocompleterCallback) {
|
||||
throw new LogicException('A hidden question cannot use the autocompleter.');
|
||||
}
|
||||
|
||||
@@ -121,7 +121,9 @@ class Question
|
||||
*/
|
||||
public function getAutocompleterValues()
|
||||
{
|
||||
return $this->autocompleterValues;
|
||||
$callback = $this->getAutocompleterCallback();
|
||||
|
||||
return $callback ? $callback('') : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -138,17 +140,46 @@ class Question
|
||||
{
|
||||
if (\is_array($values)) {
|
||||
$values = $this->isAssoc($values) ? array_merge(array_keys($values), array_values($values)) : array_values($values);
|
||||
}
|
||||
|
||||
if (null !== $values && !\is_array($values) && !$values instanceof \Traversable) {
|
||||
$callback = static function () use ($values) {
|
||||
return $values;
|
||||
};
|
||||
} elseif ($values instanceof \Traversable) {
|
||||
$valueCache = null;
|
||||
$callback = static function () use ($values, &$valueCache) {
|
||||
return $valueCache ?? $valueCache = iterator_to_array($values, false);
|
||||
};
|
||||
} elseif (null === $values) {
|
||||
$callback = null;
|
||||
} else {
|
||||
throw new InvalidArgumentException('Autocompleter values can be either an array, "null" or a "Traversable" object.');
|
||||
}
|
||||
|
||||
if ($this->hidden) {
|
||||
return $this->setAutocompleterCallback($callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the callback function used for the autocompleter.
|
||||
*/
|
||||
public function getAutocompleterCallback(): ?callable
|
||||
{
|
||||
return $this->autocompleterCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the callback function used for the autocompleter.
|
||||
*
|
||||
* The callback is passed the user input as argument and should return an iterable of corresponding suggestions.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setAutocompleterCallback(callable $callback = null): self
|
||||
{
|
||||
if ($this->hidden && null !== $callback) {
|
||||
throw new LogicException('A hidden question cannot use the autocompleter.');
|
||||
}
|
||||
|
||||
$this->autocompleterValues = $values;
|
||||
$this->autocompleterCallback = $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@ class SymfonyStyle extends OutputStyle
|
||||
*/
|
||||
public function warning($message)
|
||||
{
|
||||
$this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
|
||||
$this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ', true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+27
-5
@@ -73,8 +73,8 @@ class ApplicationTest extends TestCase
|
||||
require_once self::$fixturesPath.'/FooSubnamespaced1Command.php';
|
||||
require_once self::$fixturesPath.'/FooSubnamespaced2Command.php';
|
||||
require_once self::$fixturesPath.'/FooWithoutAliasCommand.php';
|
||||
require_once self::$fixturesPath.'/TestTiti.php';
|
||||
require_once self::$fixturesPath.'/TestToto.php';
|
||||
require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering.php';
|
||||
require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering2.php';
|
||||
}
|
||||
|
||||
protected function normalizeLineBreaks($text)
|
||||
@@ -165,6 +165,28 @@ class ApplicationTest extends TestCase
|
||||
$this->assertEquals('foo', $command->getName(), '->register() registers a new command');
|
||||
}
|
||||
|
||||
public function testRegisterAmbiguous()
|
||||
{
|
||||
$code = function (InputInterface $input, OutputInterface $output) {
|
||||
$output->writeln('It works!');
|
||||
};
|
||||
|
||||
$application = new Application();
|
||||
$application->setAutoExit(false);
|
||||
$application
|
||||
->register('test-foo')
|
||||
->setAliases(['test'])
|
||||
->setCode($code);
|
||||
|
||||
$application
|
||||
->register('test-bar')
|
||||
->setCode($code);
|
||||
|
||||
$tester = new ApplicationTester($application);
|
||||
$tester->run(['test']);
|
||||
$this->assertContains('It works!', $tester->getDisplay(true));
|
||||
}
|
||||
|
||||
public function testAdd()
|
||||
{
|
||||
$application = new Application();
|
||||
@@ -304,9 +326,9 @@ class ApplicationTest extends TestCase
|
||||
public function testFindNonAmbiguous()
|
||||
{
|
||||
$application = new Application();
|
||||
$application->add(new \TestTiti());
|
||||
$application->add(new \TestToto());
|
||||
$this->assertEquals('test-toto', $application->find('test')->getName());
|
||||
$application->add(new \TestAmbiguousCommandRegistering());
|
||||
$application->add(new \TestAmbiguousCommandRegistering2());
|
||||
$this->assertEquals('test-ambiguous', $application->find('test')->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -188,7 +188,7 @@ class CommandTest extends TestCase
|
||||
public function testSetAliasesNull()
|
||||
{
|
||||
$command = new \TestCommand();
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
|
||||
$this->expectException('InvalidArgumentException');
|
||||
$command->setAliases(null);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -4,19 +4,19 @@ use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class TestToto extends Command
|
||||
class TestAmbiguousCommandRegistering extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this
|
||||
->setName('test-toto')
|
||||
->setDescription('The test-toto command')
|
||||
->setName('test-ambiguous')
|
||||
->setDescription('The test-ambiguous command')
|
||||
->setAliases(['test'])
|
||||
;
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output)
|
||||
{
|
||||
$output->write('test-toto');
|
||||
$output->write('test-ambiguous');
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -4,18 +4,18 @@ use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class TestTiti extends Command
|
||||
class TestAmbiguousCommandRegistering2 extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this
|
||||
->setName('test-titi')
|
||||
->setDescription('The test:titi command')
|
||||
->setName('test-ambiguous2')
|
||||
->setDescription('The test-ambiguous2 command')
|
||||
;
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output)
|
||||
{
|
||||
$output->write('test-titi');
|
||||
$output->write('test-ambiguous2');
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ class OutputFormatterStyleTest extends TestCase
|
||||
$style->setForeground('default');
|
||||
$this->assertEquals("\033[39mfoo\033[39m", $style->apply('foo'));
|
||||
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
|
||||
$this->expectException('InvalidArgumentException');
|
||||
$style->setForeground('undefined-color');
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ class OutputFormatterStyleTest extends TestCase
|
||||
$style->setBackground('default');
|
||||
$this->assertEquals("\033[49mfoo\033[49m", $style->apply('foo'));
|
||||
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
|
||||
$this->expectException('InvalidArgumentException');
|
||||
$style->setBackground('undefined-color');
|
||||
}
|
||||
|
||||
@@ -97,4 +97,19 @@ class OutputFormatterStyleTest extends TestCase
|
||||
$this->assertContains('Invalid option specified: "foo"', $e->getMessage(), '->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options');
|
||||
}
|
||||
}
|
||||
|
||||
public function testHref()
|
||||
{
|
||||
$prevTerminalEmulator = getenv('TERMINAL_EMULATOR');
|
||||
putenv('TERMINAL_EMULATOR');
|
||||
|
||||
$style = new OutputFormatterStyle();
|
||||
|
||||
try {
|
||||
$style->setHref('idea://open/?file=/path/SomeFile.php&line=12');
|
||||
$this->assertSame("\e]8;;idea://open/?file=/path/SomeFile.php&line=12\e\\some URL\e]8;;\e\\", $style->apply('some URL'));
|
||||
} finally {
|
||||
putenv('TERMINAL_EMULATOR'.($prevTerminalEmulator ? "=$prevTerminalEmulator" : ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+27
-32
@@ -228,7 +228,7 @@ class OutputFormatterTest extends TestCase
|
||||
);
|
||||
}
|
||||
|
||||
public function testNotDecoratedFormatter()
|
||||
public function testFormatterHasStyles()
|
||||
{
|
||||
$formatter = new OutputFormatter(false);
|
||||
|
||||
@@ -236,40 +236,35 @@ class OutputFormatterTest extends TestCase
|
||||
$this->assertTrue($formatter->hasStyle('info'));
|
||||
$this->assertTrue($formatter->hasStyle('comment'));
|
||||
$this->assertTrue($formatter->hasStyle('question'));
|
||||
}
|
||||
|
||||
$this->assertEquals(
|
||||
'some error', $formatter->format('<error>some error</error>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
'some info', $formatter->format('<info>some info</info>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
'some comment', $formatter->format('<comment>some comment</comment>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
'some question', $formatter->format('<question>some question</question>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
'some text with inline style', $formatter->format('<fg=red>some text with inline style</>')
|
||||
);
|
||||
/**
|
||||
* @dataProvider provideDecoratedAndNonDecoratedOutput
|
||||
*/
|
||||
public function testNotDecoratedFormatter(string $input, string $expectedNonDecoratedOutput, string $expectedDecoratedOutput, string $terminalEmulator = 'foo')
|
||||
{
|
||||
$prevTerminalEmulator = getenv('TERMINAL_EMULATOR');
|
||||
putenv('TERMINAL_EMULATOR='.$terminalEmulator);
|
||||
|
||||
$formatter->setDecorated(true);
|
||||
try {
|
||||
$this->assertEquals($expectedDecoratedOutput, (new OutputFormatter(true))->format($input));
|
||||
$this->assertEquals($expectedNonDecoratedOutput, (new OutputFormatter(false))->format($input));
|
||||
} finally {
|
||||
putenv('TERMINAL_EMULATOR'.($prevTerminalEmulator ? "=$prevTerminalEmulator" : ''));
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertEquals(
|
||||
"\033[37;41msome error\033[39;49m", $formatter->format('<error>some error</error>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
"\033[32msome info\033[39m", $formatter->format('<info>some info</info>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
"\033[33msome comment\033[39m", $formatter->format('<comment>some comment</comment>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
"\033[30;46msome question\033[39;49m", $formatter->format('<question>some question</question>')
|
||||
);
|
||||
$this->assertEquals(
|
||||
"\033[31msome text with inline style\033[39m", $formatter->format('<fg=red>some text with inline style</>')
|
||||
);
|
||||
public function provideDecoratedAndNonDecoratedOutput()
|
||||
{
|
||||
return [
|
||||
['<error>some error</error>', 'some error', "\033[37;41msome error\033[39;49m"],
|
||||
['<info>some info</info>', 'some info', "\033[32msome info\033[39m"],
|
||||
['<comment>some comment</comment>', 'some comment', "\033[33msome comment\033[39m"],
|
||||
['<question>some question</question>', 'some question', "\033[30;46msome question\033[39;49m"],
|
||||
['<fg=red>some text with inline style</>', 'some text with inline style', "\033[31msome text with inline style\033[39m"],
|
||||
['<href=idea://open/?file=/path/SomeFile.php&line=12>some URL</>', 'some URL', "\033]8;;idea://open/?file=/path/SomeFile.php&line=12\033\\some URL\033]8;;\033\\"],
|
||||
['<href=idea://open/?file=/path/SomeFile.php&line=12>some URL</>', 'some URL', 'some URL', 'JetBrains-JediTerm'],
|
||||
];
|
||||
}
|
||||
|
||||
public function testContentWithLineBreaks()
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Tests\Helper;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Bridge\PhpUnit\ClassExistsMock;
|
||||
use Symfony\Component\Console\Helper\Dumper;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\VarDumper\Dumper\CliDumper;
|
||||
|
||||
class DumperNativeFallbackTest extends TestCase
|
||||
{
|
||||
public static function setUpBeforeClass()
|
||||
{
|
||||
ClassExistsMock::register(Dumper::class);
|
||||
ClassExistsMock::withMockedClasses([
|
||||
CliDumper::class => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass()
|
||||
{
|
||||
ClassExistsMock::withMockedClasses([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideVariables
|
||||
*/
|
||||
public function testInvoke($variable, $primitiveString)
|
||||
{
|
||||
$dumper = new Dumper($this->getMockBuilder(OutputInterface::class)->getMock());
|
||||
|
||||
$this->assertSame($primitiveString, $dumper($variable));
|
||||
}
|
||||
|
||||
public function provideVariables()
|
||||
{
|
||||
return [
|
||||
[null, 'null'],
|
||||
[true, 'true'],
|
||||
[false, 'false'],
|
||||
[1, '1'],
|
||||
[-1.5, '-1.5'],
|
||||
['string', '"string"'],
|
||||
[[1, '2'], "Array\n(\n [0] => 1\n [1] => 2\n)"],
|
||||
[new \stdClass(), "stdClass Object\n(\n)"],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Tests\Helper;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Console\Helper\Dumper;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\VarDumper\Test\VarDumperTestTrait;
|
||||
|
||||
class DumperTest extends TestCase
|
||||
{
|
||||
use VarDumperTestTrait;
|
||||
|
||||
public static function setUpBeforeClass()
|
||||
{
|
||||
putenv('DUMP_LIGHT_ARRAY=1');
|
||||
putenv('DUMP_COMMA_SEPARATOR=1');
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass()
|
||||
{
|
||||
putenv('DUMP_LIGHT_ARRAY');
|
||||
putenv('DUMP_COMMA_SEPARATOR');
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideVariables
|
||||
*/
|
||||
public function testInvoke($variable)
|
||||
{
|
||||
$dumper = new Dumper($this->getMockBuilder(OutputInterface::class)->getMock());
|
||||
|
||||
$this->assertDumpMatchesFormat($dumper($variable), $variable);
|
||||
}
|
||||
|
||||
public function provideVariables()
|
||||
{
|
||||
return [
|
||||
[null],
|
||||
[true],
|
||||
[false],
|
||||
[1],
|
||||
[-1.5],
|
||||
['string'],
|
||||
[[1, '2']],
|
||||
[new \stdClass()],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -880,6 +880,41 @@ class ProgressBarTest extends TestCase
|
||||
];
|
||||
}
|
||||
|
||||
public function testIterate(): void
|
||||
{
|
||||
$bar = new ProgressBar($output = $this->getOutputStream());
|
||||
|
||||
$this->assertEquals([1, 2], \iterator_to_array($bar->iterate([1, 2])));
|
||||
|
||||
rewind($output->getStream());
|
||||
$this->assertEquals(
|
||||
' 0/2 [>---------------------------] 0%'.
|
||||
$this->generateOutput(' 1/2 [==============>-------------] 50%').
|
||||
$this->generateOutput(' 2/2 [============================] 100%').
|
||||
$this->generateOutput(' 2/2 [============================] 100%'),
|
||||
stream_get_contents($output->getStream())
|
||||
);
|
||||
}
|
||||
|
||||
public function testIterateUncountable(): void
|
||||
{
|
||||
$bar = new ProgressBar($output = $this->getOutputStream());
|
||||
|
||||
$this->assertEquals([1, 2], \iterator_to_array($bar->iterate((function () {
|
||||
yield 1;
|
||||
yield 2;
|
||||
})())));
|
||||
|
||||
rewind($output->getStream());
|
||||
$this->assertEquals(
|
||||
' 0 [>---------------------------]'.
|
||||
$this->generateOutput(' 1 [->--------------------------]').
|
||||
$this->generateOutput(' 2 [-->-------------------------]').
|
||||
$this->generateOutput(' 2 [============================]'),
|
||||
stream_get_contents($output->getStream())
|
||||
);
|
||||
}
|
||||
|
||||
protected function getOutputStream($decorated = true, $verbosity = StreamOutput::VERBOSITY_NORMAL)
|
||||
{
|
||||
return new StreamOutput(fopen('php://memory', 'r+', false), $verbosity, $decorated);
|
||||
|
||||
@@ -198,6 +198,49 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
|
||||
$this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
}
|
||||
|
||||
public function testAskWithAutocompleteCallback()
|
||||
{
|
||||
if (!$this->hasSttyAvailable()) {
|
||||
$this->markTestSkipped('`stty` is required to test autocomplete functionality');
|
||||
}
|
||||
|
||||
// Po<TAB>Cr<TAB>P<DOWN ARROW><DOWN ARROW><NEWLINE>
|
||||
$inputStream = $this->getInputStream("Pa\177\177o\tCr\tP\033[A\033[A\n");
|
||||
|
||||
$dialog = new QuestionHelper();
|
||||
$helperSet = new HelperSet([new FormatterHelper()]);
|
||||
$dialog->setHelperSet($helperSet);
|
||||
|
||||
$question = new Question('What\'s for dinner?');
|
||||
|
||||
// A simple test callback - return an array containing the words the
|
||||
// user has already completed, suffixed with all known words.
|
||||
//
|
||||
// Eg: If the user inputs "Potato C", the return will be:
|
||||
//
|
||||
// ["Potato Carrot ", "Potato Creme ", "Potato Curry ", ...]
|
||||
//
|
||||
// No effort is made to avoid irrelevant suggestions, as this is handled
|
||||
// by the autocomplete function.
|
||||
$callback = function ($input) {
|
||||
$knownWords = ['Carrot', 'Creme', 'Curry', 'Parsnip', 'Pie', 'Potato', 'Tart'];
|
||||
$inputWords = explode(' ', $input);
|
||||
array_pop($inputWords);
|
||||
$suggestionBase = $inputWords ? implode(' ', $inputWords).' ' : '';
|
||||
|
||||
return array_map(
|
||||
function ($word) use ($suggestionBase) {
|
||||
return $suggestionBase.$word.' ';
|
||||
},
|
||||
$knownWords
|
||||
);
|
||||
};
|
||||
|
||||
$question->setAutocompleterCallback($callback);
|
||||
|
||||
$this->assertSame('Potato Creme Pie', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
}
|
||||
|
||||
public function testAskWithAutocompleteWithNonSequentialKeys()
|
||||
{
|
||||
if (!$this->hasSttyAvailable()) {
|
||||
@@ -667,6 +710,37 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
|
||||
$this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
}
|
||||
|
||||
public function testTraversableMultiselectAutocomplete()
|
||||
{
|
||||
// <NEWLINE>
|
||||
// F<TAB><NEWLINE>
|
||||
// A<3x UP ARROW><TAB>,F<TAB><NEWLINE>
|
||||
// F00<BACKSPACE><BACKSPACE>o<TAB>,A<DOWN ARROW>,<SPACE>SecurityBundle<NEWLINE>
|
||||
// Acme<TAB>,<SPACE>As<TAB><29x BACKSPACE>S<TAB><NEWLINE>
|
||||
// Ac<TAB>,As<TAB><3x BACKSPACE>d<TAB><NEWLINE>
|
||||
$inputStream = $this->getInputStream("\nF\t\nA\033[A\033[A\033[A\t,F\t\nF00\177\177o\t,A\033[B\t, SecurityBundle\nSecurityBundle\nAcme\t, As\t\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177S\t\nAc\t,As\t\177\177\177d\t\n");
|
||||
|
||||
$dialog = new QuestionHelper();
|
||||
$helperSet = new HelperSet([new FormatterHelper()]);
|
||||
$dialog->setHelperSet($helperSet);
|
||||
|
||||
$question = new ChoiceQuestion(
|
||||
'Please select a bundle (defaults to AcmeDemoBundle and AsseticBundle)',
|
||||
['AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle'],
|
||||
'0,1'
|
||||
);
|
||||
|
||||
// This tests that autocomplete works for all multiselect choices entered by the user
|
||||
$question->setMultiselect(true);
|
||||
|
||||
$this->assertEquals(['AcmeDemoBundle', 'AsseticBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
$this->assertEquals(['FooBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
$this->assertEquals(['AsseticBundle', 'FooBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
$this->assertEquals(['FooBundle', 'AsseticBundle', 'SecurityBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
$this->assertEquals(['SecurityBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
$this->assertEquals(['AcmeDemoBundle', 'AsseticBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
|
||||
}
|
||||
|
||||
protected function getInputStream($input)
|
||||
{
|
||||
$stream = fopen('php://memory', 'r+', false);
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Tests\Question;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Question\Question;
|
||||
|
||||
class QuestionTest extends TestCase
|
||||
{
|
||||
private $question;
|
||||
|
||||
protected function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
$this->question = new Question('Test question');
|
||||
}
|
||||
|
||||
public function providerTrueFalse()
|
||||
{
|
||||
return [[true], [false]];
|
||||
}
|
||||
|
||||
public function testGetQuestion()
|
||||
{
|
||||
self::assertSame('Test question', $this->question->getQuestion());
|
||||
}
|
||||
|
||||
public function testGetDefault()
|
||||
{
|
||||
$question = new Question('Test question', 'Default value');
|
||||
self::assertSame('Default value', $question->getDefault());
|
||||
}
|
||||
|
||||
public function testGetDefaultDefault()
|
||||
{
|
||||
self::assertNull($this->question->getDefault());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerTrueFalse
|
||||
*/
|
||||
public function testIsSetHidden(bool $hidden)
|
||||
{
|
||||
$this->question->setHidden($hidden);
|
||||
self::assertSame($hidden, $this->question->isHidden());
|
||||
}
|
||||
|
||||
public function testIsHiddenDefault()
|
||||
{
|
||||
self::assertFalse($this->question->isHidden());
|
||||
}
|
||||
|
||||
public function testSetHiddenWithAutocompleterCallback()
|
||||
{
|
||||
$this->question->setAutocompleterCallback(
|
||||
function (string $input): array { return []; }
|
||||
);
|
||||
|
||||
$this->expectException(\LogicException::class);
|
||||
$this->expectExceptionMessage(
|
||||
'A hidden question cannot use the autocompleter.'
|
||||
);
|
||||
|
||||
$this->question->setHidden(true);
|
||||
}
|
||||
|
||||
public function testSetHiddenWithNoAutocompleterCallback()
|
||||
{
|
||||
$this->question->setAutocompleterCallback(
|
||||
function (string $input): array { return []; }
|
||||
);
|
||||
$this->question->setAutocompleterCallback(null);
|
||||
|
||||
$exception = null;
|
||||
try {
|
||||
$this->question->setHidden(true);
|
||||
} catch (\Exception $exception) {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
$this->assertNull($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerTrueFalse
|
||||
*/
|
||||
public function testIsSetHiddenFallback(bool $hidden)
|
||||
{
|
||||
$this->question->setHiddenFallback($hidden);
|
||||
self::assertSame($hidden, $this->question->isHiddenFallback());
|
||||
}
|
||||
|
||||
public function testIsHiddenFallbackDefault()
|
||||
{
|
||||
self::assertTrue($this->question->isHiddenFallback());
|
||||
}
|
||||
|
||||
public function providerGetSetAutocompleterValues()
|
||||
{
|
||||
return [
|
||||
'array' => [
|
||||
['a', 'b', 'c', 'd'],
|
||||
['a', 'b', 'c', 'd'],
|
||||
],
|
||||
'associative array' => [
|
||||
['a' => 'c', 'b' => 'd'],
|
||||
['a', 'b', 'c', 'd'],
|
||||
],
|
||||
'iterator' => [
|
||||
new \ArrayIterator(['a', 'b', 'c', 'd']),
|
||||
['a', 'b', 'c', 'd'],
|
||||
],
|
||||
'null' => [null, null],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerGetSetAutocompleterValues
|
||||
*/
|
||||
public function testGetSetAutocompleterValues($values, $expectValues)
|
||||
{
|
||||
$this->question->setAutocompleterValues($values);
|
||||
self::assertSame(
|
||||
$expectValues,
|
||||
$this->question->getAutocompleterValues()
|
||||
);
|
||||
}
|
||||
|
||||
public function providerSetAutocompleterValuesInvalid()
|
||||
{
|
||||
return [
|
||||
['Potato'],
|
||||
[new \stdclass()],
|
||||
[false],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerSetAutocompleterValuesInvalid
|
||||
*/
|
||||
public function testSetAutocompleterValuesInvalid($values)
|
||||
{
|
||||
self::expectException(InvalidArgumentException::class);
|
||||
self::expectExceptionMessage(
|
||||
'Autocompleter values can be either an array, "null" or a "Traversable" object.'
|
||||
);
|
||||
|
||||
$this->question->setAutocompleterValues($values);
|
||||
}
|
||||
|
||||
public function testSetAutocompleterValuesWithTraversable()
|
||||
{
|
||||
$question1 = new Question('Test question 1');
|
||||
$iterator1 = $this->getMockForAbstractClass(\IteratorAggregate::class);
|
||||
$iterator1
|
||||
->expects($this->once())
|
||||
->method('getIterator')
|
||||
->willReturn(new \ArrayIterator(['Potato']));
|
||||
$question1->setAutocompleterValues($iterator1);
|
||||
|
||||
$question2 = new Question('Test question 2');
|
||||
$iterator2 = $this->getMockForAbstractClass(\IteratorAggregate::class);
|
||||
$iterator2
|
||||
->expects($this->once())
|
||||
->method('getIterator')
|
||||
->willReturn(new \ArrayIterator(['Carrot']));
|
||||
$question2->setAutocompleterValues($iterator2);
|
||||
|
||||
// Call multiple times to verify that Traversable result is cached, and
|
||||
// that there is no crosstalk between cached copies.
|
||||
self::assertSame(['Potato'], $question1->getAutocompleterValues());
|
||||
self::assertSame(['Carrot'], $question2->getAutocompleterValues());
|
||||
self::assertSame(['Potato'], $question1->getAutocompleterValues());
|
||||
self::assertSame(['Carrot'], $question2->getAutocompleterValues());
|
||||
}
|
||||
|
||||
public function testGetAutocompleterValuesDefault()
|
||||
{
|
||||
self::assertNull($this->question->getAutocompleterValues());
|
||||
}
|
||||
|
||||
public function testGetSetAutocompleterCallback()
|
||||
{
|
||||
$callback = function (string $input): array { return []; };
|
||||
|
||||
$this->question->setAutocompleterCallback($callback);
|
||||
self::assertSame($callback, $this->question->getAutocompleterCallback());
|
||||
}
|
||||
|
||||
public function testGetAutocompleterCallbackDefault()
|
||||
{
|
||||
self::assertNull($this->question->getAutocompleterCallback());
|
||||
}
|
||||
|
||||
public function testSetAutocompleterCallbackWhenHidden()
|
||||
{
|
||||
$this->question->setHidden(true);
|
||||
|
||||
$this->expectException(\LogicException::class);
|
||||
$this->expectExceptionMessage(
|
||||
'A hidden question cannot use the autocompleter.'
|
||||
);
|
||||
|
||||
$this->question->setAutocompleterCallback(
|
||||
function (string $input): array { return []; }
|
||||
);
|
||||
}
|
||||
|
||||
public function testSetAutocompleterCallbackWhenNotHidden()
|
||||
{
|
||||
$this->question->setHidden(true);
|
||||
$this->question->setHidden(false);
|
||||
|
||||
$exception = null;
|
||||
try {
|
||||
$this->question->setAutocompleterCallback(
|
||||
function (string $input): array { return []; }
|
||||
);
|
||||
} catch (\Exception $exception) {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
$this->assertNull($exception);
|
||||
}
|
||||
|
||||
public function providerGetSetValidator()
|
||||
{
|
||||
return [
|
||||
[function ($input) { return $input; }],
|
||||
[null],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerGetSetValidator
|
||||
*/
|
||||
public function testGetSetValidator($callback)
|
||||
{
|
||||
$this->question->setValidator($callback);
|
||||
self::assertSame($callback, $this->question->getValidator());
|
||||
}
|
||||
|
||||
public function testGetValidatorDefault()
|
||||
{
|
||||
self::assertNull($this->question->getValidator());
|
||||
}
|
||||
|
||||
public function providerGetSetMaxAttempts()
|
||||
{
|
||||
return [[1], [5], [null]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerGetSetMaxAttempts
|
||||
*/
|
||||
public function testGetSetMaxAttempts($attempts)
|
||||
{
|
||||
$this->question->setMaxAttempts($attempts);
|
||||
self::assertSame($attempts, $this->question->getMaxAttempts());
|
||||
}
|
||||
|
||||
public function providerSetMaxAttemptsInvalid()
|
||||
{
|
||||
return [['Potato'], [0], [-1]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerSetMaxAttemptsInvalid
|
||||
*/
|
||||
public function testSetMaxAttemptsInvalid($attempts)
|
||||
{
|
||||
self::expectException(\InvalidArgumentException::class);
|
||||
self::expectExceptionMessage('Maximum number of attempts must be a positive value.');
|
||||
|
||||
$this->question->setMaxAttempts($attempts);
|
||||
}
|
||||
|
||||
public function testGetMaxAttemptsDefault()
|
||||
{
|
||||
self::assertNull($this->question->getMaxAttempts());
|
||||
}
|
||||
|
||||
public function testGetSetNormalizer()
|
||||
{
|
||||
$normalizer = function ($input) { return $input; };
|
||||
$this->question->setNormalizer($normalizer);
|
||||
self::assertSame($normalizer, $this->question->getNormalizer());
|
||||
}
|
||||
|
||||
public function testGetNormalizerDefault()
|
||||
{
|
||||
self::assertNull($this->question->getNormalizer());
|
||||
}
|
||||
}
|
||||
Vendored
+7
-4
@@ -17,15 +17,17 @@
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.1.3",
|
||||
"symfony/contracts": "^1.0",
|
||||
"symfony/polyfill-mbstring": "~1.0"
|
||||
"symfony/polyfill-mbstring": "~1.0",
|
||||
"symfony/polyfill-php73": "^1.8",
|
||||
"symfony/service-contracts": "^1.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"symfony/config": "~3.4|~4.0",
|
||||
"symfony/event-dispatcher": "~3.4|~4.0",
|
||||
"symfony/event-dispatcher": "^4.3",
|
||||
"symfony/dependency-injection": "~3.4|~4.0",
|
||||
"symfony/lock": "~3.4|~4.0",
|
||||
"symfony/process": "~3.4|~4.0",
|
||||
"symfony/var-dumper": "^4.3",
|
||||
"psr/log": "~1.0"
|
||||
},
|
||||
"provide": {
|
||||
@@ -39,6 +41,7 @@
|
||||
},
|
||||
"conflict": {
|
||||
"symfony/dependency-injection": "<3.4",
|
||||
"symfony/event-dispatcher": "<4.3",
|
||||
"symfony/process": "<3.3"
|
||||
},
|
||||
"autoload": {
|
||||
@@ -50,7 +53,7 @@
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.2-dev"
|
||||
"dev-master": "4.3-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
1.1.0
|
||||
-----
|
||||
|
||||
* added `HttpClient` namespace with contracts for implementing flexible HTTP clients
|
||||
* added `EventDispatcherInterface` and `Event` in namespace `EventDispatcher`
|
||||
* added `ServiceProviderInterface` in namespace `Service`
|
||||
|
||||
1.0.0
|
||||
-----
|
||||
|
||||
* added `Service\ResetInterface` to provide a way to reset an object to its initial state
|
||||
* added `Translation\TranslatorInterface` and `Translation\TranslatorTrait`
|
||||
* added `Cache` contract to extend PSR-6 with tag invalidation, callback-based computation and stampede protection
|
||||
* added `Service\ServiceSubscriberInterface` to declare the dependencies of a class that consumes a service locator
|
||||
* added `Service\ServiceSubscriberTrait` to implement `Service\ServiceSubscriberInterface` using methods' return types
|
||||
* added `Service\ServiceLocatorTrait` to help implement PSR-11 service locators
|
||||
@@ -1,57 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Cache;
|
||||
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
use Psr\Cache\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Covers most simple to advanced caching needs.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
interface CacheInterface
|
||||
{
|
||||
/**
|
||||
* Fetches a value from the pool or computes it if not found.
|
||||
*
|
||||
* On cache misses, a callback is called that should return the missing value.
|
||||
* This callback is given a PSR-6 CacheItemInterface instance corresponding to the
|
||||
* requested key, that could be used e.g. for expiration control. It could also
|
||||
* be an ItemInterface instance when its additional features are needed.
|
||||
*
|
||||
* @param string $key The key of the item to retrieve from the cache
|
||||
* @param callable|CallbackInterface $callback Should return the computed value for the given key/item
|
||||
* @param float|null $beta A float that, as it grows, controls the likeliness of triggering
|
||||
* early expiration. 0 disables it, INF forces immediate expiration.
|
||||
* The default (or providing null) is implementation dependent but should
|
||||
* typically be 1.0, which should provide optimal stampede protection.
|
||||
* See https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration
|
||||
* @param array &$metadata The metadata of the cached item {@see ItemInterface::getMetadata()}
|
||||
*
|
||||
* @return mixed The value corresponding to the provided key
|
||||
*
|
||||
* @throws InvalidArgumentException When $key is not valid or when $beta is negative
|
||||
*/
|
||||
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null);
|
||||
|
||||
/**
|
||||
* Removes an item from the pool.
|
||||
*
|
||||
* @param string $key The key to delete
|
||||
*
|
||||
* @throws InvalidArgumentException When $key is not valid
|
||||
*
|
||||
* @return bool True if the item was successfully removed, false if there was any error
|
||||
*/
|
||||
public function delete(string $key): bool;
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Cache;
|
||||
|
||||
use Psr\Cache\CacheItemPoolInterface;
|
||||
use Psr\Cache\InvalidArgumentException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* An implementation of CacheInterface for PSR-6 CacheItemPoolInterface classes.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
trait CacheTrait
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
|
||||
{
|
||||
return $this->doGet($this, $key, $callback, $beta, $metadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function delete(string $key): bool
|
||||
{
|
||||
return $this->deleteItem($key);
|
||||
}
|
||||
|
||||
private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null, LoggerInterface $logger = null)
|
||||
{
|
||||
if (0 > $beta = $beta ?? 1.0) {
|
||||
throw new class(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', \get_class($this), $beta)) extends \InvalidArgumentException implements InvalidArgumentException {
|
||||
};
|
||||
}
|
||||
|
||||
$item = $pool->getItem($key);
|
||||
$recompute = !$item->isHit() || INF === $beta;
|
||||
$metadata = $item instanceof ItemInterface ? $item->getMetadata() : [];
|
||||
|
||||
if (!$recompute && $metadata) {
|
||||
$expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
|
||||
$ctime = $metadata[ItemInterface::METADATA_CTIME] ?? false;
|
||||
|
||||
if ($recompute = $ctime && $expiry && $expiry <= ($now = microtime(true)) - $ctime / 1000 * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX)) {
|
||||
// force applying defaultLifetime to expiry
|
||||
$item->expiresAt(null);
|
||||
$this->logger && $this->logger->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
|
||||
'key' => $key,
|
||||
'delta' => sprintf('%.1f', $expiry - $now),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($recompute) {
|
||||
$save = true;
|
||||
$item->set($callback($item, $save));
|
||||
if ($save) {
|
||||
$pool->save($item);
|
||||
}
|
||||
}
|
||||
|
||||
return $item->get();
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Cache;
|
||||
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
|
||||
/**
|
||||
* Computes and returns the cached value of an item.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
interface CallbackInterface
|
||||
{
|
||||
/**
|
||||
* @param CacheItemInterface|ItemInterface $item The item to compute the value for
|
||||
* @param bool &$save Should be set to false when the value should not be saved in the pool
|
||||
*
|
||||
* @return mixed The computed value for the passed item
|
||||
*/
|
||||
public function __invoke(CacheItemInterface $item, bool &$save);
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Cache;
|
||||
|
||||
use Psr\Cache\CacheException;
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
use Psr\Cache\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Augments PSR-6's CacheItemInterface with support for tags and metadata.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
interface ItemInterface extends CacheItemInterface
|
||||
{
|
||||
/**
|
||||
* References the Unix timestamp stating when the item will expire.
|
||||
*/
|
||||
const METADATA_EXPIRY = 'expiry';
|
||||
|
||||
/**
|
||||
* References the time the item took to be created, in milliseconds.
|
||||
*/
|
||||
const METADATA_CTIME = 'ctime';
|
||||
|
||||
/**
|
||||
* References the list of tags that were assigned to the item, as string[].
|
||||
*/
|
||||
const METADATA_TAGS = 'tags';
|
||||
|
||||
/**
|
||||
* Adds a tag to a cache item.
|
||||
*
|
||||
* Tags are strings that follow the same validation rules as keys.
|
||||
*
|
||||
* @param string|string[] $tags A tag or array of tags
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
* @throws InvalidArgumentException When $tag is not valid
|
||||
* @throws CacheException When the item comes from a pool that is not tag-aware
|
||||
*/
|
||||
public function tag($tags): self;
|
||||
|
||||
/**
|
||||
* Returns a list of metadata info that were saved alongside with the cached value.
|
||||
*
|
||||
* See ItemInterface::METADATA_* consts for keys potentially found in the returned array.
|
||||
*/
|
||||
public function getMetadata(): array;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Cache;
|
||||
|
||||
use Psr\Cache\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Allows invalidating cached items using tags.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
interface TagAwareCacheInterface extends CacheInterface
|
||||
{
|
||||
/**
|
||||
* Invalidates cached items using tags.
|
||||
*
|
||||
* When implemented on a PSR-6 pool, invalidation should not apply
|
||||
* to deferred items. Instead, they should be committed as usual.
|
||||
* This allows replacing old tagged values by new ones without
|
||||
* race conditions.
|
||||
*
|
||||
* @param string[] $tags An array of tags to invalidate
|
||||
*
|
||||
* @return bool True on success
|
||||
*
|
||||
* @throws InvalidArgumentException When $tags is not valid
|
||||
*/
|
||||
public function invalidateTags(array $tags);
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient;
|
||||
|
||||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
||||
|
||||
/**
|
||||
* The interface of chunks returned by ResponseStreamInterface::current().
|
||||
*
|
||||
* When the chunk is first, last or timeout, the content MUST be empty.
|
||||
* When an unchecked timeout or a network error occurs, a TransportExceptionInterface
|
||||
* MUST be thrown by the destructor unless one was already thrown by another method.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
interface ChunkInterface
|
||||
{
|
||||
/**
|
||||
* Tells when the inactivity timeout has been reached.
|
||||
*
|
||||
* @throws TransportExceptionInterface on a network error
|
||||
*/
|
||||
public function isTimeout(): bool;
|
||||
|
||||
/**
|
||||
* Tells when headers just arrived.
|
||||
*
|
||||
* @throws TransportExceptionInterface on a network error or when the inactivity timeout is reached
|
||||
*/
|
||||
public function isFirst(): bool;
|
||||
|
||||
/**
|
||||
* Tells when the body just completed.
|
||||
*
|
||||
* @throws TransportExceptionInterface on a network error or when the inactivity timeout is reached
|
||||
*/
|
||||
public function isLast(): bool;
|
||||
|
||||
/**
|
||||
* Returns the content of the response chunk.
|
||||
*
|
||||
* @throws TransportExceptionInterface on a network error or when the inactivity timeout is reached
|
||||
*/
|
||||
public function getContent(): string;
|
||||
|
||||
/**
|
||||
* Returns the offset of the chunk in the response body.
|
||||
*/
|
||||
public function getOffset(): int;
|
||||
|
||||
/**
|
||||
* In case of error, returns the message that describes it.
|
||||
*/
|
||||
public function getError(): ?string;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient\Exception;
|
||||
|
||||
use Symfony\Contracts\HttpClient\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Base interface for HTTP-related exceptions.
|
||||
*
|
||||
* @author Anton Chernikov <anton_ch1989@mail.ru>
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
interface HttpExceptionInterface extends ExceptionInterface
|
||||
{
|
||||
public function getResponse(): ResponseInterface;
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient\Exception;
|
||||
|
||||
/**
|
||||
* When a 3xx response is returned and the "max_redirects" option has been reached.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
interface RedirectionExceptionInterface extends HttpExceptionInterface
|
||||
{
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient;
|
||||
|
||||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Test\HttpClientTestCase;
|
||||
|
||||
/**
|
||||
* Provides flexible methods for requesting HTTP resources synchronously or asynchronously.
|
||||
*
|
||||
* @see HttpClientTestCase for a reference test suite
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
interface HttpClientInterface
|
||||
{
|
||||
public const OPTIONS_DEFAULTS = [
|
||||
'auth_basic' => null, // array|string - an array containing the username as first value, and optionally the
|
||||
// password as the second one; or string like username:password - enabling HTTP Basic
|
||||
// authentication (RFC 7617)
|
||||
'auth_bearer' => null, // string - a token enabling HTTP Bearer authorization (RFC 6750)
|
||||
'query' => [], // string[] - associative array of query string values to merge with the request's URL
|
||||
'headers' => [], // iterable|string[]|string[][] - headers names provided as keys or as part of values
|
||||
'body' => '', // array|string|resource|\Traversable|\Closure - the callback SHOULD yield a string
|
||||
// smaller than the amount requested as argument; the empty string signals EOF; when
|
||||
// an array is passed, it is meant as a form payload of field names and values
|
||||
'json' => null, // array|\JsonSerializable - when set, implementations MUST set the "body" option to
|
||||
// the JSON-encoded value and set the "content-type" headers to a JSON-compatible
|
||||
// value if they are not defined - typically "application/json"
|
||||
'user_data' => null, // mixed - any extra data to attach to the request (scalar, callable, object...) that
|
||||
// MUST be available via $response->getInfo('user_data') - not used internally
|
||||
'max_redirects' => 20, // int - the maximum number of redirects to follow; a value lower or equal to 0 means
|
||||
// redirects should not be followed; "Authorization" and "Cookie" headers MUST
|
||||
// NOT follow except for the initial host name
|
||||
'http_version' => null, // string - defaults to the best supported version, typically 1.1 or 2.0
|
||||
'base_uri' => null, // string - the URI to resolve relative URLs, following rules in RFC 3986, section 2
|
||||
'buffer' => true, // bool - whether the content of the response should be buffered or not
|
||||
'on_progress' => null, // callable(int $dlNow, int $dlSize, array $info) - throwing any exceptions MUST abort
|
||||
// the request; it MUST be called on DNS resolution, on arrival of headers and on
|
||||
// completion; it SHOULD be called on upload/download of data and at least 1/s
|
||||
'resolve' => [], // string[] - a map of host to IP address that SHOULD replace DNS resolution
|
||||
'proxy' => null, // string - by default, the proxy-related env vars handled by curl SHOULD be honored
|
||||
'no_proxy' => null, // string - a comma separated list of hosts that do not require a proxy to be reached
|
||||
'timeout' => null, // float - the inactivity timeout - defaults to ini_get('default_socket_timeout')
|
||||
'bindto' => '0', // string - the interface or the local socket to bind to
|
||||
'verify_peer' => true, // see https://php.net/context.ssl for the following options
|
||||
'verify_host' => true,
|
||||
'cafile' => null,
|
||||
'capath' => null,
|
||||
'local_cert' => null,
|
||||
'local_pk' => null,
|
||||
'passphrase' => null,
|
||||
'ciphers' => null,
|
||||
'peer_fingerprint' => null,
|
||||
'capture_peer_cert_chain' => false,
|
||||
'extra' => [], // array - additional options that can be ignored if unsupported, unlike regular options
|
||||
];
|
||||
|
||||
/**
|
||||
* Requests an HTTP resource.
|
||||
*
|
||||
* Responses MUST be lazy, but their status code MUST be
|
||||
* checked even if none of their public methods are called.
|
||||
*
|
||||
* Implementations are not required to support all options described above; they can also
|
||||
* support more custom options; but in any case, they MUST throw a TransportExceptionInterface
|
||||
* when an unsupported option is passed.
|
||||
*
|
||||
* @throws TransportExceptionInterface When an unsupported option is passed
|
||||
*/
|
||||
public function request(string $method, string $url, array $options = []): ResponseInterface;
|
||||
|
||||
/**
|
||||
* Yields responses chunk by chunk as they complete.
|
||||
*
|
||||
* @param ResponseInterface|ResponseInterface[]|iterable $responses One or more responses created by the current HTTP client
|
||||
* @param float|null $timeout The inactivity timeout before exiting the iterator
|
||||
*/
|
||||
public function stream($responses, float $timeout = null): ResponseStreamInterface;
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient;
|
||||
|
||||
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
||||
|
||||
/**
|
||||
* A (lazily retrieved) HTTP response.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
interface ResponseInterface
|
||||
{
|
||||
/**
|
||||
* Gets the HTTP status code of the response.
|
||||
*
|
||||
* @throws TransportExceptionInterface when a network error occurs
|
||||
*/
|
||||
public function getStatusCode(): int;
|
||||
|
||||
/**
|
||||
* Gets the HTTP headers of the response.
|
||||
*
|
||||
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
|
||||
*
|
||||
* @return string[][] The headers of the response keyed by header names in lowercase
|
||||
*
|
||||
* @throws TransportExceptionInterface When a network error occurs
|
||||
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
|
||||
* @throws ClientExceptionInterface On a 4xx when $throw is true
|
||||
* @throws ServerExceptionInterface On a 5xx when $throw is true
|
||||
*/
|
||||
public function getHeaders(bool $throw = true): array;
|
||||
|
||||
/**
|
||||
* Gets the response body as a string.
|
||||
*
|
||||
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
|
||||
*
|
||||
* @throws TransportExceptionInterface When a network error occurs
|
||||
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
|
||||
* @throws ClientExceptionInterface On a 4xx when $throw is true
|
||||
* @throws ServerExceptionInterface On a 5xx when $throw is true
|
||||
*/
|
||||
public function getContent(bool $throw = true): string;
|
||||
|
||||
/**
|
||||
* Gets the response body decoded as array, typically from a JSON payload.
|
||||
*
|
||||
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
|
||||
*
|
||||
* @throws TransportExceptionInterface When the body cannot be decoded or when a network error occurs
|
||||
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
|
||||
* @throws ClientExceptionInterface On a 4xx when $throw is true
|
||||
* @throws ServerExceptionInterface On a 5xx when $throw is true
|
||||
*/
|
||||
public function toArray(bool $throw = true): array;
|
||||
|
||||
/**
|
||||
* Returns info coming from the transport layer.
|
||||
*
|
||||
* This method SHOULD NOT throw any ExceptionInterface and SHOULD be non-blocking.
|
||||
* The returned info is "live": it can be empty and can change from one call to
|
||||
* another, as the request/response progresses.
|
||||
*
|
||||
* The following info MUST be returned:
|
||||
* - response_headers - an array modelled after the special $http_response_header variable
|
||||
* - redirect_count - the number of redirects followed while executing the request
|
||||
* - redirect_url - the resolved location of redirect responses, null otherwise
|
||||
* - start_time - the time when the request was sent or 0.0 when it's pending
|
||||
* - http_method - the HTTP verb of the last request
|
||||
* - http_code - the last response code or 0 when it is not known yet
|
||||
* - error - the error message when the transfer was aborted, null otherwise
|
||||
* - user_data - the value of the "user_data" request option, null if not set
|
||||
* - url - the last effective URL of the request
|
||||
*
|
||||
* When the "capture_peer_cert_chain" option is true, the "peer_certificate_chain"
|
||||
* attribute SHOULD list the peer certificates as an array of OpenSSL X.509 resources.
|
||||
*
|
||||
* Other info SHOULD be named after curl_getinfo()'s associative return value.
|
||||
*
|
||||
* @return array|mixed|null An array of all available info, or one of them when $type is
|
||||
* provided, or null when an unsupported type is requested
|
||||
*/
|
||||
public function getInfo(string $type = null);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient;
|
||||
|
||||
/**
|
||||
* Yields response chunks, returned by HttpClientInterface::stream().
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
interface ResponseStreamInterface extends \Iterator
|
||||
{
|
||||
public function key(): ResponseInterface;
|
||||
|
||||
public function current(): ChunkInterface;
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
<?php
|
||||
|
||||
if ('cli-server' !== \PHP_SAPI) {
|
||||
// safe guard against unwanted execution
|
||||
throw new \Exception("You cannot run this script directly, it's a fixture for TestHttpServer.");
|
||||
}
|
||||
|
||||
$vars = [];
|
||||
|
||||
if (!$_POST) {
|
||||
$_POST = json_decode(file_get_contents('php://input'), true);
|
||||
$_POST['content-type'] = $_SERVER['HTTP_CONTENT_TYPE'] ?? '?';
|
||||
}
|
||||
|
||||
foreach ($_SERVER as $k => $v) {
|
||||
switch ($k) {
|
||||
default:
|
||||
if (0 !== strpos($k, 'HTTP_')) {
|
||||
continue 2;
|
||||
}
|
||||
// no break
|
||||
case 'SERVER_NAME':
|
||||
case 'SERVER_PROTOCOL':
|
||||
case 'REQUEST_URI':
|
||||
case 'REQUEST_METHOD':
|
||||
case 'PHP_AUTH_USER':
|
||||
case 'PHP_AUTH_PW':
|
||||
$vars[$k] = $v;
|
||||
}
|
||||
}
|
||||
|
||||
switch ($vars['REQUEST_URI']) {
|
||||
default:
|
||||
exit;
|
||||
|
||||
case '/':
|
||||
case '/?a=a&b=b':
|
||||
case 'http://127.0.0.1:8057/':
|
||||
case 'http://localhost:8057/':
|
||||
header('Content-Type: application/json');
|
||||
ob_start('ob_gzhandler');
|
||||
break;
|
||||
|
||||
case '/404':
|
||||
header('Content-Type: application/json', true, 404);
|
||||
break;
|
||||
|
||||
case '/301':
|
||||
if ('Basic Zm9vOmJhcg==' === $vars['HTTP_AUTHORIZATION']) {
|
||||
header('Location: http://127.0.0.1:8057/302', true, 301);
|
||||
}
|
||||
break;
|
||||
|
||||
case '/301/bad-tld':
|
||||
header('Location: http://foo.example.', true, 301);
|
||||
break;
|
||||
|
||||
case '/302':
|
||||
if (!isset($vars['HTTP_AUTHORIZATION'])) {
|
||||
header('Location: http://localhost:8057/', true, 302);
|
||||
}
|
||||
break;
|
||||
|
||||
case '/302/relative':
|
||||
header('Location: ..', true, 302);
|
||||
break;
|
||||
|
||||
case '/307':
|
||||
header('Location: http://localhost:8057/post', true, 307);
|
||||
break;
|
||||
|
||||
case '/length-broken':
|
||||
header('Content-Length: 1000');
|
||||
break;
|
||||
|
||||
case '/post':
|
||||
$output = json_encode($_POST + ['REQUEST_METHOD' => $vars['REQUEST_METHOD']], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
header('Content-Type: application/json', true);
|
||||
header('Content-Length: '.\strlen($output));
|
||||
echo $output;
|
||||
exit;
|
||||
|
||||
case '/timeout-header':
|
||||
usleep(300000);
|
||||
break;
|
||||
|
||||
case '/timeout-body':
|
||||
echo '<1>';
|
||||
@ob_flush();
|
||||
flush();
|
||||
usleep(500000);
|
||||
echo '<2>';
|
||||
exit;
|
||||
|
||||
case '/timeout-long':
|
||||
ignore_user_abort(false);
|
||||
sleep(1);
|
||||
while (true) {
|
||||
echo '<1>';
|
||||
@ob_flush();
|
||||
flush();
|
||||
usleep(500);
|
||||
}
|
||||
exit;
|
||||
|
||||
case '/chunked':
|
||||
header('Transfer-Encoding: chunked');
|
||||
echo "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\nesome!\r\n0\r\n\r\n";
|
||||
exit;
|
||||
|
||||
case '/chunked-broken':
|
||||
header('Transfer-Encoding: chunked');
|
||||
echo "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\ne";
|
||||
exit;
|
||||
|
||||
case '/gzip-broken':
|
||||
header('Content-Encoding: gzip');
|
||||
echo str_repeat('-', 1000);
|
||||
exit;
|
||||
}
|
||||
|
||||
header('Content-Type: application/json', true);
|
||||
|
||||
echo json_encode($vars, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
@@ -1,733 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient\Test;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/**
|
||||
* A reference test suite for HttpClientInterface implementations.
|
||||
*
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
abstract class HttpClientTestCase extends TestCase
|
||||
{
|
||||
private static $server;
|
||||
|
||||
public static function setUpBeforeClass()
|
||||
{
|
||||
TestHttpServer::start();
|
||||
}
|
||||
|
||||
abstract protected function getHttpClient(string $testCase): HttpClientInterface;
|
||||
|
||||
public function testGetRequest()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057', [
|
||||
'headers' => ['Foo' => 'baR'],
|
||||
'user_data' => $data = new \stdClass(),
|
||||
]);
|
||||
|
||||
$this->assertSame([], $response->getInfo('response_headers'));
|
||||
$this->assertSame($data, $response->getInfo()['user_data']);
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
|
||||
$info = $response->getInfo();
|
||||
$this->assertNull($info['error']);
|
||||
$this->assertSame(0, $info['redirect_count']);
|
||||
$this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
|
||||
$this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
|
||||
$this->assertSame('http://localhost:8057/', $info['url']);
|
||||
|
||||
$headers = $response->getHeaders();
|
||||
|
||||
$this->assertSame('localhost:8057', $headers['host'][0]);
|
||||
$this->assertSame(['application/json'], $headers['content-type']);
|
||||
|
||||
$body = json_decode($response->getContent(), true);
|
||||
$this->assertSame($body, $response->toArray());
|
||||
|
||||
$this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
|
||||
$this->assertSame('/', $body['REQUEST_URI']);
|
||||
$this->assertSame('GET', $body['REQUEST_METHOD']);
|
||||
$this->assertSame('localhost:8057', $body['HTTP_HOST']);
|
||||
$this->assertSame('baR', $body['HTTP_FOO']);
|
||||
|
||||
$response = $client->request('GET', 'http://localhost:8057/length-broken');
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getContent();
|
||||
}
|
||||
|
||||
public function testNonBufferedGetRequest()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057', [
|
||||
'buffer' => false,
|
||||
'headers' => ['Foo' => 'baR'],
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
$this->assertSame('baR', $body['HTTP_FOO']);
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getContent();
|
||||
}
|
||||
|
||||
public function testUnsupportedOption()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$client->request('GET', 'http://localhost:8057', [
|
||||
'capture_peer_cert' => 1.0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function testHttpVersion()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057', [
|
||||
'http_version' => 1.0,
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
$this->assertSame('HTTP/1.0 200 OK', $response->getInfo('response_headers')[0]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame('HTTP/1.0', $body['SERVER_PROTOCOL']);
|
||||
$this->assertSame('GET', $body['REQUEST_METHOD']);
|
||||
$this->assertSame('/', $body['REQUEST_URI']);
|
||||
}
|
||||
|
||||
public function testChunkedEncoding()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/chunked');
|
||||
|
||||
$this->assertSame(['chunked'], $response->getHeaders()['transfer-encoding']);
|
||||
$this->assertSame('Symfony is awesome!', $response->getContent());
|
||||
|
||||
$response = $client->request('GET', 'http://localhost:8057/chunked-broken');
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getContent();
|
||||
}
|
||||
|
||||
public function testClientError()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/404');
|
||||
|
||||
$client->stream($response)->valid();
|
||||
|
||||
$this->assertSame(404, $response->getInfo('http_code'));
|
||||
|
||||
try {
|
||||
$response->getHeaders();
|
||||
$this->fail(ClientExceptionInterface::class.' expected');
|
||||
} catch (ClientExceptionInterface $e) {
|
||||
}
|
||||
|
||||
try {
|
||||
$response->getContent();
|
||||
$this->fail(ClientExceptionInterface::class.' expected');
|
||||
} catch (ClientExceptionInterface $e) {
|
||||
}
|
||||
|
||||
$this->assertSame(404, $response->getStatusCode());
|
||||
$this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
|
||||
$this->assertNotEmpty($response->getContent(false));
|
||||
}
|
||||
|
||||
public function testIgnoreErrors()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/404');
|
||||
|
||||
$this->assertSame(404, $response->getStatusCode());
|
||||
}
|
||||
|
||||
public function testDnsError()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
|
||||
|
||||
try {
|
||||
$response->getStatusCode();
|
||||
$this->fail(TransportExceptionInterface::class.' expected');
|
||||
} catch (TransportExceptionInterface $e) {
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
try {
|
||||
$response->getStatusCode();
|
||||
$this->fail(TransportExceptionInterface::class.' still expected');
|
||||
} catch (TransportExceptionInterface $e) {
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
$response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
|
||||
|
||||
try {
|
||||
foreach ($client->stream($response) as $r => $chunk) {
|
||||
}
|
||||
$this->fail(TransportExceptionInterface::class.' expected');
|
||||
} catch (TransportExceptionInterface $e) {
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
$this->assertSame($response, $r);
|
||||
$this->assertNotNull($chunk->getError());
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
foreach ($client->stream($response) as $chunk) {
|
||||
}
|
||||
}
|
||||
|
||||
public function testInlineAuth()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://foo:bar%3Dbar@localhost:8057');
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame('foo', $body['PHP_AUTH_USER']);
|
||||
$this->assertSame('bar=bar', $body['PHP_AUTH_PW']);
|
||||
}
|
||||
|
||||
public function testBadRequestBody()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/', [
|
||||
'body' => function () { yield []; },
|
||||
]);
|
||||
|
||||
$response->getStatusCode();
|
||||
}
|
||||
|
||||
public function testRedirects()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('POST', 'http://localhost:8057/301', [
|
||||
'auth_basic' => 'foo:bar',
|
||||
'body' => function () {
|
||||
yield 'foo=bar';
|
||||
},
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
$this->assertSame('GET', $body['REQUEST_METHOD']);
|
||||
$this->assertSame('Basic Zm9vOmJhcg==', $body['HTTP_AUTHORIZATION']);
|
||||
$this->assertSame('http://localhost:8057/', $response->getInfo('url'));
|
||||
|
||||
$this->assertSame(2, $response->getInfo('redirect_count'));
|
||||
$this->assertNull($response->getInfo('redirect_url'));
|
||||
|
||||
$expected = [
|
||||
'HTTP/1.1 301 Moved Permanently',
|
||||
'Location: http://127.0.0.1:8057/302',
|
||||
'Content-Type: application/json',
|
||||
'HTTP/1.1 302 Found',
|
||||
'Location: http://localhost:8057/',
|
||||
'Content-Type: application/json',
|
||||
'HTTP/1.1 200 OK',
|
||||
'Content-Type: application/json',
|
||||
];
|
||||
|
||||
$filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), function ($h) {
|
||||
return \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true) && 'Content-Encoding: gzip' !== $h;
|
||||
}));
|
||||
|
||||
$this->assertSame($expected, $filteredHeaders);
|
||||
}
|
||||
|
||||
public function testRelativeRedirects()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/302/relative');
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame('/', $body['REQUEST_URI']);
|
||||
$this->assertNull($response->getInfo('redirect_url'));
|
||||
|
||||
$response = $client->request('GET', 'http://localhost:8057/302/relative', [
|
||||
'max_redirects' => 0,
|
||||
]);
|
||||
|
||||
$this->assertSame(302, $response->getStatusCode());
|
||||
$this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
|
||||
}
|
||||
|
||||
public function testRedirect307()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/307', [
|
||||
'body' => function () {
|
||||
yield 'foo=bar';
|
||||
},
|
||||
'max_redirects' => 0,
|
||||
]);
|
||||
|
||||
$this->assertSame(307, $response->getStatusCode());
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/307', [
|
||||
'body' => 'foo=bar',
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
|
||||
}
|
||||
|
||||
public function testMaxRedirects()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/301', [
|
||||
'max_redirects' => 1,
|
||||
'auth_basic' => 'foo:bar',
|
||||
]);
|
||||
|
||||
try {
|
||||
$response->getHeaders();
|
||||
$this->fail(RedirectionExceptionInterface::class.' expected');
|
||||
} catch (RedirectionExceptionInterface $e) {
|
||||
}
|
||||
|
||||
$this->assertSame(302, $response->getStatusCode());
|
||||
$this->assertSame(1, $response->getInfo('redirect_count'));
|
||||
$this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
|
||||
|
||||
$expected = [
|
||||
'HTTP/1.1 301 Moved Permanently',
|
||||
'Location: http://127.0.0.1:8057/302',
|
||||
'Content-Type: application/json',
|
||||
'HTTP/1.1 302 Found',
|
||||
'Location: http://localhost:8057/',
|
||||
'Content-Type: application/json',
|
||||
];
|
||||
|
||||
$filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), function ($h) {
|
||||
return \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true);
|
||||
}));
|
||||
|
||||
$this->assertSame($expected, $filteredHeaders);
|
||||
}
|
||||
|
||||
public function testStream()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$response = $client->request('GET', 'http://localhost:8057');
|
||||
$chunks = $client->stream($response);
|
||||
$result = [];
|
||||
|
||||
foreach ($chunks as $r => $chunk) {
|
||||
if ($chunk->isTimeout()) {
|
||||
$result[] = 't';
|
||||
} elseif ($chunk->isLast()) {
|
||||
$result[] = 'l';
|
||||
} elseif ($chunk->isFirst()) {
|
||||
$result[] = 'f';
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertSame($response, $r);
|
||||
$this->assertSame(['f', 'l'], $result);
|
||||
|
||||
$chunk = null;
|
||||
$i = 0;
|
||||
|
||||
foreach ($client->stream($response) as $chunk) {
|
||||
++$i;
|
||||
}
|
||||
|
||||
$this->assertSame(1, $i);
|
||||
$this->assertTrue($chunk->isLast());
|
||||
}
|
||||
|
||||
public function testAddToStream()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$r1 = $client->request('GET', 'http://localhost:8057');
|
||||
|
||||
$completed = [];
|
||||
|
||||
$pool = [$r1];
|
||||
|
||||
while ($pool) {
|
||||
$chunks = $client->stream($pool);
|
||||
$pool = [];
|
||||
|
||||
foreach ($chunks as $r => $chunk) {
|
||||
if (!$chunk->isLast()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($r1 === $r) {
|
||||
$r2 = $client->request('GET', 'http://localhost:8057');
|
||||
$pool[] = $r2;
|
||||
}
|
||||
|
||||
$completed[] = $r;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertSame([$r1, $r2], $completed);
|
||||
}
|
||||
|
||||
public function testCompleteTypeError()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$this->expectException(\TypeError::class);
|
||||
$client->stream(123);
|
||||
}
|
||||
|
||||
public function testOnProgress()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('POST', 'http://localhost:8057/post', [
|
||||
'headers' => ['Content-Length' => 14],
|
||||
'body' => 'foo=0123456789',
|
||||
'on_progress' => function (...$state) use (&$steps) { $steps[] = $state; },
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
|
||||
$this->assertSame([0, 0], \array_slice($steps[0], 0, 2));
|
||||
$lastStep = \array_slice($steps, -1)[0];
|
||||
$this->assertSame([57, 57], \array_slice($lastStep, 0, 2));
|
||||
$this->assertSame('http://localhost:8057/post', $steps[0][2]['url']);
|
||||
}
|
||||
|
||||
public function testPostJson()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/post', [
|
||||
'json' => ['foo' => 'bar'],
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertContains('json', $body['content-type']);
|
||||
unset($body['content-type']);
|
||||
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
|
||||
}
|
||||
|
||||
public function testPostArray()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/post', [
|
||||
'body' => ['foo' => 'bar'],
|
||||
]);
|
||||
|
||||
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $response->toArray());
|
||||
}
|
||||
|
||||
public function testPostResource()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$h = fopen('php://temp', 'w+');
|
||||
fwrite($h, 'foo=0123456789');
|
||||
rewind($h);
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/post', [
|
||||
'body' => $h,
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
|
||||
}
|
||||
|
||||
public function testPostCallback()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$response = $client->request('POST', 'http://localhost:8057/post', [
|
||||
'body' => function () {
|
||||
yield 'foo';
|
||||
yield '';
|
||||
yield '=';
|
||||
yield '0123456789';
|
||||
},
|
||||
]);
|
||||
|
||||
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray());
|
||||
}
|
||||
|
||||
public function testOnProgressCancel()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
|
||||
'on_progress' => function ($dlNow) {
|
||||
if (0 < $dlNow) {
|
||||
throw new \Exception('Aborting the request');
|
||||
}
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
foreach ($client->stream([$response]) as $chunk) {
|
||||
}
|
||||
$this->fail(ClientExceptionInterface::class.' expected');
|
||||
} catch (TransportExceptionInterface $e) {
|
||||
$this->assertSame('Aborting the request', $e->getPrevious()->getMessage());
|
||||
}
|
||||
|
||||
$this->assertNotNull($response->getInfo('error'));
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getContent();
|
||||
}
|
||||
|
||||
public function testOnProgressError()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
|
||||
'on_progress' => function ($dlNow) {
|
||||
if (0 < $dlNow) {
|
||||
throw new \Error('BUG');
|
||||
}
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
foreach ($client->stream([$response]) as $chunk) {
|
||||
}
|
||||
$this->fail('Error expected');
|
||||
} catch (\Error $e) {
|
||||
$this->assertSame('BUG', $e->getMessage());
|
||||
}
|
||||
|
||||
$this->assertNotNull($response->getInfo('error'));
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getContent();
|
||||
}
|
||||
|
||||
public function testResolve()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://symfony.com:8057/', [
|
||||
'resolve' => ['symfony.com' => '127.0.0.1'],
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
$this->assertSame(200, $client->request('GET', 'http://symfony.com:8057/')->getStatusCode());
|
||||
|
||||
$response = null;
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$client->request('GET', 'http://symfony.com:8057/', ['timeout' => 3]);
|
||||
}
|
||||
|
||||
public function testTimeoutOnAccess()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/timeout-header', [
|
||||
'timeout' => 0.1,
|
||||
]);
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getHeaders();
|
||||
}
|
||||
|
||||
public function testTimeoutOnStream()
|
||||
{
|
||||
usleep(300000); // wait for the previous test to release the server
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/timeout-body');
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
$chunks = $client->stream([$response], 0.2);
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach ($chunks as $r => $chunk) {
|
||||
if ($chunk->isTimeout()) {
|
||||
$result[] = 't';
|
||||
} else {
|
||||
$result[] = $chunk->getContent();
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertSame(['<1>', 't'], $result);
|
||||
|
||||
$chunks = $client->stream([$response]);
|
||||
|
||||
foreach ($chunks as $r => $chunk) {
|
||||
$this->assertSame('<2>', $chunk->getContent());
|
||||
$this->assertSame('<1><2>', $r->getContent());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->fail('The response should have completed');
|
||||
}
|
||||
|
||||
public function testUncheckedTimeoutThrows()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/timeout-body');
|
||||
$chunks = $client->stream([$response], 0.1);
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
|
||||
foreach ($chunks as $r => $chunk) {
|
||||
}
|
||||
}
|
||||
|
||||
public function testDestruct()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
|
||||
$downloaded = 0;
|
||||
$start = microtime(true);
|
||||
$client->request('GET', 'http://localhost:8057/timeout-long');
|
||||
$client = null;
|
||||
$duration = microtime(true) - $start;
|
||||
|
||||
$this->assertGreaterThan(1, $duration);
|
||||
$this->assertLessThan(3, $duration);
|
||||
}
|
||||
|
||||
public function testProxy()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/', [
|
||||
'proxy' => 'http://localhost:8057',
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
$this->assertSame('localhost:8057', $body['HTTP_HOST']);
|
||||
$this->assertRegexp('#^http://(localhost|127\.0\.0\.1):8057/$#', $body['REQUEST_URI']);
|
||||
|
||||
$response = $client->request('GET', 'http://localhost:8057/', [
|
||||
'proxy' => 'http://foo:b%3Dar@localhost:8057',
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
$this->assertSame('Basic Zm9vOmI9YXI=', $body['HTTP_PROXY_AUTHORIZATION']);
|
||||
}
|
||||
|
||||
public function testNoProxy()
|
||||
{
|
||||
putenv('no_proxy='.$_SERVER['no_proxy'] = 'example.com, localhost');
|
||||
|
||||
try {
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/', [
|
||||
'proxy' => 'http://localhost:8057',
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
|
||||
$this->assertSame('/', $body['REQUEST_URI']);
|
||||
$this->assertSame('GET', $body['REQUEST_METHOD']);
|
||||
} finally {
|
||||
putenv('no_proxy');
|
||||
unset($_SERVER['no_proxy']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @requires extension zlib
|
||||
*/
|
||||
public function testAutoEncodingRequest()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057');
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
|
||||
$headers = $response->getHeaders();
|
||||
|
||||
$this->assertSame(['Accept-Encoding'], $headers['vary']);
|
||||
$this->assertContains('gzip', $headers['content-encoding'][0]);
|
||||
|
||||
$body = $response->toArray();
|
||||
|
||||
$this->assertContains('gzip', $body['HTTP_ACCEPT_ENCODING']);
|
||||
}
|
||||
|
||||
public function testBaseUri()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', '../404', [
|
||||
'base_uri' => 'http://localhost:8057/abc/',
|
||||
]);
|
||||
|
||||
$this->assertSame(404, $response->getStatusCode());
|
||||
$this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
|
||||
}
|
||||
|
||||
public function testQuery()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/?a=a', [
|
||||
'query' => ['b' => 'b'],
|
||||
]);
|
||||
|
||||
$body = $response->toArray();
|
||||
$this->assertSame('GET', $body['REQUEST_METHOD']);
|
||||
$this->assertSame('/?a=a&b=b', $body['REQUEST_URI']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @requires extension zlib
|
||||
*/
|
||||
public function testUserlandEncodingRequest()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057', [
|
||||
'headers' => ['Accept-Encoding' => 'gzip'],
|
||||
]);
|
||||
|
||||
$headers = $response->getHeaders();
|
||||
|
||||
$this->assertSame(['Accept-Encoding'], $headers['vary']);
|
||||
$this->assertContains('gzip', $headers['content-encoding'][0]);
|
||||
|
||||
$body = $response->getContent();
|
||||
$this->assertSame("\x1F", $body[0]);
|
||||
|
||||
$body = json_decode(gzdecode($body), true);
|
||||
$this->assertSame('gzip', $body['HTTP_ACCEPT_ENCODING']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @requires extension zlib
|
||||
*/
|
||||
public function testGzipBroken()
|
||||
{
|
||||
$client = $this->getHttpClient(__FUNCTION__);
|
||||
$response = $client->request('GET', 'http://localhost:8057/gzip-broken');
|
||||
|
||||
$this->expectException(TransportExceptionInterface::class);
|
||||
$response->getContent();
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\HttpClient\Test;
|
||||
|
||||
use Symfony\Component\Process\PhpExecutableFinder;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
* @experimental in 1.1
|
||||
*/
|
||||
class TestHttpServer
|
||||
{
|
||||
private static $server;
|
||||
|
||||
public static function start()
|
||||
{
|
||||
if (null !== self::$server) {
|
||||
return;
|
||||
}
|
||||
|
||||
$finder = new PhpExecutableFinder();
|
||||
$process = new Process(array_merge([$finder->find(false)], $finder->findArguments(), ['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:8057']));
|
||||
$process->setWorkingDirectory(__DIR__.'/Fixtures/web');
|
||||
$process->setTimeout(300);
|
||||
$process->start();
|
||||
|
||||
self::$server = new class() {
|
||||
public $process;
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
$this->process->stop();
|
||||
}
|
||||
};
|
||||
|
||||
self::$server->process = $process;
|
||||
|
||||
sleep('\\' === \DIRECTORY_SEPARATOR ? 10 : 1);
|
||||
}
|
||||
}
|
||||
Vendored
-70
@@ -1,70 +0,0 @@
|
||||
Symfony Contracts
|
||||
=================
|
||||
|
||||
A set of abstractions extracted out of the Symfony components.
|
||||
|
||||
Can be used to build on semantics that the Symfony components proved useful - and
|
||||
that already have battle tested implementations.
|
||||
|
||||
Design Principles
|
||||
-----------------
|
||||
|
||||
* contracts are split by domain, each into their own sub-namespaces;
|
||||
* contracts are small and consistent sets of PHP interfaces, traits, normative
|
||||
docblocks and reference test suites when applicable, ...;
|
||||
* all contracts must have a proven implementation to enter this repository;
|
||||
* they must be backward compatible with existing Symfony components.
|
||||
|
||||
Packages that implement specific contracts should list them in the "provide"
|
||||
section of their "composer.json" file, using the `symfony/*-contracts-implementation`
|
||||
convention (e.g. `"provide": { "symfony/cache-contracts-implementation": "1.0" }`).
|
||||
|
||||
FAQ
|
||||
---
|
||||
|
||||
### How to use this package?
|
||||
|
||||
The abstractions in this package are useful to achieve loose coupling and
|
||||
interoperability. By using the provided interfaces as type hints, you are able
|
||||
to reuse any implementations that match their contracts. It could be a Symfony
|
||||
component, or another one provided by the PHP community at large.
|
||||
|
||||
Depending on their semantics, some interfaces can be combined with autowiring to
|
||||
seamlessly inject a service in your classes.
|
||||
|
||||
Others might be useful as labeling interfaces, to hint about a specific behavior
|
||||
that could be enabled when using autoconfiguration or manual service tagging (or
|
||||
any other means provided by your framework.)
|
||||
|
||||
### How is this different from PHP-FIG's PSRs?
|
||||
|
||||
When applicable, the provided contracts are built on top of PHP-FIG's PSRs. But
|
||||
the group has different goals and different processes. Here, we're focusing on
|
||||
providing abstractions that are useful on their own while still compatible with
|
||||
implementations provided by Symfony. Although not the main target, we hope that
|
||||
the declared contracts will directly or indirectly contribute to the PHP-FIG.
|
||||
|
||||
### Why isn't this package split into several packages?
|
||||
|
||||
Putting all interfaces in one package eases discoverability and dependency
|
||||
management. Instead of dealing with a myriad of small packages and the
|
||||
corresponding matrix of versions, you just need to deal with one package and one
|
||||
version. Also when using IDE autocompletion or just reading the source code, it
|
||||
makes it easier to figure out which contracts are provided.
|
||||
|
||||
There are two downsides to this approach: you may have unused files in your
|
||||
`vendor/` directory, and in the future, it will be impossible to use two
|
||||
different sub-namespaces in different major versions of the package. For the
|
||||
"unused files" downside, it has no practical consequences: their file sizes are
|
||||
very small, and there is no performance overhead at all since they are never
|
||||
loaded. For major versions, this package follows the Symfony BC + deprecation
|
||||
policies, with an additional restriction to never remove deprecated interfaces.
|
||||
|
||||
Resources
|
||||
---------
|
||||
|
||||
* [Documentation](https://symfony.com/doc/current/components/contracts.html)
|
||||
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
|
||||
* [Report issues](https://github.com/symfony/symfony/issues) and
|
||||
[send Pull Requests](https://github.com/symfony/symfony/pulls)
|
||||
in the [main Symfony repository](https://github.com/symfony/symfony)
|
||||
@@ -1,165 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Tests\Cache;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
use Psr\Cache\CacheItemPoolInterface;
|
||||
use Symfony\Contracts\Cache\CacheTrait;
|
||||
|
||||
/**
|
||||
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
*/
|
||||
class CacheTraitTest extends TestCase
|
||||
{
|
||||
public function testSave()
|
||||
{
|
||||
$item = $this->getMockBuilder(CacheItemInterface::class)->getMock();
|
||||
$item->method('set')
|
||||
->willReturn($item);
|
||||
$item->method('isHit')
|
||||
->willReturn(false);
|
||||
|
||||
$item->expects($this->once())
|
||||
->method('set')
|
||||
->with('computed data');
|
||||
|
||||
$cache = $this->getMockBuilder(TestPool::class)
|
||||
->setMethods(['getItem', 'save'])
|
||||
->getMock();
|
||||
$cache->expects($this->once())
|
||||
->method('getItem')
|
||||
->with('key')
|
||||
->willReturn($item);
|
||||
$cache->expects($this->once())
|
||||
->method('save');
|
||||
|
||||
$callback = function (CacheItemInterface $item) {
|
||||
return 'computed data';
|
||||
};
|
||||
|
||||
$cache->get('key', $callback);
|
||||
}
|
||||
|
||||
public function testNoCallbackCallOnHit()
|
||||
{
|
||||
$item = $this->getMockBuilder(CacheItemInterface::class)->getMock();
|
||||
$item->method('isHit')
|
||||
->willReturn(true);
|
||||
|
||||
$item->expects($this->never())
|
||||
->method('set');
|
||||
|
||||
$cache = $this->getMockBuilder(TestPool::class)
|
||||
->setMethods(['getItem', 'save'])
|
||||
->getMock();
|
||||
|
||||
$cache->expects($this->once())
|
||||
->method('getItem')
|
||||
->with('key')
|
||||
->willReturn($item);
|
||||
$cache->expects($this->never())
|
||||
->method('save');
|
||||
|
||||
$callback = function (CacheItemInterface $item) {
|
||||
$this->assertTrue(false, 'This code should never be reached');
|
||||
};
|
||||
|
||||
$cache->get('key', $callback);
|
||||
}
|
||||
|
||||
public function testRecomputeOnBetaInf()
|
||||
{
|
||||
$item = $this->getMockBuilder(CacheItemInterface::class)->getMock();
|
||||
$item->method('set')
|
||||
->willReturn($item);
|
||||
$item->method('isHit')
|
||||
// We want to recompute even if it is a hit
|
||||
->willReturn(true);
|
||||
|
||||
$item->expects($this->once())
|
||||
->method('set')
|
||||
->with('computed data');
|
||||
|
||||
$cache = $this->getMockBuilder(TestPool::class)
|
||||
->setMethods(['getItem', 'save'])
|
||||
->getMock();
|
||||
|
||||
$cache->expects($this->once())
|
||||
->method('getItem')
|
||||
->with('key')
|
||||
->willReturn($item);
|
||||
$cache->expects($this->once())
|
||||
->method('save');
|
||||
|
||||
$callback = function (CacheItemInterface $item) {
|
||||
return 'computed data';
|
||||
};
|
||||
|
||||
$cache->get('key', $callback, INF);
|
||||
}
|
||||
|
||||
public function testExceptionOnNegativeBeta()
|
||||
{
|
||||
$cache = $this->getMockBuilder(TestPool::class)
|
||||
->setMethods(['getItem', 'save'])
|
||||
->getMock();
|
||||
|
||||
$callback = function (CacheItemInterface $item) {
|
||||
return 'computed data';
|
||||
};
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$cache->get('key', $callback, -2);
|
||||
}
|
||||
}
|
||||
|
||||
class TestPool implements CacheItemPoolInterface
|
||||
{
|
||||
use CacheTrait;
|
||||
|
||||
public function hasItem($key)
|
||||
{
|
||||
}
|
||||
|
||||
public function deleteItem($key)
|
||||
{
|
||||
}
|
||||
|
||||
public function deleteItems(array $keys = [])
|
||||
{
|
||||
}
|
||||
|
||||
public function getItem($key)
|
||||
{
|
||||
}
|
||||
|
||||
public function getItems(array $key = [])
|
||||
{
|
||||
}
|
||||
|
||||
public function saveDeferred(CacheItemInterface $item)
|
||||
{
|
||||
}
|
||||
|
||||
public function save(CacheItemInterface $item)
|
||||
{
|
||||
}
|
||||
|
||||
public function commit()
|
||||
{
|
||||
}
|
||||
|
||||
public function clear()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Contracts\Tests\Service;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Symfony\Contracts\Service\ServiceLocatorTrait;
|
||||
use Symfony\Contracts\Service\ServiceSubscriberInterface;
|
||||
use Symfony\Contracts\Service\ServiceSubscriberTrait;
|
||||
|
||||
class ServiceSubscriberTraitTest extends TestCase
|
||||
{
|
||||
public function testMethodsOnParentsAndChildrenAreIgnoredInGetSubscribedServices()
|
||||
{
|
||||
$expected = [TestService::class.'::aService' => '?Symfony\Contracts\Tests\Service\Service2'];
|
||||
|
||||
$this->assertEquals($expected, ChildTestService::getSubscribedServices());
|
||||
}
|
||||
|
||||
public function testSetContainerIsCalledOnParent()
|
||||
{
|
||||
$container = new class([]) implements ContainerInterface {
|
||||
use ServiceLocatorTrait;
|
||||
};
|
||||
|
||||
$this->assertSame($container, (new TestService())->setContainer($container));
|
||||
}
|
||||
}
|
||||
|
||||
class ParentTestService
|
||||
{
|
||||
public function aParentService(): Service1
|
||||
{
|
||||
}
|
||||
|
||||
public function setContainer(ContainerInterface $container)
|
||||
{
|
||||
return $container;
|
||||
}
|
||||
}
|
||||
|
||||
class TestService extends ParentTestService implements ServiceSubscriberInterface
|
||||
{
|
||||
use ServiceSubscriberTrait;
|
||||
|
||||
public function aService(): Service2
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
class ChildTestService extends TestService
|
||||
{
|
||||
public function aChildService(): Service3
|
||||
{
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
{
|
||||
"name": "symfony/contracts",
|
||||
"type": "library",
|
||||
"description": "A set of abstractions extracted out of the Symfony components",
|
||||
"keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"],
|
||||
"homepage": "https://symfony.com",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicolas Grekas",
|
||||
"email": "p@tchwork.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.1.3"
|
||||
},
|
||||
"require-dev": {
|
||||
"psr/cache": "^1.0",
|
||||
"psr/container": "^1.0",
|
||||
"symfony/polyfill-intl-idn": "^1.10"
|
||||
},
|
||||
"suggest": {
|
||||
"psr/cache": "When using the Cache contracts",
|
||||
"psr/container": "When using the Service contracts",
|
||||
"symfony/cache-contracts-implementation": "",
|
||||
"symfony/event-dispatcher-implementation": "",
|
||||
"symfony/http-client-contracts-implementation": "",
|
||||
"symfony/service-contracts-implementation": "",
|
||||
"symfony/translation-contracts-implementation": ""
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "Symfony\\Contracts\\": "" },
|
||||
"exclude-from-classmap": [
|
||||
"**/Tests/"
|
||||
]
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.1-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -89,7 +89,7 @@ class ParserTest extends TestCase
|
||||
|
||||
/** @var FunctionNode $function */
|
||||
$function = $selectors[0]->getTree();
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
|
||||
$this->expectException('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
|
||||
Parser::parseSeries($function->getArguments());
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ class TokenStreamTest extends TestCase
|
||||
|
||||
public function testFailToGetNextIdentifier()
|
||||
{
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
|
||||
$this->expectException('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
|
||||
|
||||
$stream = new TokenStream();
|
||||
$stream->push(new Token(Token::TYPE_DELIMITER, '.', 2));
|
||||
@@ -73,7 +73,7 @@ class TokenStreamTest extends TestCase
|
||||
|
||||
public function testFailToGetNextIdentifierOrStar()
|
||||
{
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
|
||||
$this->expectException('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
|
||||
|
||||
$stream = new TokenStream();
|
||||
$stream->push(new Token(Token::TYPE_DELIMITER, '.', 2));
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.2-dev"
|
||||
"dev-master": "4.3-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+8
@@ -1,6 +1,14 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* made the `ErrorHandler` and `ExceptionHandler` classes final
|
||||
* added `Exception\FlattenException::getAsString` and
|
||||
`Exception\FlattenException::getTraceAsString` to increase compatibility to php
|
||||
exception objects
|
||||
|
||||
4.0.0
|
||||
-----
|
||||
|
||||
|
||||
+43
-2
@@ -39,6 +39,7 @@ class DebugClassLoader
|
||||
private static $internalMethods = [];
|
||||
private static $annotatedParameters = [];
|
||||
private static $darwinCache = ['/' => ['/', []]];
|
||||
private static $method = [];
|
||||
|
||||
public function __construct(callable $classLoader)
|
||||
{
|
||||
@@ -236,6 +237,24 @@ class DebugClassLoader
|
||||
self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
|
||||
}
|
||||
}
|
||||
|
||||
if ($refl->isInterface() && false !== \strpos($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+(?:[\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, PREG_SET_ORDER)) {
|
||||
foreach ($notice as $method) {
|
||||
$static = '' !== $method[1];
|
||||
$name = $method[2];
|
||||
$description = $method[3] ?? null;
|
||||
if (false === strpos($name, '(')) {
|
||||
$name .= '()';
|
||||
}
|
||||
if (null !== $description) {
|
||||
$description = trim($description);
|
||||
if (!isset($method[4])) {
|
||||
$description .= '.';
|
||||
}
|
||||
}
|
||||
self::$method[$class][] = [$class, $name, $static, $description];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$parent = \get_parent_class($class);
|
||||
@@ -266,6 +285,28 @@ class DebugClassLoader
|
||||
if (isset(self::$internal[$use]) && \strncmp($ns, \str_replace('_', '\\', $use), $len)) {
|
||||
$deprecations[] = sprintf('The "%s" %s is considered internal%s. It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $class);
|
||||
}
|
||||
if (isset(self::$method[$use])) {
|
||||
if ($refl->isAbstract()) {
|
||||
if (isset(self::$method[$class])) {
|
||||
self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]);
|
||||
} else {
|
||||
self::$method[$class] = self::$method[$use];
|
||||
}
|
||||
} elseif (!$refl->isInterface()) {
|
||||
$hasCall = $refl->hasMethod('__call');
|
||||
$hasStaticCall = $refl->hasMethod('__callStatic');
|
||||
foreach (self::$method[$use] as $method) {
|
||||
list($interface, $name, $static, $description) = $method;
|
||||
if ($static ? $hasStaticCall : $hasCall) {
|
||||
continue;
|
||||
}
|
||||
$realName = substr($name, 0, strpos($name, '('));
|
||||
if (!$refl->hasMethod($realName) || !($methodRefl = $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) {
|
||||
$deprecations[] = sprintf('Class "%s" should implement method "%s::%s"%s', $class, ($static ? 'static ' : '').$interface, $name, null == $description ? '.' : ': '.$description);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (\trait_exists($class)) {
|
||||
@@ -311,7 +352,7 @@ class DebugClassLoader
|
||||
}
|
||||
|
||||
foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) {
|
||||
if (!isset($definedParameters[$parameterName]) && !($doc && preg_match("/\\n\\s+\\* @param (.*?)(?<= )\\\${$parameterName}\\b/", $doc))) {
|
||||
if (!isset($definedParameters[$parameterName]) && !($doc && preg_match("/\\n\\s+\\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\\\${$parameterName}\\b/", $doc))) {
|
||||
$deprecations[] = sprintf($deprecation, $class);
|
||||
}
|
||||
}
|
||||
@@ -334,7 +375,7 @@ class DebugClassLoader
|
||||
if ($finalOrInternal || $method->isConstructor() || false === \strpos($doc, '@param') || StatelessInvocation::class === $class) {
|
||||
continue;
|
||||
}
|
||||
if (!preg_match_all('#\n\s+\* @param (.*?)(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, PREG_SET_ORDER)) {
|
||||
if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, PREG_SET_ORDER)) {
|
||||
continue;
|
||||
}
|
||||
if (!isset(self::$annotatedParameters[$class][$method->name])) {
|
||||
|
||||
+2
@@ -45,6 +45,8 @@ use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
* @author Grégoire Pineau <lyrixx@lyrixx.info>
|
||||
*
|
||||
* @final since Symfony 4.3
|
||||
*/
|
||||
class ErrorHandler
|
||||
{
|
||||
|
||||
@@ -27,6 +27,7 @@ class FlattenException
|
||||
private $code;
|
||||
private $previous;
|
||||
private $trace;
|
||||
private $traceAsString;
|
||||
private $class;
|
||||
private $statusCode;
|
||||
private $headers;
|
||||
@@ -239,6 +240,8 @@ class FlattenException
|
||||
|
||||
public function setTraceFromThrowable(\Throwable $throwable)
|
||||
{
|
||||
$this->traceAsString = $throwable->getTraceAsString();
|
||||
|
||||
return $this->setTrace($throwable->getTrace(), $throwable->getFile(), $throwable->getLine());
|
||||
}
|
||||
|
||||
@@ -324,4 +327,33 @@ class FlattenException
|
||||
|
||||
return $array['__PHP_Incomplete_Class_Name'];
|
||||
}
|
||||
|
||||
public function getTraceAsString()
|
||||
{
|
||||
return $this->traceAsString;
|
||||
}
|
||||
|
||||
public function getAsString()
|
||||
{
|
||||
$message = '';
|
||||
$next = false;
|
||||
|
||||
foreach (array_reverse(array_merge([$this], $this->getAllPrevious())) as $exception) {
|
||||
if ($next) {
|
||||
$message .= 'Next ';
|
||||
} else {
|
||||
$next = true;
|
||||
}
|
||||
$message .= $exception->getClass();
|
||||
|
||||
if ('' != $exception->getMessage()) {
|
||||
$message .= ': '.$exception->getMessage();
|
||||
}
|
||||
|
||||
$message .= ' in '.$exception->getFile().':'.$exception->getLine().
|
||||
"\nStack trace:\n".$exception->getTraceAsString()."\n\n";
|
||||
}
|
||||
|
||||
return rtrim($message);
|
||||
}
|
||||
}
|
||||
|
||||
+23
-2
File diff suppressed because one or more lines are too long
@@ -171,7 +171,11 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
|
||||
}
|
||||
}
|
||||
|
||||
require_once $file;
|
||||
try {
|
||||
require_once $file;
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if ($this->classExists($candidate)) {
|
||||
|
||||
@@ -294,6 +294,11 @@ class DebugClassLoaderTest extends TestCase
|
||||
$this->assertSame([
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::quzMethod()" method will require a new "Quz $quz" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\ClassWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::whereAmI()" method will require a new "bool $matrix" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\InterfaceWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::iAmHere()" method will require a new "$noType" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\InterfaceWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::iAmHere()" method will require a new "callable(\Throwable|null $reason, mixed $value) $callback" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\InterfaceWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::iAmHere()" method will require a new "string $param" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\InterfaceWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::iAmHere()" method will require a new "callable ($a, $b) $anotherOne" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\InterfaceWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::iAmHere()" method will require a new "Type$WithDollarIsStillAType $ccc" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\InterfaceWithAnnotatedParameters", not defining it is deprecated.',
|
||||
'The "Symfony\Component\Debug\Tests\Fixtures\SubClassWithAnnotatedParameters::isSymfony()" method will require a new "true $yes" argument in the next major version of its parent class "Symfony\Component\Debug\Tests\Fixtures\ClassWithAnnotatedParameters", not defining it is deprecated.',
|
||||
], $deprecations);
|
||||
}
|
||||
@@ -312,6 +317,46 @@ class DebugClassLoaderTest extends TestCase
|
||||
$this->assertSame([], $deprecations);
|
||||
}
|
||||
|
||||
public function testVirtualUse()
|
||||
{
|
||||
$deprecations = [];
|
||||
set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
|
||||
$e = error_reporting(E_USER_DEPRECATED);
|
||||
|
||||
class_exists('Test\\'.__NAMESPACE__.'\\ExtendsVirtual', true);
|
||||
|
||||
error_reporting($e);
|
||||
restore_error_handler();
|
||||
|
||||
$this->assertSame([
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::sameLineInterfaceMethodNoBraces()".',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::newLineInterfaceMethod()": Some description!',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::newLineInterfaceMethodNoBraces()": Description.',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::invalidInterfaceMethod()".',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::invalidInterfaceMethodNoBraces()".',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::complexInterfaceMethod($arg, ...$args)".',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::complexInterfaceMethodTyped($arg, int ...$args)": Description ...',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "static Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::staticMethodNoBraces()".',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "static Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::staticMethodTyped(int $arg)": Description.',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtualParent" should implement method "static Symfony\Component\Debug\Tests\Fixtures\VirtualInterface::staticMethodTypedNoBraces()".',
|
||||
'Class "Test\Symfony\Component\Debug\Tests\ExtendsVirtual" should implement method "Symfony\Component\Debug\Tests\Fixtures\VirtualSubInterface::subInterfaceMethod()".',
|
||||
], $deprecations);
|
||||
}
|
||||
|
||||
public function testVirtualUseWithMagicCall()
|
||||
{
|
||||
$deprecations = [];
|
||||
set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
|
||||
$e = error_reporting(E_USER_DEPRECATED);
|
||||
|
||||
class_exists('Test\\'.__NAMESPACE__.'\\ExtendsVirtualMagicCall', true);
|
||||
|
||||
error_reporting($e);
|
||||
restore_error_handler();
|
||||
|
||||
$this->assertSame([], $deprecations);
|
||||
}
|
||||
|
||||
public function testEvaluatedCode()
|
||||
{
|
||||
$this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\DefinitionInEvaluatedCode', true));
|
||||
@@ -372,6 +417,32 @@ class ClassLoader
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsInternalsParent extends \\'.__NAMESPACE__.'\Fixtures\InternalClass implements \\'.__NAMESPACE__.'\Fixtures\InternalInterface { }');
|
||||
} elseif ('Test\\'.__NAMESPACE__.'\UseTraitWithInternalMethod' === $class) {
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; class UseTraitWithInternalMethod { use \\'.__NAMESPACE__.'\Fixtures\TraitWithInternalMethod; }');
|
||||
} elseif ('Test\\'.__NAMESPACE__.'\ExtendsVirtual' === $class) {
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsVirtual extends ExtendsVirtualParent implements \\'.__NAMESPACE__.'\Fixtures\VirtualSubInterface {
|
||||
public function ownClassMethod() { }
|
||||
public function classMethod() { }
|
||||
public function sameLineInterfaceMethodNoBraces() { }
|
||||
}');
|
||||
} elseif ('Test\\'.__NAMESPACE__.'\ExtendsVirtualParent' === $class) {
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsVirtualParent extends ExtendsVirtualAbstract {
|
||||
public function ownParentMethod() { }
|
||||
public function traitMethod() { }
|
||||
public function sameLineInterfaceMethod() { }
|
||||
public function staticMethodNoBraces() { } // should be static
|
||||
}');
|
||||
} elseif ('Test\\'.__NAMESPACE__.'\ExtendsVirtualAbstract' === $class) {
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; abstract class ExtendsVirtualAbstract extends ExtendsVirtualAbstractBase {
|
||||
public static function staticMethod() { }
|
||||
public function ownAbstractMethod() { }
|
||||
public function interfaceMethod() { }
|
||||
}');
|
||||
} elseif ('Test\\'.__NAMESPACE__.'\ExtendsVirtualAbstractBase' === $class) {
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; abstract class ExtendsVirtualAbstractBase extends \\'.__NAMESPACE__.'\Fixtures\VirtualClass implements \\'.__NAMESPACE__.'\Fixtures\VirtualInterface {
|
||||
public function ownAbstractBaseMethod() { }
|
||||
}');
|
||||
} elseif ('Test\\'.__NAMESPACE__.'\ExtendsVirtualMagicCall' === $class) {
|
||||
eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsVirtualMagicCall extends \\'.__NAMESPACE__.'\Fixtures\VirtualClassMagicCall implements \\'.__NAMESPACE__.'\Fixtures\VirtualInterface {
|
||||
}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,6 +346,41 @@ class FlattenExceptionTest extends TestCase
|
||||
$this->assertSame('Class "RuntimeException@anonymous" blah.', $flattened->getMessage());
|
||||
}
|
||||
|
||||
public function testToStringEmptyMessage()
|
||||
{
|
||||
$exception = new \RuntimeException();
|
||||
|
||||
$flattened = FlattenException::create($exception);
|
||||
|
||||
$this->assertSame($exception->getTraceAsString(), $flattened->getTraceAsString());
|
||||
$this->assertSame($exception->__toString(), $flattened->getAsString());
|
||||
}
|
||||
|
||||
public function testToString()
|
||||
{
|
||||
$test = function ($a, $b, $c, $d) {
|
||||
return new \RuntimeException('This is a test message');
|
||||
};
|
||||
|
||||
$exception = $test('foo123', 1, null, 1.5);
|
||||
|
||||
$flattened = FlattenException::create($exception);
|
||||
|
||||
$this->assertSame($exception->getTraceAsString(), $flattened->getTraceAsString());
|
||||
$this->assertSame($exception->__toString(), $flattened->getAsString());
|
||||
}
|
||||
|
||||
public function testToStringParent()
|
||||
{
|
||||
$exception = new \LogicException('This is message 1');
|
||||
$exception = new \RuntimeException('This is messsage 2', 500, $exception);
|
||||
|
||||
$flattened = FlattenException::create($exception);
|
||||
|
||||
$this->assertSame($exception->getTraceAsString(), $flattened->getTraceAsString());
|
||||
$this->assertSame($exception->__toString(), $flattened->getAsString());
|
||||
}
|
||||
|
||||
private function createException($foo)
|
||||
{
|
||||
return new \Exception();
|
||||
|
||||
+10
-1
@@ -48,8 +48,17 @@ class ExceptionHandlerTest extends TestCase
|
||||
$handler->sendPhpResponse(new \RuntimeException('Foo'));
|
||||
$response = ob_get_clean();
|
||||
|
||||
$this->assertContains('Whoops, looks like something went wrong.', $response);
|
||||
$this->assertContains('<h1 class="break-long-words exception-message">Foo</h1>', $response);
|
||||
$this->assertContains('<div class="trace trace-as-html">', $response);
|
||||
|
||||
// taken from https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
|
||||
$htmlWithXss = '<body onload=alert(\'test1\')> <b onmouseover=alert(\'Wufff!\')>click me!</b> <img src="jAvascript:alert(\'test2\')"> <meta http-equiv="refresh"
|
||||
content="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg">';
|
||||
ob_start();
|
||||
$handler->sendPhpResponse(new \RuntimeException($htmlWithXss));
|
||||
$response = ob_get_clean();
|
||||
|
||||
$this->assertContains(sprintf('<h1 class="break-long-words exception-message">%s</h1>', htmlspecialchars($htmlWithXss, ENT_COMPAT | ENT_SUBSTITUTE, 'UTF-8')), $response);
|
||||
}
|
||||
|
||||
public function testStatusCode()
|
||||
|
||||
@@ -11,4 +11,17 @@ interface InterfaceWithAnnotatedParameters
|
||||
* @param bool $matrix
|
||||
*/
|
||||
public function whereAmI();
|
||||
|
||||
/**
|
||||
* @param $noType
|
||||
* @param callable(\Throwable|null $reason, mixed $value) $callback and a comment
|
||||
* about this great param
|
||||
* @param string $param (comment with $dollar)
|
||||
* @param $defined
|
||||
* @param callable ($a, $b) $anotherOne
|
||||
* @param callable (mixed $a, $b) $definedCallable
|
||||
* @param Type$WithDollarIsStillAType $ccc
|
||||
* @param \JustAType
|
||||
*/
|
||||
public function iAmHere();
|
||||
}
|
||||
|
||||
@@ -21,4 +21,12 @@ class SubClassWithAnnotatedParameters extends ClassWithAnnotatedParameters imple
|
||||
public function whereAmI()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $defined
|
||||
* @param Type\Does\Not\Matter $definedCallable
|
||||
*/
|
||||
public function iAmHere()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Symfony\Component\Debug\Tests\Fixtures;
|
||||
|
||||
/**
|
||||
* @method string classMethod()
|
||||
*/
|
||||
class VirtualClass
|
||||
{
|
||||
use VirtualTrait;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Symfony\Component\Debug\Tests\Fixtures;
|
||||
|
||||
/**
|
||||
* @method string magicMethod()
|
||||
* @method static string staticMagicMethod()
|
||||
*/
|
||||
class VirtualClassMagicCall
|
||||
{
|
||||
public static function __callStatic($name, $arguments)
|
||||
{
|
||||
}
|
||||
|
||||
public function __call($name, $arguments)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Symfony\Component\Debug\Tests\Fixtures;
|
||||
|
||||
/**
|
||||
* @method string interfaceMethod()
|
||||
* @method sameLineInterfaceMethod($arg)
|
||||
* @method sameLineInterfaceMethodNoBraces
|
||||
*
|
||||
* Ignored
|
||||
* @method
|
||||
* @method
|
||||
*
|
||||
* Not ignored
|
||||
* @method newLineInterfaceMethod() Some description!
|
||||
* @method \stdClass newLineInterfaceMethodNoBraces Description
|
||||
*
|
||||
* Invalid
|
||||
* @method unknownType invalidInterfaceMethod()
|
||||
* @method unknownType|string invalidInterfaceMethodNoBraces
|
||||
*
|
||||
* Complex
|
||||
* @method complexInterfaceMethod($arg, ...$args)
|
||||
* @method string[]|int complexInterfaceMethodTyped($arg, int ...$args) Description ...
|
||||
*
|
||||
* Static
|
||||
* @method static Foo&Bar staticMethod()
|
||||
* @method static staticMethodNoBraces
|
||||
* @method static \stdClass staticMethodTyped(int $arg) Description
|
||||
* @method static \stdClass[] staticMethodTypedNoBraces
|
||||
*/
|
||||
interface VirtualInterface
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace Symfony\Component\Debug\Tests\Fixtures;
|
||||
|
||||
/**
|
||||
* @method string subInterfaceMethod()
|
||||
*/
|
||||
interface VirtualSubInterface extends VirtualInterface
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace Symfony\Component\Debug\Tests\Fixtures;
|
||||
|
||||
/**
|
||||
* @method string traitMethod()
|
||||
*/
|
||||
trait VirtualTrait
|
||||
{
|
||||
}
|
||||
@@ -24,7 +24,7 @@ var_dump([
|
||||
$eHandler[0]->setExceptionHandler('print_r');
|
||||
|
||||
if (true) {
|
||||
class Broken implements \Serializable
|
||||
class Broken implements \JsonSerializable
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,6 @@ array(1) {
|
||||
}
|
||||
object(Symfony\Component\Debug\Exception\FatalErrorException)#%d (%d) {
|
||||
["message":protected]=>
|
||||
string(199) "Error: Class Symfony\Component\Debug\Broken contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Serializable::serialize, Serializable::unserialize)"
|
||||
string(179) "Error: Class Symfony\Component\Debug\Broken contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (JsonSerializable::jsonSerialize)"
|
||||
%a
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -34,7 +34,7 @@
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.2-dev"
|
||||
"dev-master": "4.3-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
Symfony EventDispatcher Contracts
|
||||
=================================
|
||||
|
||||
A set of abstractions extracted out of the Symfony components.
|
||||
|
||||
Can be used to build on semantics that the Symfony components proved useful - and
|
||||
that already have battle tested implementations.
|
||||
|
||||
See https://github.com/symfony/contracts/blob/master/README.md for more information.
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "symfony/event-dispatcher-contracts",
|
||||
"type": "library",
|
||||
"description": "Generic abstractions related to dispatching event",
|
||||
"keywords": ["abstractions", "contracts", "decoupling", "interfaces", "interoperability", "standards"],
|
||||
"homepage": "https://symfony.com",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicolas Grekas",
|
||||
"email": "p@tchwork.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.1.3"
|
||||
},
|
||||
"suggest": {
|
||||
"psr/event-dispatcher": "",
|
||||
"symfony/event-dispatcher-implementation": ""
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "Symfony\\Contracts\\EventDispatcher\\": "" }
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.1-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* The signature of the `EventDispatcherInterface::dispatch()` method should be updated to `dispatch($event, string $eventName = null)`, not doing so is deprecated
|
||||
* deprecated the `Event` class, use `Symfony\Contracts\EventDispatcher\Event` instead
|
||||
|
||||
4.1.0
|
||||
-----
|
||||
|
||||
|
||||
@@ -11,11 +11,17 @@
|
||||
|
||||
namespace Symfony\Component\EventDispatcher\Debug;
|
||||
|
||||
use Psr\EventDispatcher\StoppableEventInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\BrowserKit\Request;
|
||||
use Symfony\Component\EventDispatcher\Event;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
|
||||
use Symfony\Component\EventDispatcher\LegacyEventProxy;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
use Symfony\Component\Stopwatch\Stopwatch;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
|
||||
/**
|
||||
* Collects some data about event listeners.
|
||||
@@ -33,14 +39,17 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
private $dispatcher;
|
||||
private $wrappedListeners;
|
||||
private $orphanedEvents;
|
||||
private $requestStack;
|
||||
private $currentRequestHash = '';
|
||||
|
||||
public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null)
|
||||
public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null, RequestStack $requestStack = null)
|
||||
{
|
||||
$this->dispatcher = $dispatcher;
|
||||
$this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
|
||||
$this->stopwatch = $stopwatch;
|
||||
$this->logger = $logger;
|
||||
$this->wrappedListeners = [];
|
||||
$this->orphanedEvents = [];
|
||||
$this->requestStack = $requestStack;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,37 +130,52 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param string|null $eventName
|
||||
*/
|
||||
public function dispatch($eventName, Event $event = null)
|
||||
public function dispatch($event/*, string $eventName = null*/)
|
||||
{
|
||||
if (null === $this->callStack) {
|
||||
$this->callStack = new \SplObjectStorage();
|
||||
}
|
||||
|
||||
if (null === $event) {
|
||||
$event = new Event();
|
||||
$currentRequestHash = $this->currentRequestHash = $this->requestStack && ($request = $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : '';
|
||||
$eventName = 1 < \func_num_args() ? \func_get_arg(1) : null;
|
||||
|
||||
if (\is_object($event)) {
|
||||
$eventName = $eventName ?? \get_class($event);
|
||||
} else {
|
||||
@trigger_error(sprintf('Calling the "%s::dispatch()" method with the event name as first argument is deprecated since Symfony 4.3, pass it second and provide the event object first instead.', EventDispatcherInterface::class), E_USER_DEPRECATED);
|
||||
$swap = $event;
|
||||
$event = $eventName ?? new Event();
|
||||
$eventName = $swap;
|
||||
|
||||
if (!$event instanceof Event) {
|
||||
throw new \TypeError(sprintf('Argument 1 passed to "%s::dispatch()" must be an instance of %s, %s given.', EventDispatcherInterface::class, Event::class, \is_object($event) ? \get_class($event) : \gettype($event)));
|
||||
}
|
||||
}
|
||||
|
||||
if (null !== $this->logger && $event->isPropagationStopped()) {
|
||||
if (null !== $this->logger && ($event instanceof Event || $event instanceof ContractsEvent || $event instanceof StoppableEventInterface) && $event->isPropagationStopped()) {
|
||||
$this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName));
|
||||
}
|
||||
|
||||
$this->preProcess($eventName);
|
||||
try {
|
||||
$this->preDispatch($eventName, $event);
|
||||
$this->beforeDispatch($eventName, $event);
|
||||
try {
|
||||
$e = $this->stopwatch->start($eventName, 'section');
|
||||
try {
|
||||
$this->dispatcher->dispatch($eventName, $event);
|
||||
$this->dispatcher->dispatch($event, $eventName);
|
||||
} finally {
|
||||
if ($e->isStarted()) {
|
||||
$e->stop();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$this->postDispatch($eventName, $event);
|
||||
$this->afterDispatch($eventName, $event);
|
||||
}
|
||||
} finally {
|
||||
$this->currentRequestHash = $currentRequestHash;
|
||||
$this->postProcess($eventName);
|
||||
}
|
||||
|
||||
@@ -160,18 +184,22 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param Request|null $request The request to get listeners for
|
||||
*/
|
||||
public function getCalledListeners()
|
||||
public function getCalledListeners(/* Request $request = null */)
|
||||
{
|
||||
if (null === $this->callStack) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$hash = 1 <= \func_num_args() && null !== ($request = \func_get_arg(0)) ? spl_object_hash($request) : null;
|
||||
$called = [];
|
||||
foreach ($this->callStack as $listener) {
|
||||
list($eventName) = $this->callStack->getInfo();
|
||||
|
||||
$called[] = $listener->getInfo($eventName);
|
||||
list($eventName, $requestHash) = $this->callStack->getInfo();
|
||||
if (null === $hash || $hash === $requestHash) {
|
||||
$called[] = $listener->getInfo($eventName);
|
||||
}
|
||||
}
|
||||
|
||||
return $called;
|
||||
@@ -179,8 +207,10 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param Request|null $request The request to get listeners for
|
||||
*/
|
||||
public function getNotCalledListeners()
|
||||
public function getNotCalledListeners(/* Request $request = null */)
|
||||
{
|
||||
try {
|
||||
$allListeners = $this->getListeners();
|
||||
@@ -193,13 +223,15 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
return [];
|
||||
}
|
||||
|
||||
$hash = 1 <= \func_num_args() && null !== ($request = \func_get_arg(0)) ? spl_object_hash($request) : null;
|
||||
$notCalled = [];
|
||||
foreach ($allListeners as $eventName => $listeners) {
|
||||
foreach ($listeners as $listener) {
|
||||
$called = false;
|
||||
if (null !== $this->callStack) {
|
||||
foreach ($this->callStack as $calledListener) {
|
||||
if ($calledListener->getWrappedListener() === $listener) {
|
||||
list(, $requestHash) = $this->callStack->getInfo();
|
||||
if ((null === $hash || $hash === $requestHash) && $calledListener->getWrappedListener() === $listener) {
|
||||
$called = true;
|
||||
|
||||
break;
|
||||
@@ -221,15 +253,27 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
return $notCalled;
|
||||
}
|
||||
|
||||
public function getOrphanedEvents(): array
|
||||
/**
|
||||
* @param Request|null $request The request to get orphaned events for
|
||||
*/
|
||||
public function getOrphanedEvents(/* Request $request = null */): array
|
||||
{
|
||||
return $this->orphanedEvents;
|
||||
if (1 <= \func_num_args() && null !== $request = \func_get_arg(0)) {
|
||||
return $this->orphanedEvents[spl_object_hash($request)] ?? [];
|
||||
}
|
||||
|
||||
if (!$this->orphanedEvents) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_merge(...array_values($this->orphanedEvents));
|
||||
}
|
||||
|
||||
public function reset()
|
||||
{
|
||||
$this->callStack = null;
|
||||
$this->orphanedEvents = [];
|
||||
$this->currentRequestHash = '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -248,18 +292,32 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
/**
|
||||
* Called before dispatching the event.
|
||||
*
|
||||
* @param string $eventName The event name
|
||||
* @param Event $event The event
|
||||
* @param object $event
|
||||
*/
|
||||
protected function beforeDispatch(string $eventName, $event)
|
||||
{
|
||||
$this->preDispatch($eventName, $event instanceof Event ? $event : new LegacyEventProxy($event));
|
||||
}
|
||||
|
||||
/**
|
||||
* Called after dispatching the event.
|
||||
*
|
||||
* @param object $event
|
||||
*/
|
||||
protected function afterDispatch(string $eventName, $event)
|
||||
{
|
||||
$this->postDispatch($eventName, $event instanceof Event ? $event : new LegacyEventProxy($event));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated since Symfony 4.3, will be removed in 5.0, use beforeDispatch instead
|
||||
*/
|
||||
protected function preDispatch($eventName, Event $event)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Called after dispatching the event.
|
||||
*
|
||||
* @param string $eventName The event name
|
||||
* @param Event $event The event
|
||||
* @deprecated since Symfony 4.3, will be removed in 5.0, use afterDispatch instead
|
||||
*/
|
||||
protected function postDispatch($eventName, Event $event)
|
||||
{
|
||||
@@ -268,7 +326,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
private function preProcess($eventName)
|
||||
{
|
||||
if (!$this->dispatcher->hasListeners($eventName)) {
|
||||
$this->orphanedEvents[] = $eventName;
|
||||
$this->orphanedEvents[$this->currentRequestHash][] = $eventName;
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -279,7 +337,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
|
||||
$this->wrappedListeners[$eventName][] = $wrappedListener;
|
||||
$this->dispatcher->removeListener($eventName, $listener);
|
||||
$this->dispatcher->addListener($eventName, $wrappedListener, $priority);
|
||||
$this->callStack->attach($wrappedListener, [$eventName]);
|
||||
$this->callStack->attach($wrappedListener, [$eventName, $this->currentRequestHash]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-2
@@ -12,6 +12,7 @@
|
||||
namespace Symfony\Component\EventDispatcher\Debug;
|
||||
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Contracts\Service\ResetInterface;
|
||||
|
||||
/**
|
||||
@@ -24,14 +25,18 @@ interface TraceableEventDispatcherInterface extends EventDispatcherInterface, Re
|
||||
/**
|
||||
* Gets the called listeners.
|
||||
*
|
||||
* @param Request|null $request The request to get listeners for
|
||||
*
|
||||
* @return array An array of called listeners
|
||||
*/
|
||||
public function getCalledListeners();
|
||||
public function getCalledListeners(/* Request $request = null */);
|
||||
|
||||
/**
|
||||
* Gets the not called listeners.
|
||||
*
|
||||
* @param Request|null $request The request to get listeners for
|
||||
*
|
||||
* @return array An array of not called listeners
|
||||
*/
|
||||
public function getNotCalledListeners();
|
||||
public function getNotCalledListeners(/* Request $request = null */);
|
||||
}
|
||||
|
||||
+14
-3
@@ -11,17 +11,23 @@
|
||||
|
||||
namespace Symfony\Component\EventDispatcher\Debug;
|
||||
|
||||
use Psr\EventDispatcher\StoppableEventInterface;
|
||||
use Symfony\Component\EventDispatcher\Event;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Component\EventDispatcher\LegacyEventProxy;
|
||||
use Symfony\Component\Stopwatch\Stopwatch;
|
||||
use Symfony\Component\VarDumper\Caster\ClassStub;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
|
||||
/**
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @final since Symfony 4.3: the "Event" type-hint on __invoke() will be replaced by "object" in 5.0
|
||||
*/
|
||||
class WrappedListener
|
||||
{
|
||||
private $listener;
|
||||
private $optimizedListener;
|
||||
private $name;
|
||||
private $called;
|
||||
private $stoppedPropagation;
|
||||
@@ -32,9 +38,10 @@ class WrappedListener
|
||||
private $priority;
|
||||
private static $hasClassStub;
|
||||
|
||||
public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null)
|
||||
public function __construct($listener, ?string $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null)
|
||||
{
|
||||
$this->listener = $listener;
|
||||
$this->optimizedListener = $listener instanceof \Closure ? $listener : (\is_callable($listener) ? \Closure::fromCallable($listener) : null);
|
||||
$this->stopwatch = $stopwatch;
|
||||
$this->dispatcher = $dispatcher;
|
||||
$this->called = false;
|
||||
@@ -105,6 +112,10 @@ class WrappedListener
|
||||
|
||||
public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher)
|
||||
{
|
||||
if ($event instanceof LegacyEventProxy) {
|
||||
$event = $event->getEvent();
|
||||
}
|
||||
|
||||
$dispatcher = $this->dispatcher ?: $dispatcher;
|
||||
|
||||
$this->called = true;
|
||||
@@ -112,13 +123,13 @@ class WrappedListener
|
||||
|
||||
$e = $this->stopwatch->start($this->name, 'event_listener');
|
||||
|
||||
($this->listener)($event, $eventName, $dispatcher);
|
||||
($this->optimizedListener ?? $this->listener)($event, $eventName, $dispatcher);
|
||||
|
||||
if ($e->isStarted()) {
|
||||
$e->stop();
|
||||
}
|
||||
|
||||
if ($event->isPropagationStopped()) {
|
||||
if (($event instanceof Event || $event instanceof ContractsEvent || $event instanceof StoppableEventInterface) && $event->isPropagationStopped()) {
|
||||
$this->stoppedPropagation = true;
|
||||
}
|
||||
}
|
||||
|
||||
+19
-3
@@ -27,15 +27,17 @@ class RegisterListenersPass implements CompilerPassInterface
|
||||
protected $dispatcherService;
|
||||
protected $listenerTag;
|
||||
protected $subscriberTag;
|
||||
protected $eventAliasesParameter;
|
||||
|
||||
private $hotPathEvents = [];
|
||||
private $hotPathTagName;
|
||||
|
||||
public function __construct(string $dispatcherService = 'event_dispatcher', string $listenerTag = 'kernel.event_listener', string $subscriberTag = 'kernel.event_subscriber')
|
||||
public function __construct(string $dispatcherService = 'event_dispatcher', string $listenerTag = 'kernel.event_listener', string $subscriberTag = 'kernel.event_subscriber', string $eventAliasesParameter = 'event_dispatcher.event_aliases')
|
||||
{
|
||||
$this->dispatcherService = $dispatcherService;
|
||||
$this->listenerTag = $listenerTag;
|
||||
$this->subscriberTag = $subscriberTag;
|
||||
$this->eventAliasesParameter = $eventAliasesParameter;
|
||||
}
|
||||
|
||||
public function setHotPathEvents(array $hotPathEvents, $tagName = 'container.hot_path')
|
||||
@@ -52,6 +54,12 @@ class RegisterListenersPass implements CompilerPassInterface
|
||||
return;
|
||||
}
|
||||
|
||||
if ($container->hasParameter($this->eventAliasesParameter)) {
|
||||
$aliases = $container->getParameter($this->eventAliasesParameter);
|
||||
$container->getParameterBag()->remove($this->eventAliasesParameter);
|
||||
} else {
|
||||
$aliases = [];
|
||||
}
|
||||
$definition = $container->findDefinition($this->dispatcherService);
|
||||
|
||||
foreach ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
|
||||
@@ -61,6 +69,7 @@ class RegisterListenersPass implements CompilerPassInterface
|
||||
if (!isset($event['event'])) {
|
||||
throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
|
||||
}
|
||||
$event['event'] = $aliases[$event['event']] ?? $event['event'];
|
||||
|
||||
if (!isset($event['method'])) {
|
||||
$event['method'] = 'on'.preg_replace_callback([
|
||||
@@ -98,6 +107,7 @@ class RegisterListenersPass implements CompilerPassInterface
|
||||
}
|
||||
$class = $r->name;
|
||||
|
||||
ExtractingEventDispatcher::$aliases = $aliases;
|
||||
ExtractingEventDispatcher::$subscriber = $class;
|
||||
$extractingDispatcher->addSubscriber($extractingDispatcher);
|
||||
foreach ($extractingDispatcher->listeners as $args) {
|
||||
@@ -109,6 +119,7 @@ class RegisterListenersPass implements CompilerPassInterface
|
||||
}
|
||||
}
|
||||
$extractingDispatcher->listeners = [];
|
||||
ExtractingEventDispatcher::$aliases = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,6 +131,7 @@ class ExtractingEventDispatcher extends EventDispatcher implements EventSubscrib
|
||||
{
|
||||
public $listeners = [];
|
||||
|
||||
public static $aliases = [];
|
||||
public static $subscriber;
|
||||
|
||||
public function addListener($eventName, $listener, $priority = 0)
|
||||
@@ -129,8 +141,12 @@ class ExtractingEventDispatcher extends EventDispatcher implements EventSubscrib
|
||||
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
$callback = [self::$subscriber, 'getSubscribedEvents'];
|
||||
$events = [];
|
||||
|
||||
return $callback();
|
||||
foreach ([self::$subscriber, 'getSubscribedEvents']() as $eventName => $params) {
|
||||
$events[self::$aliases[$eventName] ?? $eventName] = $params;
|
||||
}
|
||||
|
||||
return $events;
|
||||
}
|
||||
}
|
||||
|
||||
+4
-24
@@ -12,32 +12,16 @@
|
||||
namespace Symfony\Component\EventDispatcher;
|
||||
|
||||
/**
|
||||
* Event is the base class for classes containing event data.
|
||||
*
|
||||
* This class contains no event data. It is used by events that do not pass
|
||||
* state information to an event handler when an event is raised.
|
||||
*
|
||||
* You can call the method stopPropagation() to abort the execution of
|
||||
* further listeners in your event listener.
|
||||
*
|
||||
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
|
||||
* @author Jonathan Wage <jonwage@gmail.com>
|
||||
* @author Roman Borschel <roman@code-factory.org>
|
||||
* @author Bernhard Schussek <bschussek@gmail.com>
|
||||
* @deprecated since Symfony 4.3, use "Symfony\Contracts\EventDispatcher\Event" instead
|
||||
*/
|
||||
class Event
|
||||
{
|
||||
/**
|
||||
* @var bool Whether no further event listeners should be triggered
|
||||
*/
|
||||
private $propagationStopped = false;
|
||||
|
||||
/**
|
||||
* Returns whether further event listeners should be triggered.
|
||||
*
|
||||
* @see Event::stopPropagation()
|
||||
*
|
||||
* @return bool Whether propagation was already stopped for this event
|
||||
*
|
||||
* @deprecated since Symfony 4.3, use "Symfony\Contracts\EventDispatcher\Event" instead
|
||||
*/
|
||||
public function isPropagationStopped()
|
||||
{
|
||||
@@ -45,11 +29,7 @@ class Event
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the propagation of the event to further event listeners.
|
||||
*
|
||||
* If multiple event listeners are connected to the same event, no
|
||||
* further event listener will be triggered once any trigger calls
|
||||
* stopPropagation().
|
||||
* @deprecated since Symfony 4.3, use "Symfony\Contracts\EventDispatcher\Event" instead
|
||||
*/
|
||||
public function stopPropagation()
|
||||
{
|
||||
|
||||
+95
-23
@@ -11,6 +11,10 @@
|
||||
|
||||
namespace Symfony\Component\EventDispatcher;
|
||||
|
||||
use Psr\EventDispatcher\StoppableEventInterface;
|
||||
use Symfony\Component\EventDispatcher\Debug\WrappedListener;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
|
||||
/**
|
||||
* The EventDispatcherInterface is the central point of Symfony's event listener system.
|
||||
*
|
||||
@@ -30,18 +34,45 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
{
|
||||
private $listeners = [];
|
||||
private $sorted = [];
|
||||
private $optimized;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if (__CLASS__ === \get_class($this)) {
|
||||
$this->optimized = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param string|null $eventName
|
||||
*/
|
||||
public function dispatch($eventName, Event $event = null)
|
||||
public function dispatch($event/*, string $eventName = null*/)
|
||||
{
|
||||
if (null === $event) {
|
||||
$event = new Event();
|
||||
$eventName = 1 < \func_num_args() ? \func_get_arg(1) : null;
|
||||
|
||||
if (\is_object($event)) {
|
||||
$eventName = $eventName ?? \get_class($event);
|
||||
} else {
|
||||
@trigger_error(sprintf('Calling the "%s::dispatch()" method with the event name as first argument is deprecated since Symfony 4.3, pass it second and provide the event object first instead.', EventDispatcherInterface::class), E_USER_DEPRECATED);
|
||||
$swap = $event;
|
||||
$event = $eventName ?? new Event();
|
||||
$eventName = $swap;
|
||||
|
||||
if (!$event instanceof Event) {
|
||||
throw new \TypeError(sprintf('Argument 1 passed to "%s::dispatch()" must be an instance of %s, %s given.', EventDispatcherInterface::class, Event::class, \is_object($event) ? \get_class($event) : \gettype($event)));
|
||||
}
|
||||
}
|
||||
|
||||
if ($listeners = $this->getListeners($eventName)) {
|
||||
$this->doDispatch($listeners, $eventName, $event);
|
||||
if (null !== $this->optimized && null !== $eventName) {
|
||||
$listeners = $this->optimized[$eventName] ?? (empty($this->listeners[$eventName]) ? [] : $this->optimizeListeners($eventName));
|
||||
} else {
|
||||
$listeners = $this->getListeners($eventName);
|
||||
}
|
||||
|
||||
if ($listeners) {
|
||||
$this->callListeners($listeners, $eventName, $event);
|
||||
}
|
||||
|
||||
return $event;
|
||||
@@ -86,11 +117,10 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
$listener[0] = $listener[0]();
|
||||
}
|
||||
|
||||
foreach ($this->listeners[$eventName] as $priority => $listeners) {
|
||||
foreach ($listeners as $k => $v) {
|
||||
foreach ($this->listeners[$eventName] as $priority => &$listeners) {
|
||||
foreach ($listeners as &$v) {
|
||||
if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) {
|
||||
$v[0] = $v[0]();
|
||||
$this->listeners[$eventName][$priority][$k] = $v;
|
||||
}
|
||||
if ($v === $listener) {
|
||||
return $priority;
|
||||
@@ -123,7 +153,7 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
public function addListener($eventName, $listener, $priority = 0)
|
||||
{
|
||||
$this->listeners[$eventName][$priority][] = $listener;
|
||||
unset($this->sorted[$eventName]);
|
||||
unset($this->sorted[$eventName], $this->optimized[$eventName]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,21 +169,17 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
$listener[0] = $listener[0]();
|
||||
}
|
||||
|
||||
foreach ($this->listeners[$eventName] as $priority => $listeners) {
|
||||
foreach ($listeners as $k => $v) {
|
||||
foreach ($this->listeners[$eventName] as $priority => &$listeners) {
|
||||
foreach ($listeners as $k => &$v) {
|
||||
if ($v !== $listener && \is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) {
|
||||
$v[0] = $v[0]();
|
||||
}
|
||||
if ($v === $listener) {
|
||||
unset($listeners[$k], $this->sorted[$eventName]);
|
||||
} else {
|
||||
$listeners[$k] = $v;
|
||||
unset($listeners[$k], $this->sorted[$eventName], $this->optimized[$eventName]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($listeners) {
|
||||
$this->listeners[$eventName][$priority] = $listeners;
|
||||
} else {
|
||||
if (!$listeners) {
|
||||
unset($this->listeners[$eventName][$priority]);
|
||||
}
|
||||
}
|
||||
@@ -201,7 +227,29 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
*
|
||||
* @param callable[] $listeners The event listeners
|
||||
* @param string $eventName The name of the event to dispatch
|
||||
* @param Event $event The event object to pass to the event handlers/listeners
|
||||
* @param object $event The event object to pass to the event handlers/listeners
|
||||
*/
|
||||
protected function callListeners(iterable $listeners, string $eventName, $event)
|
||||
{
|
||||
if ($event instanceof Event) {
|
||||
$this->doDispatch($listeners, $eventName, $event);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$stoppable = $event instanceof ContractsEvent || $event instanceof StoppableEventInterface;
|
||||
|
||||
foreach ($listeners as $listener) {
|
||||
if ($stoppable && $event->isPropagationStopped()) {
|
||||
break;
|
||||
}
|
||||
// @deprecated: the ternary operator is part of a BC layer and should be removed in 5.0
|
||||
$listener($listener instanceof WrappedListener ? new LegacyEventProxy($event) : $event, $eventName, $this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated since Symfony 4.3, use callListeners() instead
|
||||
*/
|
||||
protected function doDispatch($listeners, $eventName, Event $event)
|
||||
{
|
||||
@@ -215,22 +263,46 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
|
||||
/**
|
||||
* Sorts the internal list of listeners for the given event by priority.
|
||||
*
|
||||
* @param string $eventName The name of the event
|
||||
*/
|
||||
private function sortListeners($eventName)
|
||||
private function sortListeners(string $eventName)
|
||||
{
|
||||
krsort($this->listeners[$eventName]);
|
||||
$this->sorted[$eventName] = [];
|
||||
|
||||
foreach ($this->listeners[$eventName] as $priority => $listeners) {
|
||||
foreach ($this->listeners[$eventName] as &$listeners) {
|
||||
foreach ($listeners as $k => $listener) {
|
||||
if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
|
||||
$listener[0] = $listener[0]();
|
||||
$this->listeners[$eventName][$priority][$k] = $listener;
|
||||
}
|
||||
$this->sorted[$eventName][] = $listener;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes the internal list of listeners for the given event by priority.
|
||||
*/
|
||||
private function optimizeListeners(string $eventName): array
|
||||
{
|
||||
krsort($this->listeners[$eventName]);
|
||||
$this->optimized[$eventName] = [];
|
||||
|
||||
foreach ($this->listeners[$eventName] as &$listeners) {
|
||||
foreach ($listeners as &$listener) {
|
||||
$closure = &$this->optimized[$eventName][];
|
||||
if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
|
||||
$closure = static function (...$args) use (&$listener, &$closure) {
|
||||
if ($listener[0] instanceof \Closure) {
|
||||
$listener[0] = $listener[0]();
|
||||
}
|
||||
($closure = \Closure::fromCallable($listener))(...$args);
|
||||
};
|
||||
} else {
|
||||
$closure = $listener instanceof \Closure || $listener instanceof WrappedListener ? $listener : \Closure::fromCallable($listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->optimized[$eventName];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
namespace Symfony\Component\EventDispatcher;
|
||||
|
||||
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;
|
||||
|
||||
/**
|
||||
* The EventDispatcherInterface is the central point of Symfony's event listener system.
|
||||
* Listeners are registered on the manager and events are dispatched through the
|
||||
@@ -18,21 +20,8 @@ namespace Symfony\Component\EventDispatcher;
|
||||
*
|
||||
* @author Bernhard Schussek <bschussek@gmail.com>
|
||||
*/
|
||||
interface EventDispatcherInterface
|
||||
interface EventDispatcherInterface extends ContractsEventDispatcherInterface
|
||||
{
|
||||
/**
|
||||
* Dispatches an event to all registered listeners.
|
||||
*
|
||||
* @param string $eventName The name of the event to dispatch. The name of
|
||||
* the event is the name of the method that is
|
||||
* invoked on listeners.
|
||||
* @param Event|null $event The event to pass to the event handlers/listeners
|
||||
* If not supplied, an empty Event instance is created
|
||||
*
|
||||
* @return Event
|
||||
*/
|
||||
public function dispatch($eventName, Event $event = null);
|
||||
|
||||
/**
|
||||
* Adds an event listener that listens on the specified events.
|
||||
*
|
||||
|
||||
@@ -22,15 +22,26 @@ class ImmutableEventDispatcher implements EventDispatcherInterface
|
||||
|
||||
public function __construct(EventDispatcherInterface $dispatcher)
|
||||
{
|
||||
$this->dispatcher = $dispatcher;
|
||||
$this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param string|null $eventName
|
||||
*/
|
||||
public function dispatch($eventName, Event $event = null)
|
||||
public function dispatch($event/*, string $eventName = null*/)
|
||||
{
|
||||
return $this->dispatcher->dispatch($eventName, $event);
|
||||
$eventName = 1 < \func_num_args() ? \func_get_arg(1) : null;
|
||||
|
||||
if (\is_scalar($event)) {
|
||||
// deprecated
|
||||
$swap = $event;
|
||||
$event = $eventName ?? new Event();
|
||||
$eventName = $swap;
|
||||
}
|
||||
|
||||
return $this->dispatcher->dispatch($event, $eventName);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\EventDispatcher;
|
||||
|
||||
use Psr\EventDispatcher\StoppableEventInterface;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;
|
||||
|
||||
/**
|
||||
* An helper class to provide BC/FC with the legacy signature of EventDispatcherInterface::dispatch().
|
||||
*
|
||||
* This class should be deprecated in Symfony 5.1
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
final class LegacyEventDispatcherProxy implements EventDispatcherInterface
|
||||
{
|
||||
private $dispatcher;
|
||||
|
||||
public static function decorate(?ContractsEventDispatcherInterface $dispatcher): ?ContractsEventDispatcherInterface
|
||||
{
|
||||
if (null === $dispatcher) {
|
||||
return null;
|
||||
}
|
||||
$r = new \ReflectionMethod($dispatcher, 'dispatch');
|
||||
$param2 = $r->getParameters()[1] ?? null;
|
||||
|
||||
if (!$param2 || !$param2->hasType() || $param2->getType()->isBuiltin()) {
|
||||
return $dispatcher;
|
||||
}
|
||||
|
||||
@trigger_error(sprintf('The signature of the "%s::dispatch()" method should be updated to "dispatch($event, string $eventName = null)", not doing so is deprecated since Symfony 4.3.', $r->class), E_USER_DEPRECATED);
|
||||
|
||||
$self = new self();
|
||||
$self->dispatcher = $dispatcher;
|
||||
|
||||
return $self;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param string|null $eventName
|
||||
*/
|
||||
public function dispatch($event/*, string $eventName = null*/)
|
||||
{
|
||||
$eventName = 1 < \func_num_args() ? \func_get_arg(1) : null;
|
||||
|
||||
if (\is_object($event)) {
|
||||
$eventName = $eventName ?? \get_class($event);
|
||||
} else {
|
||||
@trigger_error(sprintf('Calling the "%s::dispatch()" method with the event name as first argument is deprecated since Symfony 4.3, pass it second and provide the event object first instead.', ContractsEventDispatcherInterface::class), E_USER_DEPRECATED);
|
||||
$swap = $event;
|
||||
$event = $eventName ?? new Event();
|
||||
$eventName = $swap;
|
||||
|
||||
if (!$event instanceof Event) {
|
||||
throw new \TypeError(sprintf('Argument 1 passed to "%s::dispatch()" must be an instance of %s, %s given.', ContractsEventDispatcherInterface::class, Event::class, \is_object($event) ? \get_class($event) : \gettype($event)));
|
||||
}
|
||||
}
|
||||
|
||||
$listeners = $this->getListeners($eventName);
|
||||
$stoppable = $event instanceof Event || $event instanceof ContractsEvent || $event instanceof StoppableEventInterface;
|
||||
|
||||
foreach ($listeners as $listener) {
|
||||
if ($stoppable && $event->isPropagationStopped()) {
|
||||
break;
|
||||
}
|
||||
$listener($event, $eventName, $this);
|
||||
}
|
||||
|
||||
return $event;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function addListener($eventName, $listener, $priority = 0)
|
||||
{
|
||||
return $this->dispatcher->addListener($eventName, $listener, $priority);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function addSubscriber(EventSubscriberInterface $subscriber)
|
||||
{
|
||||
return $this->dispatcher->addSubscriber($subscriber);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function removeListener($eventName, $listener)
|
||||
{
|
||||
return $this->dispatcher->removeListener($eventName, $listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function removeSubscriber(EventSubscriberInterface $subscriber)
|
||||
{
|
||||
return $this->dispatcher->removeSubscriber($subscriber);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getListeners($eventName = null)
|
||||
{
|
||||
return $this->dispatcher->getListeners($eventName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getListenerPriority($eventName, $listener)
|
||||
{
|
||||
return $this->dispatcher->getListenerPriority($eventName, $listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function hasListeners($eventName = null)
|
||||
{
|
||||
return $this->dispatcher->hasListeners($eventName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxies all method calls to the original event dispatcher.
|
||||
*/
|
||||
public function __call($method, $arguments)
|
||||
{
|
||||
return $this->dispatcher->{$method}(...$arguments);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\EventDispatcher;
|
||||
|
||||
use Psr\EventDispatcher\StoppableEventInterface;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
|
||||
/**
|
||||
* @internal to be removed in 5.0.
|
||||
*/
|
||||
final class LegacyEventProxy extends Event
|
||||
{
|
||||
private $event;
|
||||
|
||||
/**
|
||||
* @param object $event
|
||||
*/
|
||||
public function __construct($event)
|
||||
{
|
||||
$this->event = $event;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object $event
|
||||
*/
|
||||
public function getEvent()
|
||||
{
|
||||
return $this->event;
|
||||
}
|
||||
|
||||
public function isPropagationStopped()
|
||||
{
|
||||
if (!$this->event instanceof ContractsEvent && !$this->event instanceof StoppableEventInterface) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->event->isPropagationStopped();
|
||||
}
|
||||
|
||||
public function stopPropagation()
|
||||
{
|
||||
if (!$this->event instanceof ContractsEvent) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->event->stopPropagation();
|
||||
}
|
||||
|
||||
public function __call($name, $args)
|
||||
{
|
||||
return $this->event->{$name}(...$args);
|
||||
}
|
||||
}
|
||||
@@ -1,442 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\EventDispatcher\Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\EventDispatcher\Event;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcher;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
|
||||
abstract class AbstractEventDispatcherTest extends TestCase
|
||||
{
|
||||
/* Some pseudo events */
|
||||
const preFoo = 'pre.foo';
|
||||
const postFoo = 'post.foo';
|
||||
const preBar = 'pre.bar';
|
||||
const postBar = 'post.bar';
|
||||
|
||||
/**
|
||||
* @var EventDispatcher
|
||||
*/
|
||||
private $dispatcher;
|
||||
|
||||
private $listener;
|
||||
|
||||
protected function setUp()
|
||||
{
|
||||
$this->dispatcher = $this->createEventDispatcher();
|
||||
$this->listener = new TestEventListener();
|
||||
}
|
||||
|
||||
protected function tearDown()
|
||||
{
|
||||
$this->dispatcher = null;
|
||||
$this->listener = null;
|
||||
}
|
||||
|
||||
abstract protected function createEventDispatcher();
|
||||
|
||||
public function testInitialState()
|
||||
{
|
||||
$this->assertEquals([], $this->dispatcher->getListeners());
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
|
||||
}
|
||||
|
||||
public function testAddListener()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.foo', [$this->listener, 'preFoo']);
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo']);
|
||||
$this->assertTrue($this->dispatcher->hasListeners());
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
|
||||
$this->assertCount(1, $this->dispatcher->getListeners(self::preFoo));
|
||||
$this->assertCount(1, $this->dispatcher->getListeners(self::postFoo));
|
||||
$this->assertCount(2, $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testGetListenersSortsByPriority()
|
||||
{
|
||||
$listener1 = new TestEventListener();
|
||||
$listener2 = new TestEventListener();
|
||||
$listener3 = new TestEventListener();
|
||||
$listener1->name = '1';
|
||||
$listener2->name = '2';
|
||||
$listener3->name = '3';
|
||||
|
||||
$this->dispatcher->addListener('pre.foo', [$listener1, 'preFoo'], -10);
|
||||
$this->dispatcher->addListener('pre.foo', [$listener2, 'preFoo'], 10);
|
||||
$this->dispatcher->addListener('pre.foo', [$listener3, 'preFoo']);
|
||||
|
||||
$expected = [
|
||||
[$listener2, 'preFoo'],
|
||||
[$listener3, 'preFoo'],
|
||||
[$listener1, 'preFoo'],
|
||||
];
|
||||
|
||||
$this->assertSame($expected, $this->dispatcher->getListeners('pre.foo'));
|
||||
}
|
||||
|
||||
public function testGetAllListenersSortsByPriority()
|
||||
{
|
||||
$listener1 = new TestEventListener();
|
||||
$listener2 = new TestEventListener();
|
||||
$listener3 = new TestEventListener();
|
||||
$listener4 = new TestEventListener();
|
||||
$listener5 = new TestEventListener();
|
||||
$listener6 = new TestEventListener();
|
||||
|
||||
$this->dispatcher->addListener('pre.foo', $listener1, -10);
|
||||
$this->dispatcher->addListener('pre.foo', $listener2);
|
||||
$this->dispatcher->addListener('pre.foo', $listener3, 10);
|
||||
$this->dispatcher->addListener('post.foo', $listener4, -10);
|
||||
$this->dispatcher->addListener('post.foo', $listener5);
|
||||
$this->dispatcher->addListener('post.foo', $listener6, 10);
|
||||
|
||||
$expected = [
|
||||
'pre.foo' => [$listener3, $listener2, $listener1],
|
||||
'post.foo' => [$listener6, $listener5, $listener4],
|
||||
];
|
||||
|
||||
$this->assertSame($expected, $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testGetListenerPriority()
|
||||
{
|
||||
$listener1 = new TestEventListener();
|
||||
$listener2 = new TestEventListener();
|
||||
|
||||
$this->dispatcher->addListener('pre.foo', $listener1, -10);
|
||||
$this->dispatcher->addListener('pre.foo', $listener2);
|
||||
|
||||
$this->assertSame(-10, $this->dispatcher->getListenerPriority('pre.foo', $listener1));
|
||||
$this->assertSame(0, $this->dispatcher->getListenerPriority('pre.foo', $listener2));
|
||||
$this->assertNull($this->dispatcher->getListenerPriority('pre.bar', $listener2));
|
||||
$this->assertNull($this->dispatcher->getListenerPriority('pre.foo', function () {}));
|
||||
}
|
||||
|
||||
public function testDispatch()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.foo', [$this->listener, 'preFoo']);
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo']);
|
||||
$this->dispatcher->dispatch(self::preFoo);
|
||||
$this->assertTrue($this->listener->preFooInvoked);
|
||||
$this->assertFalse($this->listener->postFooInvoked);
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch('noevent'));
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(self::preFoo));
|
||||
$event = new Event();
|
||||
$return = $this->dispatcher->dispatch(self::preFoo, $event);
|
||||
$this->assertSame($event, $return);
|
||||
}
|
||||
|
||||
public function testDispatchForClosure()
|
||||
{
|
||||
$invoked = 0;
|
||||
$listener = function () use (&$invoked) {
|
||||
++$invoked;
|
||||
};
|
||||
$this->dispatcher->addListener('pre.foo', $listener);
|
||||
$this->dispatcher->addListener('post.foo', $listener);
|
||||
$this->dispatcher->dispatch(self::preFoo);
|
||||
$this->assertEquals(1, $invoked);
|
||||
}
|
||||
|
||||
public function testStopEventPropagation()
|
||||
{
|
||||
$otherListener = new TestEventListener();
|
||||
|
||||
// postFoo() stops the propagation, so only one listener should
|
||||
// be executed
|
||||
// Manually set priority to enforce $this->listener to be called first
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo'], 10);
|
||||
$this->dispatcher->addListener('post.foo', [$otherListener, 'postFoo']);
|
||||
$this->dispatcher->dispatch(self::postFoo);
|
||||
$this->assertTrue($this->listener->postFooInvoked);
|
||||
$this->assertFalse($otherListener->postFooInvoked);
|
||||
}
|
||||
|
||||
public function testDispatchByPriority()
|
||||
{
|
||||
$invoked = [];
|
||||
$listener1 = function () use (&$invoked) {
|
||||
$invoked[] = '1';
|
||||
};
|
||||
$listener2 = function () use (&$invoked) {
|
||||
$invoked[] = '2';
|
||||
};
|
||||
$listener3 = function () use (&$invoked) {
|
||||
$invoked[] = '3';
|
||||
};
|
||||
$this->dispatcher->addListener('pre.foo', $listener1, -10);
|
||||
$this->dispatcher->addListener('pre.foo', $listener2);
|
||||
$this->dispatcher->addListener('pre.foo', $listener3, 10);
|
||||
$this->dispatcher->dispatch(self::preFoo);
|
||||
$this->assertEquals(['3', '2', '1'], $invoked);
|
||||
}
|
||||
|
||||
public function testRemoveListener()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.bar', $this->listener);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preBar));
|
||||
$this->dispatcher->removeListener('pre.bar', $this->listener);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preBar));
|
||||
$this->dispatcher->removeListener('notExists', $this->listener);
|
||||
}
|
||||
|
||||
public function testAddSubscriber()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
|
||||
}
|
||||
|
||||
public function testAddSubscriberWithPriorities()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
|
||||
$eventSubscriber = new TestEventSubscriberWithPriorities();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
|
||||
$listeners = $this->dispatcher->getListeners('pre.foo');
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertCount(2, $listeners);
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities', $listeners[0][0]);
|
||||
}
|
||||
|
||||
public function testAddSubscriberWithMultipleListeners()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriberWithMultipleListeners();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
|
||||
$listeners = $this->dispatcher->getListeners('pre.foo');
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertCount(2, $listeners);
|
||||
$this->assertEquals('preFoo2', $listeners[0][1]);
|
||||
}
|
||||
|
||||
public function testRemoveSubscriber()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
|
||||
}
|
||||
|
||||
public function testRemoveSubscriberWithPriorities()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriberWithPriorities();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
}
|
||||
|
||||
public function testRemoveSubscriberWithMultipleListeners()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriberWithMultipleListeners();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertCount(2, $this->dispatcher->getListeners(self::preFoo));
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
}
|
||||
|
||||
public function testEventReceivesTheDispatcherInstanceAsArgument()
|
||||
{
|
||||
$listener = new TestWithDispatcher();
|
||||
$this->dispatcher->addListener('test', [$listener, 'foo']);
|
||||
$this->assertNull($listener->name);
|
||||
$this->assertNull($listener->dispatcher);
|
||||
$this->dispatcher->dispatch('test');
|
||||
$this->assertEquals('test', $listener->name);
|
||||
$this->assertSame($this->dispatcher, $listener->dispatcher);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://bugs.php.net/bug.php?id=62976
|
||||
*
|
||||
* This bug affects:
|
||||
* - The PHP 5.3 branch for versions < 5.3.18
|
||||
* - The PHP 5.4 branch for versions < 5.4.8
|
||||
* - The PHP 5.5 branch is not affected
|
||||
*/
|
||||
public function testWorkaroundForPhpBug62976()
|
||||
{
|
||||
$dispatcher = $this->createEventDispatcher();
|
||||
$dispatcher->addListener('bug.62976', new CallableClass());
|
||||
$dispatcher->removeListener('bug.62976', function () {});
|
||||
$this->assertTrue($dispatcher->hasListeners('bug.62976'));
|
||||
}
|
||||
|
||||
public function testHasListenersWhenAddedCallbackListenerIsRemoved()
|
||||
{
|
||||
$listener = function () {};
|
||||
$this->dispatcher->addListener('foo', $listener);
|
||||
$this->dispatcher->removeListener('foo', $listener);
|
||||
$this->assertFalse($this->dispatcher->hasListeners());
|
||||
}
|
||||
|
||||
public function testGetListenersWhenAddedCallbackListenerIsRemoved()
|
||||
{
|
||||
$listener = function () {};
|
||||
$this->dispatcher->addListener('foo', $listener);
|
||||
$this->dispatcher->removeListener('foo', $listener);
|
||||
$this->assertSame([], $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testHasListenersWithoutEventsReturnsFalseAfterHasListenersWithEventHasBeenCalled()
|
||||
{
|
||||
$this->assertFalse($this->dispatcher->hasListeners('foo'));
|
||||
$this->assertFalse($this->dispatcher->hasListeners());
|
||||
}
|
||||
|
||||
public function testHasListenersIsLazy()
|
||||
{
|
||||
$called = 0;
|
||||
$listener = [function () use (&$called) { ++$called; }, 'onFoo'];
|
||||
$this->dispatcher->addListener('foo', $listener);
|
||||
$this->assertTrue($this->dispatcher->hasListeners());
|
||||
$this->assertTrue($this->dispatcher->hasListeners('foo'));
|
||||
$this->assertSame(0, $called);
|
||||
}
|
||||
|
||||
public function testDispatchLazyListener()
|
||||
{
|
||||
$called = 0;
|
||||
$factory = function () use (&$called) {
|
||||
++$called;
|
||||
|
||||
return new TestWithDispatcher();
|
||||
};
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo']);
|
||||
$this->assertSame(0, $called);
|
||||
$this->dispatcher->dispatch('foo', new Event());
|
||||
$this->dispatcher->dispatch('foo', new Event());
|
||||
$this->assertSame(1, $called);
|
||||
}
|
||||
|
||||
public function testRemoveFindsLazyListeners()
|
||||
{
|
||||
$test = new TestWithDispatcher();
|
||||
$factory = function () use ($test) { return $test; };
|
||||
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo']);
|
||||
$this->assertTrue($this->dispatcher->hasListeners('foo'));
|
||||
$this->dispatcher->removeListener('foo', [$test, 'foo']);
|
||||
$this->assertFalse($this->dispatcher->hasListeners('foo'));
|
||||
|
||||
$this->dispatcher->addListener('foo', [$test, 'foo']);
|
||||
$this->assertTrue($this->dispatcher->hasListeners('foo'));
|
||||
$this->dispatcher->removeListener('foo', [$factory, 'foo']);
|
||||
$this->assertFalse($this->dispatcher->hasListeners('foo'));
|
||||
}
|
||||
|
||||
public function testPriorityFindsLazyListeners()
|
||||
{
|
||||
$test = new TestWithDispatcher();
|
||||
$factory = function () use ($test) { return $test; };
|
||||
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo'], 3);
|
||||
$this->assertSame(3, $this->dispatcher->getListenerPriority('foo', [$test, 'foo']));
|
||||
$this->dispatcher->removeListener('foo', [$factory, 'foo']);
|
||||
|
||||
$this->dispatcher->addListener('foo', [$test, 'foo'], 5);
|
||||
$this->assertSame(5, $this->dispatcher->getListenerPriority('foo', [$factory, 'foo']));
|
||||
}
|
||||
|
||||
public function testGetLazyListeners()
|
||||
{
|
||||
$test = new TestWithDispatcher();
|
||||
$factory = function () use ($test) { return $test; };
|
||||
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo'], 3);
|
||||
$this->assertSame([[$test, 'foo']], $this->dispatcher->getListeners('foo'));
|
||||
|
||||
$this->dispatcher->removeListener('foo', [$test, 'foo']);
|
||||
$this->dispatcher->addListener('bar', [$factory, 'foo'], 3);
|
||||
$this->assertSame(['bar' => [[$test, 'foo']]], $this->dispatcher->getListeners());
|
||||
}
|
||||
}
|
||||
|
||||
class CallableClass
|
||||
{
|
||||
public function __invoke()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventListener
|
||||
{
|
||||
public $preFooInvoked = false;
|
||||
public $postFooInvoked = false;
|
||||
|
||||
/* Listener methods */
|
||||
|
||||
public function preFoo(Event $e)
|
||||
{
|
||||
$this->preFooInvoked = true;
|
||||
}
|
||||
|
||||
public function postFoo(Event $e)
|
||||
{
|
||||
$this->postFooInvoked = true;
|
||||
|
||||
$e->stopPropagation();
|
||||
}
|
||||
}
|
||||
|
||||
class TestWithDispatcher
|
||||
{
|
||||
public $name;
|
||||
public $dispatcher;
|
||||
|
||||
public function foo(Event $e, $name, $dispatcher)
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->dispatcher = $dispatcher;
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventSubscriber implements EventSubscriberInterface
|
||||
{
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
return ['pre.foo' => 'preFoo', 'post.foo' => 'postFoo'];
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventSubscriberWithPriorities implements EventSubscriberInterface
|
||||
{
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
return [
|
||||
'pre.foo' => ['preFoo', 10],
|
||||
'post.foo' => ['postFoo'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventSubscriberWithMultipleListeners implements EventSubscriberInterface
|
||||
{
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
return ['pre.foo' => [
|
||||
['preFoo1'],
|
||||
['preFoo2', 10],
|
||||
]];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\EventDispatcher\Tests;
|
||||
|
||||
use Symfony\Component\EventDispatcher\EventDispatcher;
|
||||
|
||||
class ChildEventDispatcherTest extends EventDispatcherTest
|
||||
{
|
||||
protected function createEventDispatcher()
|
||||
{
|
||||
return new ChildEventDispatcher();
|
||||
}
|
||||
}
|
||||
|
||||
class ChildEventDispatcher extends EventDispatcher
|
||||
{
|
||||
}
|
||||
+32
-18
@@ -18,6 +18,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
use Symfony\Component\Stopwatch\Stopwatch;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
|
||||
class TraceableEventDispatcherTest extends TestCase
|
||||
{
|
||||
@@ -69,7 +70,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
|
||||
// Verify that priority is preserved when listener is removed and re-added
|
||||
// in preProcess() and postProcess().
|
||||
$tdispatcher->dispatch('foo', new Event());
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
$listeners = $dispatcher->getListeners('foo');
|
||||
$this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0]));
|
||||
}
|
||||
@@ -84,7 +85,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
};
|
||||
|
||||
$tdispatcher->addListener('bar', $listener, 5);
|
||||
$tdispatcher->dispatch('bar');
|
||||
$tdispatcher->dispatch(new Event(), 'bar');
|
||||
$this->assertSame(5, $priorityWhileDispatching);
|
||||
}
|
||||
|
||||
@@ -115,7 +116,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$this->assertEquals([], $tdispatcher->getCalledListeners());
|
||||
$this->assertEquals([['event' => 'foo', 'pretty' => 'closure', 'priority' => 5]], $listeners);
|
||||
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$listeners = $tdispatcher->getCalledListeners();
|
||||
$this->assertArrayHasKey('stub', $listeners[0]);
|
||||
@@ -129,7 +130,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$tdispatcher->addListener('foo', function () {}, 5);
|
||||
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
$tdispatcher->reset();
|
||||
|
||||
$listeners = $tdispatcher->getNotCalledListeners();
|
||||
@@ -139,13 +140,26 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$this->assertEquals([['event' => 'foo', 'pretty' => 'closure', 'priority' => 5]], $listeners);
|
||||
}
|
||||
|
||||
public function testDispatchContractsEvent()
|
||||
{
|
||||
$expectedEvent = new ContractsEvent();
|
||||
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$tdispatcher->addListener('foo', function ($event) use ($expectedEvent) {
|
||||
$this->assertSame($event, $expectedEvent);
|
||||
}, 5);
|
||||
$tdispatcher->dispatch($expectedEvent, 'foo');
|
||||
|
||||
$listeners = $tdispatcher->getCalledListeners();
|
||||
$this->assertArrayHasKey('stub', $listeners[0]);
|
||||
}
|
||||
|
||||
public function testDispatchAfterReset()
|
||||
{
|
||||
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$tdispatcher->addListener('foo', function () {}, 5);
|
||||
|
||||
$tdispatcher->reset();
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$listeners = $tdispatcher->getCalledListeners();
|
||||
$this->assertArrayHasKey('stub', $listeners[0]);
|
||||
@@ -157,10 +171,10 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$dispatcher->addListener('foo', function (Event $event, $eventName, $dispatcher) use (&$tdispatcher) {
|
||||
$tdispatcher = $dispatcher;
|
||||
$dispatcher->dispatch('bar');
|
||||
$dispatcher->dispatch(new Event(), 'bar');
|
||||
});
|
||||
$dispatcher->addListener('bar', function (Event $event) {});
|
||||
$dispatcher->dispatch('foo');
|
||||
$dispatcher->dispatch(new Event(), 'foo');
|
||||
$this->assertSame($dispatcher, $tdispatcher);
|
||||
$this->assertCount(2, $dispatcher->getCalledListeners());
|
||||
}
|
||||
@@ -175,7 +189,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
public function testItReturnsOrphanedEventsAfterDispatch()
|
||||
{
|
||||
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
$events = $tdispatcher->getOrphanedEvents();
|
||||
$this->assertCount(1, $events);
|
||||
$this->assertEquals(['foo'], $events);
|
||||
@@ -185,7 +199,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
{
|
||||
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$tdispatcher->addListener('foo', function () {});
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
$events = $tdispatcher->getOrphanedEvents();
|
||||
$this->assertEmpty($events);
|
||||
}
|
||||
@@ -202,7 +216,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$logger->expects($this->at(0))->method('debug')->with('Notified event "{event}" to listener "{listener}".', ['event' => 'foo', 'listener' => 'closure']);
|
||||
$logger->expects($this->at(1))->method('debug')->with('Notified event "{event}" to listener "{listener}".', ['event' => 'foo', 'listener' => 'closure']);
|
||||
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
}
|
||||
|
||||
public function testLoggerWithStoppedEvent()
|
||||
@@ -218,7 +232,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$logger->expects($this->at(1))->method('debug')->with('Listener "{listener}" stopped propagation of the event "{event}".', ['event' => 'foo', 'listener' => 'closure']);
|
||||
$logger->expects($this->at(2))->method('debug')->with('Listener "{listener}" was not called for event "{event}".', ['event' => 'foo', 'listener' => 'closure']);
|
||||
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
}
|
||||
|
||||
public function testDispatchCallListeners()
|
||||
@@ -230,7 +244,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo1'; }, 10);
|
||||
$tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo2'; }, 20);
|
||||
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$this->assertSame(['foo2', 'foo1'], $called);
|
||||
}
|
||||
@@ -243,14 +257,14 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) {
|
||||
++$loop;
|
||||
if (2 == $loop) {
|
||||
$dispatcher->dispatch('foo');
|
||||
$dispatcher->dispatch(new Event(), 'foo');
|
||||
}
|
||||
});
|
||||
$dispatcher->addListener('foo', function () use (&$dispatchedEvents) {
|
||||
++$dispatchedEvents;
|
||||
});
|
||||
|
||||
$dispatcher->dispatch('foo');
|
||||
$dispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$this->assertSame(2, $dispatchedEvents);
|
||||
}
|
||||
@@ -260,14 +274,14 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
$nestedCall = false;
|
||||
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$dispatcher->addListener('foo', function (Event $e) use ($dispatcher) {
|
||||
$dispatcher->dispatch('bar', $e);
|
||||
$dispatcher->dispatch(new Event(), 'bar', $e);
|
||||
});
|
||||
$dispatcher->addListener('bar', function (Event $e) use (&$nestedCall) {
|
||||
$nestedCall = true;
|
||||
});
|
||||
|
||||
$this->assertFalse($nestedCall);
|
||||
$dispatcher->dispatch('foo');
|
||||
$dispatcher->dispatch(new Event(), 'foo');
|
||||
$this->assertTrue($nestedCall);
|
||||
}
|
||||
|
||||
@@ -279,7 +293,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
};
|
||||
$eventDispatcher->addListener('foo', $listener1);
|
||||
$eventDispatcher->addListener('foo', function () {});
|
||||
$eventDispatcher->dispatch('foo');
|
||||
$eventDispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed');
|
||||
}
|
||||
@@ -287,7 +301,7 @@ class TraceableEventDispatcherTest extends TestCase
|
||||
public function testClearOrphanedEvents()
|
||||
{
|
||||
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
|
||||
$tdispatcher->dispatch('foo');
|
||||
$tdispatcher->dispatch(new Event(), 'foo');
|
||||
$events = $tdispatcher->getOrphanedEvents();
|
||||
$this->assertCount(1, $events);
|
||||
$tdispatcher->reset();
|
||||
|
||||
@@ -21,7 +21,7 @@ class WrappedListenerTest extends TestCase
|
||||
/**
|
||||
* @dataProvider provideListenersToDescribe
|
||||
*/
|
||||
public function testListenerDescription(callable $listener, $expected)
|
||||
public function testListenerDescription($listener, $expected)
|
||||
{
|
||||
$wrappedListener = new WrappedListener($listener, null, $this->getMockBuilder(Stopwatch::class)->getMock(), $this->getMockBuilder(EventDispatcherInterface::class)->getMock());
|
||||
|
||||
@@ -34,6 +34,7 @@ class WrappedListenerTest extends TestCase
|
||||
[new FooListener(), 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::__invoke'],
|
||||
[[new FooListener(), 'listen'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listen'],
|
||||
[['Symfony\Component\EventDispatcher\Tests\Debug\FooListener', 'listenStatic'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listenStatic'],
|
||||
[['Symfony\Component\EventDispatcher\Tests\Debug\FooListener', 'invalidMethod'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::invalidMethod'],
|
||||
['var_dump', 'var_dump'],
|
||||
[function () {}, 'closure'],
|
||||
[\Closure::fromCallable([new FooListener(), 'listen']), 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listen'],
|
||||
|
||||
+465
-1
@@ -11,12 +11,476 @@
|
||||
|
||||
namespace Symfony\Component\EventDispatcher\Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\EventDispatcher\Event;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcher;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
use Symfony\Contracts\EventDispatcher\Event as ContractsEvent;
|
||||
|
||||
class EventDispatcherTest extends AbstractEventDispatcherTest
|
||||
class EventDispatcherTest extends TestCase
|
||||
{
|
||||
/* Some pseudo events */
|
||||
const preFoo = 'pre.foo';
|
||||
const postFoo = 'post.foo';
|
||||
const preBar = 'pre.bar';
|
||||
const postBar = 'post.bar';
|
||||
|
||||
/**
|
||||
* @var EventDispatcher
|
||||
*/
|
||||
private $dispatcher;
|
||||
|
||||
private $listener;
|
||||
|
||||
protected function setUp()
|
||||
{
|
||||
$this->dispatcher = $this->createEventDispatcher();
|
||||
$this->listener = new TestEventListener();
|
||||
}
|
||||
|
||||
protected function tearDown()
|
||||
{
|
||||
$this->dispatcher = null;
|
||||
$this->listener = null;
|
||||
}
|
||||
|
||||
protected function createEventDispatcher()
|
||||
{
|
||||
return new EventDispatcher();
|
||||
}
|
||||
|
||||
public function testInitialState()
|
||||
{
|
||||
$this->assertEquals([], $this->dispatcher->getListeners());
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
|
||||
}
|
||||
|
||||
public function testAddListener()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.foo', [$this->listener, 'preFoo']);
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo']);
|
||||
$this->assertTrue($this->dispatcher->hasListeners());
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
|
||||
$this->assertCount(1, $this->dispatcher->getListeners(self::preFoo));
|
||||
$this->assertCount(1, $this->dispatcher->getListeners(self::postFoo));
|
||||
$this->assertCount(2, $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testGetListenersSortsByPriority()
|
||||
{
|
||||
$listener1 = new TestEventListener();
|
||||
$listener2 = new TestEventListener();
|
||||
$listener3 = new TestEventListener();
|
||||
$listener1->name = '1';
|
||||
$listener2->name = '2';
|
||||
$listener3->name = '3';
|
||||
|
||||
$this->dispatcher->addListener('pre.foo', [$listener1, 'preFoo'], -10);
|
||||
$this->dispatcher->addListener('pre.foo', [$listener2, 'preFoo'], 10);
|
||||
$this->dispatcher->addListener('pre.foo', [$listener3, 'preFoo']);
|
||||
|
||||
$expected = [
|
||||
[$listener2, 'preFoo'],
|
||||
[$listener3, 'preFoo'],
|
||||
[$listener1, 'preFoo'],
|
||||
];
|
||||
|
||||
$this->assertSame($expected, $this->dispatcher->getListeners('pre.foo'));
|
||||
}
|
||||
|
||||
public function testGetAllListenersSortsByPriority()
|
||||
{
|
||||
$listener1 = new TestEventListener();
|
||||
$listener2 = new TestEventListener();
|
||||
$listener3 = new TestEventListener();
|
||||
$listener4 = new TestEventListener();
|
||||
$listener5 = new TestEventListener();
|
||||
$listener6 = new TestEventListener();
|
||||
|
||||
$this->dispatcher->addListener('pre.foo', $listener1, -10);
|
||||
$this->dispatcher->addListener('pre.foo', $listener2);
|
||||
$this->dispatcher->addListener('pre.foo', $listener3, 10);
|
||||
$this->dispatcher->addListener('post.foo', $listener4, -10);
|
||||
$this->dispatcher->addListener('post.foo', $listener5);
|
||||
$this->dispatcher->addListener('post.foo', $listener6, 10);
|
||||
|
||||
$expected = [
|
||||
'pre.foo' => [$listener3, $listener2, $listener1],
|
||||
'post.foo' => [$listener6, $listener5, $listener4],
|
||||
];
|
||||
|
||||
$this->assertSame($expected, $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testGetListenerPriority()
|
||||
{
|
||||
$listener1 = new TestEventListener();
|
||||
$listener2 = new TestEventListener();
|
||||
|
||||
$this->dispatcher->addListener('pre.foo', $listener1, -10);
|
||||
$this->dispatcher->addListener('pre.foo', $listener2);
|
||||
|
||||
$this->assertSame(-10, $this->dispatcher->getListenerPriority('pre.foo', $listener1));
|
||||
$this->assertSame(0, $this->dispatcher->getListenerPriority('pre.foo', $listener2));
|
||||
$this->assertNull($this->dispatcher->getListenerPriority('pre.bar', $listener2));
|
||||
$this->assertNull($this->dispatcher->getListenerPriority('pre.foo', function () {}));
|
||||
}
|
||||
|
||||
public function testDispatch()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.foo', [$this->listener, 'preFoo']);
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo']);
|
||||
$this->dispatcher->dispatch(new Event(), self::preFoo);
|
||||
$this->assertTrue($this->listener->preFooInvoked);
|
||||
$this->assertFalse($this->listener->postFooInvoked);
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(new Event(), 'noevent'));
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(new Event(), self::preFoo));
|
||||
$event = new Event();
|
||||
$return = $this->dispatcher->dispatch($event, self::preFoo);
|
||||
$this->assertSame($event, $return);
|
||||
}
|
||||
|
||||
public function testDispatchContractsEvent()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.foo', [$this->listener, 'preFoo']);
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo']);
|
||||
$this->dispatcher->dispatch(new ContractsEvent(), self::preFoo);
|
||||
$this->assertTrue($this->listener->preFooInvoked);
|
||||
$this->assertFalse($this->listener->postFooInvoked);
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(new Event(), 'noevent'));
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(new Event(), self::preFoo));
|
||||
$event = new Event();
|
||||
$return = $this->dispatcher->dispatch($event, self::preFoo);
|
||||
$this->assertSame($event, $return);
|
||||
}
|
||||
|
||||
public function testDispatchForClosure()
|
||||
{
|
||||
$invoked = 0;
|
||||
$listener = function () use (&$invoked) {
|
||||
++$invoked;
|
||||
};
|
||||
$this->dispatcher->addListener('pre.foo', $listener);
|
||||
$this->dispatcher->addListener('post.foo', $listener);
|
||||
$this->dispatcher->dispatch(new Event(), self::preFoo);
|
||||
$this->assertEquals(1, $invoked);
|
||||
}
|
||||
|
||||
public function testStopEventPropagation()
|
||||
{
|
||||
$otherListener = new TestEventListener();
|
||||
|
||||
// postFoo() stops the propagation, so only one listener should
|
||||
// be executed
|
||||
// Manually set priority to enforce $this->listener to be called first
|
||||
$this->dispatcher->addListener('post.foo', [$this->listener, 'postFoo'], 10);
|
||||
$this->dispatcher->addListener('post.foo', [$otherListener, 'postFoo']);
|
||||
$this->dispatcher->dispatch(new Event(), self::postFoo);
|
||||
$this->assertTrue($this->listener->postFooInvoked);
|
||||
$this->assertFalse($otherListener->postFooInvoked);
|
||||
}
|
||||
|
||||
public function testDispatchByPriority()
|
||||
{
|
||||
$invoked = [];
|
||||
$listener1 = function () use (&$invoked) {
|
||||
$invoked[] = '1';
|
||||
};
|
||||
$listener2 = function () use (&$invoked) {
|
||||
$invoked[] = '2';
|
||||
};
|
||||
$listener3 = function () use (&$invoked) {
|
||||
$invoked[] = '3';
|
||||
};
|
||||
$this->dispatcher->addListener('pre.foo', $listener1, -10);
|
||||
$this->dispatcher->addListener('pre.foo', $listener2);
|
||||
$this->dispatcher->addListener('pre.foo', $listener3, 10);
|
||||
$this->dispatcher->dispatch(new Event(), self::preFoo);
|
||||
$this->assertEquals(['3', '2', '1'], $invoked);
|
||||
}
|
||||
|
||||
public function testRemoveListener()
|
||||
{
|
||||
$this->dispatcher->addListener('pre.bar', $this->listener);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preBar));
|
||||
$this->dispatcher->removeListener('pre.bar', $this->listener);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preBar));
|
||||
$this->dispatcher->removeListener('notExists', $this->listener);
|
||||
}
|
||||
|
||||
public function testAddSubscriber()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
|
||||
}
|
||||
|
||||
public function testAddSubscriberWithPriorities()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
|
||||
$eventSubscriber = new TestEventSubscriberWithPriorities();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
|
||||
$listeners = $this->dispatcher->getListeners('pre.foo');
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertCount(2, $listeners);
|
||||
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities', $listeners[0][0]);
|
||||
}
|
||||
|
||||
public function testAddSubscriberWithMultipleListeners()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriberWithMultipleListeners();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
|
||||
$listeners = $this->dispatcher->getListeners('pre.foo');
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertCount(2, $listeners);
|
||||
$this->assertEquals('preFoo2', $listeners[0][1]);
|
||||
}
|
||||
|
||||
public function testRemoveSubscriber()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
|
||||
}
|
||||
|
||||
public function testRemoveSubscriberWithPriorities()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriberWithPriorities();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
}
|
||||
|
||||
public function testRemoveSubscriberWithMultipleListeners()
|
||||
{
|
||||
$eventSubscriber = new TestEventSubscriberWithMultipleListeners();
|
||||
$this->dispatcher->addSubscriber($eventSubscriber);
|
||||
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
|
||||
$this->assertCount(2, $this->dispatcher->getListeners(self::preFoo));
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
}
|
||||
|
||||
public function testEventReceivesTheDispatcherInstanceAsArgument()
|
||||
{
|
||||
$listener = new TestWithDispatcher();
|
||||
$this->dispatcher->addListener('test', [$listener, 'foo']);
|
||||
$this->assertNull($listener->name);
|
||||
$this->assertNull($listener->dispatcher);
|
||||
$this->dispatcher->dispatch(new Event(), 'test');
|
||||
$this->assertEquals('test', $listener->name);
|
||||
$this->assertSame($this->dispatcher, $listener->dispatcher);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://bugs.php.net/bug.php?id=62976
|
||||
*
|
||||
* This bug affects:
|
||||
* - The PHP 5.3 branch for versions < 5.3.18
|
||||
* - The PHP 5.4 branch for versions < 5.4.8
|
||||
* - The PHP 5.5 branch is not affected
|
||||
*/
|
||||
public function testWorkaroundForPhpBug62976()
|
||||
{
|
||||
$dispatcher = $this->createEventDispatcher();
|
||||
$dispatcher->addListener('bug.62976', new CallableClass());
|
||||
$dispatcher->removeListener('bug.62976', function () {});
|
||||
$this->assertTrue($dispatcher->hasListeners('bug.62976'));
|
||||
}
|
||||
|
||||
public function testHasListenersWhenAddedCallbackListenerIsRemoved()
|
||||
{
|
||||
$listener = function () {};
|
||||
$this->dispatcher->addListener('foo', $listener);
|
||||
$this->dispatcher->removeListener('foo', $listener);
|
||||
$this->assertFalse($this->dispatcher->hasListeners());
|
||||
}
|
||||
|
||||
public function testGetListenersWhenAddedCallbackListenerIsRemoved()
|
||||
{
|
||||
$listener = function () {};
|
||||
$this->dispatcher->addListener('foo', $listener);
|
||||
$this->dispatcher->removeListener('foo', $listener);
|
||||
$this->assertSame([], $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testHasListenersWithoutEventsReturnsFalseAfterHasListenersWithEventHasBeenCalled()
|
||||
{
|
||||
$this->assertFalse($this->dispatcher->hasListeners('foo'));
|
||||
$this->assertFalse($this->dispatcher->hasListeners());
|
||||
}
|
||||
|
||||
public function testHasListenersIsLazy()
|
||||
{
|
||||
$called = 0;
|
||||
$listener = [function () use (&$called) { ++$called; }, 'onFoo'];
|
||||
$this->dispatcher->addListener('foo', $listener);
|
||||
$this->assertTrue($this->dispatcher->hasListeners());
|
||||
$this->assertTrue($this->dispatcher->hasListeners('foo'));
|
||||
$this->assertSame(0, $called);
|
||||
}
|
||||
|
||||
public function testDispatchLazyListener()
|
||||
{
|
||||
$called = 0;
|
||||
$factory = function () use (&$called) {
|
||||
++$called;
|
||||
|
||||
return new TestWithDispatcher();
|
||||
};
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo']);
|
||||
$this->assertSame(0, $called);
|
||||
$this->dispatcher->dispatch(new Event(), 'foo');
|
||||
$this->dispatcher->dispatch(new Event(), 'foo');
|
||||
$this->assertSame(1, $called);
|
||||
}
|
||||
|
||||
public function testRemoveFindsLazyListeners()
|
||||
{
|
||||
$test = new TestWithDispatcher();
|
||||
$factory = function () use ($test) { return $test; };
|
||||
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo']);
|
||||
$this->assertTrue($this->dispatcher->hasListeners('foo'));
|
||||
$this->dispatcher->removeListener('foo', [$test, 'foo']);
|
||||
$this->assertFalse($this->dispatcher->hasListeners('foo'));
|
||||
|
||||
$this->dispatcher->addListener('foo', [$test, 'foo']);
|
||||
$this->assertTrue($this->dispatcher->hasListeners('foo'));
|
||||
$this->dispatcher->removeListener('foo', [$factory, 'foo']);
|
||||
$this->assertFalse($this->dispatcher->hasListeners('foo'));
|
||||
}
|
||||
|
||||
public function testPriorityFindsLazyListeners()
|
||||
{
|
||||
$test = new TestWithDispatcher();
|
||||
$factory = function () use ($test) { return $test; };
|
||||
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo'], 3);
|
||||
$this->assertSame(3, $this->dispatcher->getListenerPriority('foo', [$test, 'foo']));
|
||||
$this->dispatcher->removeListener('foo', [$factory, 'foo']);
|
||||
|
||||
$this->dispatcher->addListener('foo', [$test, 'foo'], 5);
|
||||
$this->assertSame(5, $this->dispatcher->getListenerPriority('foo', [$factory, 'foo']));
|
||||
}
|
||||
|
||||
public function testGetLazyListeners()
|
||||
{
|
||||
$test = new TestWithDispatcher();
|
||||
$factory = function () use ($test) { return $test; };
|
||||
|
||||
$this->dispatcher->addListener('foo', [$factory, 'foo'], 3);
|
||||
$this->assertSame([[$test, 'foo']], $this->dispatcher->getListeners('foo'));
|
||||
|
||||
$this->dispatcher->removeListener('foo', [$test, 'foo']);
|
||||
$this->dispatcher->addListener('bar', [$factory, 'foo'], 3);
|
||||
$this->assertSame(['bar' => [[$test, 'foo']]], $this->dispatcher->getListeners());
|
||||
}
|
||||
|
||||
public function testMutatingWhilePropagationIsStopped()
|
||||
{
|
||||
$testLoaded = false;
|
||||
$test = new TestEventListener();
|
||||
$this->dispatcher->addListener('foo', [$test, 'postFoo']);
|
||||
$this->dispatcher->addListener('foo', [function () use ($test, &$testLoaded) {
|
||||
$testLoaded = true;
|
||||
|
||||
return $test;
|
||||
}, 'preFoo']);
|
||||
|
||||
$this->dispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$this->assertTrue($test->postFooInvoked);
|
||||
$this->assertFalse($test->preFooInvoked);
|
||||
|
||||
$this->assertsame(0, $this->dispatcher->getListenerPriority('foo', [$test, 'preFoo']));
|
||||
|
||||
$test->preFoo(new Event());
|
||||
$this->dispatcher->dispatch(new Event(), 'foo');
|
||||
|
||||
$this->assertTrue($testLoaded);
|
||||
}
|
||||
}
|
||||
|
||||
class CallableClass
|
||||
{
|
||||
public function __invoke()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventListener
|
||||
{
|
||||
public $preFooInvoked = false;
|
||||
public $postFooInvoked = false;
|
||||
|
||||
/* Listener methods */
|
||||
|
||||
public function preFoo($e)
|
||||
{
|
||||
$this->preFooInvoked = true;
|
||||
}
|
||||
|
||||
public function postFoo($e)
|
||||
{
|
||||
$this->postFooInvoked = true;
|
||||
|
||||
if (!$this->preFooInvoked) {
|
||||
$e->stopPropagation();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TestWithDispatcher
|
||||
{
|
||||
public $name;
|
||||
public $dispatcher;
|
||||
|
||||
public function foo($e, $name, $dispatcher)
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->dispatcher = $dispatcher;
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventSubscriber implements EventSubscriberInterface
|
||||
{
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
return ['pre.foo' => 'preFoo', 'post.foo' => 'postFoo'];
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventSubscriberWithPriorities implements EventSubscriberInterface
|
||||
{
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
return [
|
||||
'pre.foo' => ['preFoo', 10],
|
||||
'post.foo' => ['postFoo'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventSubscriberWithMultipleListeners implements EventSubscriberInterface
|
||||
{
|
||||
public static function getSubscribedEvents()
|
||||
{
|
||||
return ['pre.foo' => [
|
||||
['preFoo1'],
|
||||
['preFoo2', 10],
|
||||
]];
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\EventDispatcher\Event;
|
||||
|
||||
/**
|
||||
* Test class for Event.
|
||||
* @group legacy
|
||||
*/
|
||||
class EventTest extends TestCase
|
||||
{
|
||||
|
||||
@@ -92,7 +92,7 @@ class GenericEventTest extends TestCase
|
||||
$this->assertEquals('Event', $this->event['name']);
|
||||
|
||||
// test getting invalid arg
|
||||
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
|
||||
$this->expectException('InvalidArgumentException');
|
||||
$this->assertFalse($this->event['nameNotExist']);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,10 +42,10 @@ class ImmutableEventDispatcherTest extends TestCase
|
||||
|
||||
$this->innerDispatcher->expects($this->once())
|
||||
->method('dispatch')
|
||||
->with('event', $event)
|
||||
->with($event, 'event')
|
||||
->will($this->returnValue('result'));
|
||||
|
||||
$this->assertSame('result', $this->dispatcher->dispatch('event', $event));
|
||||
$this->assertSame('result', $this->dispatcher->dispatch($event, 'event'));
|
||||
}
|
||||
|
||||
public function testGetListenersDelegates()
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\EventDispatcher\Tests;
|
||||
|
||||
use Symfony\Component\EventDispatcher\Event;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcher;
|
||||
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
|
||||
|
||||
/**
|
||||
* @group legacy
|
||||
*/
|
||||
class LegacyEventDispatcherTest extends EventDispatcherTest
|
||||
{
|
||||
protected function createEventDispatcher()
|
||||
{
|
||||
return LegacyEventDispatcherProxy::decorate(new TestLegacyEventDispatcher());
|
||||
}
|
||||
}
|
||||
|
||||
class TestLegacyEventDispatcher extends EventDispatcher
|
||||
{
|
||||
public function dispatch($eventName, Event $event = null)
|
||||
{
|
||||
return parent::dispatch($event, $eventName);
|
||||
}
|
||||
}
|
||||
+8
-2
@@ -17,18 +17,24 @@
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.1.3",
|
||||
"symfony/contracts": "^1.0"
|
||||
"symfony/event-dispatcher-contracts": "^1.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"symfony/dependency-injection": "~3.4|~4.0",
|
||||
"symfony/expression-language": "~3.4|~4.0",
|
||||
"symfony/config": "~3.4|~4.0",
|
||||
"symfony/http-foundation": "^3.4|^4.0",
|
||||
"symfony/service-contracts": "^1.1",
|
||||
"symfony/stopwatch": "~3.4|~4.0",
|
||||
"psr/log": "~1.0"
|
||||
},
|
||||
"conflict": {
|
||||
"symfony/dependency-injection": "<3.4"
|
||||
},
|
||||
"provide": {
|
||||
"psr/event-dispatcher-implementation": "1.0",
|
||||
"symfony/event-dispatcher-implementation": "1.1"
|
||||
},
|
||||
"suggest": {
|
||||
"symfony/dependency-injection": "",
|
||||
"symfony/http-kernel": ""
|
||||
@@ -42,7 +48,7 @@
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.2-dev"
|
||||
"dev-master": "4.3-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+5
@@ -1,6 +1,11 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
4.3.0
|
||||
-----
|
||||
|
||||
* added Finder::ignoreVCSIgnored() to ignore files based on rules listed in .gitignore
|
||||
|
||||
4.2.0
|
||||
-----
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Finder\Exception;
|
||||
|
||||
/**
|
||||
* @author Andreas Erhard <andreas.erhard@i-med.ac.at>
|
||||
*/
|
||||
class DirectoryNotFoundException extends \InvalidArgumentException
|
||||
{
|
||||
}
|
||||
Vendored
+30
-2
@@ -13,6 +13,7 @@ namespace Symfony\Component\Finder;
|
||||
|
||||
use Symfony\Component\Finder\Comparator\DateComparator;
|
||||
use Symfony\Component\Finder\Comparator\NumberComparator;
|
||||
use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
|
||||
use Symfony\Component\Finder\Iterator\CustomFilterIterator;
|
||||
use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
|
||||
use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
|
||||
@@ -39,6 +40,7 @@ class Finder implements \IteratorAggregate, \Countable
|
||||
{
|
||||
const IGNORE_VCS_FILES = 1;
|
||||
const IGNORE_DOT_FILES = 2;
|
||||
const IGNORE_VCS_IGNORED_FILES = 4;
|
||||
|
||||
private $mode = 0;
|
||||
private $names = [];
|
||||
@@ -373,6 +375,24 @@ class Finder implements \IteratorAggregate, \Countable
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces Finder to obey .gitignore and ignore files based on rules listed there.
|
||||
*
|
||||
* This option is disabled by default.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function ignoreVCSIgnored(bool $ignoreVCSIgnored)
|
||||
{
|
||||
if ($ignoreVCSIgnored) {
|
||||
$this->ignore |= static::IGNORE_VCS_IGNORED_FILES;
|
||||
} else {
|
||||
$this->ignore &= ~static::IGNORE_VCS_IGNORED_FILES;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds VCS patterns.
|
||||
*
|
||||
@@ -566,7 +586,7 @@ class Finder implements \IteratorAggregate, \Countable
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
* @throws \InvalidArgumentException if one of the directories does not exist
|
||||
* @throws DirectoryNotFoundException if one of the directories does not exist
|
||||
*/
|
||||
public function in($dirs)
|
||||
{
|
||||
@@ -578,7 +598,7 @@ class Finder implements \IteratorAggregate, \Countable
|
||||
} elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) {
|
||||
$resolvedDirs = array_merge($resolvedDirs, array_map([$this, 'normalizeDir'], $glob));
|
||||
} else {
|
||||
throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
|
||||
throw new DirectoryNotFoundException(sprintf('The "%s" directory does not exist.', $dir));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -685,6 +705,14 @@ class Finder implements \IteratorAggregate, \Countable
|
||||
$notPaths[] = '#(^|/)\..+(/|$)#';
|
||||
}
|
||||
|
||||
if (static::IGNORE_VCS_IGNORED_FILES === (static::IGNORE_VCS_IGNORED_FILES & $this->ignore)) {
|
||||
$gitignoreFilePath = sprintf('%s/.gitignore', $dir);
|
||||
if (!is_readable($gitignoreFilePath)) {
|
||||
throw new \RuntimeException(sprintf('The "ignoreVCSIgnored" option cannot be used by the Finder as the "%s" file is not readable.', $gitignoreFilePath));
|
||||
}
|
||||
$notPaths = array_merge($notPaths, [Gitignore::toRegex(file_get_contents($gitignoreFilePath))]);
|
||||
}
|
||||
|
||||
$minDepth = 0;
|
||||
$maxDepth = PHP_INT_MAX;
|
||||
|
||||
|
||||
Vendored
+107
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Finder;
|
||||
|
||||
/**
|
||||
* Gitignore matches against text.
|
||||
*
|
||||
* @author Ahmed Abdou <mail@ahmd.io>
|
||||
*/
|
||||
class Gitignore
|
||||
{
|
||||
/**
|
||||
* Returns a regexp which is the equivalent of the gitignore pattern.
|
||||
*
|
||||
* @param string $gitignoreFileContent
|
||||
*
|
||||
* @return string The regexp
|
||||
*/
|
||||
public static function toRegex(string $gitignoreFileContent): string
|
||||
{
|
||||
$gitignoreFileContent = preg_replace('/^[^\\\\]*#.*/', '', $gitignoreFileContent);
|
||||
$gitignoreLines = preg_split('/\r\n|\r|\n/', $gitignoreFileContent);
|
||||
$gitignoreLines = array_map('trim', $gitignoreLines);
|
||||
$gitignoreLines = array_filter($gitignoreLines);
|
||||
|
||||
$ignoreLinesPositive = array_filter($gitignoreLines, function (string $line) {
|
||||
return !preg_match('/^!/', $line);
|
||||
});
|
||||
|
||||
$ignoreLinesNegative = array_filter($gitignoreLines, function (string $line) {
|
||||
return preg_match('/^!/', $line);
|
||||
});
|
||||
|
||||
$ignoreLinesNegative = array_map(function (string $line) {
|
||||
return preg_replace('/^!(.*)/', '${1}', $line);
|
||||
}, $ignoreLinesNegative);
|
||||
$ignoreLinesNegative = array_map([__CLASS__, 'getRegexFromGitignore'], $ignoreLinesNegative);
|
||||
|
||||
$ignoreLinesPositive = array_map([__CLASS__, 'getRegexFromGitignore'], $ignoreLinesPositive);
|
||||
if (empty($ignoreLinesPositive)) {
|
||||
return '/^$/';
|
||||
}
|
||||
|
||||
if (empty($ignoreLinesNegative)) {
|
||||
return sprintf('/%s/', implode('|', $ignoreLinesPositive));
|
||||
}
|
||||
|
||||
return sprintf('/(?=^(?:(?!(%s)).)*$)(%s)/', implode('|', $ignoreLinesNegative), implode('|', $ignoreLinesPositive));
|
||||
}
|
||||
|
||||
private static function getRegexFromGitignore(string $gitignorePattern): string
|
||||
{
|
||||
$regex = '(';
|
||||
if (0 === strpos($gitignorePattern, '/')) {
|
||||
$gitignorePattern = substr($gitignorePattern, 1);
|
||||
$regex .= '^';
|
||||
} else {
|
||||
$regex .= '(^|\/)';
|
||||
}
|
||||
|
||||
if ('/' === $gitignorePattern[\strlen($gitignorePattern) - 1]) {
|
||||
$gitignorePattern = substr($gitignorePattern, 0, -1);
|
||||
}
|
||||
|
||||
$iMax = \strlen($gitignorePattern);
|
||||
for ($i = 0; $i < $iMax; ++$i) {
|
||||
$doubleChars = substr($gitignorePattern, $i, 2);
|
||||
if ('**' === $doubleChars) {
|
||||
$regex .= '.+';
|
||||
++$i;
|
||||
continue;
|
||||
}
|
||||
|
||||
$c = $gitignorePattern[$i];
|
||||
switch ($c) {
|
||||
case '*':
|
||||
$regex .= '[^\/]+';
|
||||
break;
|
||||
case '/':
|
||||
case '.':
|
||||
case ':':
|
||||
case '(':
|
||||
case ')':
|
||||
case '{':
|
||||
case '}':
|
||||
$regex .= '\\'.$c;
|
||||
break;
|
||||
default:
|
||||
$regex .= $c;
|
||||
}
|
||||
}
|
||||
|
||||
$regex .= '($|\/)';
|
||||
$regex .= ')';
|
||||
|
||||
return $regex;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -42,7 +42,7 @@ class SortableIterator implements \IteratorAggregate
|
||||
|
||||
if (self::SORT_BY_NAME === $sort) {
|
||||
$this->sort = function ($a, $b) use ($order) {
|
||||
return $order * strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
|
||||
return $order * strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname());
|
||||
};
|
||||
} elseif (self::SORT_BY_NAME_NATURAL === $sort) {
|
||||
$this->sort = function ($a, $b) use ($order) {
|
||||
@@ -56,7 +56,7 @@ class SortableIterator implements \IteratorAggregate
|
||||
return $order;
|
||||
}
|
||||
|
||||
return $order * strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
|
||||
return $order * strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname());
|
||||
};
|
||||
} elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
|
||||
$this->sort = function ($a, $b) use ($order) {
|
||||
|
||||
+7
@@ -57,6 +57,13 @@ class SplFileInfo extends \SplFileInfo
|
||||
return $this->relativePathname;
|
||||
}
|
||||
|
||||
public function getFilenameWithoutExtension(): string
|
||||
{
|
||||
$filename = $this->getFilename();
|
||||
|
||||
return \pathinfo($filename, PATHINFO_FILENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the contents of the file.
|
||||
*
|
||||
|
||||
+77
-2
@@ -347,6 +347,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder = $this->buildFinder();
|
||||
$this->assertSame($finder, $finder->ignoreVCS(false)->ignoreDotFiles(false));
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
@@ -373,6 +374,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder = $this->buildFinder();
|
||||
$finder->ignoreVCS(false)->ignoreVCS(false)->ignoreDotFiles(false);
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
@@ -399,6 +401,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder = $this->buildFinder();
|
||||
$this->assertSame($finder, $finder->ignoreVCS(true)->ignoreDotFiles(false));
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
'test.php',
|
||||
@@ -421,6 +424,28 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
]), $finder->in(self::$tmpDir)->getIterator());
|
||||
}
|
||||
|
||||
public function testIgnoreVCSIgnored()
|
||||
{
|
||||
$finder = $this->buildFinder();
|
||||
$this->assertSame(
|
||||
$finder,
|
||||
$finder
|
||||
->ignoreVCS(true)
|
||||
->ignoreDotFiles(true)
|
||||
->ignoreVCSIgnored(true)
|
||||
);
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
'test.py',
|
||||
'toto',
|
||||
'foo bar',
|
||||
'qux',
|
||||
'qux/baz_100_1.py',
|
||||
'qux/baz_1_2.py',
|
||||
]), $finder->in(self::$tmpDir)->getIterator());
|
||||
}
|
||||
|
||||
public function testIgnoreVCSCanBeDisabledAfterFirstIteration()
|
||||
{
|
||||
$finder = $this->buildFinder();
|
||||
@@ -428,6 +453,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder->ignoreDotFiles(false);
|
||||
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
'qux',
|
||||
@@ -450,7 +476,9 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
]), $finder->getIterator());
|
||||
|
||||
$finder->ignoreVCS(false);
|
||||
$this->assertIterator($this->toAbsolute(['.git',
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
'qux',
|
||||
@@ -479,6 +507,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder = $this->buildFinder();
|
||||
$this->assertSame($finder, $finder->ignoreDotFiles(false)->ignoreVCS(false));
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'.bar',
|
||||
'.foo',
|
||||
@@ -505,6 +534,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder = $this->buildFinder();
|
||||
$finder->ignoreDotFiles(false)->ignoreDotFiles(false)->ignoreVCS(false);
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'.bar',
|
||||
'.foo',
|
||||
@@ -574,6 +604,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
|
||||
$finder->ignoreDotFiles(false);
|
||||
$this->assertIterator($this->toAbsolute([
|
||||
'.gitignore',
|
||||
'foo',
|
||||
'foo/bar.tmp',
|
||||
'qux',
|
||||
@@ -842,6 +873,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
|
||||
$expected = [
|
||||
self::$tmpDir.\DIRECTORY_SEPARATOR.'test.php',
|
||||
__DIR__.\DIRECTORY_SEPARATOR.'GitignoreTest.php',
|
||||
__DIR__.\DIRECTORY_SEPARATOR.'FinderTest.php',
|
||||
__DIR__.\DIRECTORY_SEPARATOR.'GlobTest.php',
|
||||
self::$tmpDir.\DIRECTORY_SEPARATOR.'qux_0_1.php',
|
||||
@@ -856,7 +888,7 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \InvalidArgumentException
|
||||
* @expectedException \Symfony\Component\Finder\Exception\DirectoryNotFoundException
|
||||
*/
|
||||
public function testInWithNonExistentDirectory()
|
||||
{
|
||||
@@ -864,6 +896,15 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$finder->in('foobar');
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \InvalidArgumentException
|
||||
*/
|
||||
public function testInWithNonExistentDirectoryLegacyException()
|
||||
{
|
||||
$finder = new Finder();
|
||||
$finder->in('foobar');
|
||||
}
|
||||
|
||||
public function testInWithGlob()
|
||||
{
|
||||
$finder = $this->buildFinder();
|
||||
@@ -979,6 +1020,40 @@ class FinderTest extends Iterator\RealIteratorTestCase
|
||||
$this->assertEquals($ref, $paths);
|
||||
}
|
||||
|
||||
public function testGetFilenameWithoutExtension()
|
||||
{
|
||||
$finder = $this->buildFinder()->in(self::$tmpDir)->sortByName();
|
||||
|
||||
$fileNames = [];
|
||||
|
||||
foreach ($finder as $file) {
|
||||
$fileNames[] = $file->getFilenameWithoutExtension();
|
||||
}
|
||||
|
||||
$ref = [
|
||||
'test',
|
||||
'toto',
|
||||
'test',
|
||||
'foo',
|
||||
'bar',
|
||||
'foo bar',
|
||||
'qux',
|
||||
'baz_100_1',
|
||||
'baz_1_2',
|
||||
'qux_0_1',
|
||||
'qux_1000_1',
|
||||
'qux_1002_0',
|
||||
'qux_10_2',
|
||||
'qux_12_0',
|
||||
'qux_2_0',
|
||||
];
|
||||
|
||||
sort($fileNames);
|
||||
sort($ref);
|
||||
|
||||
$this->assertEquals($ref, $fileNames);
|
||||
}
|
||||
|
||||
public function testAppendWithAFinder()
|
||||
{
|
||||
$finder = $this->buildFinder();
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Finder\Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Finder\Gitignore;
|
||||
|
||||
class GitignoreTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @dataProvider provider
|
||||
*
|
||||
* @param string $patterns
|
||||
* @param array $matchingCases
|
||||
* @param array $nonMatchingCases
|
||||
*/
|
||||
public function testCases(string $patterns, array $matchingCases, array $nonMatchingCases)
|
||||
{
|
||||
$regex = Gitignore::toRegex($patterns);
|
||||
|
||||
foreach ($matchingCases as $matchingCase) {
|
||||
$this->assertRegExp($regex, $matchingCase, sprintf('Failed asserting path [%s] matches gitignore patterns [%s] using regex [%s]', $matchingCase, $patterns, $regex));
|
||||
}
|
||||
|
||||
foreach ($nonMatchingCases as $nonMatchingCase) {
|
||||
$this->assertNotRegExp($regex, $nonMatchingCase, sprintf('Failed asserting path [%s] not matching gitignore patterns [%s] using regex [%s]', $nonMatchingCase, $patterns, $regex));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array return is array of
|
||||
* [
|
||||
* [
|
||||
* '', // Git-ignore Pattern
|
||||
* [], // array of file paths matching
|
||||
* [], // array of file paths not matching
|
||||
* ],
|
||||
* ]
|
||||
*/
|
||||
public function provider()
|
||||
{
|
||||
return [
|
||||
[
|
||||
'
|
||||
*
|
||||
!/bin/bash
|
||||
',
|
||||
['bin/cat', 'abc/bin/cat'],
|
||||
['bin/bash'],
|
||||
],
|
||||
[
|
||||
'fi#le.txt',
|
||||
[],
|
||||
['#file.txt'],
|
||||
],
|
||||
[
|
||||
'
|
||||
/bin/
|
||||
/usr/local/
|
||||
!/bin/bash
|
||||
!/usr/local/bin/bash
|
||||
',
|
||||
['bin/cat'],
|
||||
['bin/bash'],
|
||||
],
|
||||
[
|
||||
'*.py[co]',
|
||||
['file.pyc', 'file.pyc'],
|
||||
['filexpyc', 'file.pycx', 'file.py'],
|
||||
],
|
||||
[
|
||||
'dir1/**/dir2/',
|
||||
['dir1/dirA/dir2/', 'dir1/dirA/dirB/dir2/'],
|
||||
[],
|
||||
],
|
||||
[
|
||||
'dir1/*/dir2/',
|
||||
['dir1/dirA/dir2/'],
|
||||
['dir1/dirA/dirB/dir2/'],
|
||||
],
|
||||
[
|
||||
'/*.php',
|
||||
['file.php'],
|
||||
['app/file.php'],
|
||||
],
|
||||
[
|
||||
'\#file.txt',
|
||||
['#file.txt'],
|
||||
[],
|
||||
],
|
||||
[
|
||||
'*.php',
|
||||
['app/file.php', 'file.php'],
|
||||
['file.phps', 'file.phps', 'filephps'],
|
||||
],
|
||||
[
|
||||
'app/cache/',
|
||||
['app/cache/file.txt', 'app/cache/dir1/dir2/file.txt', 'a/app/cache/file.txt'],
|
||||
[],
|
||||
],
|
||||
[
|
||||
'
|
||||
#IamComment
|
||||
/app/cache/',
|
||||
['app/cache/file.txt', 'app/cache/subdir/ile.txt'],
|
||||
['a/app/cache/file.txt'],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ class DepthRangeFilterIteratorTest extends RealIteratorTestCase
|
||||
public function getAcceptData()
|
||||
{
|
||||
$lessThan1 = [
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'test.py',
|
||||
'foo',
|
||||
@@ -51,6 +52,7 @@ class DepthRangeFilterIteratorTest extends RealIteratorTestCase
|
||||
];
|
||||
|
||||
$lessThanOrEqualTo1 = [
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'test.py',
|
||||
'foo',
|
||||
|
||||
@@ -31,6 +31,7 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase
|
||||
public function getAcceptData()
|
||||
{
|
||||
$foo = [
|
||||
'.gitignore',
|
||||
'.bar',
|
||||
'.foo',
|
||||
'.foo/.bar',
|
||||
@@ -53,6 +54,7 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase
|
||||
];
|
||||
|
||||
$fo = [
|
||||
'.gitignore',
|
||||
'.bar',
|
||||
'.foo',
|
||||
'.foo/.bar',
|
||||
@@ -77,6 +79,7 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase
|
||||
];
|
||||
|
||||
$toto = [
|
||||
'.gitignore',
|
||||
'.bar',
|
||||
'.foo',
|
||||
'.foo/.bar',
|
||||
|
||||
@@ -63,6 +63,8 @@ abstract class RealIteratorTestCase extends IteratorTestCase
|
||||
file_put_contents(self::toAbsolute('test.php'), str_repeat(' ', 800));
|
||||
file_put_contents(self::toAbsolute('test.py'), str_repeat(' ', 2000));
|
||||
|
||||
file_put_contents(self::toAbsolute('.gitignore'), '*.php');
|
||||
|
||||
touch(self::toAbsolute('foo/bar.tmp'), strtotime('2005-10-15'));
|
||||
touch(self::toAbsolute('test.php'), strtotime('2005-10-15'));
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -27,7 +27,7 @@
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.2-dev"
|
||||
"dev-master": "4.3-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user