Folded all curly brackets of control structures to conform to PEAR/ZF CS

This commit is contained in:
Jordi Boggiano 2010-05-07 16:09:11 +02:00 committed by Fabien Potencier
parent e79976817d
commit 2684de0d8e
223 changed files with 1916 additions and 4272 deletions

View File

@ -75,8 +75,7 @@ abstract class Client
*/ */
public function insulate($insulated = true) public function insulate($insulated = true)
{ {
if (!class_exists('Symfony\\Components\\Process\\Process')) if (!class_exists('Symfony\\Components\\Process\\Process')) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.'); throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.');
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -189,8 +188,7 @@ abstract class Client
$uri = $this->getAbsoluteUri($uri); $uri = $this->getAbsoluteUri($uri);
$server = array_merge($this->server, $server); $server = array_merge($this->server, $server);
if (!$this->history->isEmpty()) if (!$this->history->isEmpty()) {
{
$server['HTTP_REFERER'] = $this->history->current()->getUri(); $server['HTTP_REFERER'] = $this->history->current()->getUri();
} }
$server['HTTP_HOST'] = parse_url($uri, PHP_URL_HOST); $server['HTTP_HOST'] = parse_url($uri, PHP_URL_HOST);
@ -200,17 +198,13 @@ abstract class Client
$this->request = $this->filterRequest($request); $this->request = $this->filterRequest($request);
if (true === $changeHistory) if (true === $changeHistory) {
{
$this->history->add($request); $this->history->add($request);
} }
if ($this->insulated) if ($this->insulated) {
{
$this->response = $this->doRequestInProcess($this->request); $this->response = $this->doRequestInProcess($this->request);
} } else {
else
{
$this->response = $this->doRequest($this->request); $this->response = $this->doRequest($this->request);
} }
@ -220,8 +214,7 @@ abstract class Client
$this->redirect = $response->getHeader('Location'); $this->redirect = $response->getHeader('Location');
if ($this->followRedirects && $this->redirect) if ($this->followRedirects && $this->redirect) {
{
return $this->crawler = $this->followRedirect(); return $this->crawler = $this->followRedirect();
} }
@ -242,8 +235,7 @@ abstract class Client
$process = new PhpProcess($this->getScript($request)); $process = new PhpProcess($this->getScript($request));
$process->run(); $process->run();
if ($process->getExitCode() > 0) if ($process->getExitCode() > 0) {
{
throw new \RuntimeException($process->getErrorOutput()); throw new \RuntimeException($process->getErrorOutput());
} }
@ -324,8 +316,7 @@ abstract class Client
*/ */
public function followRedirect() public function followRedirect()
{ {
if (empty($this->redirect)) if (empty($this->redirect)) {
{
throw new \LogicException('The request was not redirected.'); throw new \LogicException('The request was not redirected.');
} }
@ -346,17 +337,13 @@ abstract class Client
protected function getAbsoluteUri($uri) protected function getAbsoluteUri($uri)
{ {
// already absolute? // already absolute?
if ('http' === substr($uri, 0, 4)) if ('http' === substr($uri, 0, 4)) {
{
return $uri; return $uri;
} }
if (!$this->history->isEmpty()) if (!$this->history->isEmpty()) {
{
$currentUri = $this->history->current()->getUri(); $currentUri = $this->history->current()->getUri();
} } else {
else
{
$currentUri = sprintf('http%s://%s/', $currentUri = sprintf('http%s://%s/',
isset($this->server['HTTPS']) ? 's' : '', isset($this->server['HTTPS']) ? 's' : '',
isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost' isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
@ -364,17 +351,14 @@ abstract class Client
} }
// anchor? // anchor?
if (!$uri || '#' == $uri[0]) if (!$uri || '#' == $uri[0]) {
{
return preg_replace('/#.*?$/', '', $currentUri).$uri; return preg_replace('/#.*?$/', '', $currentUri).$uri;
} }
if ('/' !== $uri[0]) if ('/' !== $uri[0]) {
{
$path = parse_url($currentUri, PHP_URL_PATH); $path = parse_url($currentUri, PHP_URL_PATH);
if ('/' !== substr($path, -1)) if ('/' !== substr($path, -1)) {
{
$path = substr($path, 0, strrpos($path, '/') + 1); $path = substr($path, 0, strrpos($path, '/') + 1);
} }

View File

@ -71,8 +71,7 @@ class CookieJar
*/ */
public function updateFromResponse(Response $response) public function updateFromResponse(Response $response)
{ {
foreach ($response->getCookies() as $name => $cookie) foreach ($response->getCookies() as $name => $cookie) {
{
$this->set(new Cookie( $this->set(new Cookie(
$name, $name,
isset($cookie['value']) ? $cookie['value'] : '', isset($cookie['value']) ? $cookie['value'] : '',
@ -110,20 +109,17 @@ class CookieJar
$parts = parse_url($uri); $parts = parse_url($uri);
$cookies = array(); $cookies = array();
foreach ($this->cookieJar as $cookie) foreach ($this->cookieJar as $cookie) {
{
if ($cookie->getDomain() && $cookie->getDomain() != substr($parts['host'], -strlen($cookie->getDomain()))) if ($cookie->getDomain() && $cookie->getDomain() != substr($parts['host'], -strlen($cookie->getDomain())))
{ {
continue; continue;
} }
if ($cookie->getPath() != substr($parts['path'], 0, strlen($cookie->getPath()))) if ($cookie->getPath() != substr($parts['path'], 0, strlen($cookie->getPath()))) {
{
continue; continue;
} }
if ($cookie->isSecure() && 'https' != $parts['scheme']) if ($cookie->isSecure() && 'https' != $parts['scheme']) {
{
continue; continue;
} }
@ -139,8 +135,7 @@ class CookieJar
public function flushExpiredCookies() public function flushExpiredCookies()
{ {
$cookies = $this->cookieJar; $cookies = $this->cookieJar;
foreach ($cookies as $name => $cookie) foreach ($cookies as $name => $cookie) {
{
if ($cookie->isExpired()) if ($cookie->isExpired())
{ {
unset($this->cookieJar[$name]); unset($this->cookieJar[$name]);

View File

@ -71,8 +71,7 @@ class History
*/ */
public function back() public function back()
{ {
if ($this->position < 1) if ($this->position < 1) {
{
throw new \LogicException('You are already on the first page.'); throw new \LogicException('You are already on the first page.');
} }
@ -88,8 +87,7 @@ class History
*/ */
public function forward() public function forward()
{ {
if ($this->position > count($this->stack) - 2) if ($this->position > count($this->stack) - 2) {
{
throw new \LogicException('You are already on the last page.'); throw new \LogicException('You are already on the last page.');
} }
@ -105,8 +103,7 @@ class History
*/ */
public function current() public function current()
{ {
if (-1 == $this->position) if (-1 == $this->position) {
{
throw new \LogicException('The page history is empty.'); throw new \LogicException('The page history is empty.');
} }

View File

@ -44,12 +44,10 @@ class Response
public function __toString() public function __toString()
{ {
$headers = ''; $headers = '';
foreach ($this->headers as $name => $value) foreach ($this->headers as $name => $value) {
{
$headers .= sprintf("%s: %s\n", $name, $value); $headers .= sprintf("%s: %s\n", $name, $value);
} }
foreach ($this->cookies as $name => $cookie) foreach ($this->cookies as $name => $cookie) {
{
$headers .= sprintf("Set-Cookie: %s=%s\n", $name, $cookie['value']); $headers .= sprintf("Set-Cookie: %s=%s\n", $name, $cookie['value']);
} }
@ -95,8 +93,7 @@ class Response
*/ */
public function getHeader($header) public function getHeader($header)
{ {
foreach ($this->headers as $key => $value) foreach ($this->headers as $key => $value) {
{
if (str_replace('-', '_', strtolower($key)) == str_replace('-', '_', strtolower($header))) if (str_replace('-', '_', strtolower($key)) == str_replace('-', '_', strtolower($header)))
{ {
return $value; return $value;

View File

@ -104,22 +104,17 @@ class Application
*/ */
public function run(InputInterface $input = null, OutputInterface $output = null) public function run(InputInterface $input = null, OutputInterface $output = null)
{ {
if (null === $input) if (null === $input) {
{
$input = new ArgvInput(); $input = new ArgvInput();
} }
if (null === $output) if (null === $output) {
{
$output = new ConsoleOutput(); $output = new ConsoleOutput();
} }
try try {
{
$statusCode = $this->doRun($input, $output); $statusCode = $this->doRun($input, $output);
} } catch (\Exception $e) {
catch (\Exception $e)
{
if (!$this->catchExceptions) if (!$this->catchExceptions)
{ {
throw $e; throw $e;
@ -131,14 +126,11 @@ class Application
$statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1; $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
} }
if ($this->autoExit) if ($this->autoExit) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
exit($statusCode); exit($statusCode);
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} } else {
else
{
return $statusCode; return $statusCode;
} }
} }
@ -155,47 +147,37 @@ class Application
{ {
$name = $input->getFirstArgument('command'); $name = $input->getFirstArgument('command');
if (true === $input->hasParameterOption(array('--color', '-c'))) if (true === $input->hasParameterOption(array('--color', '-c'))) {
{
$output->setDecorated(true); $output->setDecorated(true);
} }
if (true === $input->hasParameterOption(array('--help', '-H'))) if (true === $input->hasParameterOption(array('--help', '-H'))) {
{
if (!$name) if (!$name)
{ {
$name = 'help'; $name = 'help';
$input = new ArrayInput(array('command' => 'help')); $input = new ArrayInput(array('command' => 'help'));
} } else {
else
{
$this->wantHelps = true; $this->wantHelps = true;
} }
} }
if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
{
$input->setInteractive(false); $input->setInteractive(false);
} }
if (true === $input->hasParameterOption(array('--quiet', '-q'))) if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
{
$output->setVerbosity(Output::VERBOSITY_QUIET); $output->setVerbosity(Output::VERBOSITY_QUIET);
} } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
elseif (true === $input->hasParameterOption(array('--verbose', '-v')))
{
$output->setVerbosity(Output::VERBOSITY_VERBOSE); $output->setVerbosity(Output::VERBOSITY_VERBOSE);
} }
if (true === $input->hasParameterOption(array('--version', '-V'))) if (true === $input->hasParameterOption(array('--version', '-V'))) {
{
$output->writeln($this->getLongVersion()); $output->writeln($this->getLongVersion());
return 0; return 0;
} }
if (!$name) if (!$name) {
{
$name = 'list'; $name = 'list';
$input = new ArrayInput(array('command' => 'list')); $input = new ArrayInput(array('command' => 'list'));
} }
@ -255,8 +237,7 @@ class Application
'<comment>Options:</comment>', '<comment>Options:</comment>',
); );
foreach ($this->definition->getOptions() as $option) foreach ($this->definition->getOptions() as $option) {
{
$messages[] = sprintf(' %-29s %s %s', $messages[] = sprintf(' %-29s %s %s',
'<info>--'.$option->getName().'</info>', '<info>--'.$option->getName().'</info>',
$option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ', $option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
@ -334,12 +315,9 @@ class Application
*/ */
public function getLongVersion() public function getLongVersion()
{ {
if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
{
return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion()); return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
} } else {
else
{
return '<info>Console Tool</info>'; return '<info>Console Tool</info>';
} }
} }
@ -363,8 +341,7 @@ class Application
*/ */
public function addCommands(array $commands) public function addCommands(array $commands)
{ {
foreach ($commands as $command) foreach ($commands as $command) {
{
$this->addCommand($command); $this->addCommand($command);
} }
} }
@ -384,8 +361,7 @@ class Application
$this->commands[$command->getFullName()] = $command; $this->commands[$command->getFullName()] = $command;
foreach ($command->getAliases() as $alias) foreach ($command->getAliases() as $alias) {
{
$this->aliases[$alias] = $command; $this->aliases[$alias] = $command;
} }
@ -403,15 +379,13 @@ class Application
*/ */
public function getCommand($name) public function getCommand($name)
{ {
if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
{
throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
} }
$command = isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name]; $command = isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
if ($this->wantHelps) if ($this->wantHelps) {
{
$this->wantHelps = false; $this->wantHelps = false;
$helpCommand = $this->getCommand('help'); $helpCommand = $this->getCommand('help');
@ -445,8 +419,7 @@ class Application
public function getNamespaces() public function getNamespaces()
{ {
$namespaces = array(); $namespaces = array();
foreach ($this->commands as $command) foreach ($this->commands as $command) {
{
if ($command->getNamespace()) if ($command->getNamespace())
{ {
$namespaces[$command->getNamespace()] = true; $namespaces[$command->getNamespace()] = true;
@ -467,13 +440,11 @@ class Application
{ {
$abbrevs = static::getAbbreviations($this->getNamespaces()); $abbrevs = static::getAbbreviations($this->getNamespaces());
if (!isset($abbrevs[$namespace])) if (!isset($abbrevs[$namespace])) {
{
throw new \InvalidArgumentException(sprintf('There are no commands defined in the "%s" namespace.', $namespace)); throw new \InvalidArgumentException(sprintf('There are no commands defined in the "%s" namespace.', $namespace));
} }
if (count($abbrevs[$namespace]) > 1) if (count($abbrevs[$namespace]) > 1) {
{
throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$namespace]))); throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$namespace])));
} }
@ -496,8 +467,7 @@ class Application
{ {
// namespace // namespace
$namespace = ''; $namespace = '';
if (false !== $pos = strrpos($name, ':')) if (false !== $pos = strrpos($name, ':')) {
{
$namespace = $this->findNamespace(substr($name, 0, $pos)); $namespace = $this->findNamespace(substr($name, 0, $pos));
$name = substr($name, $pos + 1); $name = substr($name, $pos + 1);
} }
@ -506,8 +476,7 @@ class Application
// name // name
$commands = array(); $commands = array();
foreach ($this->commands as $command) foreach ($this->commands as $command) {
{
if ($command->getNamespace() == $namespace) if ($command->getNamespace() == $namespace)
{ {
$commands[] = $command->getName(); $commands[] = $command->getName();
@ -515,13 +484,11 @@ class Application
} }
$abbrevs = static::getAbbreviations($commands); $abbrevs = static::getAbbreviations($commands);
if (isset($abbrevs[$name]) && 1 == count($abbrevs[$name])) if (isset($abbrevs[$name]) && 1 == count($abbrevs[$name])) {
{
return $this->getCommand($namespace ? $namespace.':'.$abbrevs[$name][0] : $abbrevs[$name][0]); return $this->getCommand($namespace ? $namespace.':'.$abbrevs[$name][0] : $abbrevs[$name][0]);
} }
if (isset($abbrevs[$name]) && count($abbrevs[$name]) > 1) if (isset($abbrevs[$name]) && count($abbrevs[$name]) > 1) {
{
$suggestions = $this->getAbbreviationSuggestions(array_map(function ($command) use ($namespace) { return $namespace.':'.$command; }, $abbrevs[$name])); $suggestions = $this->getAbbreviationSuggestions(array_map(function ($command) use ($namespace) { return $namespace.':'.$command; }, $abbrevs[$name]));
throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $suggestions)); throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $suggestions));
@ -529,13 +496,11 @@ class Application
// aliases // aliases
$abbrevs = static::getAbbreviations(array_keys($this->aliases)); $abbrevs = static::getAbbreviations(array_keys($this->aliases));
if (!isset($abbrevs[$fullName])) if (!isset($abbrevs[$fullName])) {
{
throw new \InvalidArgumentException(sprintf('Command "%s" is not defined.', $fullName)); throw new \InvalidArgumentException(sprintf('Command "%s" is not defined.', $fullName));
} }
if (count($abbrevs[$fullName]) > 1) if (count($abbrevs[$fullName]) > 1) {
{
throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $this->getAbbreviationSuggestions($abbrevs[$fullName]))); throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $this->getAbbreviationSuggestions($abbrevs[$fullName])));
} }
@ -553,14 +518,12 @@ class Application
*/ */
public function getCommands($namespace = null) public function getCommands($namespace = null)
{ {
if (null === $namespace) if (null === $namespace) {
{
return $this->commands; return $this->commands;
} }
$commands = array(); $commands = array();
foreach ($this->commands as $name => $command) foreach ($this->commands as $name => $command) {
{
if ($namespace === $command->getNamespace()) if ($namespace === $command->getNamespace())
{ {
$commands[$name] = $command; $commands[$name] = $command;
@ -580,25 +543,20 @@ class Application
static public function getAbbreviations($names) static public function getAbbreviations($names)
{ {
$abbrevs = array(); $abbrevs = array();
foreach ($names as $name) foreach ($names as $name) {
{
for ($len = strlen($name) - 1; $len > 0; --$len) for ($len = strlen($name) - 1; $len > 0; --$len)
{ {
$abbrev = substr($name, 0, $len); $abbrev = substr($name, 0, $len);
if (!isset($abbrevs[$abbrev])) if (!isset($abbrevs[$abbrev])) {
{
$abbrevs[$abbrev] = array($name); $abbrevs[$abbrev] = array($name);
} } else {
else
{
$abbrevs[$abbrev][] = $name; $abbrevs[$abbrev][] = $name;
} }
} }
} }
// Non-abbreviations always get entered, even if they aren't unique // Non-abbreviations always get entered, even if they aren't unique
foreach ($names as $name) foreach ($names as $name) {
{
$abbrevs[$name] = array($name); $abbrevs[$name] = array($name);
} }
@ -617,32 +575,26 @@ class Application
$commands = $namespace ? $this->getCommands($this->findNamespace($namespace)) : $this->commands; $commands = $namespace ? $this->getCommands($this->findNamespace($namespace)) : $this->commands;
$messages = array($this->getHelp(), ''); $messages = array($this->getHelp(), '');
if ($namespace) if ($namespace) {
{
$messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace); $messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace);
} } else {
else
{
$messages[] = '<comment>Available commands:</comment>'; $messages[] = '<comment>Available commands:</comment>';
} }
$width = 0; $width = 0;
foreach ($commands as $command) foreach ($commands as $command) {
{
$width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width; $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
} }
$width += 2; $width += 2;
// add commands by namespace // add commands by namespace
foreach ($this->sortCommands($commands) as $space => $commands) foreach ($this->sortCommands($commands) as $space => $commands) {
{
if (!$namespace && '_global' !== $space) if (!$namespace && '_global' !== $space)
{ {
$messages[] = '<comment>'.$space.'</comment>'; $messages[] = '<comment>'.$space.'</comment>';
} }
foreach ($commands as $command) foreach ($commands as $command) {
{
$aliases = $command->getAliases() ? '<comment> ('.implode(', ', $command->getAliases()).')</comment>' : ''; $aliases = $command->getAliases() ? '<comment> ('.implode(', ', $command->getAliases()).')</comment>' : '';
$messages[] = sprintf(" <info>%-${width}s</info> %s%s", ($command->getNamespace() ? ':' : '').$command->getName(), $command->getDescription(), $aliases); $messages[] = sprintf(" <info>%-${width}s</info> %s%s", ($command->getNamespace() ? ':' : '').$command->getName(), $command->getDescription(), $aliases);
@ -670,26 +622,21 @@ class Application
$xml->appendChild($commandsXML = $dom->createElement('commands')); $xml->appendChild($commandsXML = $dom->createElement('commands'));
if ($namespace) if ($namespace) {
{
$commandsXML->setAttribute('namespace', $namespace); $commandsXML->setAttribute('namespace', $namespace);
} } else {
else
{
$xml->appendChild($namespacesXML = $dom->createElement('namespaces')); $xml->appendChild($namespacesXML = $dom->createElement('namespaces'));
} }
// add commands by namespace // add commands by namespace
foreach ($this->sortCommands($commands) as $space => $commands) foreach ($this->sortCommands($commands) as $space => $commands) {
{
if (!$namespace) if (!$namespace)
{ {
$namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace')); $namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace'));
$namespaceArrayXML->setAttribute('id', $space); $namespaceArrayXML->setAttribute('id', $space);
} }
foreach ($commands as $command) foreach ($commands as $command) {
{
if (!$namespace) if (!$namespace)
{ {
$namespaceArrayXML->appendChild($commandXML = $dom->createElement('command')); $namespaceArrayXML->appendChild($commandXML = $dom->createElement('command'));
@ -725,36 +672,31 @@ class Application
$title = sprintf(' [%s] ', get_class($e)); $title = sprintf(' [%s] ', get_class($e));
$len = $strlen($title); $len = $strlen($title);
$lines = array(); $lines = array();
foreach (explode("\n", $e->getMessage()) as $line) foreach (explode("\n", $e->getMessage()) as $line) {
{
$lines[] = sprintf(' %s ', $line); $lines[] = sprintf(' %s ', $line);
$len = max($strlen($line) + 4, $len); $len = max($strlen($line) + 4, $len);
} }
$messages = array(str_repeat(' ', $len), $title.str_repeat(' ', $len - $strlen($title))); $messages = array(str_repeat(' ', $len), $title.str_repeat(' ', $len - $strlen($title)));
foreach ($lines as $line) foreach ($lines as $line) {
{
$messages[] = $line.str_repeat(' ', $len - $strlen($line)); $messages[] = $line.str_repeat(' ', $len - $strlen($line));
} }
$messages[] = str_repeat(' ', $len); $messages[] = str_repeat(' ', $len);
$output->writeln("\n"); $output->writeln("\n");
foreach ($messages as $message) foreach ($messages as $message) {
{
$output->writeln('<error>'.$message.'</error>'); $output->writeln('<error>'.$message.'</error>');
} }
$output->writeln("\n"); $output->writeln("\n");
if (null !== $this->runningCommand) if (null !== $this->runningCommand) {
{
$output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName()))); $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
$output->writeln("\n"); $output->writeln("\n");
} }
if (Output::VERBOSITY_VERBOSE === $output->getVerbosity()) if (Output::VERBOSITY_VERBOSE === $output->getVerbosity()) {
{
$output->writeln('</comment>Exception trace:</comment>'); $output->writeln('</comment>Exception trace:</comment>');
// exception related properties // exception related properties
@ -766,8 +708,7 @@ class Application
'args' => array(), 'args' => array(),
)); ));
for ($i = 0, $count = count($trace); $i < $count; $i++) for ($i = 0, $count = count($trace); $i < $count; $i++) {
{
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : ''; $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : ''; $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function']; $function = $trace[$i]['function'];
@ -784,12 +725,10 @@ class Application
private function sortCommands($commands) private function sortCommands($commands)
{ {
$namespacedCommands = array(); $namespacedCommands = array();
foreach ($commands as $name => $command) foreach ($commands as $name => $command) {
{
$key = $command->getNamespace() ? $command->getNamespace() : '_global'; $key = $command->getNamespace() ? $command->getNamespace() : '_global';
if (!isset($namespacedCommands[$key])) if (!isset($namespacedCommands[$key])) {
{
$namespacedCommands[$key] = array(); $namespacedCommands[$key] = array();
} }
@ -797,8 +736,7 @@ class Application
} }
ksort($namespacedCommands); ksort($namespacedCommands);
foreach ($namespacedCommands as $name => &$commands) foreach ($namespacedCommands as $name => &$commands) {
{
ksort($commands); ksort($commands);
} }

View File

@ -53,15 +53,13 @@ class Command
$this->applicationDefinitionMerged = false; $this->applicationDefinitionMerged = false;
$this->aliases = array(); $this->aliases = array();
if (null !== $name) if (null !== $name) {
{
$this->setName($name); $this->setName($name);
} }
$this->configure(); $this->configure();
if (!$this->name) if (!$this->name) {
{
throw new \LogicException('The command name cannot be empty.'); throw new \LogicException('The command name cannot be empty.');
} }
} }
@ -133,12 +131,9 @@ class Command
$this->mergeApplicationDefinition(); $this->mergeApplicationDefinition();
// bind the input against the command specific arguments/options // bind the input against the command specific arguments/options
try try {
{
$input->bind($this->definition); $input->bind($this->definition);
} } catch (\Exception $e) {
catch (\Exception $e)
{
if (!$this->ignoreValidationErrors) if (!$this->ignoreValidationErrors)
{ {
throw $e; throw $e;
@ -147,19 +142,15 @@ class Command
$this->initialize($input, $output); $this->initialize($input, $output);
if ($input->isInteractive()) if ($input->isInteractive()) {
{
$this->interact($input, $output); $this->interact($input, $output);
} }
$input->validate(); $input->validate();
if ($this->code) if ($this->code) {
{
return call_user_func($this->code, $input, $output); return call_user_func($this->code, $input, $output);
} } else {
else
{
return $this->execute($input, $output); return $this->execute($input, $output);
} }
} }
@ -183,8 +174,7 @@ class Command
*/ */
protected function mergeApplicationDefinition() protected function mergeApplicationDefinition()
{ {
if (null === $this->application || true === $this->applicationDefinitionMerged) if (null === $this->application || true === $this->applicationDefinitionMerged) {
{
return; return;
} }
@ -207,12 +197,9 @@ class Command
*/ */
public function setDefinition($definition) public function setDefinition($definition)
{ {
if ($definition instanceof InputDefinition) if ($definition instanceof InputDefinition) {
{
$this->definition = $definition; $this->definition = $definition;
} } else {
else
{
$this->definition->setDefinition($definition); $this->definition->setDefinition($definition);
} }
@ -282,18 +269,14 @@ class Command
*/ */
public function setName($name) public function setName($name)
{ {
if (false !== $pos = strrpos($name, ':')) if (false !== $pos = strrpos($name, ':')) {
{
$namespace = substr($name, 0, $pos); $namespace = substr($name, 0, $pos);
$name = substr($name, $pos + 1); $name = substr($name, $pos + 1);
} } else {
else
{
$namespace = $this->namespace; $namespace = $this->namespace;
} }
if (!$name) if (!$name) {
{
throw new \InvalidArgumentException('A command name cannot be empty.'); throw new \InvalidArgumentException('A command name cannot be empty.');
} }
@ -478,15 +461,13 @@ class Command
'', '',
); );
if ($this->getAliases()) if ($this->getAliases()) {
{
$messages[] = '<comment>Aliases:</comment> <info>'.implode(', ', $this->getAliases()).'</info>'; $messages[] = '<comment>Aliases:</comment> <info>'.implode(', ', $this->getAliases()).'</info>';
} }
$messages[] = $this->definition->asText(); $messages[] = $this->definition->asText();
if ($help = $this->getProcessedHelp()) if ($help = $this->getProcessedHelp()) {
{
$messages[] = '<comment>Help:</comment>'; $messages[] = '<comment>Help:</comment>';
$messages[] = ' '.implode("\n ", explode("\n", $help))."\n"; $messages[] = ' '.implode("\n ", explode("\n", $help))."\n";
} }
@ -521,8 +502,7 @@ class Command
$helpXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $help)))); $helpXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $help))));
$commandXML->appendChild($aliasesXML = $dom->createElement('aliases')); $commandXML->appendChild($aliasesXML = $dom->createElement('aliases'));
foreach ($this->getAliases() as $alias) foreach ($this->getAliases() as $alias) {
{
$aliasesXML->appendChild($aliasXML = $dom->createElement('alias')); $aliasesXML->appendChild($aliasXML = $dom->createElement('alias'));
$aliasXML->appendChild($dom->createTextNode($alias)); $aliasXML->appendChild($dom->createTextNode($alias));
} }

View File

@ -66,17 +66,13 @@ EOF
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
if (null === $this->command) if (null === $this->command) {
{
$this->command = $this->application->getCommand($input->getArgument('command_name')); $this->command = $this->application->getCommand($input->getArgument('command_name'));
} }
if ($input->getOption('xml')) if ($input->getOption('xml')) {
{
$output->writeln($this->command->asXml(), Output::OUTPUT_RAW); $output->writeln($this->command->asXml(), Output::OUTPUT_RAW);
} } else {
else
{
$output->writeln($this->command->asText()); $output->writeln($this->command->asText());
} }
} }

View File

@ -60,12 +60,9 @@ EOF
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
if ($input->getOption('xml')) if ($input->getOption('xml')) {
{
$output->writeln($this->application->asXml($input->getArgument('namespace')), Output::OUTPUT_RAW); $output->writeln($this->application->asXml($input->getArgument('namespace')), Output::OUTPUT_RAW);
} } else {
else
{
$output->writeln($this->application->asText($input->getArgument('namespace'))); $output->writeln($this->application->asText($input->getArgument('namespace')));
} }
} }

View File

@ -57,17 +57,13 @@ class DialogHelper extends Helper
{ {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$answer = 'z'; $answer = 'z';
while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
{
$answer = $this->ask($output, $question); $answer = $this->ask($output, $question);
} }
if (false === $default) if (false === $default) {
{
return $answer && 'y' == strtolower($answer[0]); return $answer && 'y' == strtolower($answer[0]);
} } else {
else
{
return !$answer || 'y' == strtolower($answer[0]); return !$answer || 'y' == strtolower($answer[0]);
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -89,8 +85,7 @@ class DialogHelper extends Helper
{ {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$error = null; $error = null;
while (false === $attempts || $attempts--) while (false === $attempts || $attempts--) {
{
if (null !== $error) if (null !== $error)
{ {
$output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error')); $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'));
@ -98,12 +93,9 @@ class DialogHelper extends Helper
$value = $this->ask($output, $question, null); $value = $this->ask($output, $question, null);
try try {
{
return $validator($value); return $validator($value);
} } catch (\Exception $error) {
catch (\Exception $error)
{
} }
} }

View File

@ -43,31 +43,26 @@ class FormatterHelper extends Helper
*/ */
public function formatBlock($messages, $style, $large = false) public function formatBlock($messages, $style, $large = false)
{ {
if (!is_array($messages)) if (!is_array($messages)) {
{
$messages = array($messages); $messages = array($messages);
} }
$len = 0; $len = 0;
$lines = array(); $lines = array();
foreach ($messages as $message) foreach ($messages as $message) {
{
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message); $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
$len = max($this->strlen($message) + ($large ? 4 : 2), $len); $len = max($this->strlen($message) + ($large ? 4 : 2), $len);
} }
$messages = $large ? array(str_repeat(' ', $len)) : array(); $messages = $large ? array(str_repeat(' ', $len)) : array();
foreach ($lines as $line) foreach ($lines as $line) {
{
$messages[] = $line.str_repeat(' ', $len - $this->strlen($line)); $messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
} }
if ($large) if ($large) {
{
$messages[] = str_repeat(' ', $len); $messages[] = str_repeat(' ', $len);
} }
foreach ($messages as &$message) foreach ($messages as &$message) {
{
$message = sprintf('<%s>%s</%s>', $style, $message, $style); $message = sprintf('<%s>%s</%s>', $style, $message, $style);
} }

View File

@ -31,8 +31,7 @@ class HelperSet
*/ */
public function __construct(array $helpers = array()) public function __construct(array $helpers = array())
{ {
foreach ($helpers as $alias => $helper) foreach ($helpers as $alias => $helper) {
{
$this->set($helper, is_int($alias) ? null : $alias); $this->set($helper, is_int($alias) ? null : $alias);
} }
} }
@ -46,8 +45,7 @@ class HelperSet
public function set(HelperInterface $helper, $alias = null) public function set(HelperInterface $helper, $alias = null)
{ {
$this->helpers[$helper->getName()] = $helper; $this->helpers[$helper->getName()] = $helper;
if (null !== $alias) if (null !== $alias) {
{
$this->helpers[$alias] = $helper; $this->helpers[$alias] = $helper;
} }
@ -77,8 +75,7 @@ class HelperSet
*/ */
public function get($name) public function get($name)
{ {
if (!$this->has($name)) if (!$this->has($name)) {
{
throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name)); throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
} }

View File

@ -51,8 +51,7 @@ class ArgvInput extends Input
*/ */
public function __construct(array $argv = null, InputDefinition $definition = null) public function __construct(array $argv = null, InputDefinition $definition = null)
{ {
if (null === $argv) if (null === $argv) {
{
$argv = $_SERVER['argv']; $argv = $_SERVER['argv'];
} }
@ -70,18 +69,13 @@ class ArgvInput extends Input
protected function parse() protected function parse()
{ {
$this->parsed = $this->tokens; $this->parsed = $this->tokens;
while (null !== $token = array_shift($this->parsed)) while (null !== $token = array_shift($this->parsed)) {
{
if ('--' === substr($token, 0, 2)) if ('--' === substr($token, 0, 2))
{ {
$this->parseLongOption($token); $this->parseLongOption($token);
} } elseif ('-' === $token[0]) {
elseif ('-' === $token[0])
{
$this->parseShortOption($token); $this->parseShortOption($token);
} } else {
else
{
$this->parseArgument($token); $this->parseArgument($token);
} }
} }
@ -96,20 +90,15 @@ class ArgvInput extends Input
{ {
$name = substr($token, 1); $name = substr($token, 1);
if (strlen($name) > 1) if (strlen($name) > 1) {
{
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptParameter()) if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptParameter())
{ {
// an option with a value (with no space) // an option with a value (with no space)
$this->addShortOption($name[0], substr($name, 1)); $this->addShortOption($name[0], substr($name, 1));
} } else {
else
{
$this->parseShortOptionSet($name); $this->parseShortOptionSet($name);
} }
} } else {
else
{
$this->addShortOption($name, null); $this->addShortOption($name, null);
} }
} }
@ -124,22 +113,18 @@ class ArgvInput extends Input
protected function parseShortOptionSet($name) protected function parseShortOptionSet($name)
{ {
$len = strlen($name); $len = strlen($name);
for ($i = 0; $i < $len; $i++) for ($i = 0; $i < $len; $i++) {
{
if (!$this->definition->hasShortcut($name[$i])) if (!$this->definition->hasShortcut($name[$i]))
{ {
throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i])); throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
} }
$option = $this->definition->getOptionForShortcut($name[$i]); $option = $this->definition->getOptionForShortcut($name[$i]);
if ($option->acceptParameter()) if ($option->acceptParameter()) {
{
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1)); $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
break; break;
} } else {
else
{
$this->addLongOption($option->getName(), true); $this->addLongOption($option->getName(), true);
} }
} }
@ -154,12 +139,9 @@ class ArgvInput extends Input
{ {
$name = substr($token, 2); $name = substr($token, 2);
if (false !== $pos = strpos($name, '=')) if (false !== $pos = strpos($name, '=')) {
{
$this->addLongOption(substr($name, 0, $pos), substr($name, $pos + 1)); $this->addLongOption(substr($name, 0, $pos), substr($name, $pos + 1));
} } else {
else
{
$this->addLongOption($name, null); $this->addLongOption($name, null);
} }
} }
@ -173,8 +155,7 @@ class ArgvInput extends Input
*/ */
protected function parseArgument($token) protected function parseArgument($token)
{ {
if (!$this->definition->hasArgument(count($this->arguments))) if (!$this->definition->hasArgument(count($this->arguments))) {
{
throw new \RuntimeException('Too many arguments.'); throw new \RuntimeException('Too many arguments.');
} }
@ -191,8 +172,7 @@ class ArgvInput extends Input
*/ */
protected function addShortOption($shortcut, $value) protected function addShortOption($shortcut, $value)
{ {
if (!$this->definition->hasShortcut($shortcut)) if (!$this->definition->hasShortcut($shortcut)) {
{
throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut)); throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
} }
@ -209,30 +189,24 @@ class ArgvInput extends Input
*/ */
protected function addLongOption($name, $value) protected function addLongOption($name, $value)
{ {
if (!$this->definition->hasOption($name)) if (!$this->definition->hasOption($name)) {
{
throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name)); throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
} }
$option = $this->definition->getOption($name); $option = $this->definition->getOption($name);
if (null === $value && $option->acceptParameter()) if (null === $value && $option->acceptParameter()) {
{
// if option accepts an optional or mandatory argument // if option accepts an optional or mandatory argument
// let's see if there is one provided // let's see if there is one provided
$next = array_shift($this->parsed); $next = array_shift($this->parsed);
if ('-' !== $next[0]) if ('-' !== $next[0]) {
{
$value = $next; $value = $next;
} } else {
else
{
array_unshift($this->parsed, $next); array_unshift($this->parsed, $next);
} }
} }
if (null === $value) if (null === $value) {
{
if ($option->isParameterRequired()) if ($option->isParameterRequired())
{ {
throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name)); throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
@ -251,8 +225,7 @@ class ArgvInput extends Input
*/ */
public function getFirstArgument() public function getFirstArgument()
{ {
foreach ($this->tokens as $token) foreach ($this->tokens as $token) {
{
if ($token && '-' === $token[0]) if ($token && '-' === $token[0])
{ {
continue; continue;
@ -274,13 +247,11 @@ class ArgvInput extends Input
*/ */
public function hasParameterOption($values) public function hasParameterOption($values)
{ {
if (!is_array($values)) if (!is_array($values)) {
{
$values = array($values); $values = array($values);
} }
foreach ($this->tokens as $v) foreach ($this->tokens as $v) {
{
if (in_array($v, $values)) if (in_array($v, $values))
{ {
return true; return true;

View File

@ -46,8 +46,7 @@ class ArrayInput extends Input
*/ */
public function getFirstArgument() public function getFirstArgument()
{ {
foreach ($this->parameters as $key => $value) foreach ($this->parameters as $key => $value) {
{
if ($key && '-' === $key[0]) if ($key && '-' === $key[0])
{ {
continue; continue;
@ -69,20 +68,17 @@ class ArrayInput extends Input
*/ */
public function hasParameterOption($values) public function hasParameterOption($values)
{ {
if (!is_array($values)) if (!is_array($values)) {
{
$values = array($values); $values = array($values);
} }
foreach ($this->parameters as $k => $v) foreach ($this->parameters as $k => $v) {
{
if (!is_int($k)) if (!is_int($k))
{ {
$v = $k; $v = $k;
} }
if (in_array($v, $values)) if (in_array($v, $values)) {
{
return true; return true;
} }
} }
@ -95,18 +91,13 @@ class ArrayInput extends Input
*/ */
protected function parse() protected function parse()
{ {
foreach ($this->parameters as $key => $value) foreach ($this->parameters as $key => $value) {
{
if ('--' === substr($key, 0, 2)) if ('--' === substr($key, 0, 2))
{ {
$this->addLongOption(substr($key, 2), $value); $this->addLongOption(substr($key, 2), $value);
} } elseif ('-' === $key[0]) {
elseif ('-' === $key[0])
{
$this->addShortOption(substr($key, 1), $value); $this->addShortOption(substr($key, 1), $value);
} } else {
else
{
$this->addArgument($key, $value); $this->addArgument($key, $value);
} }
} }
@ -122,8 +113,7 @@ class ArrayInput extends Input
*/ */
protected function addShortOption($shortcut, $value) protected function addShortOption($shortcut, $value)
{ {
if (!$this->definition->hasShortcut($shortcut)) if (!$this->definition->hasShortcut($shortcut)) {
{
throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut)); throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
} }
@ -141,15 +131,13 @@ class ArrayInput extends Input
*/ */
protected function addLongOption($name, $value) protected function addLongOption($name, $value)
{ {
if (!$this->definition->hasOption($name)) if (!$this->definition->hasOption($name)) {
{
throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
} }
$option = $this->definition->getOption($name); $option = $this->definition->getOption($name);
if (null === $value) if (null === $value) {
{
if ($option->isParameterRequired()) if ($option->isParameterRequired())
{ {
throw new \InvalidArgumentException(sprintf('The "--%s" option requires a value.', $name)); throw new \InvalidArgumentException(sprintf('The "--%s" option requires a value.', $name));
@ -171,8 +159,7 @@ class ArrayInput extends Input
*/ */
protected function addArgument($name, $value) protected function addArgument($name, $value)
{ {
if (!$this->definition->hasArgument($name)) if (!$this->definition->hasArgument($name)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
} }

View File

@ -38,12 +38,9 @@ abstract class Input implements InputInterface
*/ */
public function __construct(InputDefinition $definition = null) public function __construct(InputDefinition $definition = null)
{ {
if (null === $definition) if (null === $definition) {
{
$this->definition = new InputDefinition(); $this->definition = new InputDefinition();
} } else {
else
{
$this->bind($definition); $this->bind($definition);
$this->validate(); $this->validate();
} }
@ -73,8 +70,7 @@ abstract class Input implements InputInterface
*/ */
public function validate() public function validate()
{ {
if (count($this->arguments) < $this->definition->getArgumentRequiredCount()) if (count($this->arguments) < $this->definition->getArgumentRequiredCount()) {
{
throw new \RuntimeException('Not enough arguments.'); throw new \RuntimeException('Not enough arguments.');
} }
} }
@ -110,8 +106,7 @@ abstract class Input implements InputInterface
*/ */
public function getArgument($name) public function getArgument($name)
{ {
if (!$this->definition->hasArgument($name)) if (!$this->definition->hasArgument($name)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
} }
@ -128,8 +123,7 @@ abstract class Input implements InputInterface
*/ */
public function setArgument($name, $value) public function setArgument($name, $value)
{ {
if (!$this->definition->hasArgument($name)) if (!$this->definition->hasArgument($name)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
} }
@ -169,8 +163,7 @@ abstract class Input implements InputInterface
*/ */
public function getOption($name) public function getOption($name)
{ {
if (!$this->definition->hasOption($name)) if (!$this->definition->hasOption($name)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
} }
@ -187,8 +180,7 @@ abstract class Input implements InputInterface
*/ */
public function setOption($name, $value) public function setOption($name, $value)
{ {
if (!$this->definition->hasOption($name)) if (!$this->definition->hasOption($name)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" option does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
} }

View File

@ -41,12 +41,9 @@ class InputArgument
*/ */
public function __construct($name, $mode = null, $description = '', $default = null) public function __construct($name, $mode = null, $description = '', $default = null)
{ {
if (null === $mode) if (null === $mode) {
{
$mode = self::OPTIONAL; $mode = self::OPTIONAL;
} } else if (is_string($mode) || $mode > 7) {
else if (is_string($mode) || $mode > 7)
{
throw new \InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode)); throw new \InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode));
} }
@ -96,19 +93,15 @@ class InputArgument
*/ */
public function setDefault($default = null) public function setDefault($default = null)
{ {
if (self::REQUIRED === $this->mode && null !== $default) if (self::REQUIRED === $this->mode && null !== $default) {
{
throw new \LogicException('Cannot set a default value except for Parameter::OPTIONAL mode.'); throw new \LogicException('Cannot set a default value except for Parameter::OPTIONAL mode.');
} }
if ($this->isArray()) if ($this->isArray()) {
{
if (null === $default) if (null === $default)
{ {
$default = array(); $default = array();
} } else if (!is_array($default)) {
else if (!is_array($default))
{
throw new \LogicException('A default value for an array argument must be an array.'); throw new \LogicException('A default value for an array argument must be an array.');
} }
} }

View File

@ -48,14 +48,11 @@ class InputDefinition
{ {
$arguments = array(); $arguments = array();
$options = array(); $options = array();
foreach ($definition as $item) foreach ($definition as $item) {
{
if ($item instanceof InputOption) if ($item instanceof InputOption)
{ {
$options[] = $item; $options[] = $item;
} } else {
else
{
$arguments[] = $item; $arguments[] = $item;
} }
} }
@ -84,8 +81,7 @@ class InputDefinition
*/ */
public function addArguments($arguments = array()) public function addArguments($arguments = array())
{ {
if (null !== $arguments) if (null !== $arguments) {
{
foreach ($arguments as $argument) foreach ($arguments as $argument)
{ {
$this->addArgument($argument); $this->addArgument($argument);
@ -102,32 +98,25 @@ class InputDefinition
*/ */
public function addArgument(InputArgument $argument) public function addArgument(InputArgument $argument)
{ {
if (isset($this->arguments[$argument->getName()])) if (isset($this->arguments[$argument->getName()])) {
{
throw new \LogicException(sprintf('An argument with name "%s" already exist.', $argument->getName())); throw new \LogicException(sprintf('An argument with name "%s" already exist.', $argument->getName()));
} }
if ($this->hasAnArrayArgument) if ($this->hasAnArrayArgument) {
{
throw new \LogicException('Cannot add an argument after an array argument.'); throw new \LogicException('Cannot add an argument after an array argument.');
} }
if ($argument->isRequired() && $this->hasOptional) if ($argument->isRequired() && $this->hasOptional) {
{
throw new \LogicException('Cannot add a required argument after an optional one.'); throw new \LogicException('Cannot add a required argument after an optional one.');
} }
if ($argument->isArray()) if ($argument->isArray()) {
{
$this->hasAnArrayArgument = true; $this->hasAnArrayArgument = true;
} }
if ($argument->isRequired()) if ($argument->isRequired()) {
{
++$this->requiredCount; ++$this->requiredCount;
} } else {
else
{
$this->hasOptional = true; $this->hasOptional = true;
} }
@ -147,8 +136,7 @@ class InputDefinition
{ {
$arguments = is_int($name) ? array_values($this->arguments) : $this->arguments; $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
if (!$this->hasArgument($name)) if (!$this->hasArgument($name)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
} }
@ -207,8 +195,7 @@ class InputDefinition
public function getArgumentDefaults() public function getArgumentDefaults()
{ {
$values = array(); $values = array();
foreach ($this->arguments as $argument) foreach ($this->arguments as $argument) {
{
$values[$argument->getName()] = $argument->getDefault(); $values[$argument->getName()] = $argument->getDefault();
} }
@ -234,8 +221,7 @@ class InputDefinition
*/ */
public function addOptions($options = array()) public function addOptions($options = array())
{ {
foreach ($options as $option) foreach ($options as $option) {
{
$this->addOption($option); $this->addOption($option);
} }
} }
@ -249,18 +235,14 @@ class InputDefinition
*/ */
public function addOption(InputOption $option) public function addOption(InputOption $option)
{ {
if (isset($this->options[$option->getName()])) if (isset($this->options[$option->getName()])) {
{
throw new \LogicException(sprintf('An option named "%s" already exist.', $option->getName())); throw new \LogicException(sprintf('An option named "%s" already exist.', $option->getName()));
} } else if (isset($this->shortcuts[$option->getShortcut()])) {
else if (isset($this->shortcuts[$option->getShortcut()]))
{
throw new \LogicException(sprintf('An option with shortcut "%s" already exist.', $option->getShortcut())); throw new \LogicException(sprintf('An option with shortcut "%s" already exist.', $option->getShortcut()));
} }
$this->options[$option->getName()] = $option; $this->options[$option->getName()] = $option;
if ($option->getShortcut()) if ($option->getShortcut()) {
{
$this->shortcuts[$option->getShortcut()] = $option->getName(); $this->shortcuts[$option->getShortcut()] = $option->getName();
} }
} }
@ -274,8 +256,7 @@ class InputDefinition
*/ */
public function getOption($name) public function getOption($name)
{ {
if (!$this->hasOption($name)) if (!$this->hasOption($name)) {
{
throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name)); throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
} }
@ -334,8 +315,7 @@ class InputDefinition
public function getOptionDefaults() public function getOptionDefaults()
{ {
$values = array(); $values = array();
foreach ($this->options as $option) foreach ($this->options as $option) {
{
$values[$option->getName()] = $option->getDefault(); $values[$option->getName()] = $option->getDefault();
} }
@ -353,8 +333,7 @@ class InputDefinition
*/ */
protected function shortcutToName($shortcut) protected function shortcutToName($shortcut)
{ {
if (!isset($this->shortcuts[$shortcut])) if (!isset($this->shortcuts[$shortcut])) {
{
throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut)); throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
} }
@ -369,18 +348,15 @@ class InputDefinition
public function getSynopsis() public function getSynopsis()
{ {
$elements = array(); $elements = array();
foreach ($this->getOptions() as $option) foreach ($this->getOptions() as $option) {
{
$shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : ''; $shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
$elements[] = sprintf('['.($option->isParameterRequired() ? '%s--%s="..."' : ($option->isParameterOptional() ? '%s--%s[="..."]' : '%s--%s')).']', $shortcut, $option->getName()); $elements[] = sprintf('['.($option->isParameterRequired() ? '%s--%s="..."' : ($option->isParameterOptional() ? '%s--%s[="..."]' : '%s--%s')).']', $shortcut, $option->getName());
} }
foreach ($this->getArguments() as $argument) foreach ($this->getArguments() as $argument) {
{
$elements[] = sprintf($argument->isRequired() ? '%s' : '[%s]', $argument->getName().($argument->isArray() ? '1' : '')); $elements[] = sprintf($argument->isRequired() ? '%s' : '[%s]', $argument->getName().($argument->isArray() ? '1' : ''));
if ($argument->isArray()) if ($argument->isArray()) {
{
$elements[] = sprintf('... [%sN]', $argument->getName()); $elements[] = sprintf('... [%sN]', $argument->getName());
} }
} }
@ -397,29 +373,23 @@ class InputDefinition
{ {
// find the largest option or argument name // find the largest option or argument name
$max = 0; $max = 0;
foreach ($this->getOptions() as $option) foreach ($this->getOptions() as $option) {
{
$max = strlen($option->getName()) + 2 > $max ? strlen($option->getName()) + 2 : $max; $max = strlen($option->getName()) + 2 > $max ? strlen($option->getName()) + 2 : $max;
} }
foreach ($this->getArguments() as $argument) foreach ($this->getArguments() as $argument) {
{
$max = strlen($argument->getName()) > $max ? strlen($argument->getName()) : $max; $max = strlen($argument->getName()) > $max ? strlen($argument->getName()) : $max;
} }
++$max; ++$max;
$text = array(); $text = array();
if ($this->getArguments()) if ($this->getArguments()) {
{
$text[] = '<comment>Arguments:</comment>'; $text[] = '<comment>Arguments:</comment>';
foreach ($this->getArguments() as $argument) foreach ($this->getArguments() as $argument) {
{
if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault()))) if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault())))
{ {
$default = sprintf('<comment> (default: %s)</comment>', is_array($argument->getDefault()) ? str_replace("\n", '', var_export($argument->getDefault(), true)): $argument->getDefault()); $default = sprintf('<comment> (default: %s)</comment>', is_array($argument->getDefault()) ? str_replace("\n", '', var_export($argument->getDefault(), true)): $argument->getDefault());
} } else {
else
{
$default = ''; $default = '';
} }
@ -429,18 +399,14 @@ class InputDefinition
$text[] = ''; $text[] = '';
} }
if ($this->getOptions()) if ($this->getOptions()) {
{
$text[] = '<comment>Options:</comment>'; $text[] = '<comment>Options:</comment>';
foreach ($this->getOptions() as $option) foreach ($this->getOptions() as $option) {
{
if ($option->acceptParameter() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) if ($option->acceptParameter() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault())))
{ {
$default = sprintf('<comment> (default: %s)</comment>', is_array($option->getDefault()) ? str_replace("\n", '', print_r($option->getDefault(), true)): $option->getDefault()); $default = sprintf('<comment> (default: %s)</comment>', is_array($option->getDefault()) ? str_replace("\n", '', print_r($option->getDefault(), true)): $option->getDefault());
} } else {
else
{
$default = ''; $default = '';
} }
@ -468,8 +434,7 @@ class InputDefinition
$dom->appendChild($definitionXML = $dom->createElement('definition')); $dom->appendChild($definitionXML = $dom->createElement('definition'));
$definitionXML->appendChild($argumentsXML = $dom->createElement('arguments')); $definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
foreach ($this->getArguments() as $argument) foreach ($this->getArguments() as $argument) {
{
$argumentsXML->appendChild($argumentXML = $dom->createElement('argument')); $argumentsXML->appendChild($argumentXML = $dom->createElement('argument'));
$argumentXML->setAttribute('name', $argument->getName()); $argumentXML->setAttribute('name', $argument->getName());
$argumentXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0); $argumentXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0);
@ -479,16 +444,14 @@ class InputDefinition
$argumentXML->appendChild($defaultsXML = $dom->createElement('defaults')); $argumentXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$defaults = is_array($argument->getDefault()) ? $argument->getDefault() : ($argument->getDefault() ? array($argument->getDefault()) : array()); $defaults = is_array($argument->getDefault()) ? $argument->getDefault() : ($argument->getDefault() ? array($argument->getDefault()) : array());
foreach ($defaults as $default) foreach ($defaults as $default) {
{
$defaultsXML->appendChild($defaultXML = $dom->createElement('default')); $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default)); $defaultXML->appendChild($dom->createTextNode($default));
} }
} }
$definitionXML->appendChild($optionsXML = $dom->createElement('options')); $definitionXML->appendChild($optionsXML = $dom->createElement('options'));
foreach ($this->getOptions() as $option) foreach ($this->getOptions() as $option) {
{
$optionsXML->appendChild($optionXML = $dom->createElement('option')); $optionsXML->appendChild($optionXML = $dom->createElement('option'));
$optionXML->setAttribute('name', '--'.$option->getName()); $optionXML->setAttribute('name', '--'.$option->getName());
$optionXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : ''); $optionXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : '');
@ -498,12 +461,10 @@ class InputDefinition
$optionXML->appendChild($descriptionXML = $dom->createElement('description')); $optionXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode($option->getDescription())); $descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
if ($option->acceptParameter()) if ($option->acceptParameter()) {
{
$optionXML->appendChild($defaultsXML = $dom->createElement('defaults')); $optionXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$defaults = is_array($option->getDefault()) ? $option->getDefault() : ($option->getDefault() ? array($option->getDefault()) : array()); $defaults = is_array($option->getDefault()) ? $option->getDefault() : ($option->getDefault() ? array($option->getDefault()) : array());
foreach ($defaults as $default) foreach ($defaults as $default) {
{
$defaultsXML->appendChild($defaultXML = $dom->createElement('default')); $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default)); $defaultXML->appendChild($dom->createTextNode($default));
} }

View File

@ -44,30 +44,24 @@ class InputOption
*/ */
public function __construct($name, $shortcut = null, $mode = null, $description = '', $default = null) public function __construct($name, $shortcut = null, $mode = null, $description = '', $default = null)
{ {
if ('--' === substr($name, 0, 2)) if ('--' === substr($name, 0, 2)) {
{
$name = substr($name, 2); $name = substr($name, 2);
} }
if (empty($shortcut)) if (empty($shortcut)) {
{
$shortcut = null; $shortcut = null;
} }
if (null !== $shortcut) if (null !== $shortcut) {
{
if ('-' === $shortcut[0]) if ('-' === $shortcut[0])
{ {
$shortcut = substr($shortcut, 1); $shortcut = substr($shortcut, 1);
} }
} }
if (null === $mode) if (null === $mode) {
{
$mode = self::PARAMETER_NONE; $mode = self::PARAMETER_NONE;
} } else if (!is_int($mode) || $mode > 15) {
else if (!is_int($mode) || $mode > 15)
{
throw new \InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode)); throw new \InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode));
} }
@ -76,8 +70,7 @@ class InputOption
$this->mode = $mode; $this->mode = $mode;
$this->description = $description; $this->description = $description;
if ($this->isArray() && !$this->acceptParameter()) if ($this->isArray() && !$this->acceptParameter()) {
{
throw new \InvalidArgumentException('Impossible to have an option mode PARAMETER_IS_ARRAY if the option does not accept a parameter.'); throw new \InvalidArgumentException('Impossible to have an option mode PARAMETER_IS_ARRAY if the option does not accept a parameter.');
} }
@ -151,19 +144,15 @@ class InputOption
*/ */
public function setDefault($default = null) public function setDefault($default = null)
{ {
if (self::PARAMETER_NONE === (self::PARAMETER_NONE & $this->mode) && null !== $default) if (self::PARAMETER_NONE === (self::PARAMETER_NONE & $this->mode) && null !== $default) {
{
throw new \LogicException('Cannot set a default value when using Option::PARAMETER_NONE mode.'); throw new \LogicException('Cannot set a default value when using Option::PARAMETER_NONE mode.');
} }
if ($this->isArray()) if ($this->isArray()) {
{
if (null === $default) if (null === $default)
{ {
$default = array(); $default = array();
} } elseif (!is_array($default)) {
elseif (!is_array($default))
{
throw new \LogicException('A default value for an array option must be an array.'); throw new \LogicException('A default value for an array option must be an array.');
} }
} }

View File

@ -50,25 +50,16 @@ class StringInput extends ArgvInput
$tokens = array(); $tokens = array();
$length = strlen($input); $length = strlen($input);
$cursor = 0; $cursor = 0;
while ($cursor < $length) while ($cursor < $length) {
{
if (preg_match('/\s+/A', $input, $match, null, $cursor)) if (preg_match('/\s+/A', $input, $match, null, $cursor))
{ {
} } elseif (preg_match('/([^="\' ]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
elseif (preg_match('/([^="\' ]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor))
{
$tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2))); $tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
} } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor))
{
$tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2)); $tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
} } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor))
{
$tokens[] = stripcslashes($match[1]); $tokens[] = stripcslashes($match[1]);
} } else {
else
{
// should never happen // should never happen
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10))); throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));

View File

@ -132,18 +132,15 @@ abstract class Output implements OutputInterface
*/ */
public function write($messages, $newline = false, $type = 0) public function write($messages, $newline = false, $type = 0)
{ {
if (self::VERBOSITY_QUIET === $this->verbosity) if (self::VERBOSITY_QUIET === $this->verbosity) {
{
return; return;
} }
if (!is_array($messages)) if (!is_array($messages)) {
{
$messages = array($messages); $messages = array($messages);
} }
foreach ($messages as $message) foreach ($messages as $message) {
{
switch ($type) switch ($type)
{ {
case Output::OUTPUT_NORMAL: case Output::OUTPUT_NORMAL:
@ -189,31 +186,26 @@ abstract class Output implements OutputInterface
*/ */
protected function replaceStartStyle($match) protected function replaceStartStyle($match)
{ {
if (!$this->decorated) if (!$this->decorated) {
{
return ''; return '';
} }
if (!isset(static::$styles[strtolower($match[1])])) if (!isset(static::$styles[strtolower($match[1])])) {
{
throw new \InvalidArgumentException(sprintf('Unknown style "%s".', $match[1])); throw new \InvalidArgumentException(sprintf('Unknown style "%s".', $match[1]));
} }
$parameters = static::$styles[strtolower($match[1])]; $parameters = static::$styles[strtolower($match[1])];
$codes = array(); $codes = array();
if (isset($parameters['fg'])) if (isset($parameters['fg'])) {
{
$codes[] = static::$foreground[$parameters['fg']]; $codes[] = static::$foreground[$parameters['fg']];
} }
if (isset($parameters['bg'])) if (isset($parameters['bg'])) {
{
$codes[] = static::$background[$parameters['bg']]; $codes[] = static::$background[$parameters['bg']];
} }
foreach (static::$options as $option => $value) foreach (static::$options as $option => $value) {
{
if (isset($parameters[$option]) && $parameters[$option]) if (isset($parameters[$option]) && $parameters[$option])
{ {
$codes[] = $value; $codes[] = $value;
@ -225,8 +217,7 @@ abstract class Output implements OutputInterface
protected function replaceEndStyle($match) protected function replaceEndStyle($match)
{ {
if (!$this->decorated) if (!$this->decorated) {
{
return ''; return '';
} }

View File

@ -41,15 +41,13 @@ class StreamOutput extends Output
*/ */
public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null) public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null)
{ {
if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) {
{
throw new \InvalidArgumentException('The StreamOutput class needs a stream as its first argument.'); throw new \InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');
} }
$this->stream = $stream; $this->stream = $stream;
if (null === $decorated) if (null === $decorated) {
{
$decorated = $this->hasColorSupport($decorated); $decorated = $this->hasColorSupport($decorated);
} }
@ -76,8 +74,7 @@ class StreamOutput extends Output
*/ */
public function doWrite($message, $newline) public function doWrite($message, $newline)
{ {
if (false === @fwrite($this->stream, $message.($newline ? PHP_EOL : ''))) if (false === @fwrite($this->stream, $message.($newline ? PHP_EOL : ''))) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
// should never happen // should never happen
throw new \RuntimeException('Unable to write output.'); throw new \RuntimeException('Unable to write output.');
@ -100,12 +97,9 @@ class StreamOutput extends Output
protected function hasColorSupport() protected function hasColorSupport()
{ {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if (DIRECTORY_SEPARATOR == '\\') if (DIRECTORY_SEPARATOR == '\\') {
{
return false !== getenv('ANSICON'); return false !== getenv('ANSICON');
} } else {
else
{
return function_exists('posix_isatty') && @posix_isatty($this->stream); return function_exists('posix_isatty') && @posix_isatty($this->stream);
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd

View File

@ -43,8 +43,7 @@ class Shell
*/ */
public function __construct(Application $application) public function __construct(Application $application)
{ {
if (!function_exists('readline')) if (!function_exists('readline')) {
{
throw new \RuntimeException('Unable to start the shell as the Readline extension is not enabled.'); throw new \RuntimeException('Unable to start the shell as the Readline extension is not enabled.');
} }
@ -65,12 +64,10 @@ class Shell
readline_completion_function(array($this, 'autocompleter')); readline_completion_function(array($this, 'autocompleter'));
$this->output->writeln($this->getHeader()); $this->output->writeln($this->getHeader());
while (true) while (true) {
{
$command = readline($this->application->getName().' > '); $command = readline($this->application->getName().' > ');
if (false === $command) if (false === $command) {
{
$this->output->writeln("\n"); $this->output->writeln("\n");
break; break;
@ -79,8 +76,7 @@ class Shell
readline_add_history($command); readline_add_history($command);
readline_write_history($this->history); readline_write_history($this->history);
if (0 !== $ret = $this->application->run(new StringInput($command), $this->output)) if (0 !== $ret = $this->application->run(new StringInput($command), $this->output)) {
{
$this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret)); $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
} }
} }
@ -97,30 +93,24 @@ class Shell
$info = readline_info(); $info = readline_info();
$text = substr($info['line_buffer'], 0, $info['end']); $text = substr($info['line_buffer'], 0, $info['end']);
if ($info['point'] !== $info['end']) if ($info['point'] !== $info['end']) {
{
return true; return true;
} }
// task name? // task name?
if (false === strpos($text, ' ') || !$text) if (false === strpos($text, ' ') || !$text) {
{
return array_keys($this->application->getCommands()); return array_keys($this->application->getCommands());
} }
// options and arguments? // options and arguments?
try try {
{
$command = $this->application->findCommand(substr($text, 0, strpos($text, ' '))); $command = $this->application->findCommand(substr($text, 0, strpos($text, ' ')));
} } catch (\Exception $e) {
catch (\Exception $e)
{
return true; return true;
} }
$list = array('--help'); $list = array('--help');
foreach ($command->getDefinition()->getOptions() as $option) foreach ($command->getDefinition()->getOptions() as $option) {
{
$list[] = '--'.$option->getName(); $list[] = '--'.$option->getName();
} }

View File

@ -52,18 +52,15 @@ class ApplicationTester
public function run(array $input, $options = array()) public function run(array $input, $options = array())
{ {
$this->input = new ArrayInput($input); $this->input = new ArrayInput($input);
if (isset($options['interactive'])) if (isset($options['interactive'])) {
{
$this->input->setInteractive($options['interactive']); $this->input->setInteractive($options['interactive']);
} }
$this->output = new StreamOutput(fopen('php://memory', 'w', false)); $this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) if (isset($options['decorated'])) {
{
$this->output->setDecorated($options['decorated']); $this->output->setDecorated($options['decorated']);
} }
if (isset($options['verbosity'])) if (isset($options['verbosity'])) {
{
$this->output->setVerbosity($options['verbosity']); $this->output->setVerbosity($options['verbosity']);
} }

View File

@ -52,18 +52,15 @@ class CommandTester
public function execute(array $input, array $options = array()) public function execute(array $input, array $options = array())
{ {
$this->input = new ArrayInput(array_merge($input, array('command' => $this->command->getFullName()))); $this->input = new ArrayInput(array_merge($input, array('command' => $this->command->getFullName())));
if (isset($options['interactive'])) if (isset($options['interactive'])) {
{
$this->input->setInteractive($options['interactive']); $this->input->setInteractive($options['interactive']);
} }
$this->output = new StreamOutput(fopen('php://memory', 'w', false)); $this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) if (isset($options['decorated'])) {
{
$this->output->setDecorated($options['decorated']); $this->output->setDecorated($options['decorated']);
} }
if (isset($options['verbosity'])) if (isset($options['verbosity'])) {
{
$this->output->setVerbosity($options['verbosity']); $this->output->setVerbosity($options['verbosity']);
} }

View File

@ -43,12 +43,9 @@ class AttribNode implements NodeInterface
public function __toString() public function __toString()
{ {
if ($this->operator == 'exists') if ($this->operator == 'exists') {
{
return sprintf('%s[%s[%s]]', __CLASS__, $this->selector, $this->formatAttrib()); return sprintf('%s[%s[%s]]', __CLASS__, $this->selector, $this->formatAttrib());
} } else {
else
{
return sprintf('%s[%s[%s %s %s]]', __CLASS__, $this->selector, $this->formatAttrib(), $this->operator, $this->value); return sprintf('%s[%s[%s %s %s]]', __CLASS__, $this->selector, $this->formatAttrib(), $this->operator, $this->value);
} }
} }
@ -61,52 +58,32 @@ class AttribNode implements NodeInterface
$path = $this->selector->toXpath(); $path = $this->selector->toXpath();
$attrib = $this->xpathAttrib(); $attrib = $this->xpathAttrib();
$value = $this->value; $value = $this->value;
if ($this->operator == 'exists') if ($this->operator == 'exists') {
{
$path->addCondition($attrib); $path->addCondition($attrib);
} } elseif ($this->operator == '=') {
elseif ($this->operator == '=')
{
$path->addCondition(sprintf('%s = %s', $attrib, XPathExpr::xpathLiteral($value))); $path->addCondition(sprintf('%s = %s', $attrib, XPathExpr::xpathLiteral($value)));
} } elseif ($this->operator == '!=') {
elseif ($this->operator == '!=')
{
// FIXME: this seems like a weird hack... // FIXME: this seems like a weird hack...
if ($value) if ($value) {
{
$path->addCondition(sprintf('not(%s) or %s != %s', $attrib, $attrib, XPathExpr::xpathLiteral($value))); $path->addCondition(sprintf('not(%s) or %s != %s', $attrib, $attrib, XPathExpr::xpathLiteral($value)));
} } else {
else
{
$path->addCondition(sprintf('%s != %s', $attrib, XPathExpr::xpathLiteral($value))); $path->addCondition(sprintf('%s != %s', $attrib, XPathExpr::xpathLiteral($value)));
} }
// path.addCondition('%s != %s' % (attrib, xpathLiteral(value))) // path.addCondition('%s != %s' % (attrib, xpathLiteral(value)))
} } elseif ($this->operator == '~=') {
elseif ($this->operator == '~=')
{
$path->addCondition(sprintf("contains(concat(' ', normalize-space(%s), ' '), %s)", $attrib, XPathExpr::xpathLiteral(' '.$value.' '))); $path->addCondition(sprintf("contains(concat(' ', normalize-space(%s), ' '), %s)", $attrib, XPathExpr::xpathLiteral(' '.$value.' ')));
} } elseif ($this->operator == '|=') {
elseif ($this->operator == '|=')
{
// Weird, but true... // Weird, but true...
$path->addCondition(sprintf('%s = %s or starts-with(%s, %s)', $attrib, XPathExpr::xpathLiteral($value), $attrib, XPathExpr::xpathLiteral($value.'-'))); $path->addCondition(sprintf('%s = %s or starts-with(%s, %s)', $attrib, XPathExpr::xpathLiteral($value), $attrib, XPathExpr::xpathLiteral($value.'-')));
} } elseif ($this->operator == '^=') {
elseif ($this->operator == '^=')
{
$path->addCondition(sprintf('starts-with(%s, %s)', $attrib, XPathExpr::xpathLiteral($value))); $path->addCondition(sprintf('starts-with(%s, %s)', $attrib, XPathExpr::xpathLiteral($value)));
} } elseif ($this->operator == '$=') {
elseif ($this->operator == '$=')
{
// Oddly there is a starts-with in XPath 1.0, but not ends-with // Oddly there is a starts-with in XPath 1.0, but not ends-with
$path->addCondition(sprintf('substring(%s, string-length(%s)-%s) = %s', $attrib, $attrib, strlen($value) - 1, XPathExpr::xpathLiteral($value))); $path->addCondition(sprintf('substring(%s, string-length(%s)-%s) = %s', $attrib, $attrib, strlen($value) - 1, XPathExpr::xpathLiteral($value)));
} } elseif ($this->operator == '*=') {
elseif ($this->operator == '*=')
{
// FIXME: case sensitive? // FIXME: case sensitive?
$path->addCondition(sprintf('contains(%s, %s)', $attrib, XPathExpr::xpathLiteral($value))); $path->addCondition(sprintf('contains(%s, %s)', $attrib, XPathExpr::xpathLiteral($value)));
} } else {
else
{
throw new SyntaxError(sprintf('Unknown operator: %s', $this->operator)); throw new SyntaxError(sprintf('Unknown operator: %s', $this->operator));
} }
@ -116,8 +93,7 @@ class AttribNode implements NodeInterface
protected function xpathAttrib() protected function xpathAttrib()
{ {
// FIXME: if attrib is *? // FIXME: if attrib is *?
if ($this->namespace == '*') if ($this->namespace == '*') {
{
return '@'.$this->attrib; return '@'.$this->attrib;
} }
@ -126,8 +102,7 @@ class AttribNode implements NodeInterface
protected function formatAttrib() protected function formatAttrib()
{ {
if ($this->namespace == '*') if ($this->namespace == '*') {
{
return $this->attrib; return $this->attrib;
} }

View File

@ -55,8 +55,7 @@ class CombinedSelectorNode implements NodeInterface
*/ */
public function toXpath() public function toXpath()
{ {
if (!isset(self::$_method_mapping[$this->combinator])) if (!isset(self::$_method_mapping[$this->combinator])) {
{
throw new SyntaxError(sprintf('Unknown combinator: %s', $this->combinator)); throw new SyntaxError(sprintf('Unknown combinator: %s', $this->combinator));
} }

View File

@ -41,8 +41,7 @@ class ElementNode implements NodeInterface
public function formatElement() public function formatElement()
{ {
if ($this->namespace == '*') if ($this->namespace == '*') {
{
return $this->element; return $this->element;
} }
@ -51,12 +50,9 @@ class ElementNode implements NodeInterface
public function toXpath() public function toXpath()
{ {
if ($this->namespace == '*') if ($this->namespace == '*') {
{
$el = strtolower($this->element); $el = strtolower($this->element);
} } else {
else
{
// FIXME: Should we lowercase here? // FIXME: Should we lowercase here?
$el = sprintf('%s:%s', $this->namespace, $this->element); $el = sprintf('%s:%s', $this->namespace, $this->element);
} }

View File

@ -52,13 +52,11 @@ class FunctionNode implements NodeInterface
public function toXpath() public function toXpath()
{ {
$sel_path = $this->selector->toXpath(); $sel_path = $this->selector->toXpath();
if (in_array($this->name, self::$unsupported)) if (in_array($this->name, self::$unsupported)) {
{
throw new SyntaxError(sprintf('The pseudo-class %s is not supported', $this->name)); throw new SyntaxError(sprintf('The pseudo-class %s is not supported', $this->name));
} }
$method = '_xpath_'.str_replace('-', '_', $this->name); $method = '_xpath_'.str_replace('-', '_', $this->name);
if (!method_exists($this, $method)) if (!method_exists($this, $method)) {
{
throw new SyntaxError(sprintf('The pseudo-class %s is unknown', $this->name)); throw new SyntaxError(sprintf('The pseudo-class %s is unknown', $this->name));
} }
@ -68,22 +66,19 @@ class FunctionNode implements NodeInterface
protected function _xpath_nth_child($xpath, $expr, $last = false, $addNameTest = true) protected function _xpath_nth_child($xpath, $expr, $last = false, $addNameTest = true)
{ {
list($a, $b) = $this->parseSeries($expr); list($a, $b) = $this->parseSeries($expr);
if (!$a && !$b && !$last) if (!$a && !$b && !$last) {
{
// a=0 means nothing is returned... // a=0 means nothing is returned...
$xpath->addCondition('false() and position() = 0'); $xpath->addCondition('false() and position() = 0');
return $xpath; return $xpath;
} }
if ($addNameTest) if ($addNameTest) {
{
$xpath->addNameTest(); $xpath->addNameTest();
} }
$xpath->addStarPrefix(); $xpath->addStarPrefix();
if ($a == 0) if ($a == 0) {
{
if ($last) if ($last)
{ {
$b = sprintf('last() - %s', $b); $b = sprintf('last() - %s', $b);
@ -93,43 +88,32 @@ class FunctionNode implements NodeInterface
return $xpath; return $xpath;
} }
if ($last) if ($last) {
{
// FIXME: I'm not sure if this is right // FIXME: I'm not sure if this is right
$a = -$a; $a = -$a;
$b = -$b; $b = -$b;
} }
if ($b > 0) if ($b > 0) {
{
$b_neg = -$b; $b_neg = -$b;
} } else {
else
{
$b_neg = sprintf('+%s', -$b); $b_neg = sprintf('+%s', -$b);
} }
if ($a != 1) if ($a != 1) {
{
$expr = array(sprintf('(position() %s) mod %s = 0', $b_neg, $a)); $expr = array(sprintf('(position() %s) mod %s = 0', $b_neg, $a));
} } else {
else
{
$expr = array(); $expr = array();
} }
if ($b >= 0) if ($b >= 0) {
{
$expr[] = sprintf('position() >= %s', $b); $expr[] = sprintf('position() >= %s', $b);
} } elseif ($b < 0 && $last) {
elseif ($b < 0 && $last)
{
$expr[] = sprintf('position() < (last() %s)', $b); $expr[] = sprintf('position() < (last() %s)', $b);
} }
$expr = implode($expr, ' and '); $expr = implode($expr, ' and ');
if ($expr) if ($expr) {
{
$xpath->addCondition($expr); $xpath->addCondition($expr);
} }
@ -150,8 +134,7 @@ class FunctionNode implements NodeInterface
protected function _xpath_nth_of_type($xpath, $expr) protected function _xpath_nth_of_type($xpath, $expr)
{ {
if ($xpath->getElement() == '*') if ($xpath->getElement() == '*') {
{
throw new SyntaxError('*:nth-of-type() is not implemented'); throw new SyntaxError('*:nth-of-type() is not implemented');
} }
@ -166,8 +149,7 @@ class FunctionNode implements NodeInterface
protected function _xpath_contains($xpath, $expr) protected function _xpath_contains($xpath, $expr)
{ {
// text content, minus tags, must contain expr // text content, minus tags, must contain expr
if ($expr instanceof ElementNode) if ($expr instanceof ElementNode) {
{
$expr = $expr->formatElement(); $expr = $expr->formatElement();
} }
@ -194,69 +176,52 @@ class FunctionNode implements NodeInterface
// Parses things like '1n+2', or 'an+b' generally, returning (a, b) // Parses things like '1n+2', or 'an+b' generally, returning (a, b)
protected function parseSeries($s) protected function parseSeries($s)
{ {
if ($s instanceof ElementNode) if ($s instanceof ElementNode) {
{
$s = $s->formatElement(); $s = $s->formatElement();
} }
if (!$s || $s == '*') if (!$s || $s == '*') {
{
// Happens when there's nothing, which the CSS parser thinks of as * // Happens when there's nothing, which the CSS parser thinks of as *
return array(0, 0); return array(0, 0);
} }
if (is_string($s)) if (is_string($s)) {
{
// Happens when you just get a number // Happens when you just get a number
return array(0, $s); return array(0, $s);
} }
if ($s == 'odd') if ($s == 'odd') {
{
return array(2, 1); return array(2, 1);
} }
if ($s == 'even') if ($s == 'even') {
{
return array(2, 0); return array(2, 0);
} }
if ($s == 'n') if ($s == 'n') {
{
return array(1, 0); return array(1, 0);
} }
if (false === strpos($s, 'n')) if (false === strpos($s, 'n')) {
{
// Just a b // Just a b
return array(0, intval((string) $s)); return array(0, intval((string) $s));
} }
list($a, $b) = explode('n', $s); list($a, $b) = explode('n', $s);
if (!$a) if (!$a) {
{
$a = 1; $a = 1;
} } elseif ($a == '-' || $a == '+') {
elseif ($a == '-' || $a == '+')
{
$a = intval($a.'1'); $a = intval($a.'1');
} } else {
else
{
$a = intval($a); $a = intval($a);
} }
if (!$b) if (!$b) {
{
$b = 0; $b = 0;
} } elseif ($b == '-' || $b == '+') {
elseif ($b == '-' || $b == '+')
{
$b = intval($b.'1'); $b = intval($b.'1');
} } else {
else
{
$b = intval($b); $b = intval($b);
} }

View File

@ -40,8 +40,7 @@ class OrNode implements NodeInterface
public function toXpath() public function toXpath()
{ {
$paths = array(); $paths = array();
foreach ($this->items as $item) foreach ($this->items as $item) {
{
$paths[] = $item->toXpath(); $paths[] = $item->toXpath();
} }

View File

@ -42,8 +42,7 @@ class PseudoNode implements NodeInterface
{ {
$this->element = $element; $this->element = $element;
if (!in_array($type, array(':', '::'))) if (!in_array($type, array(':', '::'))) {
{
throw new SyntaxError(sprintf('The PseudoNode type can only be : or :: (%s given).', $type)); throw new SyntaxError(sprintf('The PseudoNode type can only be : or :: (%s given).', $type));
} }
@ -63,13 +62,11 @@ class PseudoNode implements NodeInterface
{ {
$el_xpath = $this->element->toXpath(); $el_xpath = $this->element->toXpath();
if (in_array($this->ident, self::$unsupported)) if (in_array($this->ident, self::$unsupported)) {
{
throw new SyntaxError(sprintf('The pseudo-class %s is unsupported', $this->ident)); throw new SyntaxError(sprintf('The pseudo-class %s is unsupported', $this->ident));
} }
$method = 'xpath_'.str_replace('-', '_', $this->ident); $method = 'xpath_'.str_replace('-', '_', $this->ident);
if (!method_exists($this, $method)) if (!method_exists($this, $method)) {
{
throw new SyntaxError(sprintf('The pseudo-class %s is unknown', $this->ident)); throw new SyntaxError(sprintf('The pseudo-class %s is unknown', $this->ident));
} }
@ -113,8 +110,7 @@ class PseudoNode implements NodeInterface
protected function xpath_first_of_type($xpath) protected function xpath_first_of_type($xpath)
{ {
if ($xpath->getElement() == '*') if ($xpath->getElement() == '*') {
{
throw new SyntaxError('*:first-of-type is not implemented'); throw new SyntaxError('*:first-of-type is not implemented');
} }
$xpath->addStarPrefix(); $xpath->addStarPrefix();
@ -128,8 +124,7 @@ class PseudoNode implements NodeInterface
*/ */
protected function xpath_last_of_type($xpath) protected function xpath_last_of_type($xpath)
{ {
if ($xpath->getElement() == '*') if ($xpath->getElement() == '*') {
{
throw new SyntaxError('*:last-of-type is not implemented'); throw new SyntaxError('*:last-of-type is not implemented');
} }
$xpath->addStarPrefix(); $xpath->addStarPrefix();
@ -152,8 +147,7 @@ class PseudoNode implements NodeInterface
*/ */
protected function xpath_only_of_type($xpath) protected function xpath_only_of_type($xpath)
{ {
if ($xpath->getElement() == '*') if ($xpath->getElement() == '*') {
{
throw new SyntaxError('*:only-of-type is not implemented'); throw new SyntaxError('*:only-of-type is not implemented');
} }
$xpath->addCondition('last() = 1'); $xpath->addCondition('last() = 1');

View File

@ -31,20 +31,17 @@ class Parser
*/ */
static public function cssToXpath($cssExpr, $prefix = 'descendant-or-self::') static public function cssToXpath($cssExpr, $prefix = 'descendant-or-self::')
{ {
if (is_string($cssExpr)) if (is_string($cssExpr)) {
{
if (preg_match('#^\w+\s*$#u', $cssExpr, $match)) if (preg_match('#^\w+\s*$#u', $cssExpr, $match))
{ {
return $prefix.trim($match[0]); return $prefix.trim($match[0]);
} }
if (preg_match('~^(\w*)#(\w+)\s*$~u', $cssExpr, $match)) if (preg_match('~^(\w*)#(\w+)\s*$~u', $cssExpr, $match)) {
{
return sprintf("%s%s[@id = '%s']", $prefix, $match[1] ? $match[1] : '*', $match[2]); return sprintf("%s%s[@id = '%s']", $prefix, $match[1] ? $match[1] : '*', $match[2]);
} }
if (preg_match('#^(\w*)\.(\w+)\s*$#u', $cssExpr, $match)) if (preg_match('#^(\w*)\.(\w+)\s*$#u', $cssExpr, $match)) {
{
return sprintf("%s%s[contains(concat(' ', normalize-space(@class), ' '), ' %s ')]", $prefix, $match[1] ? $match[1] : '*', $match[2]); return sprintf("%s%s[contains(concat(' ', normalize-space(@class), ' '), ' %s ')]", $prefix, $match[1] ? $match[1] : '*', $match[2]);
} }
@ -55,14 +52,12 @@ class Parser
$expr = $cssExpr->toXpath(); $expr = $cssExpr->toXpath();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if (!$expr) if (!$expr) {
{
throw new SyntaxError(sprintf('Got None for xpath expression from %s.', $cssExpr)); throw new SyntaxError(sprintf('Got None for xpath expression from %s.', $cssExpr));
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
if ($prefix) if ($prefix) {
{
$expr->addPrefix($prefix); $expr->addPrefix($prefix);
} }
@ -78,12 +73,9 @@ class Parser
$stream = new TokenStream($tokenizer->tokenize($string), $string); $stream = new TokenStream($tokenizer->tokenize($string), $string);
try try {
{
return $this->parseSelectorGroup($stream); return $this->parseSelectorGroup($stream);
} } catch (\Exception $e) {
catch (\Exception $e)
{
$class = get_class($e); $class = get_class($e);
throw new $class(sprintf('%s at %s -> %s', $e->getMessage(), implode($stream->getUsed(), ''), $stream->peek())); throw new $class(sprintf('%s at %s -> %s', $e->getMessage(), implode($stream->getUsed(), ''), $stream->peek()));
@ -93,21 +85,16 @@ class Parser
protected function parseSelectorGroup($stream) protected function parseSelectorGroup($stream)
{ {
$result = array(); $result = array();
while (1) while (1) {
{
$result[] = $this->parseSelector($stream); $result[] = $this->parseSelector($stream);
if ($stream->peek() == ',') if ($stream->peek() == ',') {
{
$stream->next(); $stream->next();
} } else {
else
{
break; break;
} }
} }
if (count($result) == 1) if (count($result) == 1) {
{
return $result[0]; return $result[0];
} }
@ -121,26 +108,19 @@ class Parser
{ {
$result = $this->parseSimpleSelector($stream); $result = $this->parseSimpleSelector($stream);
while (1) while (1) {
{
$peek = $stream->peek(); $peek = $stream->peek();
if ($peek == ',' || $peek === null) if ($peek == ',' || $peek === null) {
{
return $result; return $result;
} } elseif (in_array($peek, array('+', '>', '~'))) {
elseif (in_array($peek, array('+', '>', '~')))
{
// A combinator // A combinator
$combinator = (string) $stream->next(); $combinator = (string) $stream->next();
} } else {
else
{
$combinator = ' '; $combinator = ' ';
} }
$consumed = count($stream->getUsed()); $consumed = count($stream->getUsed());
$next_selector = $this->parseSimpleSelector($stream); $next_selector = $this->parseSimpleSelector($stream);
if ($consumed == count($stream->getUsed())) if ($consumed == count($stream->getUsed())) {
{
throw new SyntaxError(sprintf("Expected selector, got '%s'", $stream->peek())); throw new SyntaxError(sprintf("Expected selector, got '%s'", $stream->peek()));
} }
@ -156,30 +136,22 @@ class Parser
protected function parseSimpleSelector($stream) protected function parseSimpleSelector($stream)
{ {
$peek = $stream->peek(); $peek = $stream->peek();
if ($peek != '*' && !$peek->isType('Symbol')) if ($peek != '*' && !$peek->isType('Symbol')) {
{
$element = $namespace = '*'; $element = $namespace = '*';
} } else {
else
{
$next = $stream->next(); $next = $stream->next();
if ($next != '*' && !$next->isType('Symbol')) if ($next != '*' && !$next->isType('Symbol')) {
{
throw new SyntaxError(sprintf("Expected symbol, got '%s'", $next)); throw new SyntaxError(sprintf("Expected symbol, got '%s'", $next));
} }
if ($stream->peek() == '|') if ($stream->peek() == '|') {
{
$namespace = $next; $namespace = $next;
$stream->next(); $stream->next();
$element = $stream->next(); $element = $stream->next();
if ($element != '*' && !$next->isType('Symbol')) if ($element != '*' && !$next->isType('Symbol')) {
{
throw new SyntaxError(sprintf("Expected symbol, got '%s'", $next)); throw new SyntaxError(sprintf("Expected symbol, got '%s'", $next));
} }
} } else {
else
{
$namespace = '*'; $namespace = '*';
$element = $next; $element = $next;
} }
@ -187,11 +159,9 @@ class Parser
$result = new Node\ElementNode($namespace, $element); $result = new Node\ElementNode($namespace, $element);
$has_hash = false; $has_hash = false;
while (1) while (1) {
{
$peek = $stream->peek(); $peek = $stream->peek();
if ($peek == '#') if ($peek == '#') {
{
if ($has_hash) if ($has_hash)
{ {
/* You can't have two hashes /* You can't have two hashes
@ -205,69 +175,50 @@ class Parser
$has_hash = true; $has_hash = true;
continue; continue;
} } elseif ($peek == '.') {
elseif ($peek == '.')
{
$stream->next(); $stream->next();
$result = new Node\ClassNode($result, $stream->next()); $result = new Node\ClassNode($result, $stream->next());
continue; continue;
} } elseif ($peek == '[') {
elseif ($peek == '[')
{
$stream->next(); $stream->next();
$result = $this->parseAttrib($result, $stream); $result = $this->parseAttrib($result, $stream);
$next = $stream->next(); $next = $stream->next();
if ($next != ']') if ($next != ']') {
{
throw new SyntaxError(sprintf("] expected, got '%s'", $next)); throw new SyntaxError(sprintf("] expected, got '%s'", $next));
} }
continue; continue;
} } elseif ($peek == ':' || $peek == '::') {
elseif ($peek == ':' || $peek == '::')
{
$type = $stream->next(); $type = $stream->next();
$ident = $stream->next(); $ident = $stream->next();
if (!$ident || !$ident->isType('Symbol')) if (!$ident || !$ident->isType('Symbol')) {
{
throw new SyntaxError(sprintf("Expected symbol, got '%s'", $ident)); throw new SyntaxError(sprintf("Expected symbol, got '%s'", $ident));
} }
if ($stream->peek() == '(') if ($stream->peek() == '(') {
{
$stream->next(); $stream->next();
$peek = $stream->peek(); $peek = $stream->peek();
if ($peek->isType('String')) if ($peek->isType('String')) {
{
$selector = $stream->next(); $selector = $stream->next();
} } elseif ($peek->isType('Symbol') && is_int($peek)) {
elseif ($peek->isType('Symbol') && is_int($peek))
{
$selector = intval($stream->next()); $selector = intval($stream->next());
} } else {
else
{
// FIXME: parseSimpleSelector, or selector, or...? // FIXME: parseSimpleSelector, or selector, or...?
$selector = $this->parseSimpleSelector($stream); $selector = $this->parseSimpleSelector($stream);
} }
$next = $stream->next(); $next = $stream->next();
if ($next != ')') if ($next != ')') {
{
throw new SyntaxError(sprintf("Expected ')', got '%s' and '%s'", $next, $selector)); throw new SyntaxError(sprintf("Expected ')', got '%s' and '%s'", $next, $selector));
} }
$result = new Node\FunctionNode($result, $type, $ident, $selector); $result = new Node\FunctionNode($result, $type, $ident, $selector);
} } else {
else
{
$result = new Node\PseudoNode($result, $type, $ident); $result = new Node\PseudoNode($result, $type, $ident);
} }
continue; continue;
} } else {
else
{
if ($peek == ' ') if ($peek == ' ')
{ {
$stream->next(); $stream->next();
@ -287,31 +238,25 @@ class Parser
protected function parseAttrib($selector, $stream) protected function parseAttrib($selector, $stream)
{ {
$attrib = $stream->next(); $attrib = $stream->next();
if ($stream->peek() == '|') if ($stream->peek() == '|') {
{
$namespace = $attrib; $namespace = $attrib;
$stream->next(); $stream->next();
$attrib = $stream->next(); $attrib = $stream->next();
} } else {
else
{
$namespace = '*'; $namespace = '*';
} }
if ($stream->peek() == ']') if ($stream->peek() == ']') {
{
return new Node\AttribNode($selector, $namespace, $attrib, 'exists', null); return new Node\AttribNode($selector, $namespace, $attrib, 'exists', null);
} }
$op = $stream->next(); $op = $stream->next();
if (!in_array($op, array('^=', '$=', '*=', '=', '~=', '|=', '!='))) if (!in_array($op, array('^=', '$=', '*=', '=', '~=', '|=', '!='))) {
{
throw new SyntaxError(sprintf("Operator expected, got '%s'", $op)); throw new SyntaxError(sprintf("Operator expected, got '%s'", $op));
} }
$value = $stream->next(); $value = $stream->next();
if (!$value->isType('Symbol') && !$value->isType('String')) if (!$value->isType('Symbol') && !$value->isType('String')) {
{
throw new SyntaxError(sprintf("Expected string or symbol, got '%s'", $value)); throw new SyntaxError(sprintf("Expected string or symbol, got '%s'", $value));
} }

View File

@ -45,16 +45,14 @@ class TokenStream
public function next() public function next()
{ {
if ($this->peeking) if ($this->peeking) {
{
$this->peeking = false; $this->peeking = false;
$this->used[] = $this->peeked; $this->used[] = $this->peeked;
return $this->peeked; return $this->peeked;
} }
if (!count($this->tokens)) if (!count($this->tokens)) {
{
return null; return null;
} }
@ -66,8 +64,7 @@ class TokenStream
public function peek() public function peek()
{ {
if (!$this->peeking) if (!$this->peeking) {
{
if (!count($this->tokens)) if (!count($this->tokens))
{ {
return null; return null;

View File

@ -25,8 +25,7 @@ class Tokenizer
{ {
public function tokenize($s) public function tokenize($s)
{ {
if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
{
$mbEncoding = mb_internal_encoding(); $mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII'); mb_internal_encoding('ASCII');
} }
@ -35,20 +34,16 @@ class Tokenizer
$pos = 0; $pos = 0;
$s = preg_replace('#/\*.*?\*/#s', '', $s); $s = preg_replace('#/\*.*?\*/#s', '', $s);
while (1) while (1) {
{
if (preg_match('#\s+#A', $s, $match, 0, $pos)) if (preg_match('#\s+#A', $s, $match, 0, $pos))
{ {
$preceding_whitespace_pos = $pos; $preceding_whitespace_pos = $pos;
$pos += strlen($match[0]); $pos += strlen($match[0]);
} } else {
else
{
$preceding_whitespace_pos = 0; $preceding_whitespace_pos = 0;
} }
if ($pos >= strlen($s)) if ($pos >= strlen($s)) {
{
if (isset($mbEncoding)) if (isset($mbEncoding))
{ {
mb_internal_encoding($mbEncoding); mb_internal_encoding($mbEncoding);
@ -57,8 +52,7 @@ class Tokenizer
return $tokens; return $tokens;
} }
if (preg_match('#[+-]?\d*n(?:[+-]\d+)?#A', $s, $match, 0, $pos) && 'n' !== $match[0]) if (preg_match('#[+-]?\d*n(?:[+-]\d+)?#A', $s, $match, 0, $pos) && 'n' !== $match[0]) {
{
$sym = substr($s, $pos, strlen($match[0])); $sym = substr($s, $pos, strlen($match[0]));
$tokens[] = new Token('Symbol', $sym, $pos); $tokens[] = new Token('Symbol', $sym, $pos);
$pos += strlen($match[0]); $pos += strlen($match[0]);
@ -68,16 +62,14 @@ class Tokenizer
$c = $s[$pos]; $c = $s[$pos];
$c2 = substr($s, $pos, 2); $c2 = substr($s, $pos, 2);
if (in_array($c2, array('~=', '|=', '^=', '$=', '*=', '::', '!='))) if (in_array($c2, array('~=', '|=', '^=', '$=', '*=', '::', '!='))) {
{
$tokens[] = new Token('Token', $c2, $pos); $tokens[] = new Token('Token', $c2, $pos);
$pos += 2; $pos += 2;
continue; continue;
} }
if (in_array($c, array('>', '+', '~', ',', '.', '*', '=', '[', ']', '(', ')', '|', ':', '#'))) if (in_array($c, array('>', '+', '~', ',', '.', '*', '=', '[', ']', '(', ')', '|', ':', '#'))) {
{
if (in_array($c, array('.', '#', '[')) && $preceding_whitespace_pos > 0) if (in_array($c, array('.', '#', '[')) && $preceding_whitespace_pos > 0)
{ {
$tokens[] = new Token('Token', ' ', $preceding_whitespace_pos); $tokens[] = new Token('Token', ' ', $preceding_whitespace_pos);
@ -88,8 +80,7 @@ class Tokenizer
continue; continue;
} }
if ($c === '"' || $c === "'") if ($c === '"' || $c === "'") {
{
// Quoted string // Quoted string
$old_pos = $pos; $old_pos = $pos;
list($sym, $pos) = $this->tokenizeEscapedString($s, $pos); list($sym, $pos) = $this->tokenizeEscapedString($s, $pos);
@ -117,24 +108,20 @@ class Tokenizer
$pos = $pos + 1; $pos = $pos + 1;
$start = $pos; $start = $pos;
while (1) while (1) {
{
$next = strpos($s, $quote, $pos); $next = strpos($s, $quote, $pos);
if (false === $next) if (false === $next) {
{
throw new SyntaxError(sprintf('Expected closing %s for string in: %s', $quote, substr($s, $start))); throw new SyntaxError(sprintf('Expected closing %s for string in: %s', $quote, substr($s, $start)));
} }
$result = substr($s, $start, $next - $start); $result = substr($s, $start, $next - $start);
if ('\\' === $result[strlen($result) - 1]) if ('\\' === $result[strlen($result) - 1]) {
{
// next quote character is escaped // next quote character is escaped
$pos = $next + 1; $pos = $next + 1;
$continue; $continue;
} }
if (false !== strpos($result, '\\')) if (false !== strpos($result, '\\')) {
{
$result = $this->unescapeStringLiteral($result); $result = $this->unescapeStringLiteral($result);
} }
@ -149,16 +136,12 @@ class Tokenizer
{ {
return preg_replace_callback('#(\\\\(?:[A-Fa-f0-9]{1,6}(?:\r\n|\s)?|[^A-Fa-f0-9]))#', function ($matches) use ($literal) return preg_replace_callback('#(\\\\(?:[A-Fa-f0-9]{1,6}(?:\r\n|\s)?|[^A-Fa-f0-9]))#', function ($matches) use ($literal)
{ {
if ($matches[0][0] == '\\' && strlen($matches[0]) > 1) if ($matches[0][0] == '\\' && strlen($matches[0]) > 1) {
{
$matches[0] = substr($matches[0], 1); $matches[0] = substr($matches[0], 1);
if (in_array($matches[0][0], array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'))) if (in_array($matches[0][0], array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'))) {
{
return chr(trim($matches[0])); return chr(trim($matches[0]));
} }
} } else {
else
{
throw new SyntaxError(sprintf('Invalid escape sequence %s in string %s', $matches[0], $literal)); throw new SyntaxError(sprintf('Invalid escape sequence %s in string %s', $matches[0], $literal));
} }
}, $literal); }, $literal);
@ -171,16 +154,14 @@ class Tokenizer
{ {
$start = $pos; $start = $pos;
if (!preg_match('#[^\w\-]#', $s, $match, PREG_OFFSET_CAPTURE, $pos)) if (!preg_match('#[^\w\-]#', $s, $match, PREG_OFFSET_CAPTURE, $pos)) {
{
// Goes to end of s // Goes to end of s
return array(substr($s, $start), strlen($s)); return array(substr($s, $start), strlen($s));
} }
$matchStart = $match[0][1]; $matchStart = $match[0][1];
if ($matchStart == $pos) if ($matchStart == $pos) {
{
throw new SyntaxError(sprintf('Unexpected symbol: %s at %s', $s[$pos], $pos)); throw new SyntaxError(sprintf('Unexpected symbol: %s at %s', $s[$pos], $pos));
} }

View File

@ -66,20 +66,17 @@ class XPathExpr
public function __toString() public function __toString()
{ {
$path = ''; $path = '';
if (null !== $this->prefix) if (null !== $this->prefix) {
{
$path .= $this->prefix; $path .= $this->prefix;
} }
if (null !== $this->path) if (null !== $this->path) {
{
$path .= $this->path; $path .= $this->path;
} }
$path .= $this->element; $path .= $this->element;
if ($this->condition) if ($this->condition) {
{
$path .= sprintf('[%s]', $this->condition); $path .= sprintf('[%s]', $this->condition);
} }
@ -88,32 +85,25 @@ class XPathExpr
public function addCondition($condition) public function addCondition($condition)
{ {
if ($this->condition) if ($this->condition) {
{
$this->condition = sprintf('%s and (%s)', $this->condition, $condition); $this->condition = sprintf('%s and (%s)', $this->condition, $condition);
} } else {
else
{
$this->condition = $condition; $this->condition = $condition;
} }
} }
public function addPrefix($prefix) public function addPrefix($prefix)
{ {
if ($this->prefix) if ($this->prefix) {
{
$this->prefix = $prefix.$this->prefix; $this->prefix = $prefix.$this->prefix;
} } else {
else
{
$this->prefix = $prefix; $this->prefix = $prefix;
} }
} }
public function addNameTest() public function addNameTest()
{ {
if ($this->element == '*') if ($this->element == '*') {
{
// We weren't doing a test anyway // We weren't doing a test anyway
return; return;
} }
@ -128,12 +118,9 @@ class XPathExpr
Adds a /* prefix if there is no prefix. This is when you need Adds a /* prefix if there is no prefix. This is when you need
to keep context's constrained to a single parent. to keep context's constrained to a single parent.
*/ */
if ($this->path) if ($this->path) {
{
$this->path .= '*/'; $this->path .= '*/';
} } else {
else
{
$this->path = '*/'; $this->path = '*/';
} }
@ -149,8 +136,7 @@ class XPathExpr
/* We don't need a star prefix if we are joining to this other /* We don't need a star prefix if we are joining to this other
prefix; so we'll get rid of it */ prefix; so we'll get rid of it */
if ($other->hasStarPrefix() && $path == '*/') if ($other->hasStarPrefix() && $path == '*/') {
{
$path = ''; $path = '';
} }
$this->prefix = $prefix; $this->prefix = $prefix;
@ -161,38 +147,30 @@ class XPathExpr
static public function xpathLiteral($s) static public function xpathLiteral($s)
{ {
if ($s instanceof Node\ElementNode) if ($s instanceof Node\ElementNode) {
{
// This is probably a symbol that looks like an expression... // This is probably a symbol that looks like an expression...
$s = $s->formatElement(); $s = $s->formatElement();
} } else {
else
{
$s = (string) $s; $s = (string) $s;
} }
if (false === strpos($s, "'")) if (false === strpos($s, "'")) {
{
return sprintf("'%s'", $s); return sprintf("'%s'", $s);
} }
if (false === strpos($s, '"')) if (false === strpos($s, '"')) {
{
return sprintf('"%s"', $s); return sprintf('"%s"', $s);
} }
$string = $s; $string = $s;
$parts = array(); $parts = array();
while (true) while (true) {
{
if (false !== $pos = strpos($string, "'")) if (false !== $pos = strpos($string, "'"))
{ {
$parts[] = sprintf("'%s'", substr($string, 0, $pos)); $parts[] = sprintf("'%s'", substr($string, 0, $pos));
$parts[] = "\"'\""; $parts[] = "\"'\"";
$string = substr($string, $pos + 1); $string = substr($string, $pos + 1);
} } else {
else
{
$parts[] = "'$string'"; $parts[] = "'$string'";
break; break;
} }

View File

@ -36,8 +36,7 @@ class XPathExprOr extends XPathExpr
$prefix = $this->prefix; $prefix = $this->prefix;
$tmp = array(); $tmp = array();
foreach ($this->items as $i) foreach ($this->items as $i) {
{
$tmp[] = sprintf('%s%s', $prefix, $i); $tmp[] = sprintf('%s%s', $prefix, $i);
} }

View File

@ -65,28 +65,21 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function getService($id, $invalidBehavior = Container::EXCEPTION_ON_INVALID_REFERENCE) public function getService($id, $invalidBehavior = Container::EXCEPTION_ON_INVALID_REFERENCE)
{ {
try try {
{
return parent::getService($id, Container::EXCEPTION_ON_INVALID_REFERENCE); return parent::getService($id, Container::EXCEPTION_ON_INVALID_REFERENCE);
} } catch (\InvalidArgumentException $e) {
catch (\InvalidArgumentException $e)
{
if (isset($this->loading[$id])) if (isset($this->loading[$id]))
{ {
throw new \LogicException(sprintf('The service "%s" has a circular reference to itself.', $id)); throw new \LogicException(sprintf('The service "%s" has a circular reference to itself.', $id));
} }
if (!$this->hasDefinition($id) && isset($this->aliases[$id])) if (!$this->hasDefinition($id) && isset($this->aliases[$id])) {
{
return $this->getService($this->aliases[$id]); return $this->getService($this->aliases[$id]);
} }
try try {
{
$definition = $this->getDefinition($id); $definition = $this->getDefinition($id);
} } catch (\InvalidArgumentException $e) {
catch (\InvalidArgumentException $e)
{
if (Container::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) if (Container::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior)
{ {
return null; return null;
@ -125,8 +118,7 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function merge(BuilderConfiguration $configuration = null) public function merge(BuilderConfiguration $configuration = null)
{ {
if (null === $configuration) if (null === $configuration) {
{
return; return;
} }
@ -134,14 +126,12 @@ class Builder extends Container implements AnnotatedContainerInterface
$this->addAliases($configuration->getAliases()); $this->addAliases($configuration->getAliases());
$currentParameters = $this->getParameters(); $currentParameters = $this->getParameters();
foreach ($configuration->getParameters() as $key => $value) foreach ($configuration->getParameters() as $key => $value) {
{
$this->setParameter($key, $value); $this->setParameter($key, $value);
} }
$this->addParameters($currentParameters); $this->addParameters($currentParameters);
foreach ($this->parameters as $key => $value) foreach ($this->parameters as $key => $value) {
{
$this->parameters[$key] = self::resolveValue($value, $this->parameters); $this->parameters[$key] = self::resolveValue($value, $this->parameters);
} }
} }
@ -163,8 +153,7 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function addAliases(array $aliases) public function addAliases(array $aliases)
{ {
foreach ($aliases as $alias => $id) foreach ($aliases as $alias => $id) {
{
$this->setAlias($alias, $id); $this->setAlias($alias, $id);
} }
} }
@ -226,8 +215,7 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function getAlias($id) public function getAlias($id)
{ {
if (!$this->hasAlias($id)) if (!$this->hasAlias($id)) {
{
throw new \InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id)); throw new \InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
} }
@ -257,8 +245,7 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function addDefinitions(array $definitions) public function addDefinitions(array $definitions)
{ {
foreach ($definitions as $id => $definition) foreach ($definitions as $id => $definition) {
{
$this->setDefinition($id, $definition); $this->setDefinition($id, $definition);
} }
} }
@ -320,8 +307,7 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function getDefinition($id) public function getDefinition($id)
{ {
if (!$this->hasDefinition($id)) if (!$this->hasDefinition($id)) {
{
throw new \InvalidArgumentException(sprintf('The service definition "%s" does not exist.', $id)); throw new \InvalidArgumentException(sprintf('The service definition "%s" does not exist.', $id));
} }
@ -340,8 +326,7 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
protected function createService(Definition $definition, $id) protected function createService(Definition $definition, $id)
{ {
if (null !== $definition->getFile()) if (null !== $definition->getFile()) {
{
require_once self::resolveValue($definition->getFile(), $this->parameters); require_once self::resolveValue($definition->getFile(), $this->parameters);
} }
@ -349,27 +334,21 @@ class Builder extends Container implements AnnotatedContainerInterface
$arguments = $this->resolveServices(self::resolveValue($definition->getArguments(), $this->parameters)); $arguments = $this->resolveServices(self::resolveValue($definition->getArguments(), $this->parameters));
if (null !== $definition->getConstructor()) if (null !== $definition->getConstructor()) {
{
$service = call_user_func_array(array(self::resolveValue($definition->getClass(), $this->parameters), $definition->getConstructor()), $arguments); $service = call_user_func_array(array(self::resolveValue($definition->getClass(), $this->parameters), $definition->getConstructor()), $arguments);
} } else {
else
{
$service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments); $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
} }
if ($definition->isShared()) if ($definition->isShared()) {
{
$this->services[$id] = $service; $this->services[$id] = $service;
} }
foreach ($definition->getMethodCalls() as $call) foreach ($definition->getMethodCalls() as $call) {
{
$services = self::getServiceConditionals($call[1]); $services = self::getServiceConditionals($call[1]);
$ok = true; $ok = true;
foreach ($services as $s) foreach ($services as $s) {
{
if (!$this->hasService($s)) if (!$this->hasService($s))
{ {
$ok = false; $ok = false;
@ -377,25 +356,20 @@ class Builder extends Container implements AnnotatedContainerInterface
} }
} }
if ($ok) if ($ok) {
{
call_user_func_array(array($service, $call[0]), $this->resolveServices(self::resolveValue($call[1], $this->parameters))); call_user_func_array(array($service, $call[0]), $this->resolveServices(self::resolveValue($call[1], $this->parameters)));
} }
} }
if ($callable = $definition->getConfigurator()) if ($callable = $definition->getConfigurator()) {
{
if (is_array($callable) && is_object($callable[0]) && $callable[0] instanceof Reference) if (is_array($callable) && is_object($callable[0]) && $callable[0] instanceof Reference)
{ {
$callable[0] = $this->getService((string) $callable[0]); $callable[0] = $this->getService((string) $callable[0]);
} } elseif (is_array($callable)) {
elseif (is_array($callable))
{
$callable[0] = self::resolveValue($callable[0], $this->parameters); $callable[0] = self::resolveValue($callable[0], $this->parameters);
} }
if (!is_callable($callable)) if (!is_callable($callable)) {
{
throw new \InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service))); throw new \InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service)));
} }
@ -416,35 +390,27 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
static public function resolveValue($value, $parameters) static public function resolveValue($value, $parameters)
{ {
if (is_array($value)) if (is_array($value)) {
{
$args = array(); $args = array();
foreach ($value as $k => $v) foreach ($value as $k => $v) {
{
$args[self::resolveValue($k, $parameters)] = self::resolveValue($v, $parameters); $args[self::resolveValue($k, $parameters)] = self::resolveValue($v, $parameters);
} }
$value = $args; $value = $args;
} } else if (is_string($value)) {
else if (is_string($value))
{
if (preg_match('/^%([^%]+)%$/', $value, $match)) if (preg_match('/^%([^%]+)%$/', $value, $match))
{ {
// we do this to deal with non string values (boolean, integer, ...) // we do this to deal with non string values (boolean, integer, ...)
// the preg_replace_callback converts them to strings // the preg_replace_callback converts them to strings
if (!array_key_exists($name = strtolower($match[1]), $parameters)) if (!array_key_exists($name = strtolower($match[1]), $parameters)) {
{
throw new \RuntimeException(sprintf('The parameter "%s" must be defined.', $name)); throw new \RuntimeException(sprintf('The parameter "%s" must be defined.', $name));
} }
$value = $parameters[$name]; $value = $parameters[$name];
} } else {
else
{
$replaceParameter = function ($match) use ($parameters, $value) $replaceParameter = function ($match) use ($parameters, $value)
{ {
if (!array_key_exists($name = strtolower($match[2]), $parameters)) if (!array_key_exists($name = strtolower($match[2]), $parameters)) {
{
throw new \RuntimeException(sprintf('The parameter "%s" must be defined (used in the following expression: "%s").', $name, $value)); throw new \RuntimeException(sprintf('The parameter "%s" must be defined (used in the following expression: "%s").', $name, $value));
} }
@ -467,15 +433,12 @@ class Builder extends Container implements AnnotatedContainerInterface
*/ */
public function resolveServices($value) public function resolveServices($value)
{ {
if (is_array($value)) if (is_array($value)) {
{
foreach ($value as &$v) foreach ($value as &$v)
{ {
$v = $this->resolveServices($v); $v = $this->resolveServices($v);
} }
} } else if (is_object($value) && $value instanceof Reference) {
else if (is_object($value) && $value instanceof Reference)
{
$value = $this->getService((string) $value, $value->getInvalidBehavior()); $value = $this->getService((string) $value, $value->getInvalidBehavior());
} }
@ -492,8 +455,7 @@ class Builder extends Container implements AnnotatedContainerInterface
public function findAnnotatedServiceIds($name) public function findAnnotatedServiceIds($name)
{ {
$annotations = array(); $annotations = array();
foreach ($this->getDefinitions() as $id => $definition) foreach ($this->getDefinitions() as $id => $definition) {
{
if ($definition->getAnnotation($name)) if ($definition->getAnnotation($name))
{ {
$annotations[$id] = $definition->getAnnotation($name); $annotations[$id] = $definition->getAnnotation($name);
@ -507,15 +469,12 @@ class Builder extends Container implements AnnotatedContainerInterface
{ {
$services = array(); $services = array();
if (is_array($value)) if (is_array($value)) {
{
foreach ($value as $v) foreach ($value as $v)
{ {
$services = array_unique(array_merge($services, self::getServiceConditionals($v))); $services = array_unique(array_merge($services, self::getServiceConditionals($v)));
} }
} } elseif (is_object($value) && $value instanceof Reference && $value->getInvalidBehavior() === Container::IGNORE_ON_INVALID_REFERENCE) {
elseif (is_object($value) && $value instanceof Reference && $value->getInvalidBehavior() === Container::IGNORE_ON_INVALID_REFERENCE)
{
$services[] = (string) $value; $services[] = (string) $value;
} }

View File

@ -66,8 +66,7 @@ class BuilderConfiguration
*/ */
public function merge(BuilderConfiguration $configuration = null) public function merge(BuilderConfiguration $configuration = null)
{ {
if (null === $configuration) if (null === $configuration) {
{
return; return;
} }
@ -75,8 +74,7 @@ class BuilderConfiguration
$this->addAliases($configuration->getAliases()); $this->addAliases($configuration->getAliases());
$this->addParameters($configuration->getParameters()); $this->addParameters($configuration->getParameters());
foreach ($configuration->getResources() as $resource) foreach ($configuration->getResources() as $resource) {
{
$this->addResource($resource); $this->addResource($resource);
} }
@ -112,8 +110,7 @@ class BuilderConfiguration
public function setParameters(array $parameters) public function setParameters(array $parameters)
{ {
$this->parameters = array(); $this->parameters = array();
foreach ($parameters as $key => $value) foreach ($parameters as $key => $value) {
{
$this->parameters[strtolower($key)] = $value; $this->parameters[strtolower($key)] = $value;
} }
@ -167,8 +164,7 @@ class BuilderConfiguration
*/ */
public function getParameter($name) public function getParameter($name)
{ {
if (!$this->hasParameter($name)) if (!$this->hasParameter($name)) {
{
throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
} }
@ -216,8 +212,7 @@ class BuilderConfiguration
*/ */
public function addAliases(array $aliases) public function addAliases(array $aliases)
{ {
foreach ($aliases as $alias => $id) foreach ($aliases as $alias => $id) {
{
$this->setAlias($alias, $id); $this->setAlias($alias, $id);
} }
@ -257,8 +252,7 @@ class BuilderConfiguration
*/ */
public function getAlias($alias) public function getAlias($alias)
{ {
if (!$this->hasAlias($alias)) if (!$this->hasAlias($alias)) {
{
throw new \InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $alias)); throw new \InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $alias));
} }
@ -291,8 +285,7 @@ class BuilderConfiguration
*/ */
public function addDefinitions(array $definitions) public function addDefinitions(array $definitions)
{ {
foreach ($definitions as $id => $definition) foreach ($definitions as $id => $definition) {
{
$this->setDefinition($id, $definition); $this->setDefinition($id, $definition);
} }
@ -347,8 +340,7 @@ class BuilderConfiguration
*/ */
public function getDefinition($id) public function getDefinition($id)
{ {
if (!$this->hasDefinition($id)) if (!$this->hasDefinition($id)) {
{
throw new \InvalidArgumentException(sprintf('The service definition "%s" does not exist.', $id)); throw new \InvalidArgumentException(sprintf('The service definition "%s" does not exist.', $id));
} }
@ -368,8 +360,7 @@ class BuilderConfiguration
*/ */
public function findDefinition($id) public function findDefinition($id)
{ {
if ($this->hasAlias($id)) if ($this->hasAlias($id)) {
{
return $this->findDefinition($this->getAlias($id)); return $this->findDefinition($this->getAlias($id));
} }

View File

@ -78,8 +78,7 @@ class Container implements ContainerInterface, \ArrayAccess
public function setParameters(array $parameters) public function setParameters(array $parameters)
{ {
$this->parameters = array(); $this->parameters = array();
foreach ($parameters as $key => $value) foreach ($parameters as $key => $value) {
{
$this->parameters[strtolower($key)] = $value; $this->parameters[strtolower($key)] = $value;
} }
} }
@ -117,8 +116,7 @@ class Container implements ContainerInterface, \ArrayAccess
{ {
$name = strtolower($name); $name = strtolower($name);
if (!array_key_exists($name, $this->parameters)) if (!array_key_exists($name, $this->parameters)) {
{
throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
} }
@ -188,27 +186,21 @@ class Container implements ContainerInterface, \ArrayAccess
*/ */
public function getService($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE) public function getService($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
{ {
if (!is_string($id)) if (!is_string($id)) {
{
throw new \InvalidArgumentException(sprintf('A service id should be a string (%s given).', str_replace("\n", '', var_export($id, true)))); throw new \InvalidArgumentException(sprintf('A service id should be a string (%s given).', str_replace("\n", '', var_export($id, true))));
} }
if (isset($this->services[$id])) if (isset($this->services[$id])) {
{
return $this->services[$id]; return $this->services[$id];
} }
if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service') && 'getService' !== $method) if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service') && 'getService' !== $method) {
{
return $this->$method(); return $this->$method();
} }
if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
{
throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $id)); throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $id));
} } else {
else
{
return null; return null;
} }
} }
@ -222,8 +214,7 @@ class Container implements ContainerInterface, \ArrayAccess
{ {
$ids = array(); $ids = array();
$r = new \ReflectionClass($this); $r = new \ReflectionClass($this);
foreach ($r->getMethods() as $method) foreach ($r->getMethods() as $method) {
{
if (preg_match('/^get(.+)Service$/', $name = $method->getName(), $match)) if (preg_match('/^get(.+)Service$/', $name = $method->getName(), $match))
{ {
$ids[] = self::underscore($match[1]); $ids[] = self::underscore($match[1]);
@ -337,8 +328,7 @@ class Container implements ContainerInterface, \ArrayAccess
*/ */
public function __call($method, $arguments) public function __call($method, $arguments)
{ {
if (!preg_match('/^get(.+)Service$/', $method, $match)) if (!preg_match('/^get(.+)Service$/', $method, $match)) {
{
throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s.', get_class($this), $method)); throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
} }

View File

@ -140,8 +140,7 @@ class Definition
public function setMethodCalls(array $calls = array()) public function setMethodCalls(array $calls = array())
{ {
$this->calls = array(); $this->calls = array();
foreach ($calls as $call) foreach ($calls as $call) {
{
$this->addMethodCall($call[0], $call[1]); $this->addMethodCall($call[0], $call[1]);
} }
@ -192,8 +191,7 @@ class Definition
*/ */
public function getAnnotation($name) public function getAnnotation($name)
{ {
if (!isset($this->annotations[$name])) if (!isset($this->annotations[$name])) {
{
$this->annotations[$name] = array(); $this->annotations[$name] = array();
} }
@ -210,8 +208,7 @@ class Definition
*/ */
public function addAnnotation($name, array $attributes = array()) public function addAnnotation($name, array $attributes = array())
{ {
if (!isset($this->annotations[$name])) if (!isset($this->annotations[$name])) {
{
$this->annotations[$name] = array(); $this->annotations[$name] = array();
} }

View File

@ -59,8 +59,7 @@ class GraphvizDumper extends Dumper
'node.missing' => array('fillcolor' => '#ff9999', 'style' => 'filled'), 'node.missing' => array('fillcolor' => '#ff9999', 'style' => 'filled'),
); );
foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) {
{
if (isset($options[$key])) if (isset($options[$key]))
{ {
$this->options[$key] = array_merge($this->options[$key], $options[$key]); $this->options[$key] = array_merge($this->options[$key], $options[$key]);
@ -70,12 +69,10 @@ class GraphvizDumper extends Dumper
$this->nodes = $this->findNodes(); $this->nodes = $this->findNodes();
$this->edges = array(); $this->edges = array();
foreach ($this->container->getDefinitions() as $id => $definition) foreach ($this->container->getDefinitions() as $id => $definition) {
{
$this->edges[$id] = $this->findEdges($id, $definition->getArguments(), true, ''); $this->edges[$id] = $this->findEdges($id, $definition->getArguments(), true, '');
foreach ($definition->getMethodCalls() as $call) foreach ($definition->getMethodCalls() as $call) {
{
$this->edges[$id] = array_merge( $this->edges[$id] = array_merge(
$this->edges[$id], $this->edges[$id],
$this->findEdges($id, $call[1], false, $call[0].'()') $this->findEdges($id, $call[1], false, $call[0].'()')
@ -89,8 +86,7 @@ class GraphvizDumper extends Dumper
protected function addNodes() protected function addNodes()
{ {
$code = ''; $code = '';
foreach ($this->nodes as $id => $node) foreach ($this->nodes as $id => $node) {
{
$aliases = $this->getAliases($id); $aliases = $this->getAliases($id);
$code .= sprintf(" node_%s [label=\"%s\\n%s\\n\", shape=%s%s];\n", $this->dotize($id), $id.($aliases ? ' ('.implode(', ', $aliases).')' : ''), $node['class'], $this->options['node']['shape'], $this->addAttributes($node['attributes'])); $code .= sprintf(" node_%s [label=\"%s\\n%s\\n\", shape=%s%s];\n", $this->dotize($id), $id.($aliases ? ' ('.implode(', ', $aliases).')' : ''), $node['class'], $this->options['node']['shape'], $this->addAttributes($node['attributes']));
@ -102,8 +98,7 @@ class GraphvizDumper extends Dumper
protected function addEdges() protected function addEdges()
{ {
$code = ''; $code = '';
foreach ($this->edges as $id => $edges) foreach ($this->edges as $id => $edges) {
{
foreach ($edges as $edge) foreach ($edges as $edge)
{ {
$code .= sprintf(" node_%s -> node_%s [label=\"%s\" style=\"%s\"];\n", $this->dotize($id), $this->dotize($edge['to']), $edge['name'], $edge['required'] ? 'filled' : 'dashed'); $code .= sprintf(" node_%s -> node_%s [label=\"%s\" style=\"%s\"];\n", $this->dotize($id), $this->dotize($edge['to']), $edge['name'], $edge['required'] ? 'filled' : 'dashed');
@ -116,28 +111,22 @@ class GraphvizDumper extends Dumper
protected function findEdges($id, $arguments, $required, $name) protected function findEdges($id, $arguments, $required, $name)
{ {
$edges = array(); $edges = array();
foreach ($arguments as $argument) foreach ($arguments as $argument) {
{
if (is_object($argument) && $argument instanceof Parameter) if (is_object($argument) && $argument instanceof Parameter)
{ {
$argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null; $argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null;
} } elseif (is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) {
elseif (is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match))
{
$argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null; $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null;
} }
if ($argument instanceof Reference) if ($argument instanceof Reference) {
{
if (!$this->container->hasService((string) $argument)) if (!$this->container->hasService((string) $argument))
{ {
$this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']); $this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']);
} }
$edges[] = array('name' => $name, 'required' => $required, 'to' => $argument); $edges[] = array('name' => $name, 'required' => $required, 'to' => $argument);
} } elseif (is_array($argument)) {
elseif (is_array($argument))
{
$edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name)); $edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name));
} }
} }
@ -151,24 +140,20 @@ class GraphvizDumper extends Dumper
$container = clone $this->container; $container = clone $this->container;
foreach ($container->getDefinitions() as $id => $definition) foreach ($container->getDefinitions() as $id => $definition) {
{
$nodes[$id] = array('class' => str_replace('\\', '\\\\', $this->getValue($definition->getClass())), 'attributes' => array_merge($this->options['node.definition'], array('style' => $definition->isShared() ? 'filled' : 'dotted'))); $nodes[$id] = array('class' => str_replace('\\', '\\\\', $this->getValue($definition->getClass())), 'attributes' => array_merge($this->options['node.definition'], array('style' => $definition->isShared() ? 'filled' : 'dotted')));
$container->setDefinition($id, new Definition('stdClass')); $container->setDefinition($id, new Definition('stdClass'));
} }
foreach ($container->getServiceIds() as $id) foreach ($container->getServiceIds() as $id) {
{
$service = $container->getService($id); $service = $container->getService($id);
if (in_array($id, array_keys($container->getAliases()))) if (in_array($id, array_keys($container->getAliases()))) {
{
continue; continue;
} }
if (!$container->hasDefinition($id)) if (!$container->hasDefinition($id)) {
{
$nodes[$id] = array('class' => str_replace('\\', '\\\\', get_class($service)), 'attributes' => $this->options['node.instance']); $nodes[$id] = array('class' => str_replace('\\', '\\\\', get_class($service)), 'attributes' => $this->options['node.instance']);
} }
} }
@ -200,8 +185,7 @@ class GraphvizDumper extends Dumper
protected function addAttributes($attributes) protected function addAttributes($attributes)
{ {
$code = array(); $code = array();
foreach ($attributes as $k => $v) foreach ($attributes as $k => $v) {
{
$code[] = sprintf('%s="%s"', $k, $v); $code[] = sprintf('%s="%s"', $k, $v);
} }
@ -211,8 +195,7 @@ class GraphvizDumper extends Dumper
protected function addOptions($options) protected function addOptions($options)
{ {
$code = array(); $code = array();
foreach ($options as $k => $v) foreach ($options as $k => $v) {
{
$code[] = sprintf('%s="%s"', $k, $v); $code[] = sprintf('%s="%s"', $k, $v);
} }
@ -227,8 +210,7 @@ class GraphvizDumper extends Dumper
protected function getAliases($id) protected function getAliases($id)
{ {
$aliases = array(); $aliases = array();
foreach ($this->container->getAliases() as $alias => $origin) foreach ($this->container->getAliases() as $alias => $origin) {
{
if ($id == $origin) if ($id == $origin)
{ {
$aliases[] = $alias; $aliases[] = $alias;

View File

@ -56,16 +56,14 @@ class PhpDumper extends Dumper
protected function addServiceInclude($id, $definition) protected function addServiceInclude($id, $definition)
{ {
if (null !== $definition->getFile()) if (null !== $definition->getFile()) {
{
return sprintf(" require_once %s;\n\n", $this->dumpValue($definition->getFile())); return sprintf(" require_once %s;\n\n", $this->dumpValue($definition->getFile()));
} }
} }
protected function addServiceShared($id, $definition) protected function addServiceShared($id, $definition)
{ {
if ($definition->isShared()) if ($definition->isShared()) {
{
return <<<EOF return <<<EOF
if (isset(\$this->shared['$id'])) return \$this->shared['$id']; if (isset(\$this->shared['$id'])) return \$this->shared['$id'];
@ -89,26 +87,19 @@ EOF;
$class = $this->dumpValue($definition->getClass()); $class = $this->dumpValue($definition->getClass());
$arguments = array(); $arguments = array();
foreach ($definition->getArguments() as $value) foreach ($definition->getArguments() as $value) {
{
$arguments[] = $this->dumpValue($value); $arguments[] = $this->dumpValue($value);
} }
if (null !== $definition->getConstructor()) if (null !== $definition->getConstructor()) {
{
$code = sprintf(" \$instance = call_user_func(array(%s, '%s')%s);\n", $class, $definition->getConstructor(), $arguments ? ', '.implode(', ', $arguments) : ''); $code = sprintf(" \$instance = call_user_func(array(%s, '%s')%s);\n", $class, $definition->getConstructor(), $arguments ? ', '.implode(', ', $arguments) : '');
} } elseif ($class != "'".str_replace('\\', '\\\\', $definition->getClass())."'") {
elseif ($class != "'".str_replace('\\', '\\\\', $definition->getClass())."'")
{
$code = sprintf(" \$class = %s;\n \$instance = new \$class(%s);\n", $class, implode(', ', $arguments)); $code = sprintf(" \$class = %s;\n \$instance = new \$class(%s);\n", $class, implode(', ', $arguments));
} } else {
else
{
$code = sprintf(" \$instance = new %s(%s);\n", $definition->getClass(), implode(', ', $arguments)); $code = sprintf(" \$instance = new %s(%s);\n", $definition->getClass(), implode(', ', $arguments));
} }
if ($definition->isShared()) if ($definition->isShared()) {
{
$code .= sprintf(" \$this->shared['$id'] = \$instance;\n"); $code .= sprintf(" \$this->shared['$id'] = \$instance;\n");
} }
@ -118,11 +109,9 @@ EOF;
protected function addServiceMethodCalls($id, $definition) protected function addServiceMethodCalls($id, $definition)
{ {
$calls = ''; $calls = '';
foreach ($definition->getMethodCalls() as $call) foreach ($definition->getMethodCalls() as $call) {
{
$arguments = array(); $arguments = array();
foreach ($call[1] as $value) foreach ($call[1] as $value) {
{
$arguments[] = $this->dumpValue($value); $arguments[] = $this->dumpValue($value);
} }
@ -134,24 +123,18 @@ EOF;
protected function addServiceConfigurator($id, $definition) protected function addServiceConfigurator($id, $definition)
{ {
if (!$callable = $definition->getConfigurator()) if (!$callable = $definition->getConfigurator()) {
{
return ''; return '';
} }
if (is_array($callable)) if (is_array($callable)) {
{
if (is_object($callable[0]) && $callable[0] instanceof Reference) if (is_object($callable[0]) && $callable[0] instanceof Reference)
{ {
return sprintf(" %s->%s(\$instance);\n", $this->getServiceCall((string) $callable[0]), $callable[1]); return sprintf(" %s->%s(\$instance);\n", $this->getServiceCall((string) $callable[0]), $callable[1]);
} } else {
else
{
return sprintf(" call_user_func(array(%s, '%s'), \$instance);\n", $this->dumpValue($callable[0]), $callable[1]); return sprintf(" call_user_func(array(%s, '%s'), \$instance);\n", $this->dumpValue($callable[0]), $callable[1]);
} }
} } else {
else
{
return sprintf(" %s(\$instance);\n", $callable); return sprintf(" %s(\$instance);\n", $callable);
} }
} }
@ -163,8 +146,7 @@ EOF;
$type = 0 === strpos($class, '%') ? 'Object' : $class; $type = 0 === strpos($class, '%') ? 'Object' : $class;
$doc = ''; $doc = '';
if ($definition->isShared()) if ($definition->isShared()) {
{
$doc = <<<EOF $doc = <<<EOF
* *
@ -202,8 +184,7 @@ EOF;
$name = Container::camelize($alias); $name = Container::camelize($alias);
$type = 'Object'; $type = 'Object';
if ($this->container->hasDefinition($id)) if ($this->container->hasDefinition($id)) {
{
$class = $this->container->getDefinition($id)->getClass(); $class = $this->container->getDefinition($id)->getClass();
$type = 0 === strpos($class, '%') ? 'Object' : $class; $type = 0 === strpos($class, '%') ? 'Object' : $class;
} }
@ -226,13 +207,11 @@ EOF;
protected function addServices() protected function addServices()
{ {
$code = ''; $code = '';
foreach ($this->container->getDefinitions() as $id => $definition) foreach ($this->container->getDefinitions() as $id => $definition) {
{
$code .= $this->addService($id, $definition); $code .= $this->addService($id, $definition);
} }
foreach ($this->container->getAliases() as $alias => $id) foreach ($this->container->getAliases() as $alias => $id) {
{
$code .= $this->addServiceAlias($alias, $id); $code .= $this->addServiceAlias($alias, $id);
} }
@ -242,12 +221,10 @@ EOF;
protected function addAnnotations() protected function addAnnotations()
{ {
$annotations = array(); $annotations = array();
foreach ($this->container->getDefinitions() as $id => $definition) foreach ($this->container->getDefinitions() as $id => $definition) {
{
foreach ($definition->getAnnotations() as $name => $ann) foreach ($definition->getAnnotations() as $name => $ann)
{ {
if (!isset($annotations[$name])) if (!isset($annotations[$name])) {
{
$annotations[$name] = array(); $annotations[$name] = array();
} }
@ -278,17 +255,14 @@ EOF;
protected function startClass($class, $baseClass) protected function startClass($class, $baseClass)
{ {
$properties = array(); $properties = array();
foreach ($this->container->getDefinitions() as $id => $definition) foreach ($this->container->getDefinitions() as $id => $definition) {
{
$type = 0 === strpos($definition->getClass(), '%') ? 'Object' : $definition->getClass(); $type = 0 === strpos($definition->getClass(), '%') ? 'Object' : $definition->getClass();
$properties[] = sprintf(' * @property %s $%s', $type, $id); $properties[] = sprintf(' * @property %s $%s', $type, $id);
} }
foreach ($this->container->getAliases() as $alias => $id) foreach ($this->container->getAliases() as $alias => $id) {
{
$type = 'Object'; $type = 'Object';
if ($this->container->hasDefinition($id)) if ($this->container->hasDefinition($id)) {
{
$sclass = $this->container->getDefinition($id)->getClass(); $sclass = $this->container->getDefinition($id)->getClass();
$type = 0 === strpos($sclass, '%') ? 'Object' : $sclass; $type = 0 === strpos($sclass, '%') ? 'Object' : $sclass;
} }
@ -296,8 +270,7 @@ EOF;
$properties[] = sprintf(' * @property %s $%s', $type, $alias); $properties[] = sprintf(' * @property %s $%s', $type, $alias);
} }
$properties = implode("\n", $properties); $properties = implode("\n", $properties);
if ($properties) if ($properties) {
{
$properties = "\n *\n".$properties; $properties = "\n *\n".$properties;
} }
@ -323,8 +296,7 @@ EOF;
protected function addConstructor() protected function addConstructor()
{ {
if (!$this->container->getParameters()) if (!$this->container->getParameters()) {
{
return ''; return '';
} }
@ -345,8 +317,7 @@ EOF;
protected function addDefaultParametersMethod() protected function addDefaultParametersMethod()
{ {
if (!$this->container->getParameters()) if (!$this->container->getParameters()) {
{
return ''; return '';
} }
@ -370,18 +341,13 @@ EOF;
protected function exportParameters($parameters, $indent = 12) protected function exportParameters($parameters, $indent = 12)
{ {
$php = array(); $php = array();
foreach ($parameters as $key => $value) foreach ($parameters as $key => $value) {
{
if (is_array($value)) if (is_array($value))
{ {
$value = $this->exportParameters($value, $indent + 4); $value = $this->exportParameters($value, $indent + 4);
} } elseif ($value instanceof Reference) {
elseif ($value instanceof Reference)
{
throw new \InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service %s found).', $value)); throw new \InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service %s found).', $value));
} } else {
else
{
$value = var_export($value, true); $value = var_export($value, true);
} }
@ -401,53 +367,41 @@ EOF;
protected function wrapServiceConditionals($value, $code) protected function wrapServiceConditionals($value, $code)
{ {
if (!$services = Builder::getServiceConditionals($value)) if (!$services = Builder::getServiceConditionals($value)) {
{
return $code; return $code;
} }
$conditions = array(); $conditions = array();
foreach ($services as $service) foreach ($services as $service) {
{
$conditions[] = sprintf("\$this->hasService('%s')", $service); $conditions[] = sprintf("\$this->hasService('%s')", $service);
} }
// re-indent the wrapped code // re-indent the wrapped code
$code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code))); $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
return sprintf(" if (%s)\n {\n%s }\n", implode(' && ', $conditions), $code); return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code);
} }
protected function dumpValue($value) protected function dumpValue($value)
{ {
if (is_array($value)) if (is_array($value)) {
{
$code = array(); $code = array();
foreach ($value as $k => $v) foreach ($value as $k => $v) {
{
$code[] = sprintf('%s => %s', $this->dumpValue($k), $this->dumpValue($v)); $code[] = sprintf('%s => %s', $this->dumpValue($k), $this->dumpValue($v));
} }
return sprintf('array(%s)', implode(', ', $code)); return sprintf('array(%s)', implode(', ', $code));
} } elseif (is_object($value) && $value instanceof Reference) {
elseif (is_object($value) && $value instanceof Reference)
{
return $this->getServiceCall((string) $value, $value); return $this->getServiceCall((string) $value, $value);
} } elseif (is_object($value) && $value instanceof Parameter) {
elseif (is_object($value) && $value instanceof Parameter)
{
return sprintf("\$this->getParameter('%s')", strtolower($value)); return sprintf("\$this->getParameter('%s')", strtolower($value));
} } elseif (is_string($value)) {
elseif (is_string($value))
{
if (preg_match('/^%([^%]+)%$/', $value, $match)) if (preg_match('/^%([^%]+)%$/', $value, $match))
{ {
// we do this to deal with non string values (boolean, integer, ...) // we do this to deal with non string values (boolean, integer, ...)
// the preg_replace_callback converts them to strings // the preg_replace_callback converts them to strings
return sprintf("\$this->getParameter('%s')", strtolower($match[1])); return sprintf("\$this->getParameter('%s')", strtolower($match[1]));
} } else {
else
{
$replaceParameters = function ($match) $replaceParameters = function ($match)
{ {
return sprintf("'.\$this->getParameter('%s').'", strtolower($match[2])); return sprintf("'.\$this->getParameter('%s').'", strtolower($match[2]));
@ -460,37 +414,28 @@ EOF;
return $code; return $code;
} }
} } elseif (is_object($value) || is_resource($value)) {
elseif (is_object($value) || is_resource($value))
{
throw new \RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); throw new \RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
} } else {
else
{
return var_export($value, true); return var_export($value, true);
} }
} }
protected function getServiceCall($id, Reference $reference = null) protected function getServiceCall($id, Reference $reference = null)
{ {
if ('service_container' === $id) if ('service_container' === $id) {
{
return '$this'; return '$this';
} }
if (null !== $reference && Container::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) if (null !== $reference && Container::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
{
return sprintf('$this->getService(\'%s\', Container::NULL_ON_INVALID_REFERENCE)', $id); return sprintf('$this->getService(\'%s\', Container::NULL_ON_INVALID_REFERENCE)', $id);
} } else {
else
{
if ($this->container->hasAlias($id)) if ($this->container->hasAlias($id))
{ {
$id = $this->container->getAlias($id); $id = $this->container->getAlias($id);
} }
if ($this->container->hasDefinition($id)) if ($this->container->hasDefinition($id)) {
{
return sprintf('$this->get%sService()', Container::camelize($id)); return sprintf('$this->get%sService()', Container::camelize($id));
} }

View File

@ -38,8 +38,7 @@ class XmlDumper extends Dumper
protected function addParameters() protected function addParameters()
{ {
if (!$this->container->getParameters()) if (!$this->container->getParameters()) {
{
return ''; return '';
} }
@ -55,13 +54,11 @@ class XmlDumper extends Dumper
!$definition->isShared() ? ' shared="false"' : '' !$definition->isShared() ? ' shared="false"' : ''
); );
foreach ($definition->getAnnotations() as $name => $annotations) foreach ($definition->getAnnotations() as $name => $annotations) {
{
foreach ($annotations as $attributes) foreach ($annotations as $attributes)
{ {
$att = array(); $att = array();
foreach ($attributes as $key => $value) foreach ($attributes as $key => $value) {
{
$att[] = sprintf('%s="%s"', $key, $value); $att[] = sprintf('%s="%s"', $key, $value);
} }
$att = $att ? ' '.implode(' ', $att) : ''; $att = $att ? ' '.implode(' ', $att) : '';
@ -70,43 +67,32 @@ class XmlDumper extends Dumper
} }
} }
if ($definition->getFile()) if ($definition->getFile()) {
{
$code .= sprintf(" <file>%s</file>\n", $definition->getFile()); $code .= sprintf(" <file>%s</file>\n", $definition->getFile());
} }
if ($definition->getArguments()) if ($definition->getArguments()) {
{
$code .= $this->convertParameters($definition->getArguments(), 'argument', 6); $code .= $this->convertParameters($definition->getArguments(), 'argument', 6);
} }
foreach ($definition->getMethodCalls() as $call) foreach ($definition->getMethodCalls() as $call) {
{
if (count($call[1])) if (count($call[1]))
{ {
$code .= sprintf(" <call method=\"%s\">\n%s </call>\n", $call[0], $this->convertParameters($call[1], 'argument', 8)); $code .= sprintf(" <call method=\"%s\">\n%s </call>\n", $call[0], $this->convertParameters($call[1], 'argument', 8));
} } else {
else
{
$code .= sprintf(" <call method=\"%s\" />\n", $call[0]); $code .= sprintf(" <call method=\"%s\" />\n", $call[0]);
} }
} }
if ($callable = $definition->getConfigurator()) if ($callable = $definition->getConfigurator()) {
{
if (is_array($callable)) if (is_array($callable))
{ {
if (is_object($callable[0]) && $callable[0] instanceof Reference) if (is_object($callable[0]) && $callable[0] instanceof Reference) {
{
$code .= sprintf(" <configurator service=\"%s\" method=\"%s\" />\n", $callable[0], $callable[1]); $code .= sprintf(" <configurator service=\"%s\" method=\"%s\" />\n", $callable[0], $callable[1]);
} } else {
else
{
$code .= sprintf(" <configurator class=\"%s\" method=\"%s\" />\n", $callable[0], $callable[1]); $code .= sprintf(" <configurator class=\"%s\" method=\"%s\" />\n", $callable[0], $callable[1]);
} }
} } else {
else
{
$code .= sprintf(" <configurator function=\"%s\" />\n", $callable); $code .= sprintf(" <configurator function=\"%s\" />\n", $callable);
} }
} }
@ -123,19 +109,16 @@ class XmlDumper extends Dumper
protected function addServices() protected function addServices()
{ {
if (!$this->container->getDefinitions()) if (!$this->container->getDefinitions()) {
{
return ''; return '';
} }
$code = ''; $code = '';
foreach ($this->container->getDefinitions() as $id => $definition) foreach ($this->container->getDefinitions() as $id => $definition) {
{
$code .= $this->addService($id, $definition); $code .= $this->addService($id, $definition);
} }
foreach ($this->container->getAliases() as $alias => $id) foreach ($this->container->getAliases() as $alias => $id) {
{
$code .= $this->addServiceAlias($alias, $id); $code .= $this->addServiceAlias($alias, $id);
} }
@ -147,22 +130,17 @@ class XmlDumper extends Dumper
$white = str_repeat(' ', $depth); $white = str_repeat(' ', $depth);
$xml = ''; $xml = '';
$withKeys = array_keys($parameters) !== range(0, count($parameters) - 1); $withKeys = array_keys($parameters) !== range(0, count($parameters) - 1);
foreach ($parameters as $key => $value) foreach ($parameters as $key => $value) {
{
$attributes = ''; $attributes = '';
$key = $withKeys ? sprintf(' key="%s"', $key) : ''; $key = $withKeys ? sprintf(' key="%s"', $key) : '';
if (is_array($value)) if (is_array($value)) {
{
$value = "\n".$this->convertParameters($value, $type, $depth + 2).$white; $value = "\n".$this->convertParameters($value, $type, $depth + 2).$white;
$attributes = ' type="collection"'; $attributes = ' type="collection"';
} }
if (is_object($value) && $value instanceof Reference) if (is_object($value) && $value instanceof Reference) {
{
$xml .= sprintf("%s<%s%s type=\"service\" id=\"%s\" %s/>\n", $white, $type, $key, (string) $value, $this->getXmlInvalidBehavior($value)); $xml .= sprintf("%s<%s%s type=\"service\" id=\"%s\" %s/>\n", $white, $type, $key, (string) $value, $this->getXmlInvalidBehavior($value));
} } else {
else
{
if (in_array($value, array('null', 'true', 'false'), true)) if (in_array($value, array('null', 'true', 'false'), true))
{ {
$attributes = ' type="string"'; $attributes = ' type="string"';
@ -194,8 +172,7 @@ EOF;
protected function getXmlInvalidBehavior(Reference $reference) protected function getXmlInvalidBehavior(Reference $reference)
{ {
switch ($reference->getInvalidBehavior()) switch ($reference->getInvalidBehavior()) {
{
case Container::NULL_ON_INVALID_REFERENCE: case Container::NULL_ON_INVALID_REFERENCE:
return 'on-invalid="null" '; return 'on-invalid="null" ';
case Container::IGNORE_ON_INVALID_REFERENCE: case Container::IGNORE_ON_INVALID_REFERENCE:
@ -208,18 +185,13 @@ EOF;
protected function escape($arguments) protected function escape($arguments)
{ {
$args = array(); $args = array();
foreach ($arguments as $k => $v) foreach ($arguments as $k => $v) {
{
if (is_array($v)) if (is_array($v))
{ {
$args[$k] = $this->escape($v); $args[$k] = $this->escape($v);
} } elseif (is_string($v)) {
elseif (is_string($v))
{
$args[$k] = str_replace('%', '%%', $v); $args[$k] = str_replace('%', '%%', $v);
} } else {
else
{
$args[$k] = $v; $args[$k] = $v;
} }
} }
@ -232,8 +204,7 @@ EOF;
*/ */
static public function phpToXml($value) static public function phpToXml($value)
{ {
switch (true) switch (true) {
{
case null === $value: case null === $value:
return 'null'; return 'null';
case true === $value: case true === $value:

View File

@ -43,13 +43,11 @@ class YamlDumper extends Dumper
$code .= sprintf(" class: %s\n", $definition->getClass()); $code .= sprintf(" class: %s\n", $definition->getClass());
$annotationsCode = ''; $annotationsCode = '';
foreach ($definition->getAnnotations() as $name => $annotations) foreach ($definition->getAnnotations() as $name => $annotations) {
{
foreach ($annotations as $attributes) foreach ($annotations as $attributes)
{ {
$att = array(); $att = array();
foreach ($attributes as $key => $value) foreach ($attributes as $key => $value) {
{
$att[] = sprintf('%s: %s', Yaml::dump($key), Yaml::dump($value)); $att[] = sprintf('%s: %s', Yaml::dump($key), Yaml::dump($value));
} }
$att = $att ? ', '.implode(' ', $att) : ''; $att = $att ? ', '.implode(' ', $att) : '';
@ -57,46 +55,36 @@ class YamlDumper extends Dumper
$annotationsCode .= sprintf(" - { name: %s%s }\n", Yaml::dump($name), $att); $annotationsCode .= sprintf(" - { name: %s%s }\n", Yaml::dump($name), $att);
} }
} }
if ($annotationsCode) if ($annotationsCode) {
{
$code .= " annotations:\n".$annotationsCode; $code .= " annotations:\n".$annotationsCode;
} }
if ($definition->getFile()) if ($definition->getFile()) {
{
$code .= sprintf(" file: %s\n", $definition->getFile()); $code .= sprintf(" file: %s\n", $definition->getFile());
} }
if ($definition->getConstructor()) if ($definition->getConstructor()) {
{
$code .= sprintf(" constructor: %s\n", $definition->getConstructor()); $code .= sprintf(" constructor: %s\n", $definition->getConstructor());
} }
if ($definition->getArguments()) if ($definition->getArguments()) {
{
$code .= sprintf(" arguments: %s\n", Yaml::dump($this->dumpValue($definition->getArguments()), 0)); $code .= sprintf(" arguments: %s\n", Yaml::dump($this->dumpValue($definition->getArguments()), 0));
} }
if ($definition->getMethodCalls()) if ($definition->getMethodCalls()) {
{
$code .= sprintf(" calls:\n %s\n", str_replace("\n", "\n ", Yaml::dump($this->dumpValue($definition->getMethodCalls()), 1))); $code .= sprintf(" calls:\n %s\n", str_replace("\n", "\n ", Yaml::dump($this->dumpValue($definition->getMethodCalls()), 1)));
} }
if (!$definition->isShared()) if (!$definition->isShared()) {
{
$code .= " shared: false\n"; $code .= " shared: false\n";
} }
if ($callable = $definition->getConfigurator()) if ($callable = $definition->getConfigurator()) {
{
if (is_array($callable)) if (is_array($callable))
{ {
if (is_object($callable[0]) && $callable[0] instanceof Reference) if (is_object($callable[0]) && $callable[0] instanceof Reference) {
{
$callable = array($this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]); $callable = array($this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]);
} } else {
else
{
$callable = array($callable[0], $callable[1]); $callable = array($callable[0], $callable[1]);
} }
} }
@ -114,19 +102,16 @@ class YamlDumper extends Dumper
protected function addServices() protected function addServices()
{ {
if (!$this->container->getDefinitions()) if (!$this->container->getDefinitions()) {
{
return ''; return '';
} }
$code = "services:\n"; $code = "services:\n";
foreach ($this->container->getDefinitions() as $id => $definition) foreach ($this->container->getDefinitions() as $id => $definition) {
{
$code .= $this->addService($id, $definition); $code .= $this->addService($id, $definition);
} }
foreach ($this->container->getAliases() as $alias => $id) foreach ($this->container->getAliases() as $alias => $id) {
{
$code .= $this->addServiceAlias($alias, $id); $code .= $this->addServiceAlias($alias, $id);
} }
@ -135,8 +120,7 @@ class YamlDumper extends Dumper
protected function addParameters() protected function addParameters()
{ {
if (!$this->container->getParameters()) if (!$this->container->getParameters()) {
{
return ''; return '';
} }
@ -148,42 +132,29 @@ class YamlDumper extends Dumper
*/ */
protected function dumpValue($value) protected function dumpValue($value)
{ {
if (is_array($value)) if (is_array($value)) {
{
$code = array(); $code = array();
foreach ($value as $k => $v) foreach ($value as $k => $v) {
{
$code[$k] = $this->dumpValue($v); $code[$k] = $this->dumpValue($v);
} }
return $code; return $code;
} } elseif (is_object($value) && $value instanceof Reference) {
elseif (is_object($value) && $value instanceof Reference)
{
return $this->getServiceCall((string) $value, $value); return $this->getServiceCall((string) $value, $value);
} } elseif (is_object($value) && $value instanceof Parameter) {
elseif (is_object($value) && $value instanceof Parameter)
{
return $this->getParameterCall((string) $value); return $this->getParameterCall((string) $value);
} } elseif (is_object($value) || is_resource($value)) {
elseif (is_object($value) || is_resource($value))
{
throw new \RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); throw new \RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
} } else {
else
{
return $value; return $value;
} }
} }
protected function getServiceCall($id, Reference $reference = null) protected function getServiceCall($id, Reference $reference = null)
{ {
if (null !== $reference && Container::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) if (null !== $reference && Container::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
{
return sprintf('@@%s', $id); return sprintf('@@%s', $id);
} } else {
else
{
return sprintf('@%s', $id); return sprintf('@%s', $id);
} }
} }
@ -196,14 +167,11 @@ class YamlDumper extends Dumper
protected function prepareParameters($parameters) protected function prepareParameters($parameters)
{ {
$filtered = array(); $filtered = array();
foreach ($parameters as $key => $value) foreach ($parameters as $key => $value) {
{
if (is_array($value)) if (is_array($value))
{ {
$value = $this->prepareParameters($value); $value = $this->prepareParameters($value);
} } elseif ($value instanceof Reference) {
elseif ($value instanceof Reference)
{
$value = '@'.$value; $value = '@'.$value;
} }
@ -216,18 +184,13 @@ class YamlDumper extends Dumper
protected function escape($arguments) protected function escape($arguments)
{ {
$args = array(); $args = array();
foreach ($arguments as $k => $v) foreach ($arguments as $k => $v) {
{
if (is_array($v)) if (is_array($v))
{ {
$args[$k] = $this->escape($v); $args[$k] = $this->escape($v);
} } elseif (is_string($v)) {
elseif (is_string($v))
{
$args[$k] = str_replace('%', '%%', $v); $args[$k] = str_replace('%', '%%', $v);
} } else {
else
{
$args[$k] = $v; $args[$k] = $v;
} }
} }

View File

@ -51,8 +51,7 @@ class FileResource implements ResourceInterface
*/ */
public function isUptodate($timestamp) public function isUptodate($timestamp)
{ {
if (!file_exists($this->resource)) if (!file_exists($this->resource)) {
{
return false; return false;
} }

View File

@ -29,8 +29,7 @@ abstract class FileLoader extends Loader
*/ */
public function __construct($paths = array()) public function __construct($paths = array())
{ {
if (!is_array($paths)) if (!is_array($paths)) {
{
$paths = array($paths); $paths = array($paths);
} }
@ -43,8 +42,7 @@ abstract class FileLoader extends Loader
protected function findFile($file) protected function findFile($file)
{ {
$path = $this->getAbsolutePath($file); $path = $this->getAbsolutePath($file);
if (!file_exists($path)) if (!file_exists($path)) {
{
throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $file, implode(', ', $this->paths))); throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $file, implode(', ', $this->paths)));
} }
@ -53,20 +51,14 @@ abstract class FileLoader extends Loader
protected function getAbsolutePath($file, $currentPath = null) protected function getAbsolutePath($file, $currentPath = null)
{ {
if (self::isAbsolutePath($file)) if (self::isAbsolutePath($file)) {
{
return $file; return $file;
} } else if (null !== $currentPath && file_exists($currentPath.DIRECTORY_SEPARATOR.$file)) {
else if (null !== $currentPath && file_exists($currentPath.DIRECTORY_SEPARATOR.$file))
{
return $currentPath.DIRECTORY_SEPARATOR.$file; return $currentPath.DIRECTORY_SEPARATOR.$file;
} } else {
else
{
foreach ($this->paths as $path) foreach ($this->paths as $path)
{ {
if (file_exists($path.DIRECTORY_SEPARATOR.$file)) if (file_exists($path.DIRECTORY_SEPARATOR.$file)) {
{
return $path.DIRECTORY_SEPARATOR.$file; return $path.DIRECTORY_SEPARATOR.$file;
} }
} }

View File

@ -41,13 +41,11 @@ class IniFileLoader extends FileLoader
$configuration->addResource(new FileResource($path)); $configuration->addResource(new FileResource($path));
$result = parse_ini_file($path, true); $result = parse_ini_file($path, true);
if (false === $result || array() === $result) if (false === $result || array() === $result) {
{
throw new \InvalidArgumentException(sprintf('The %s file is not valid.', $file)); throw new \InvalidArgumentException(sprintf('The %s file is not valid.', $file));
} }
if (isset($result['parameters']) && is_array($result['parameters'])) if (isset($result['parameters']) && is_array($result['parameters'])) {
{
foreach ($result['parameters'] as $key => $value) foreach ($result['parameters'] as $key => $value)
{ {
$configuration->setParameter(strtolower($key), $value); $configuration->setParameter(strtolower($key), $value);

View File

@ -45,8 +45,7 @@ abstract class LoaderExtension implements LoaderExtensionInterface
*/ */
public function load($tag, array $config) public function load($tag, array $config)
{ {
if (!method_exists($this, $method = $tag.'Load')) if (!method_exists($this, $method = $tag.'Load')) {
{
throw new \InvalidArgumentException(sprintf('The tag "%s" is not defined in the "%s" extension.', $tag, $this->getNamespace())); throw new \InvalidArgumentException(sprintf('The tag "%s" is not defined in the "%s" extension.', $tag, $this->getNamespace()));
} }

View File

@ -63,8 +63,7 @@ class XmlFileLoader extends FileLoader
protected function parseParameters(BuilderConfiguration $configuration, $xml, $file) protected function parseParameters(BuilderConfiguration $configuration, $xml, $file)
{ {
if (!$xml->parameters) if (!$xml->parameters) {
{
return; return;
} }
@ -73,13 +72,11 @@ class XmlFileLoader extends FileLoader
protected function parseImports(BuilderConfiguration $configuration, $xml, $file) protected function parseImports(BuilderConfiguration $configuration, $xml, $file)
{ {
if (!$xml->imports) if (!$xml->imports) {
{
return; return;
} }
foreach ($xml->imports->import as $import) foreach ($xml->imports->import as $import) {
{
$configuration->merge($this->parseImport($import, $file)); $configuration->merge($this->parseImport($import, $file));
} }
} }
@ -87,15 +84,11 @@ class XmlFileLoader extends FileLoader
protected function parseImport($import, $file) protected function parseImport($import, $file)
{ {
$class = null; $class = null;
if (isset($import['class']) && $import['class'] !== get_class($this)) if (isset($import['class']) && $import['class'] !== get_class($this)) {
{
$class = (string) $import['class']; $class = (string) $import['class'];
} } else {
else
{
// try to detect loader with the extension // try to detect loader with the extension
switch (pathinfo((string) $import['resource'], PATHINFO_EXTENSION)) switch (pathinfo((string) $import['resource'], PATHINFO_EXTENSION)) {
{
case 'yml': case 'yml':
$class = 'Symfony\\Components\\DependencyInjection\\Loader\\YamlFileLoader'; $class = 'Symfony\\Components\\DependencyInjection\\Loader\\YamlFileLoader';
break; break;
@ -114,21 +107,18 @@ class XmlFileLoader extends FileLoader
protected function parseDefinitions(BuilderConfiguration $configuration, $xml, $file) protected function parseDefinitions(BuilderConfiguration $configuration, $xml, $file)
{ {
if (!$xml->services) if (!$xml->services) {
{
return; return;
} }
foreach ($xml->services->service as $service) foreach ($xml->services->service as $service) {
{
$this->parseDefinition($configuration, (string) $service['id'], $service, $file); $this->parseDefinition($configuration, (string) $service['id'], $service, $file);
} }
} }
protected function parseDefinition(BuilderConfiguration $configuration, $id, $service, $file) protected function parseDefinition(BuilderConfiguration $configuration, $id, $service, $file)
{ {
if ((string) $service['alias']) if ((string) $service['alias']) {
{
$configuration->setAlias($id, (string) $service['alias']); $configuration->setAlias($id, (string) $service['alias']);
return; return;
@ -136,8 +126,7 @@ class XmlFileLoader extends FileLoader
$definition = new Definition((string) $service['class']); $definition = new Definition((string) $service['class']);
foreach (array('shared', 'constructor') as $key) foreach (array('shared', 'constructor') as $key) {
{
if (isset($service[$key])) if (isset($service[$key]))
{ {
$method = 'set'.ucfirst($key); $method = 'set'.ucfirst($key);
@ -145,27 +134,21 @@ class XmlFileLoader extends FileLoader
} }
} }
if ($service->file) if ($service->file) {
{
$definition->setFile((string) $service->file); $definition->setFile((string) $service->file);
} }
$definition->setArguments($service->getArgumentsAsPhp('argument')); $definition->setArguments($service->getArgumentsAsPhp('argument'));
if (isset($service->configurator)) if (isset($service->configurator)) {
{
if (isset($service->configurator['function'])) if (isset($service->configurator['function']))
{ {
$definition->setConfigurator((string) $service->configurator['function']); $definition->setConfigurator((string) $service->configurator['function']);
} } else {
else
{
if (isset($service->configurator['service'])) if (isset($service->configurator['service']))
{ {
$class = new Reference((string) $service->configurator['service']); $class = new Reference((string) $service->configurator['service']);
} } else {
else
{
$class = (string) $service->configurator['class']; $class = (string) $service->configurator['class'];
} }
@ -173,16 +156,13 @@ class XmlFileLoader extends FileLoader
} }
} }
foreach ($service->call as $call) foreach ($service->call as $call) {
{
$definition->addMethodCall((string) $call['method'], $call->getArgumentsAsPhp('argument')); $definition->addMethodCall((string) $call['method'], $call->getArgumentsAsPhp('argument'));
} }
foreach ($service->annotation as $annotation) foreach ($service->annotation as $annotation) {
{
$parameters = array(); $parameters = array();
foreach ($annotation->attributes() as $name => $value) foreach ($annotation->attributes() as $name => $value) {
{
if ('name' === $name) if ('name' === $name)
{ {
continue; continue;
@ -204,8 +184,7 @@ class XmlFileLoader extends FileLoader
{ {
$dom = new \DOMDocument(); $dom = new \DOMDocument();
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
if (!$dom->load($file, LIBXML_COMPACT)) if (!$dom->load($file, LIBXML_COMPACT)) {
{
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors())); throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
} }
$dom->validateOnParse = true; $dom->validateOnParse = true;
@ -224,8 +203,7 @@ class XmlFileLoader extends FileLoader
// find anonymous service definitions // find anonymous service definitions
$xml->registerXPathNamespace('container', 'http://www.symfony-project.org/schema/dic/services'); $xml->registerXPathNamespace('container', 'http://www.symfony-project.org/schema/dic/services');
$nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]'); $nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]');
foreach ($nodes as $node) foreach ($nodes as $node) {
{
// give it a unique names // give it a unique names
$node['id'] = sprintf('_%s_%d', md5($file), ++$count); $node['id'] = sprintf('_%s_%d', md5($file), ++$count);
@ -235,8 +213,7 @@ class XmlFileLoader extends FileLoader
// resolve definitions // resolve definitions
krsort($definitions); krsort($definitions);
foreach ($definitions as $id => $def) foreach ($definitions as $id => $def) {
{
$this->parseDefinition($configuration, $id, $def[0], $def[1]); $this->parseDefinition($configuration, $id, $def[0], $def[1]);
$oNode = dom_import_simplexml($def[0]); $oNode = dom_import_simplexml($def[0]);
@ -260,17 +237,14 @@ class XmlFileLoader extends FileLoader
{ {
$schemaLocations = array('http://www.symfony-project.org/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')); $schemaLocations = array('http://www.symfony-project.org/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd'));
if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
{
$items = preg_split('/\s+/', $element); $items = preg_split('/\s+/', $element);
for ($i = 0, $nb = count($items); $i < $nb; $i += 2) for ($i = 0, $nb = count($items); $i < $nb; $i += 2) {
{
if ($extension = static::getExtension($items[$i])) if ($extension = static::getExtension($items[$i]))
{ {
$path = str_replace('http://www.symfony-project.org/', str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]); $path = str_replace('http://www.symfony-project.org/', str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
if (!file_exists($path)) if (!file_exists($path)) {
{
throw new \RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path)); throw new \RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path));
} }
@ -280,8 +254,7 @@ class XmlFileLoader extends FileLoader
} }
$imports = ''; $imports = '';
foreach ($schemaLocations as $namespace => $location) foreach ($schemaLocations as $namespace => $location) {
{
$imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location); $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
} }
@ -299,8 +272,7 @@ EOF
; ;
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
if (!$dom->schemaValidateSource($source)) if (!$dom->schemaValidateSource($source)) {
{
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors())); throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
} }
libxml_use_internal_errors(false); libxml_use_internal_errors(false);
@ -311,21 +283,18 @@ EOF
*/ */
protected function validateExtensions($dom, $file) protected function validateExtensions($dom, $file)
{ {
foreach ($dom->documentElement->childNodes as $node) foreach ($dom->documentElement->childNodes as $node) {
{
if (!$node instanceof \DOMElement || in_array($node->tagName, array('imports', 'parameters', 'services'))) if (!$node instanceof \DOMElement || in_array($node->tagName, array('imports', 'parameters', 'services')))
{ {
continue; continue;
} }
if ($node->namespaceURI === 'http://www.symfony-project.org/schema/dic/services') if ($node->namespaceURI === 'http://www.symfony-project.org/schema/dic/services') {
{
throw new \InvalidArgumentException(sprintf('The "%s" tag is not valid (in %s).', $node->tagName, $file)); throw new \InvalidArgumentException(sprintf('The "%s" tag is not valid (in %s).', $node->tagName, $file));
} }
// can it be handled by an extension? // can it be handled by an extension?
if (!static::getExtension($node->namespaceURI)) if (!static::getExtension($node->namespaceURI)) {
{
throw new \InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s).', $node->tagName, $file)); throw new \InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s).', $node->tagName, $file));
} }
} }
@ -334,8 +303,7 @@ EOF
protected function getXmlErrors() protected function getXmlErrors()
{ {
$errors = array(); $errors = array();
foreach (libxml_get_errors() as $error) foreach (libxml_get_errors() as $error) {
{
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code, $error->code,
@ -353,8 +321,7 @@ EOF
protected function loadFromExtensions(BuilderConfiguration $configuration, $xml) protected function loadFromExtensions(BuilderConfiguration $configuration, $xml)
{ {
foreach (dom_import_simplexml($xml)->childNodes as $node) foreach (dom_import_simplexml($xml)->childNodes as $node) {
{
if (!$node instanceof \DOMElement || $node->namespaceURI === 'http://www.symfony-project.org/schema/dic/services') if (!$node instanceof \DOMElement || $node->namespaceURI === 'http://www.symfony-project.org/schema/dic/services')
{ {
continue; continue;
@ -393,35 +360,27 @@ EOF
{ {
$empty = true; $empty = true;
$config = array(); $config = array();
foreach ($element->attributes as $name => $node) foreach ($element->attributes as $name => $node) {
{
$config[$name] = SimpleXMLElement::phpize($node->value); $config[$name] = SimpleXMLElement::phpize($node->value);
$empty = false; $empty = false;
} }
$nodeValue = false; $nodeValue = false;
foreach ($element->childNodes as $node) foreach ($element->childNodes as $node) {
{
if ($node instanceof \DOMText) if ($node instanceof \DOMText)
{ {
if (trim($node->nodeValue)) if (trim($node->nodeValue)) {
{
$nodeValue = trim($node->nodeValue); $nodeValue = trim($node->nodeValue);
$empty = false; $empty = false;
} }
} } elseif (!$node instanceof \DOMComment) {
elseif (!$node instanceof \DOMComment)
{
if (isset($config[$node->localName])) if (isset($config[$node->localName]))
{ {
if (!is_array($config[$node->localName])) if (!is_array($config[$node->localName])) {
{
$config[$node->localName] = array($config[$node->localName]); $config[$node->localName] = array($config[$node->localName]);
} }
$config[$node->localName][] = static::convertDomElementToArray($node); $config[$node->localName][] = static::convertDomElementToArray($node);
} } else {
else
{
$config[$node->localName] = static::convertDomElementToArray($node); $config[$node->localName] = static::convertDomElementToArray($node);
} }
@ -429,15 +388,11 @@ EOF
} }
} }
if (false !== $nodeValue) if (false !== $nodeValue) {
{
$value = SimpleXMLElement::phpize($nodeValue); $value = SimpleXMLElement::phpize($nodeValue);
if (count($config)) if (count($config)) {
{
$config['value'] = $value; $config['value'] = $value;
} } else {
else
{
$config = $value; $config = $value;
} }
} }

View File

@ -46,8 +46,7 @@ class YamlFileLoader extends FileLoader
$configuration->addResource(new FileResource($path)); $configuration->addResource(new FileResource($path));
if (!$content) if (!$content) {
{
return $configuration; return $configuration;
} }
@ -55,8 +54,7 @@ class YamlFileLoader extends FileLoader
$this->parseImports($configuration, $content, $file); $this->parseImports($configuration, $content, $file);
// parameters // parameters
if (isset($content['parameters'])) if (isset($content['parameters'])) {
{
foreach ($content['parameters'] as $key => $value) foreach ($content['parameters'] as $key => $value)
{ {
$configuration->setParameter(strtolower($key), $this->resolveServices($value)); $configuration->setParameter(strtolower($key), $this->resolveServices($value));
@ -74,13 +72,11 @@ class YamlFileLoader extends FileLoader
protected function parseImports(BuilderConfiguration $configuration, $content, $file) protected function parseImports(BuilderConfiguration $configuration, $content, $file)
{ {
if (!isset($content['imports'])) if (!isset($content['imports'])) {
{
return; return;
} }
foreach ($content['imports'] as $import) foreach ($content['imports'] as $import) {
{
$configuration->merge($this->parseImport($import, $file)); $configuration->merge($this->parseImport($import, $file));
} }
} }
@ -88,15 +84,11 @@ class YamlFileLoader extends FileLoader
protected function parseImport($import, $file) protected function parseImport($import, $file)
{ {
$class = null; $class = null;
if (isset($import['class']) && $import['class'] !== get_class($this)) if (isset($import['class']) && $import['class'] !== get_class($this)) {
{
$class = $import['class']; $class = $import['class'];
} } else {
else
{
// try to detect loader with the extension // try to detect loader with the extension
switch (pathinfo($import['resource'], PATHINFO_EXTENSION)) switch (pathinfo($import['resource'], PATHINFO_EXTENSION)) {
{
case 'xml': case 'xml':
$class = 'Symfony\\Components\\DependencyInjection\\Loader\\XmlFileLoader'; $class = 'Symfony\\Components\\DependencyInjection\\Loader\\XmlFileLoader';
break; break;
@ -115,21 +107,18 @@ class YamlFileLoader extends FileLoader
protected function parseDefinitions(BuilderConfiguration $configuration, $content, $file) protected function parseDefinitions(BuilderConfiguration $configuration, $content, $file)
{ {
if (!isset($content['services'])) if (!isset($content['services'])) {
{
return; return;
} }
foreach ($content['services'] as $id => $service) foreach ($content['services'] as $id => $service) {
{
$this->parseDefinition($configuration, $id, $service, $file); $this->parseDefinition($configuration, $id, $service, $file);
} }
} }
protected function parseDefinition(BuilderConfiguration $configuration, $id, $service, $file) protected function parseDefinition(BuilderConfiguration $configuration, $id, $service, $file)
{ {
if (is_string($service) && 0 === strpos($service, '@')) if (is_string($service) && 0 === strpos($service, '@')) {
{
$configuration->setAlias($id, substr($service, 1)); $configuration->setAlias($id, substr($service, 1));
return; return;
@ -137,48 +126,39 @@ class YamlFileLoader extends FileLoader
$definition = new Definition($service['class']); $definition = new Definition($service['class']);
if (isset($service['shared'])) if (isset($service['shared'])) {
{
$definition->setShared($service['shared']); $definition->setShared($service['shared']);
} }
if (isset($service['constructor'])) if (isset($service['constructor'])) {
{
$definition->setConstructor($service['constructor']); $definition->setConstructor($service['constructor']);
} }
if (isset($service['file'])) if (isset($service['file'])) {
{
$definition->setFile($service['file']); $definition->setFile($service['file']);
} }
if (isset($service['arguments'])) if (isset($service['arguments'])) {
{
$definition->setArguments($this->resolveServices($service['arguments'])); $definition->setArguments($this->resolveServices($service['arguments']));
} }
if (isset($service['configurator'])) if (isset($service['configurator'])) {
{
if (is_string($service['configurator'])) if (is_string($service['configurator']))
{ {
$definition->setConfigurator($service['configurator']); $definition->setConfigurator($service['configurator']);
} } else {
else
{
$definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1])); $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1]));
} }
} }
if (isset($service['calls'])) if (isset($service['calls'])) {
{
foreach ($service['calls'] as $call) foreach ($service['calls'] as $call)
{ {
$definition->addMethodCall($call[0], $this->resolveServices($call[1])); $definition->addMethodCall($call[0], $this->resolveServices($call[1]));
} }
} }
if (isset($service['annotations'])) if (isset($service['annotations'])) {
{
foreach ($service['annotations'] as $annotation) foreach ($service['annotations'] as $annotation)
{ {
$name = $annotation['name']; $name = $annotation['name'];
@ -201,29 +181,24 @@ class YamlFileLoader extends FileLoader
*/ */
protected function validate($content, $file) protected function validate($content, $file)
{ {
if (null === $content) if (null === $content) {
{
return $content; return $content;
} }
if (!is_array($content)) if (!is_array($content)) {
{
throw new \InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); throw new \InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file));
} }
foreach (array_keys($content) as $key) foreach (array_keys($content) as $key) {
{
if (in_array($key, array('imports', 'parameters', 'services'))) if (in_array($key, array('imports', 'parameters', 'services')))
{ {
continue; continue;
} }
// can it be handled by an extension? // can it be handled by an extension?
if (false !== strpos($key, '.')) if (false !== strpos($key, '.')) {
{
list($namespace, $tag) = explode('.', $key); list($namespace, $tag) = explode('.', $key);
if (!static::getExtension($namespace)) if (!static::getExtension($namespace)) {
{
throw new \InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s).', $key, $file)); throw new \InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s).', $key, $file));
} }
@ -238,16 +213,11 @@ class YamlFileLoader extends FileLoader
protected function resolveServices($value) protected function resolveServices($value)
{ {
if (is_array($value)) if (is_array($value)) {
{
$value = array_map(array($this, 'resolveServices'), $value); $value = array_map(array($this, 'resolveServices'), $value);
} } else if (is_string($value) && 0 === strpos($value, '@@')) {
else if (is_string($value) && 0 === strpos($value, '@@'))
{
$value = new Reference(substr($value, 2), Container::IGNORE_ON_INVALID_REFERENCE); $value = new Reference(substr($value, 2), Container::IGNORE_ON_INVALID_REFERENCE);
} } else if (is_string($value) && 0 === strpos($value, '@')) {
else if (is_string($value) && 0 === strpos($value, '@'))
{
$value = new Reference(substr($value, 1)); $value = new Reference(substr($value, 1));
} }
@ -256,8 +226,7 @@ class YamlFileLoader extends FileLoader
protected function loadFromExtensions(BuilderConfiguration $configuration, $content) protected function loadFromExtensions(BuilderConfiguration $configuration, $content)
{ {
foreach ($content as $key => $values) foreach ($content as $key => $values) {
{
if (in_array($key, array('imports', 'parameters', 'services'))) if (in_array($key, array('imports', 'parameters', 'services')))
{ {
continue; continue;
@ -265,8 +234,7 @@ class YamlFileLoader extends FileLoader
list($namespace, $tag) = explode('.', $key); list($namespace, $tag) = explode('.', $key);
if (!is_array($values)) if (!is_array($values)) {
{
$values = array(); $values = array();
} }

View File

@ -28,26 +28,20 @@ class SimpleXMLElement extends \SimpleXMLElement
public function getArgumentsAsPhp($name) public function getArgumentsAsPhp($name)
{ {
$arguments = array(); $arguments = array();
foreach ($this->$name as $arg) foreach ($this->$name as $arg) {
{
$key = isset($arg['key']) ? (string) $arg['key'] : (!$arguments ? 0 : max(array_keys($arguments)) + 1); $key = isset($arg['key']) ? (string) $arg['key'] : (!$arguments ? 0 : max(array_keys($arguments)) + 1);
// parameter keys are case insensitive // parameter keys are case insensitive
if ('parameter' == $name) if ('parameter' == $name) {
{
$key = strtolower($key); $key = strtolower($key);
} }
switch ($arg['type']) switch ($arg['type']) {
{
case 'service': case 'service':
$invalidBehavior = Container::EXCEPTION_ON_INVALID_REFERENCE; $invalidBehavior = Container::EXCEPTION_ON_INVALID_REFERENCE;
if (isset($arg['on-invalid']) && 'ignore' == $arg['on-invalid']) if (isset($arg['on-invalid']) && 'ignore' == $arg['on-invalid']) {
{
$invalidBehavior = Container::IGNORE_ON_INVALID_REFERENCE; $invalidBehavior = Container::IGNORE_ON_INVALID_REFERENCE;
} } elseif (isset($arg['on-invalid']) && 'null' == $arg['on-invalid']) {
elseif (isset($arg['on-invalid']) && 'null' == $arg['on-invalid'])
{
$invalidBehavior = Container::NULL_ON_INVALID_REFERENCE; $invalidBehavior = Container::NULL_ON_INVALID_REFERENCE;
} }
$arguments[$key] = new Reference((string) $arg['id'], $invalidBehavior); $arguments[$key] = new Reference((string) $arg['id'], $invalidBehavior);
@ -74,8 +68,7 @@ class SimpleXMLElement extends \SimpleXMLElement
$value = (string) $value; $value = (string) $value;
$lowercaseValue = strtolower($value); $lowercaseValue = strtolower($value);
switch (true) switch (true) {
{
case 'null' === $lowercaseValue: case 'null' === $lowercaseValue:
return null; return null;
case ctype_digit($value): case ctype_digit($value):

View File

@ -58,45 +58,34 @@ class Crawler extends \SplObjectStorage
*/ */
public function add($node) public function add($node)
{ {
if ($node instanceof \DOMNodeList) if ($node instanceof \DOMNodeList) {
{
$this->addNodeList($node); $this->addNodeList($node);
} } elseif (is_array($node)) {
elseif (is_array($node))
{
$this->addNodes($node); $this->addNodes($node);
} } elseif (null !== $node) {
elseif (null !== $node)
{
$this->addNode($node); $this->addNode($node);
} }
} }
public function addContent($content, $type = null) public function addContent($content, $type = null)
{ {
if (empty($type)) if (empty($type)) {
{
$type = 'text/html'; $type = 'text/html';
} }
// DOM only for HTML/XML content // DOM only for HTML/XML content
if (!preg_match('/(x|ht)ml/i', $type, $matches)) if (!preg_match('/(x|ht)ml/i', $type, $matches)) {
{
return null; return null;
} }
$charset = 'ISO-8859-1'; $charset = 'ISO-8859-1';
if (false !== $pos = strpos($type, 'charset=')) if (false !== $pos = strpos($type, 'charset=')) {
{
$charset = substr($type, $pos + 8); $charset = substr($type, $pos + 8);
} }
if ('x' === $matches[1]) if ('x' === $matches[1]) {
{
$this->addXmlContent($content, $charset); $this->addXmlContent($content, $charset);
} } else {
else
{
$this->addHtmlContent($content, $charset); $this->addHtmlContent($content, $charset);
} }
} }
@ -139,8 +128,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function addDocument(\DOMDocument $dom) public function addDocument(\DOMDocument $dom)
{ {
if ($dom->documentElement) if ($dom->documentElement) {
{
$this->addNode($dom->documentElement); $this->addNode($dom->documentElement);
} }
} }
@ -152,8 +140,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function addNodeList(\DOMNodeList $nodes) public function addNodeList(\DOMNodeList $nodes)
{ {
foreach ($nodes as $node) foreach ($nodes as $node) {
{
$this->addNode($node); $this->addNode($node);
} }
} }
@ -165,8 +152,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function addNodes(array $nodes) public function addNodes(array $nodes)
{ {
foreach ($nodes as $node) foreach ($nodes as $node) {
{
$this->add($node); $this->add($node);
} }
} }
@ -178,12 +164,9 @@ class Crawler extends \SplObjectStorage
*/ */
public function addNode(\DOMNode $node) public function addNode(\DOMNode $node)
{ {
if ($node instanceof \DOMDocument) if ($node instanceof \DOMDocument) {
{
$this->attach($node->documentElement); $this->attach($node->documentElement);
} } else {
else
{
$this->attach($node); $this->attach($node);
} }
} }
@ -207,8 +190,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function eq($position) public function eq($position)
{ {
foreach ($this as $i => $node) foreach ($this as $i => $node) {
{
if ($i == $position) if ($i == $position)
{ {
return new static($node, $this->uri); return new static($node, $this->uri);
@ -237,8 +219,7 @@ class Crawler extends \SplObjectStorage
public function each(\Closure $closure) public function each(\Closure $closure)
{ {
$data = array(); $data = array();
foreach ($this as $i => $node) foreach ($this as $i => $node) {
{
$data[] = $closure($node, $i); $data[] = $closure($node, $i);
} }
@ -257,8 +238,7 @@ class Crawler extends \SplObjectStorage
public function reduce(\Closure $closure) public function reduce(\Closure $closure)
{ {
$nodes = array(); $nodes = array();
foreach ($this as $i => $node) foreach ($this as $i => $node) {
{
if (false !== $closure($node, $i)) if (false !== $closure($node, $i))
{ {
$nodes[] = $node; $nodes[] = $node;
@ -297,8 +277,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function siblings() public function siblings()
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -314,8 +293,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function nextAll() public function nextAll()
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -329,8 +307,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function previousAll() public function previousAll()
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -346,16 +323,14 @@ class Crawler extends \SplObjectStorage
*/ */
public function parents() public function parents()
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
$node = $this->getNode(0); $node = $this->getNode(0);
$nodes = array(); $nodes = array();
while ($node = $node->parentNode) while ($node = $node->parentNode) {
{
if (1 === $node->nodeType && '_root' !== $node->nodeName) if (1 === $node->nodeType && '_root' !== $node->nodeName)
{ {
$nodes[] = $node; $nodes[] = $node;
@ -374,8 +349,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function children() public function children()
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -393,8 +367,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function attr($attribute) public function attr($attribute)
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -410,8 +383,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function text() public function text()
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -433,23 +405,18 @@ class Crawler extends \SplObjectStorage
*/ */
public function extract($attributes) public function extract($attributes)
{ {
if (!is_array($attributes)) if (!is_array($attributes)) {
{
$attributes = array($attributes); $attributes = array($attributes);
} }
$data = array(); $data = array();
foreach ($this as $node) foreach ($this as $node) {
{
$elements = array(); $elements = array();
foreach ($attributes as $attribute) foreach ($attributes as $attribute) {
{
if ('_text' === $attribute) if ('_text' === $attribute)
{ {
$elements[] = $node->nodeValue; $elements[] = $node->nodeValue;
} } else {
else
{
$elements[] = $node->getAttribute($attribute); $elements[] = $node->getAttribute($attribute);
} }
} }
@ -471,8 +438,7 @@ class Crawler extends \SplObjectStorage
{ {
$document = new \DOMDocument('1.0', 'UTF-8'); $document = new \DOMDocument('1.0', 'UTF-8');
$root = $document->appendChild($document->createElement('_root')); $root = $document->appendChild($document->createElement('_root'));
foreach ($this as $node) foreach ($this as $node) {
{
$root->appendChild($document->importNode($node, true)); $root->appendChild($document->importNode($node, true));
} }
@ -494,8 +460,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function filter($selector) public function filter($selector)
{ {
if (!class_exists('Symfony\\Components\\CssSelector\\Parser')) if (!class_exists('Symfony\\Components\\CssSelector\\Parser')) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector is not installed (you can use filterXPath instead).'); throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector is not installed (you can use filterXPath instead).');
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -546,8 +511,7 @@ class Crawler extends \SplObjectStorage
*/ */
public function link($method = 'get') public function link($method = 'get')
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
@ -564,8 +528,7 @@ class Crawler extends \SplObjectStorage
public function links() public function links()
{ {
$links = array(); $links = array();
foreach ($this as $node) foreach ($this as $node) {
{
$links[] = new Link($node, 'get', $this->host, $this->path); $links[] = new Link($node, 'get', $this->host, $this->path);
} }
@ -584,15 +547,13 @@ class Crawler extends \SplObjectStorage
*/ */
public function form(array $values = null, $method = null) public function form(array $values = null, $method = null)
{ {
if (!count($this)) if (!count($this)) {
{
throw new \InvalidArgumentException('The current node list is empty.'); throw new \InvalidArgumentException('The current node list is empty.');
} }
$form = new Form($this->getNode(0), $method, $this->host, $this->path); $form = new Form($this->getNode(0), $method, $this->host, $this->path);
if (null !== $values) if (null !== $values) {
{
$form->setValues($values); $form->setValues($values);
} }
@ -601,8 +562,7 @@ class Crawler extends \SplObjectStorage
protected function getNode($position) protected function getNode($position)
{ {
foreach ($this as $i => $node) foreach ($this as $i => $node) {
{
if ($i == $position) if ($i == $position)
{ {
return $node; return $node;
@ -616,15 +576,13 @@ class Crawler extends \SplObjectStorage
protected function parseUri($uri) protected function parseUri($uri)
{ {
if ('http' !== substr($uri, 0, 4)) if ('http' !== substr($uri, 0, 4)) {
{
return array(null, '/'); return array(null, '/');
} }
$path = parse_url($uri, PHP_URL_PATH); $path = parse_url($uri, PHP_URL_PATH);
if ('/' !== substr($path, -1)) if ('/' !== substr($path, -1)) {
{
$path = substr($path, 0, strrpos($path, '/') + 1); $path = substr($path, 0, strrpos($path, '/') + 1);
} }
@ -635,42 +593,35 @@ class Crawler extends \SplObjectStorage
{ {
$nodes = array(); $nodes = array();
do do {
{
if ($node !== $this->getNode(0) && $node->nodeType === 1) if ($node !== $this->getNode(0) && $node->nodeType === 1)
{ {
$nodes[] = $node; $nodes[] = $node;
} }
} } while($node = $node->$siblingDir);
while($node = $node->$siblingDir);
return $nodes; return $nodes;
} }
static public function xpathLiteral($s) static public function xpathLiteral($s)
{ {
if (false === strpos($s, "'")) if (false === strpos($s, "'")) {
{
return sprintf("'%s'", $s); return sprintf("'%s'", $s);
} }
if (false === strpos($s, '"')) if (false === strpos($s, '"')) {
{
return sprintf('"%s"', $s); return sprintf('"%s"', $s);
} }
$string = $s; $string = $s;
$parts = array(); $parts = array();
while (true) while (true) {
{
if (false !== $pos = strpos($string, "'")) if (false !== $pos = strpos($string, "'"))
{ {
$parts[] = sprintf("'%s'", substr($string, 0, $pos)); $parts[] = sprintf("'%s'", substr($string, 0, $pos));
$parts[] = "\"'\""; $parts[] = "\"'\"";
$string = substr($string, $pos + 1); $string = substr($string, $pos + 1);
} } else {
else
{
$parts[] = "'$string'"; $parts[] = "'$string'";
break; break;
} }

View File

@ -34,8 +34,7 @@ class ChoiceFormField extends FormField
public function hasValue() public function hasValue()
{ {
// don't send a value for unchecked checkboxes // don't send a value for unchecked checkboxes
if (in_array($this->type, array('checkbox', 'radio')) && null === $this->value) if (in_array($this->type, array('checkbox', 'radio')) && null === $this->value) {
{
return false; return false;
} }
@ -51,49 +50,36 @@ class ChoiceFormField extends FormField
*/ */
public function setValue($value) public function setValue($value)
{ {
if ('checkbox' == $this->type && false === $value) if ('checkbox' == $this->type && false === $value) {
{
// uncheck // uncheck
$this->value = null; $this->value = null;
} } elseif ('checkbox' == $this->type && true === $value) {
elseif ('checkbox' == $this->type && true === $value)
{
// check // check
$this->value = $this->options[0]; $this->value = $this->options[0];
} } else {
else
{
if (is_array($value)) if (is_array($value))
{ {
if (!$this->multiple) if (!$this->multiple) {
{
throw new \InvalidArgumentException(sprintf('The value for "%s" cannot be an array.', $this->name)); throw new \InvalidArgumentException(sprintf('The value for "%s" cannot be an array.', $this->name));
} }
foreach ($value as $v) foreach ($value as $v) {
{
if (!in_array($v, $this->options)) if (!in_array($v, $this->options))
{ {
throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: %s).', $this->name, $v, implode(', ', $this->options))); throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: %s).', $this->name, $v, implode(', ', $this->options)));
} }
} }
} } elseif (!in_array($value, $this->options)) {
elseif (!in_array($value, $this->options))
{
throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: %s).', $this->name, $value, implode(', ', $this->options))); throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: %s).', $this->name, $value, implode(', ', $this->options)));
} }
if ($this->multiple && !is_array($value)) if ($this->multiple && !is_array($value)) {
{
$value = array($value); $value = array($value);
} }
if (is_array($value)) if (is_array($value)) {
{
$this->value = $value; $this->value = $value;
} } else {
else
{
parent::setValue($value); parent::setValue($value);
} }
} }
@ -110,15 +96,13 @@ class ChoiceFormField extends FormField
*/ */
public function addChoice(\DOMNode $node) public function addChoice(\DOMNode $node)
{ {
if (!$this->multiple && 'radio' != $this->type) if (!$this->multiple && 'radio' != $this->type) {
{
throw new \LogicException(sprintf('Unable to add a choice for "%s" as it is not multiple or is not a radio button.', $this->name)); throw new \LogicException(sprintf('Unable to add a choice for "%s" as it is not multiple or is not a radio button.', $this->name));
} }
$this->options[] = $value = $node->hasAttribute('value') ? $node->getAttribute('value') : '1'; $this->options[] = $value = $node->hasAttribute('value') ? $node->getAttribute('value') : '1';
if ($node->getAttribute('checked')) if ($node->getAttribute('checked')) {
{
$this->value = $value; $this->value = $value;
} }
} }
@ -150,13 +134,11 @@ class ChoiceFormField extends FormField
*/ */
protected function initialize() protected function initialize()
{ {
if ('input' != $this->node->nodeName && 'select' != $this->node->nodeName) if ('input' != $this->node->nodeName && 'select' != $this->node->nodeName) {
{
throw new \LogicException(sprintf('A ChoiceFormField can only be created from an input or select tag (%s given).', $this->node->nodeName)); throw new \LogicException(sprintf('A ChoiceFormField can only be created from an input or select tag (%s given).', $this->node->nodeName));
} }
if ('input' == $this->node->nodeName && 'checkbox' != $this->node->getAttribute('type') && 'radio' != $this->node->getAttribute('type')) if ('input' == $this->node->nodeName && 'checkbox' != $this->node->getAttribute('type') && 'radio' != $this->node->getAttribute('type')) {
{
throw new \LogicException(sprintf('A ChoiceFormField can only be created from an input tag with a type of checkbox or radio (given type is %s).', $this->node->getAttribute('type'))); throw new \LogicException(sprintf('A ChoiceFormField can only be created from an input tag with a type of checkbox or radio (given type is %s).', $this->node->getAttribute('type')));
} }
@ -164,40 +146,30 @@ class ChoiceFormField extends FormField
$this->options = array(); $this->options = array();
$this->multiple = false; $this->multiple = false;
if ('input' == $this->node->nodeName) if ('input' == $this->node->nodeName) {
{
$this->type = $this->node->getAttribute('type'); $this->type = $this->node->getAttribute('type');
$this->options[] = $value = $this->node->hasAttribute('value') ? $this->node->getAttribute('value') : '1'; $this->options[] = $value = $this->node->hasAttribute('value') ? $this->node->getAttribute('value') : '1';
if ($this->node->getAttribute('checked')) if ($this->node->getAttribute('checked')) {
{
$this->value = $value; $this->value = $value;
} }
} } else {
else
{
$this->type = 'select'; $this->type = 'select';
if ($this->node->hasAttribute('multiple')) if ($this->node->hasAttribute('multiple')) {
{
$this->multiple = true; $this->multiple = true;
$this->value = array(); $this->value = array();
$this->name = str_replace('[]', '', $this->name); $this->name = str_replace('[]', '', $this->name);
} }
$found = false; $found = false;
foreach ($this->xpath->query('descendant::option', $this->node) as $option) foreach ($this->xpath->query('descendant::option', $this->node) as $option) {
{
$this->options[] = $option->getAttribute('value'); $this->options[] = $option->getAttribute('value');
if ($option->getAttribute('selected')) if ($option->getAttribute('selected')) {
{
$found = true; $found = true;
if ($this->multiple) if ($this->multiple) {
{
$this->value[] = $option->getAttribute('value'); $this->value[] = $option->getAttribute('value');
} } else {
else
{
$this->value = $option->getAttribute('value'); $this->value = $option->getAttribute('value');
} }
} }
@ -205,8 +177,7 @@ class ChoiceFormField extends FormField
// if no option is selected and if it is a simple select box, take the first option as the value // if no option is selected and if it is a simple select box, take the first option as the value
$option = $this->xpath->query('descendant::option', $this->node)->item(0); $option = $this->xpath->query('descendant::option', $this->node)->item(0);
if (!$found && !$this->multiple && $option instanceof \DOMElement) if (!$found && !$this->multiple && $option instanceof \DOMElement) {
{
$this->value = $option->getAttribute('value'); $this->value = $option->getAttribute('value');
} }
} }

View File

@ -30,8 +30,7 @@ class FileFormField extends FormField
public function setErrorCode($error) public function setErrorCode($error)
{ {
$codes = array(UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION); $codes = array(UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION);
if (!in_array($error, $codes)) if (!in_array($error, $codes)) {
{
throw new \InvalidArgumentException(sprintf('The error code %s is not valid.', $error)); throw new \InvalidArgumentException(sprintf('The error code %s is not valid.', $error));
} }
@ -45,13 +44,10 @@ class FileFormField extends FormField
*/ */
public function setValue($value) public function setValue($value)
{ {
if (null !== $value && is_readable($value)) if (null !== $value && is_readable($value)) {
{
$error = UPLOAD_ERR_OK; $error = UPLOAD_ERR_OK;
$size = filesize($value); $size = filesize($value);
} } else {
else
{
$error = UPLOAD_ERR_NO_FILE; $error = UPLOAD_ERR_NO_FILE;
$size = 0; $size = 0;
$value = ''; $value = '';
@ -67,13 +63,11 @@ class FileFormField extends FormField
*/ */
protected function initialize() protected function initialize()
{ {
if ('input' != $this->node->nodeName) if ('input' != $this->node->nodeName) {
{
throw new \LogicException(sprintf('A FileFormField can only be created from an input tag (%s given).', $this->node->nodeName)); throw new \LogicException(sprintf('A FileFormField can only be created from an input tag (%s given).', $this->node->nodeName));
} }
if ('file' != $this->node->getAttribute('type')) if ('file' != $this->node->getAttribute('type')) {
{
throw new \LogicException(sprintf('A FileFormField can only be created from an input tag with a type of file (given type is %s).', $this->node->getAttribute('type'))); throw new \LogicException(sprintf('A FileFormField can only be created from an input tag with a type of file (given type is %s).', $this->node->getAttribute('type')));
} }

View File

@ -30,18 +30,15 @@ class InputFormField extends FormField
*/ */
protected function initialize() protected function initialize()
{ {
if ('input' != $this->node->nodeName) if ('input' != $this->node->nodeName) {
{
throw new \LogicException(sprintf('An InputFormField can only be created from an input tag (%s given).', $this->node->nodeName)); throw new \LogicException(sprintf('An InputFormField can only be created from an input tag (%s given).', $this->node->nodeName));
} }
if ('checkbox' == $this->node->getAttribute('type')) if ('checkbox' == $this->node->getAttribute('type')) {
{
throw new \LogicException('Checkboxes should be instances of ChoiceFormField.'); throw new \LogicException('Checkboxes should be instances of ChoiceFormField.');
} }
if ('file' == $this->node->getAttribute('type')) if ('file' == $this->node->getAttribute('type')) {
{
throw new \LogicException('File inputs should be instances of FileFormField.'); throw new \LogicException('File inputs should be instances of FileFormField.');
} }

View File

@ -27,14 +27,12 @@ class TextareaFormField extends FormField
*/ */
protected function initialize() protected function initialize()
{ {
if ('textarea' != $this->node->nodeName) if ('textarea' != $this->node->nodeName) {
{
throw new \LogicException(sprintf('A TextareaFormField can only be created from a textarea tag (%s given).', $this->node->nodeName)); throw new \LogicException(sprintf('A TextareaFormField can only be created from a textarea tag (%s given).', $this->node->nodeName));
} }
$this->value = null; $this->value = null;
foreach ($this->node->childNodes as $node) foreach ($this->node->childNodes as $node) {
{
$this->value .= $this->document->saveXML($node); $this->value .= $this->document->saveXML($node);
} }
} }

View File

@ -41,20 +41,15 @@ class Form
public function __construct(\DOMNode $node, $method = null, $host = null, $path = '/') public function __construct(\DOMNode $node, $method = null, $host = null, $path = '/')
{ {
$this->button = $node; $this->button = $node;
if ('button' == $node->nodeName || ('input' == $node->nodeName && in_array($node->getAttribute('type'), array('submit', 'button', 'image')))) if ('button' == $node->nodeName || ('input' == $node->nodeName && in_array($node->getAttribute('type'), array('submit', 'button', 'image')))) {
{
do do
{ {
// use the ancestor form element // use the ancestor form element
if (null === $node = $node->parentNode) if (null === $node = $node->parentNode) {
{
throw new \LogicException('The selected node does not have a form ancestor.'); throw new \LogicException('The selected node does not have a form ancestor.');
} }
} } while ('form' != $node->nodeName);
while ('form' != $node->nodeName); } else {
}
else
{
throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName)); throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
} }
$this->node = $node; $this->node = $node;
@ -84,8 +79,7 @@ class Form
*/ */
public function getValue($name) public function getValue($name)
{ {
if (!$this->hasField($name)) if (!$this->hasField($name)) {
{
throw new \InvalidArgumentException(sprintf('The form field "%s" does not exist', $name)); throw new \InvalidArgumentException(sprintf('The form field "%s" does not exist', $name));
} }
@ -102,8 +96,7 @@ class Form
*/ */
public function setValue($name, $value) public function setValue($name, $value)
{ {
if (!$this->hasField($name)) if (!$this->hasField($name)) {
{
throw new \InvalidArgumentException(sprintf('The form field "%s" does not exist', $name)); throw new \InvalidArgumentException(sprintf('The form field "%s" does not exist', $name));
} }
@ -119,8 +112,7 @@ class Form
*/ */
public function setValues(array $values) public function setValues(array $values)
{ {
foreach ($values as $name => $value) foreach ($values as $name => $value) {
{
$this->setValue($name, $value); $this->setValue($name, $value);
} }
@ -137,8 +129,7 @@ class Form
public function getValues() public function getValues()
{ {
$values = array(); $values = array();
foreach ($this->fields as $name => $field) foreach ($this->fields as $name => $field) {
{
if (!$field instanceof Field\FileFormField && $field->hasValue()) if (!$field instanceof Field\FileFormField && $field->hasValue())
{ {
$values[$name] = $field->getValue(); $values[$name] = $field->getValue();
@ -155,14 +146,12 @@ class Form
*/ */
public function getFiles() public function getFiles()
{ {
if (!in_array($this->getMethod(), array('post', 'put', 'delete'))) if (!in_array($this->getMethod(), array('post', 'put', 'delete'))) {
{
return array(); return array();
} }
$files = array(); $files = array();
foreach ($this->fields as $name => $field) foreach ($this->fields as $name => $field) {
{
if ($field instanceof Field\FileFormField) if ($field instanceof Field\FileFormField)
{ {
$files[$name] = $field->getValue(); $files[$name] = $field->getValue();
@ -219,19 +208,16 @@ class Form
{ {
$uri = $this->node->getAttribute('action'); $uri = $this->node->getAttribute('action');
if (!in_array($this->getMethod(), array('post', 'put', 'delete')) && $queryString = http_build_query($this->getValues(), null, '&')) if (!in_array($this->getMethod(), array('post', 'put', 'delete')) && $queryString = http_build_query($this->getValues(), null, '&')) {
{
$sep = false === strpos($uri, '?') ? '?' : '&'; $sep = false === strpos($uri, '?') ? '?' : '&';
$uri .= $sep.$queryString; $uri .= $sep.$queryString;
} }
if ($uri && '/' !== $uri[0]) if ($uri && '/' !== $uri[0]) {
{
$uri = $this->path.$uri; $uri = $this->path.$uri;
} }
if ($absolute && null !== $this->host) if ($absolute && null !== $this->host) {
{
return $this->host.$uri; return $this->host.$uri;
} }
@ -247,8 +233,7 @@ class Form
*/ */
public function getMethod() public function getMethod()
{ {
if (null !== $this->method) if (null !== $this->method) {
{
return $this->method; return $this->method;
} }
@ -278,8 +263,7 @@ class Form
*/ */
public function getField($name) public function getField($name)
{ {
if (!$this->hasField($name)) if (!$this->hasField($name)) {
{
throw new \InvalidArgumentException(sprintf('The form has no "%s" field', $name)); throw new \InvalidArgumentException(sprintf('The form has no "%s" field', $name));
} }
@ -320,8 +304,7 @@ class Form
$root->appendChild($button); $root->appendChild($button);
$xpath = new \DOMXPath($document); $xpath = new \DOMXPath($document);
foreach ($xpath->query('descendant::input | descendant::textarea | descendant::select', $root) as $node) foreach ($xpath->query('descendant::input | descendant::textarea | descendant::select', $root) as $node) {
{
if ($node->hasAttribute('disabled') || !$node->hasAttribute('name')) if ($node->hasAttribute('disabled') || !$node->hasAttribute('name'))
{ {
continue; continue;
@ -329,35 +312,22 @@ class Form
$nodeName = $node->nodeName; $nodeName = $node->nodeName;
if ($node === $button) if ($node === $button) {
{
$this->setField(new Field\InputFormField($node)); $this->setField(new Field\InputFormField($node));
} } elseif ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == $node->getAttribute('type')) {
elseif ('select' == $nodeName || 'input' == $nodeName && 'checkbox' == $node->getAttribute('type'))
{
$this->setField(new Field\ChoiceFormField($node)); $this->setField(new Field\ChoiceFormField($node));
} } elseif ('input' == $nodeName && 'radio' == $node->getAttribute('type')) {
elseif ('input' == $nodeName && 'radio' == $node->getAttribute('type'))
{
if ($this->hasField($node->getAttribute('name'))) if ($this->hasField($node->getAttribute('name')))
{ {
$this->getField($node->getAttribute('name'))->addChoice($node); $this->getField($node->getAttribute('name'))->addChoice($node);
} } else {
else
{
$this->setField(new Field\ChoiceFormField($node)); $this->setField(new Field\ChoiceFormField($node));
} }
} } elseif ('input' == $nodeName && 'file' == $node->getAttribute('type')) {
elseif ('input' == $nodeName && 'file' == $node->getAttribute('type'))
{
$this->setField(new Field\FileFormField($node)); $this->setField(new Field\FileFormField($node));
} } elseif ('input' == $nodeName && !in_array($node->getAttribute('type'), array('submit', 'button', 'image'))) {
elseif ('input' == $nodeName && !in_array($node->getAttribute('type'), array('submit', 'button', 'image')))
{
$this->setField(new Field\InputFormField($node)); $this->setField(new Field\InputFormField($node));
} } elseif ('textarea' == $nodeName) {
elseif ('textarea' == $nodeName)
{
$this->setField(new Field\TextareaFormField($node)); $this->setField(new Field\TextareaFormField($node));
} }
} }

View File

@ -37,8 +37,7 @@ class Link
*/ */
public function __construct(\DOMNode $node, $method = 'get', $host = null, $path = '/') public function __construct(\DOMNode $node, $method = 'get', $host = null, $path = '/')
{ {
if ('a' != $node->nodeName) if ('a' != $node->nodeName) {
{
throw new \LogicException(sprintf('Unable to click on a "%s" tag.', $node->nodeName)); throw new \LogicException(sprintf('Unable to click on a "%s" tag.', $node->nodeName));
} }
@ -69,13 +68,11 @@ class Link
{ {
$uri = $this->node->getAttribute('href'); $uri = $this->node->getAttribute('href');
if ($uri && '/' !== $uri[0]) if ($uri && '/' !== $uri[0]) {
{
$uri = $this->path.$uri; $uri = $this->path.$uri;
} }
if ($absolute && null !== $this->host) if ($absolute && null !== $this->host) {
{
return $this->host.$uri; return $this->host.$uri;
} }

View File

@ -132,8 +132,7 @@ class Event implements \ArrayAccess
*/ */
public function getParameter($name) public function getParameter($name)
{ {
if (!array_key_exists($name, $this->parameters)) if (!array_key_exists($name, $this->parameters)) {
{
throw new \InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name)); throw new \InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name));
} }
@ -172,8 +171,7 @@ class Event implements \ArrayAccess
*/ */
public function offsetGet($name) public function offsetGet($name)
{ {
if (!array_key_exists($name, $this->parameters)) if (!array_key_exists($name, $this->parameters)) {
{
throw new \InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name)); throw new \InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name));
} }

View File

@ -31,8 +31,7 @@ class EventDispatcher
*/ */
public function connect($name, $listener) public function connect($name, $listener)
{ {
if (!isset($this->listeners[$name])) if (!isset($this->listeners[$name])) {
{
$this->listeners[$name] = array(); $this->listeners[$name] = array();
} }
@ -49,13 +48,11 @@ class EventDispatcher
*/ */
public function disconnect($name, $listener) public function disconnect($name, $listener)
{ {
if (!isset($this->listeners[$name])) if (!isset($this->listeners[$name])) {
{
return false; return false;
} }
foreach ($this->listeners[$name] as $i => $callable) foreach ($this->listeners[$name] as $i => $callable) {
{
if ($listener === $callable) if ($listener === $callable)
{ {
unset($this->listeners[$name][$i]); unset($this->listeners[$name][$i]);
@ -72,8 +69,7 @@ class EventDispatcher
*/ */
public function notify(Event $event) public function notify(Event $event)
{ {
foreach ($this->getListeners($event->getName()) as $listener) foreach ($this->getListeners($event->getName()) as $listener) {
{
call_user_func($listener, $event); call_user_func($listener, $event);
} }
@ -89,8 +85,7 @@ class EventDispatcher
*/ */
public function notifyUntil(Event $event) public function notifyUntil(Event $event)
{ {
foreach ($this->getListeners($event->getName()) as $listener) foreach ($this->getListeners($event->getName()) as $listener) {
{
if (call_user_func($listener, $event)) if (call_user_func($listener, $event))
{ {
$event->setProcessed(true); $event->setProcessed(true);
@ -111,8 +106,7 @@ class EventDispatcher
*/ */
public function filter(Event $event, $value) public function filter(Event $event, $value)
{ {
foreach ($this->getListeners($event->getName()) as $listener) foreach ($this->getListeners($event->getName()) as $listener) {
{
$value = call_user_func($listener, $event, $value); $value = call_user_func($listener, $event, $value);
} }
@ -130,8 +124,7 @@ class EventDispatcher
*/ */
public function hasListeners($name) public function hasListeners($name)
{ {
if (!isset($this->listeners[$name])) if (!isset($this->listeners[$name])) {
{
$this->listeners[$name] = array(); $this->listeners[$name] = array();
} }
@ -147,8 +140,7 @@ class EventDispatcher
*/ */
public function getListeners($name) public function getListeners($name)
{ {
if (!isset($this->listeners[$name])) if (!isset($this->listeners[$name])) {
{
return array(); return array();
} }

View File

@ -287,13 +287,11 @@ class Finder implements \IteratorAggregate
*/ */
public function in($dirs) public function in($dirs)
{ {
if (!is_array($dirs)) if (!is_array($dirs)) {
{
$dirs = array($dirs); $dirs = array($dirs);
} }
foreach ($dirs as $dir) foreach ($dirs as $dir) {
{
if (!is_dir($dir)) if (!is_dir($dir))
{ {
throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir)); throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
@ -316,19 +314,16 @@ class Finder implements \IteratorAggregate
*/ */
public function getIterator() public function getIterator()
{ {
if (0 === count($this->dirs)) if (0 === count($this->dirs)) {
{
throw new \LogicException('You must call the in() method before iterating over a Finder.'); throw new \LogicException('You must call the in() method before iterating over a Finder.');
} }
if (1 === count($this->dirs)) if (1 === count($this->dirs)) {
{
return $this->searchInDirectory($this->dirs[0]); return $this->searchInDirectory($this->dirs[0]);
} }
$iterator = new \AppendIterator(); $iterator = new \AppendIterator();
foreach ($this->dirs as $dir) foreach ($this->dirs as $dir) {
{
$iterator->append($this->searchInDirectory($dir)); $iterator->append($this->searchInDirectory($dir));
} }
@ -339,50 +334,41 @@ class Finder implements \IteratorAggregate
{ {
$flags = \FilesystemIterator::SKIP_DOTS; $flags = \FilesystemIterator::SKIP_DOTS;
if ($this->followLinks) if ($this->followLinks) {
{
$flags |= \FilesystemIterator::FOLLOW_SYMLINKS; $flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
} }
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, $flags), \RecursiveIteratorIterator::SELF_FIRST); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
if ($this->mindepth > 0 || $this->maxdepth < INF) if ($this->mindepth > 0 || $this->maxdepth < INF) {
{
$iterator = new Iterator\LimitDepthFilterIterator($iterator, $this->mindepth, $this->maxdepth); $iterator = new Iterator\LimitDepthFilterIterator($iterator, $this->mindepth, $this->maxdepth);
} }
if ($this->mode) if ($this->mode) {
{
$iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode); $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
} }
if ($this->exclude) if ($this->exclude) {
{
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude); $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
} }
if ($this->ignoreVCS) if ($this->ignoreVCS) {
{
$iterator = new Iterator\IgnoreVcsFilterIterator($iterator); $iterator = new Iterator\IgnoreVcsFilterIterator($iterator);
} }
if ($this->names || $this->notNames) if ($this->names || $this->notNames) {
{
$iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames); $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
} }
if ($this->sizes) if ($this->sizes) {
{
$iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes); $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
} }
if ($this->filters) if ($this->filters) {
{
$iterator = new Iterator\CustomFilterIterator($iterator, $this->filters); $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
} }
if ($this->sort) if ($this->sort) {
{
$iterator = new Iterator\SortableIterator($iterator, $this->sort); $iterator = new Iterator\SortableIterator($iterator, $this->sort);
} }

View File

@ -51,11 +51,9 @@ class Glob
$inCurlies = 0; $inCurlies = 0;
$regex = ''; $regex = '';
$sizeGlob = strlen($glob); $sizeGlob = strlen($glob);
for ($i = 0; $i < $sizeGlob; $i++) for ($i = 0; $i < $sizeGlob; $i++) {
{
$car = $glob[$i]; $car = $glob[$i];
if ($firstByte) if ($firstByte) {
{
if ($strictLeadingDot && $car !== '.') if ($strictLeadingDot && $car !== '.')
{ {
$regex .= '(?=[^\.])'; $regex .= '(?=[^\.])';
@ -64,59 +62,39 @@ class Glob
$firstByte = false; $firstByte = false;
} }
if ($car === '/') if ($car === '/') {
{
$firstByte = true; $firstByte = true;
} }
if ($car === '.' || $car === '(' || $car === ')' || $car === '|' || $car === '+' || $car === '^' || $car === '$') if ($car === '.' || $car === '(' || $car === ')' || $car === '|' || $car === '+' || $car === '^' || $car === '$') {
{
$regex .= "\\$car"; $regex .= "\\$car";
} } elseif ($car === '*') {
elseif ($car === '*')
{
$regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*'); $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
} } elseif ($car === '?') {
elseif ($car === '?')
{
$regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.'); $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
} } elseif ($car === '{') {
elseif ($car === '{')
{
$regex .= $escaping ? '\\{' : '('; $regex .= $escaping ? '\\{' : '(';
if (!$escaping) if (!$escaping) {
{
++$inCurlies; ++$inCurlies;
} }
} } elseif ($car === '}' && $inCurlies) {
elseif ($car === '}' && $inCurlies)
{
$regex .= $escaping ? '}' : ')'; $regex .= $escaping ? '}' : ')';
if (!$escaping) if (!$escaping) {
{
--$inCurlies; --$inCurlies;
} }
} } elseif ($car === ',' && $inCurlies) {
elseif ($car === ',' && $inCurlies)
{
$regex .= $escaping ? ',' : '|'; $regex .= $escaping ? ',' : '|';
} } elseif ($car === '\\') {
elseif ($car === '\\')
{
if ($escaping) if ($escaping)
{ {
$regex .= '\\\\'; $regex .= '\\\\';
$escaping = false; $escaping = false;
} } else {
else
{
$escaping = true; $escaping = true;
} }
continue; continue;
} } else {
else
{
$regex .= $car; $regex .= $car;
} }
$escaping = false; $escaping = false;

View File

@ -47,8 +47,7 @@ class CustomFilterIterator extends \FilterIterator
{ {
$fileinfo = $this->getInnerIterator()->current(); $fileinfo = $this->getInnerIterator()->current();
foreach ($this->filters as $filter) foreach ($this->filters as $filter) {
{
if (false === $filter($fileinfo)) if (false === $filter($fileinfo))
{ {
return false; return false;

View File

@ -31,8 +31,7 @@ class ExcludeDirectoryFilterIterator extends \FilterIterator
public function __construct(\Iterator $iterator, array $directories) public function __construct(\Iterator $iterator, array $directories)
{ {
$this->patterns = array(); $this->patterns = array();
foreach ($directories as $directory) foreach ($directories as $directory) {
{
$this->patterns[] = '#/'.preg_quote($directory, '#').'(/|$)#'; $this->patterns[] = '#/'.preg_quote($directory, '#').'(/|$)#';
} }
@ -48,16 +47,13 @@ class ExcludeDirectoryFilterIterator extends \FilterIterator
{ {
$fileinfo = $this->getInnerIterator()->current(); $fileinfo = $this->getInnerIterator()->current();
foreach ($this->patterns as $pattern) foreach ($this->patterns as $pattern) {
{
$path = $fileinfo->getPathname(); $path = $fileinfo->getPathname();
if ($fileinfo->isDir()) if ($fileinfo->isDir()) {
{
$path .= '/'; $path .= '/';
} }
if (preg_match($pattern, $path)) if (preg_match($pattern, $path)) {
{
return false; return false;
} }
} }

View File

@ -47,12 +47,9 @@ class FileTypeFilterIterator extends \FilterIterator
{ {
$fileinfo = $this->getInnerIterator()->current(); $fileinfo = $this->getInnerIterator()->current();
if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) {
{
return false; return false;
} } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) {
elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir())
{
return false; return false;
} }

View File

@ -35,14 +35,12 @@ class FilenameFilterIterator extends \FilterIterator
public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns) public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
{ {
$this->matchRegexps = array(); $this->matchRegexps = array();
foreach ($matchPatterns as $pattern) foreach ($matchPatterns as $pattern) {
{
$this->matchRegexps[] = $this->toRegex($pattern); $this->matchRegexps[] = $this->toRegex($pattern);
} }
$this->noMatchRegexps = array(); $this->noMatchRegexps = array();
foreach ($noMatchPatterns as $pattern) foreach ($noMatchPatterns as $pattern) {
{
$this->noMatchRegexps[] = $this->toRegex($pattern); $this->noMatchRegexps[] = $this->toRegex($pattern);
} }
@ -59,38 +57,30 @@ class FilenameFilterIterator extends \FilterIterator
$fileinfo = $this->getInnerIterator()->current(); $fileinfo = $this->getInnerIterator()->current();
// should at least match one rule // should at least match one rule
if ($this->matchRegexps) if ($this->matchRegexps) {
{
$match = false; $match = false;
foreach ($this->matchRegexps as $regex) foreach ($this->matchRegexps as $regex) {
{
if (preg_match($regex, $fileinfo->getFilename())) if (preg_match($regex, $fileinfo->getFilename()))
{ {
$match = true; $match = true;
break; break;
} }
} }
} } else {
else
{
$match = true; $match = true;
} }
// should at least not match one rule to exclude // should at least not match one rule to exclude
if ($this->noMatchRegexps) if ($this->noMatchRegexps) {
{
$exclude = false; $exclude = false;
foreach ($this->noMatchRegexps as $regex) foreach ($this->noMatchRegexps as $regex) {
{
if (preg_match($regex, $fileinfo->getFilename())) if (preg_match($regex, $fileinfo->getFilename()))
{ {
$exclude = true; $exclude = true;
break; break;
} }
} }
} } else {
else
{
$exclude = false; $exclude = false;
} }
@ -99,8 +89,7 @@ class FilenameFilterIterator extends \FilterIterator
protected function toRegex($str) protected function toRegex($str)
{ {
if (preg_match('/^([^a-zA-Z0-9\\\\]).+?\\1[ims]?$/', $str)) if (preg_match('/^([^a-zA-Z0-9\\\\]).+?\\1[ims]?$/', $str)) {
{
return $str; return $str;
} }

View File

@ -44,14 +44,12 @@ class SizeRangeFilterIterator extends \FilterIterator
{ {
$fileinfo = $this->getInnerIterator()->current(); $fileinfo = $this->getInnerIterator()->current();
if (!$fileinfo->isFile()) if (!$fileinfo->isFile()) {
{
return true; return true;
} }
$filesize = $fileinfo->getSize(); $filesize = $fileinfo->getSize();
foreach ($this->patterns as $compare) foreach ($this->patterns as $compare) {
{
if (!$compare->test($filesize)) if (!$compare->test($filesize))
{ {
return false; return false;

View File

@ -31,31 +31,23 @@ class SortableIterator extends \ArrayIterator
*/ */
public function __construct(\Iterator $iterator, $sort) public function __construct(\Iterator $iterator, $sort)
{ {
if (!$sort instanceof \Closure && self::SORT_BY_NAME == $sort) if (!$sort instanceof \Closure && self::SORT_BY_NAME == $sort) {
{
$sort = function ($a, $b) $sort = function ($a, $b)
{ {
return strcmp($a->getRealpath(), $b->getRealpath()); return strcmp($a->getRealpath(), $b->getRealpath());
}; };
} } elseif (!$sort instanceof \Closure && self::SORT_BY_TYPE == $sort) {
elseif (!$sort instanceof \Closure && self::SORT_BY_TYPE == $sort)
{
$sort = function ($a, $b) $sort = function ($a, $b)
{ {
if ($a->isDir() && $b->isFile()) if ($a->isDir() && $b->isFile()) {
{
return -1; return -1;
} } elseif ($a->isFile() && $b->isDir()) {
elseif ($a->isFile() && $b->isDir())
{
return 1; return 1;
} }
return strcmp($a->getRealpath(), $b->getRealpath()); return strcmp($a->getRealpath(), $b->getRealpath());
}; };
} } elseif (!$sort instanceof \Closure) {
elseif (!$sort instanceof \Closure)
{
throw new \InvalidArgumentException(sprintf('The SortableIterator takes a \Closure or a valid built-in sort algorithm as an argument (%s given).', $sort)); throw new \InvalidArgumentException(sprintf('The SortableIterator takes a \Closure or a valid built-in sort algorithm as an argument (%s given).', $sort));
} }

View File

@ -45,8 +45,7 @@ class NumberCompare
*/ */
public function __construct($test) public function __construct($test)
{ {
if (!preg_match('#^\s*([<>=]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) if (!preg_match('#^\s*([<>=]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
{
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a test.', $test)); throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a test.', $test));
} }
@ -54,8 +53,7 @@ class NumberCompare
$this->comparison = isset($matches[1]) ? $matches[1] : '=='; $this->comparison = isset($matches[1]) ? $matches[1] : '==';
$magnitude = strtolower(isset($matches[3]) ? $matches[3] : ''); $magnitude = strtolower(isset($matches[3]) ? $matches[3] : '');
switch ($magnitude) switch ($magnitude) {
{
case 'k': case 'k':
$this->target *= 1000; $this->target *= 1000;
break; break;
@ -84,23 +82,19 @@ class NumberCompare
*/ */
public function test($number) public function test($number)
{ {
if ($this->comparison === '>') if ($this->comparison === '>') {
{
return ($number > $this->target); return ($number > $this->target);
} }
if ($this->comparison === '>=') if ($this->comparison === '>=') {
{
return ($number >= $this->target); return ($number >= $this->target);
} }
if ($this->comparison === '<') if ($this->comparison === '<') {
{
return ($number < $this->target); return ($number < $this->target);
} }
if ($this->comparison === '<=') if ($this->comparison === '<=') {
{
return ($number <= $this->target); return ($number <= $this->target);
} }

View File

@ -36,8 +36,7 @@ class CacheControl
*/ */
public function __construct(HeaderBag $bag, $header, $type = null) public function __construct(HeaderBag $bag, $header, $type = null)
{ {
if (null !== $type && !in_array($type, array('request', 'response'))) if (null !== $type && !in_array($type, array('request', 'response'))) {
{
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the CacheControl constructor.', $type)); throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the CacheControl constructor.', $type));
} }
$this->type = $type; $this->type = $type;
@ -50,14 +49,11 @@ class CacheControl
{ {
$parts = array(); $parts = array();
ksort($this->attributes); ksort($this->attributes);
foreach ($this->attributes as $key => $value) foreach ($this->attributes as $key => $value) {
{
if (true === $value) if (true === $value)
{ {
$parts[] = $key; $parts[] = $key;
} } else {
else
{
if (preg_match('#[^a-zA-Z0-9._-]#', $value)) if (preg_match('#[^a-zA-Z0-9._-]#', $value))
{ {
$value = '"'.$value.'"'; $value = '"'.$value.'"';
@ -245,8 +241,7 @@ class CacheControl
{ {
$attributes = array(); $attributes = array();
preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER); preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
foreach ($matches as $match) foreach ($matches as $match) {
{
$attributes[strtolower($match[1])] = isset($match[2]) && $match[2] ? $match[2] : (isset($match[3]) ? $match[3] : true); $attributes[strtolower($match[1])] = isset($match[2]) && $match[2] ? $match[2] : (isset($match[3]) ? $match[3] : true);
} }
@ -255,12 +250,9 @@ class CacheControl
protected function setValue($key, $value, $isBoolean = false) protected function setValue($key, $value, $isBoolean = false)
{ {
if (false === $value) if (false === $value) {
{
unset($this->attributes[$key]); unset($this->attributes[$key]);
} } else {
else
{
$this->attributes[$key] = $isBoolean ? true : $value; $this->attributes[$key] = $isBoolean ? true : $value;
} }
@ -269,8 +261,7 @@ class CacheControl
protected function checkAttribute($name, $expected) protected function checkAttribute($name, $expected)
{ {
if (null !== $this->type && $expected !== $this->type) if (null !== $this->type && $expected !== $this->type) {
{
throw new \LogicException(sprintf("The property %s only applies to the %s Cache-Control.", $name, $expected)); throw new \LogicException(sprintf("The property %s only applies to the %s Cache-Control.", $name, $expected));
} }
} }

View File

@ -22,8 +22,7 @@ class ForbiddenHttpException extends HttpException
{ {
public function __construct($message = '') public function __construct($message = '')
{ {
if (!$message) if (!$message) {
{
$message = 'Forbidden'; $message = 'Forbidden';
} }

View File

@ -22,8 +22,7 @@ class NotFoundHttpException extends HttpException
{ {
public function __construct($message = '') public function __construct($message = '')
{ {
if (!$message) if (!$message) {
{
$message = 'Not Found'; $message = 'Not Found';
} }

View File

@ -22,8 +22,7 @@ class UnauthorizedHttpException extends HttpException
{ {
public function __construct($message = '') public function __construct($message = '')
{ {
if (!$message) if (!$message) {
{
$message = 'Unauthorized'; $message = 'Unauthorized';
} }

View File

@ -33,8 +33,7 @@ class HeaderBag extends ParameterBag
{ {
$this->replace($parameters); $this->replace($parameters);
if (null !== $type && !in_array($type, array('request', 'response'))) if (null !== $type && !in_array($type, array('request', 'response'))) {
{
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBag constructor.', $type)); throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBag constructor.', $type));
} }
$this->type = $type; $this->type = $type;
@ -49,8 +48,7 @@ class HeaderBag extends ParameterBag
{ {
$this->cacheControl = null; $this->cacheControl = null;
$this->parameters = array(); $this->parameters = array();
foreach ($parameters as $key => $value) foreach ($parameters as $key => $value) {
{
$this->parameters[strtr(strtolower($key), '_', '-')] = $value; $this->parameters[strtr(strtolower($key), '_', '-')] = $value;
} }
} }
@ -79,8 +77,7 @@ class HeaderBag extends ParameterBag
{ {
$key = strtr(strtolower($key), '_', '-'); $key = strtr(strtolower($key), '_', '-');
if (false === $replace) if (false === $replace) {
{
$current = $this->get($key, ''); $current = $this->get($key, '');
$value = ($current ? $current.', ' : '').$value; $value = ($current ? $current.', ' : '').$value;
} }
@ -117,8 +114,7 @@ class HeaderBag extends ParameterBag
*/ */
public function getCacheControl() public function getCacheControl()
{ {
if (null === $this->cacheControl) if (null === $this->cacheControl) {
{
$this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type); $this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type);
} }

View File

@ -65,22 +65,17 @@ class HttpKernel implements HttpKernelInterface
{ {
$main = (Boolean) $main; $main = (Boolean) $main;
if (null === $request) if (null === $request) {
{
$request = new Request(); $request = new Request();
} }
if (true === $main) if (true === $main) {
{
$this->request = $request; $this->request = $request;
} }
try try {
{
return $this->handleRaw($request, $main); return $this->handleRaw($request, $main);
} } catch (\Exception $e) {
catch (\Exception $e)
{
if (true === $raw) if (true === $raw)
{ {
throw $e; throw $e;
@ -88,8 +83,7 @@ class HttpKernel implements HttpKernelInterface
// exception // exception
$event = $this->dispatcher->notifyUntil(new Event($this, 'core.exception', array('main_request' => $main, 'request' => $request, 'exception' => $e))); $event = $this->dispatcher->notifyUntil(new Event($this, 'core.exception', array('main_request' => $main, 'request' => $request, 'exception' => $e)));
if ($event->isProcessed()) if ($event->isProcessed()) {
{
return $this->filterResponse($event->getReturnValue(), $request, 'A "core.exception" listener returned a non response object.', $main); return $this->filterResponse($event->getReturnValue(), $request, 'A "core.exception" listener returned a non response object.', $main);
} }
@ -116,41 +110,33 @@ class HttpKernel implements HttpKernelInterface
// request // request
$event = $this->dispatcher->notifyUntil(new Event($this, 'core.request', array('main_request' => $main, 'request' => $request))); $event = $this->dispatcher->notifyUntil(new Event($this, 'core.request', array('main_request' => $main, 'request' => $request)));
if ($event->isProcessed()) if ($event->isProcessed()) {
{
return $this->filterResponse($event->getReturnValue(), $request, 'A "core.request" listener returned a non response object.', $main); return $this->filterResponse($event->getReturnValue(), $request, 'A "core.request" listener returned a non response object.', $main);
} }
// load controller // load controller
$event = $this->dispatcher->notifyUntil(new Event($this, 'core.load_controller', array('main_request' => $main, 'request' => $request))); $event = $this->dispatcher->notifyUntil(new Event($this, 'core.load_controller', array('main_request' => $main, 'request' => $request)));
if (!$event->isProcessed()) if (!$event->isProcessed()) {
{
throw new NotFoundHttpException('Unable to find the controller.'); throw new NotFoundHttpException('Unable to find the controller.');
} }
list($controller, $arguments) = $event->getReturnValue(); list($controller, $arguments) = $event->getReturnValue();
// controller must be a callable // controller must be a callable
if (!is_callable($controller)) if (!is_callable($controller)) {
{
throw new \LogicException(sprintf('The controller must be a callable (%s).', var_export($controller, true))); throw new \LogicException(sprintf('The controller must be a callable (%s).', var_export($controller, true)));
} }
// controller // controller
$event = $this->dispatcher->notifyUntil(new Event($this, 'core.controller', array('main_request' => $main, 'request' => $request, 'controller' => &$controller, 'arguments' => &$arguments))); $event = $this->dispatcher->notifyUntil(new Event($this, 'core.controller', array('main_request' => $main, 'request' => $request, 'controller' => &$controller, 'arguments' => &$arguments)));
if ($event->isProcessed()) if ($event->isProcessed()) {
{
try try
{ {
return $this->filterResponse($event->getReturnValue(), $request, 'A "core.controller" listener returned a non response object.', $main); return $this->filterResponse($event->getReturnValue(), $request, 'A "core.controller" listener returned a non response object.', $main);
} } catch (\Exception $e) {
catch (\Exception $e)
{
$retval = $event->getReturnValue(); $retval = $event->getReturnValue();
} }
} } else {
else
{
// call controller // call controller
$retval = call_user_func_array($controller, $arguments); $retval = call_user_func_array($controller, $arguments);
} }
@ -173,16 +159,14 @@ class HttpKernel implements HttpKernelInterface
*/ */
protected function filterResponse($response, $request, $message, $main) protected function filterResponse($response, $request, $message, $main)
{ {
if (!$response instanceof Response) if (!$response instanceof Response) {
{
throw new \RuntimeException($message); throw new \RuntimeException($message);
} }
$event = $this->dispatcher->filter(new Event($this, 'core.response', array('main_request' => $main, 'request' => $request)), $response); $event = $this->dispatcher->filter(new Event($this, 'core.response', array('main_request' => $main, 'request' => $request)), $response);
$response = $event->getReturnValue(); $response = $event->getReturnValue();
if (!$response instanceof Response) if (!$response instanceof Response) {
{
throw new \RuntimeException('A "core.response" listener returned a non response object.'); throw new \RuntimeException('A "core.response" listener returned a non response object.');
} }

View File

@ -150,13 +150,11 @@ class ParameterBag
public function getDate($key, \DateTime $default = null) public function getDate($key, \DateTime $default = null)
{ {
if (null === $value = $this->get($key)) if (null === $value = $this->get($key)) {
{
return $default; return $default;
} }
if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
{
throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value)); throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
} }

View File

@ -117,22 +117,18 @@ class Request
'SCRIPT_FILENAME' => '', 'SCRIPT_FILENAME' => '',
); );
if (in_array(strtolower($method), array('post', 'put', 'delete'))) if (in_array(strtolower($method), array('post', 'put', 'delete'))) {
{
$request = $parameters; $request = $parameters;
$query = array(); $query = array();
$defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; $defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
} } else {
else
{
$request = array(); $request = array();
$query = $parameters; $query = $parameters;
} }
$queryString = false !== ($pos = strpos($uri, '?')) ? html_entity_decode(substr($uri, $pos + 1)) : ''; $queryString = false !== ($pos = strpos($uri, '?')) ? html_entity_decode(substr($uri, $pos + 1)) : '';
parse_str($queryString, $qs); parse_str($queryString, $qs);
if (is_array($qs)) if (is_array($qs)) {
{
$query = array_replace($qs, $query); $query = array_replace($qs, $query);
} }
@ -204,8 +200,7 @@ class Request
public function getPathInfo() public function getPathInfo()
{ {
if (null === $this->pathInfo) if (null === $this->pathInfo) {
{
$this->pathInfo = $this->preparePathInfo(); $this->pathInfo = $this->preparePathInfo();
} }
@ -214,8 +209,7 @@ class Request
public function getBasePath() public function getBasePath()
{ {
if (null === $this->basePath) if (null === $this->basePath) {
{
$this->basePath = $this->prepareBasePath(); $this->basePath = $this->prepareBasePath();
} }
@ -224,8 +218,7 @@ class Request
public function getBaseUrl() public function getBaseUrl()
{ {
if (null === $this->baseUrl) if (null === $this->baseUrl) {
{
$this->baseUrl = $this->prepareBaseUrl(); $this->baseUrl = $this->prepareBaseUrl();
} }
@ -245,8 +238,7 @@ class Request
public function getHttpHost() public function getHttpHost()
{ {
$host = $this->headers->get('HOST'); $host = $this->headers->get('HOST');
if (!empty($host)) if (!empty($host)) {
{
return $host; return $host;
} }
@ -254,20 +246,16 @@ class Request
$name = $this->server->get('SERVER_NAME'); $name = $this->server->get('SERVER_NAME');
$port = $this->server->get('SERVER_PORT'); $port = $this->server->get('SERVER_PORT');
if (($scheme === 'http' && $port === 80) || ($scheme === 'https' && $port === 443)) if (($scheme === 'http' && $port === 80) || ($scheme === 'https' && $port === 443)) {
{
return $name; return $name;
} } else {
else
{
return $name.':'.$port; return $name.':'.$port;
} }
} }
public function getRequestUri() public function getRequestUri()
{ {
if (null === $this->requestUri) if (null === $this->requestUri) {
{
$this->requestUri = $this->prepareRequestUri(); $this->requestUri = $this->prepareRequestUri();
} }
@ -292,14 +280,11 @@ class Request
*/ */
public function getHost() public function getHost()
{ {
if ($host = $this->headers->get('X_FORWARDED_HOST')) if ($host = $this->headers->get('X_FORWARDED_HOST')) {
{
$elements = implode(',', $host); $elements = implode(',', $host);
return trim($elements[count($elements) - 1]); return trim($elements[count($elements) - 1]);
} } else {
else
{
return $this->headers->get('HOST', $this->server->get('SERVER_NAME', $this->server->get('SERVER_ADDR', ''))); return $this->headers->get('HOST', $this->server->get('SERVER_NAME', $this->server->get('SERVER_ADDR', '')));
} }
} }
@ -317,8 +302,7 @@ class Request
*/ */
public function getMethod() public function getMethod()
{ {
if (null === $this->method) if (null === $this->method) {
{
switch ($this->server->get('REQUEST_METHOD', 'GET')) switch ($this->server->get('REQUEST_METHOD', 'GET'))
{ {
case 'POST': case 'POST':
@ -354,8 +338,7 @@ class Request
*/ */
public function getMimeType($format) public function getMimeType($format)
{ {
if (null === static::$formats) if (null === static::$formats) {
{
static::initializeFormats(); static::initializeFormats();
} }
@ -371,13 +354,11 @@ class Request
*/ */
public function getFormat($mimeType) public function getFormat($mimeType)
{ {
if (null === static::$formats) if (null === static::$formats) {
{
static::initializeFormats(); static::initializeFormats();
} }
foreach (static::$formats as $format => $mimeTypes) foreach (static::$formats as $format => $mimeTypes) {
{
if (in_array($mimeType, (array) $mimeTypes)) if (in_array($mimeType, (array) $mimeTypes))
{ {
return $format; return $format;
@ -395,8 +376,7 @@ class Request
*/ */
public function setFormat($format, $mimeTypes) public function setFormat($format, $mimeTypes)
{ {
if (null === static::$formats) if (null === static::$formats) {
{
static::initializeFormats(); static::initializeFormats();
} }
@ -416,8 +396,7 @@ class Request
*/ */
public function getRequestFormat() public function getRequestFormat()
{ {
if (null === $this->format) if (null === $this->format) {
{
$this->format = $this->get('_format', 'html'); $this->format = $this->get('_format', 'html');
} }
@ -445,13 +424,11 @@ class Request
{ {
$preferredLanguages = $this->getLanguages(); $preferredLanguages = $this->getLanguages();
if (null === $cultures) if (null === $cultures) {
{
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null; return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
} }
if (!$preferredLanguages) if (!$preferredLanguages) {
{
return $cultures[0]; return $cultures[0];
} }
@ -467,37 +444,28 @@ class Request
*/ */
public function getLanguages() public function getLanguages()
{ {
if (null !== $this->languages) if (null !== $this->languages) {
{
return $this->languages; return $this->languages;
} }
$languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language')); $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
foreach ($languages as $lang) foreach ($languages as $lang) {
{
if (strstr($lang, '-')) if (strstr($lang, '-'))
{ {
$codes = explode('-', $lang); $codes = explode('-', $lang);
if ($codes[0] == 'i') if ($codes[0] == 'i') {
{
// Language not listed in ISO 639 that are not variants // Language not listed in ISO 639 that are not variants
// of any listed language, which can be registered with the // of any listed language, which can be registered with the
// i-prefix, such as i-cherokee // i-prefix, such as i-cherokee
if (count($codes) > 1) if (count($codes) > 1) {
{
$lang = $codes[1]; $lang = $codes[1];
} }
} } else {
else
{
for ($i = 0, $max = count($codes); $i < $max; $i++) for ($i = 0, $max = count($codes); $i < $max; $i++)
{ {
if ($i == 0) if ($i == 0) {
{
$lang = strtolower($codes[0]); $lang = strtolower($codes[0]);
} } else {
else
{
$lang .= '_'.strtoupper($codes[$i]); $lang .= '_'.strtoupper($codes[$i]);
} }
} }
@ -517,8 +485,7 @@ class Request
*/ */
public function getCharsets() public function getCharsets()
{ {
if (null !== $this->charsets) if (null !== $this->charsets) {
{
return $this->charsets; return $this->charsets;
} }
@ -532,8 +499,7 @@ class Request
*/ */
public function getAcceptableContentTypes() public function getAcceptableContentTypes()
{ {
if (null !== $this->acceptableContentTypes) if (null !== $this->acceptableContentTypes) {
{
return $this->acceptableContentTypes; return $this->acceptableContentTypes;
} }
@ -560,27 +526,21 @@ class Request
*/ */
public function splitHttpAcceptHeader($header) public function splitHttpAcceptHeader($header)
{ {
if (!$header) if (!$header) {
{
return array(); return array();
} }
$values = array(); $values = array();
foreach (array_filter(explode(',', $header)) as $value) foreach (array_filter(explode(',', $header)) as $value) {
{
// Cut off any q-value that might come after a semi-colon // Cut off any q-value that might come after a semi-colon
if ($pos = strpos($value, ';')) if ($pos = strpos($value, ';')) {
{
$q = (float) trim(substr($value, strpos($value, '=') + 1)); $q = (float) trim(substr($value, strpos($value, '=') + 1));
$value = trim(substr($value, 0, $pos)); $value = trim(substr($value, 0, $pos));
} } else {
else
{
$q = 1; $q = 1;
} }
if (0 < $q) if (0 < $q) {
{
$values[trim($value)] = $q; $values[trim($value)] = $q;
} }
} }
@ -602,32 +562,23 @@ class Request
{ {
$requestUri = ''; $requestUri = '';
if ($this->headers->has('X_REWRITE_URL')) if ($this->headers->has('X_REWRITE_URL')) {
{
// check this first so IIS will catch // check this first so IIS will catch
$requestUri = $this->headers->get('X_REWRITE_URL'); $requestUri = $this->headers->get('X_REWRITE_URL');
} } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '')
{
// IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem) // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
$requestUri = $this->server->get('UNENCODED_URL'); $requestUri = $this->server->get('UNENCODED_URL');
} } elseif ($this->server->has('REQUEST_URI')) {
elseif ($this->server->has('REQUEST_URI'))
{
$requestUri = $this->server->get('REQUEST_URI'); $requestUri = $this->server->get('REQUEST_URI');
// HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
$schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost(); $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
if (strpos($requestUri, $schemeAndHttpHost) === 0) if (strpos($requestUri, $schemeAndHttpHost) === 0) {
{
$requestUri = substr($requestUri, strlen($schemeAndHttpHost)); $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
} }
} } elseif ($this->server->has('ORIG_PATH_INFO')) {
elseif ($this->server->has('ORIG_PATH_INFO'))
{
// IIS 5.0, PHP as CGI // IIS 5.0, PHP as CGI
$requestUri = $this->server->get('ORIG_PATH_INFO'); $requestUri = $this->server->get('ORIG_PATH_INFO');
if ($this->server->get('QUERY_STRING')) if ($this->server->get('QUERY_STRING')) {
{
$requestUri .= '?'.$this->server->get('QUERY_STRING'); $requestUri .= '?'.$this->server->get('QUERY_STRING');
} }
} }
@ -641,20 +592,13 @@ class Request
$filename = basename($this->server->get('SCRIPT_FILENAME')); $filename = basename($this->server->get('SCRIPT_FILENAME'));
if (basename($this->server->get('SCRIPT_NAME')) === $filename) if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
{
$baseUrl = $this->server->get('SCRIPT_NAME'); $baseUrl = $this->server->get('SCRIPT_NAME');
} } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
elseif (basename($this->server->get('PHP_SELF')) === $filename)
{
$baseUrl = $this->server->get('PHP_SELF'); $baseUrl = $this->server->get('PHP_SELF');
} } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename)
{
$baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
} } else {
else
{
// Backtrack up the script_filename to find the portion matching // Backtrack up the script_filename to find the portion matching
// php_self // php_self
$path = $this->server->get('PHP_SELF', ''); $path = $this->server->get('PHP_SELF', '');
@ -664,8 +608,7 @@ class Request
$index = 0; $index = 0;
$last = count($segs); $last = count($segs);
$baseUrl = ''; $baseUrl = '';
do do {
{
$seg = $segs[$index]; $seg = $segs[$index];
$baseUrl = '/'.$seg.$baseUrl; $baseUrl = '/'.$seg.$baseUrl;
++$index; ++$index;
@ -675,27 +618,23 @@ class Request
// Does the baseUrl have anything in common with the request_uri? // Does the baseUrl have anything in common with the request_uri?
$requestUri = $this->getRequestUri(); $requestUri = $this->getRequestUri();
if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
{
// full $baseUrl matches // full $baseUrl matches
return $baseUrl; return $baseUrl;
} }
if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
{
// directory portion of $baseUrl matches // directory portion of $baseUrl matches
return rtrim(dirname($baseUrl), '/'); return rtrim(dirname($baseUrl), '/');
} }
$truncatedRequestUri = $requestUri; $truncatedRequestUri = $requestUri;
if (($pos = strpos($requestUri, '?')) !== false) if (($pos = strpos($requestUri, '?')) !== false) {
{
$truncatedRequestUri = substr($requestUri, 0, $pos); $truncatedRequestUri = substr($requestUri, 0, $pos);
} }
$basename = basename($baseUrl); $basename = basename($baseUrl);
if (empty($basename) || !strpos($truncatedRequestUri, $basename)) if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
{
// no match whatsoever; set it blank // no match whatsoever; set it blank
return ''; return '';
} }
@ -703,8 +642,7 @@ class Request
// If using mod_rewrite or ISAPI_Rewrite strip the script filename // If using mod_rewrite or ISAPI_Rewrite strip the script filename
// out of baseUrl. $pos !== 0 makes sure it is not matching a value // out of baseUrl. $pos !== 0 makes sure it is not matching a value
// from PATH_INFO or QUERY_STRING // from PATH_INFO or QUERY_STRING
if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
{
$baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
} }
@ -716,22 +654,17 @@ class Request
$basePath = ''; $basePath = '';
$filename = basename($this->server->get('SCRIPT_FILENAME')); $filename = basename($this->server->get('SCRIPT_FILENAME'));
$baseUrl = $this->getBaseUrl(); $baseUrl = $this->getBaseUrl();
if (empty($baseUrl)) if (empty($baseUrl)) {
{
return ''; return '';
} }
if (basename($baseUrl) === $filename) if (basename($baseUrl) === $filename) {
{
$basePath = dirname($baseUrl); $basePath = dirname($baseUrl);
} } else {
else
{
$basePath = $baseUrl; $basePath = $baseUrl;
} }
if ('\\' === DIRECTORY_SEPARATOR) if ('\\' === DIRECTORY_SEPARATOR) {
{
$basePath = str_replace('\\', '/', $basePath); $basePath = str_replace('\\', '/', $basePath);
} }
@ -742,26 +675,21 @@ class Request
{ {
$baseUrl = $this->getBaseUrl(); $baseUrl = $this->getBaseUrl();
if (null === ($requestUri = $this->getRequestUri())) if (null === ($requestUri = $this->getRequestUri())) {
{
return ''; return '';
} }
$pathInfo = ''; $pathInfo = '';
// Remove the query string from REQUEST_URI // Remove the query string from REQUEST_URI
if ($pos = strpos($requestUri, '?')) if ($pos = strpos($requestUri, '?')) {
{
$requestUri = substr($requestUri, 0, $pos); $requestUri = substr($requestUri, 0, $pos);
} }
if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
{
// If substr() returns false then PATH_INFO is set to an empty string // If substr() returns false then PATH_INFO is set to an empty string
return ''; return '';
} } elseif (null === $baseUrl) {
elseif (null === $baseUrl)
{
return $requestUri; return $requestUri;
} }
@ -780,8 +708,7 @@ class Request
protected function convertFileInformation(array $taintedFiles) protected function convertFileInformation(array $taintedFiles)
{ {
$files = array(); $files = array();
foreach ($taintedFiles as $key => $data) foreach ($taintedFiles as $key => $data) {
{
$files[$key] = $this->fixPhpFilesArray($data); $files[$key] = $this->fixPhpFilesArray($data);
} }
@ -791,8 +718,7 @@ class Request
protected function initializeHeaders() protected function initializeHeaders()
{ {
$headers = array(); $headers = array();
foreach ($this->server->all() as $key => $value) foreach ($this->server->all() as $key => $value) {
{
if ('http_' === strtolower(substr($key, 0, 5))) if ('http_' === strtolower(substr($key, 0, 5)))
{ {
$headers[substr($key, 5)] = $value; $headers[substr($key, 5)] = $value;
@ -821,18 +747,15 @@ class Request
$keys = array_keys($data); $keys = array_keys($data);
sort($keys); sort($keys);
if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
{
return $data; return $data;
} }
$files = $data; $files = $data;
foreach ($fileKeys as $k) foreach ($fileKeys as $k) {
{
unset($files[$k]); unset($files[$k]);
} }
foreach (array_keys($data['name']) as $key) foreach (array_keys($data['name']) as $key) {
{
$files[$key] = self::fixPhpFilesArray(array( $files[$key] = self::fixPhpFilesArray(array(
'error' => $data['error'][$key], 'error' => $data['error'][$key],
'name' => $data['name'][$key], 'name' => $data['name'][$key],

View File

@ -112,8 +112,7 @@ class Response
*/ */
public function sendHeaders() public function sendHeaders()
{ {
if (!$this->headers->has('Content-Type')) if (!$this->headers->has('Content-Type')) {
{
$this->headers->set('Content-Type', 'text/html'); $this->headers->set('Content-Type', 'text/html');
} }
@ -121,14 +120,12 @@ class Response
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)); header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
// headers // headers
foreach ($this->headers->all() as $name => $value) foreach ($this->headers->all() as $name => $value) {
{
header($name.': '.$value); header($name.': '.$value);
} }
// cookies // cookies
foreach ($this->cookies as $cookie) foreach ($this->cookies as $cookie) {
{
setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']); setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']);
} }
} }
@ -205,17 +202,13 @@ class Response
*/ */
public function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false) public function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false)
{ {
if (null !== $expire) if (null !== $expire) {
{
if (is_numeric($expire)) if (is_numeric($expire))
{ {
$expire = (int) $expire; $expire = (int) $expire;
} } else {
else
{
$expire = strtotime($expire); $expire = strtotime($expire);
if (false === $expire || -1 == $expire) if (false === $expire || -1 == $expire) {
{
throw new \InvalidArgumentException('The cookie expire parameter is not valid.'); throw new \InvalidArgumentException('The cookie expire parameter is not valid.');
} }
} }
@ -253,8 +246,7 @@ class Response
public function setStatusCode($code, $text = null) public function setStatusCode($code, $text = null)
{ {
$this->statusCode = (int) $code; $this->statusCode = (int) $code;
if ($this->statusCode < 100 || $this->statusCode > 599) if ($this->statusCode < 100 || $this->statusCode > 599) {
{
throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code)); throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
} }
@ -284,13 +276,11 @@ class Response
*/ */
public function isCacheable() public function isCacheable()
{ {
if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
{
return false; return false;
} }
if ($this->headers->getCacheControl()->isNoStore() || $this->headers->getCacheControl()->isPrivate()) if ($this->headers->getCacheControl()->isNoStore() || $this->headers->getCacheControl()->isPrivate()) {
{
return false; return false;
} }
@ -362,8 +352,7 @@ class Response
*/ */
public function getDate() public function getDate()
{ {
if (null === $date = $this->headers->getDate('Date')) if (null === $date = $this->headers->getDate('Date')) {
{
$date = new \DateTime(); $date = new \DateTime();
$this->headers->set('Date', $date->format(DATE_RFC2822)); $this->headers->set('Date', $date->format(DATE_RFC2822));
} }
@ -378,8 +367,7 @@ class Response
*/ */
public function getAge() public function getAge()
{ {
if ($age = $this->headers->get('Age')) if ($age = $this->headers->get('Age')) {
{
return $age; return $age;
} }
@ -391,8 +379,7 @@ class Response
*/ */
public function expire() public function expire()
{ {
if ($this->isFresh()) if ($this->isFresh()) {
{
$this->headers->set('Age', $this->getMaxAge()); $this->headers->set('Age', $this->getMaxAge());
} }
} }
@ -416,12 +403,9 @@ class Response
*/ */
public function setExpires(\DateTime $date = null) public function setExpires(\DateTime $date = null)
{ {
if (null === $date) if (null === $date) {
{
$this->headers->delete('Expires'); $this->headers->delete('Expires');
} } else {
else
{
$this->headers->set('Expires', $date->format(DATE_RFC2822)); $this->headers->set('Expires', $date->format(DATE_RFC2822));
} }
} }
@ -437,18 +421,15 @@ class Response
*/ */
public function getMaxAge() public function getMaxAge()
{ {
if ($age = $this->headers->getCacheControl()->getSharedMaxAge()) if ($age = $this->headers->getCacheControl()->getSharedMaxAge()) {
{
return $age; return $age;
} }
if ($age = $this->headers->getCacheControl()->getMaxAge()) if ($age = $this->headers->getCacheControl()->getMaxAge()) {
{
return $age; return $age;
} }
if (null !== $this->getExpires()) if (null !== $this->getExpires()) {
{
return $this->getExpires()->format('U') - $this->getDate()->format('U'); return $this->getExpires()->format('U') - $this->getDate()->format('U');
} }
@ -491,8 +472,7 @@ class Response
*/ */
public function getTtl() public function getTtl()
{ {
if ($maxAge = $this->getMaxAge()) if ($maxAge = $this->getMaxAge()) {
{
return $maxAge - $this->getAge(); return $maxAge - $this->getAge();
} }
@ -542,12 +522,9 @@ class Response
*/ */
public function setLastModified(\DateTime $date = null) public function setLastModified(\DateTime $date = null)
{ {
if (null === $date) if (null === $date) {
{
$this->headers->delete('Last-Modified'); $this->headers->delete('Last-Modified');
} } else {
else
{
$this->headers->set('Last-Modified', $date->format(DATE_RFC2822)); $this->headers->set('Last-Modified', $date->format(DATE_RFC2822));
} }
@ -565,12 +542,9 @@ class Response
public function setEtag($etag = null) public function setEtag($etag = null)
{ {
if (null === $etag) if (null === $etag) {
{
$this->headers->delete('Etag'); $this->headers->delete('Etag');
} } else {
else
{
$this->headers->set('ETag', $etag); $this->headers->set('ETag', $etag);
} }
} }
@ -589,8 +563,7 @@ class Response
$this->setContent(null); $this->setContent(null);
// remove headers that MUST NOT be included with 304 Not Modified responses // remove headers that MUST NOT be included with 304 Not Modified responses
foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
{
$this->headers->delete($header); $this->headers->delete($header);
} }
} }
@ -612,8 +585,7 @@ class Response
*/ */
public function getVary() public function getVary()
{ {
if (!$vary = $this->headers->get('Vary')) if (!$vary = $this->headers->get('Vary')) {
{
return array(); return array();
} }
@ -635,19 +607,15 @@ class Response
{ {
$lastModified = $request->headers->get('If-Modified-Since'); $lastModified = $request->headers->get('If-Modified-Since');
$notModified = false; $notModified = false;
if ($etags = $request->headers->get('If-None-Match')) if ($etags = $request->headers->get('If-None-Match')) {
{
$etags = preg_split('/\s*,\s*/', $etags); $etags = preg_split('/\s*,\s*/', $etags);
$notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified); $notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
} } elseif ($lastModified) {
elseif ($lastModified)
{
$notModified = $lastModified == $this->headers->get('Last-Modified'); $notModified = $lastModified == $this->headers->get('Last-Modified');
} }
if ($notModified) if ($notModified) {
{
$this->setNotModified(); $this->setNotModified();
} }

View File

@ -92,8 +92,7 @@ class Client extends BaseClient
*/ */
public function getTester($name) public function getTester($name)
{ {
if (!isset($this->testers[$name])) if (!isset($this->testers[$name])) {
{
throw new \InvalidArgumentException(sprintf('Tester "%s" does not exist.', $name)); throw new \InvalidArgumentException(sprintf('Tester "%s" does not exist.', $name));
} }
@ -151,8 +150,7 @@ EOF;
protected function filterRequest(DomRequest $request) protected function filterRequest(DomRequest $request)
{ {
$uri = $request->getUri(); $uri = $request->getUri();
if (preg_match('#^https?\://([^/]+)/(.*)$#', $uri, $matches)) if (preg_match('#^https?\://([^/]+)/(.*)$#', $uri, $matches)) {
{
$uri = '/'.$matches[2]; $uri = '/'.$matches[2];
} }
@ -181,26 +179,22 @@ EOF;
*/ */
public function __call($method, $arguments) public function __call($method, $arguments)
{ {
if ('assert' !== substr($method, 0, 6)) if ('assert' !== substr($method, 0, 6)) {
{
throw new \BadMethodCallException(sprintf('Method %s::%s is not defined.', get_class($this), $method)); throw new \BadMethodCallException(sprintf('Method %s::%s is not defined.', get_class($this), $method));
} }
// standard PHPUnit assert? // standard PHPUnit assert?
if (method_exists($this->test, $method)) if (method_exists($this->test, $method)) {
{
return call_user_func_array(array($this->test, $method), $arguments); return call_user_func_array(array($this->test, $method), $arguments);
} }
if (!preg_match('/^assert([A-Z].+?)([A-Z].+)$/', $method, $matches)) if (!preg_match('/^assert([A-Z].+?)([A-Z].+)$/', $method, $matches)) {
{
throw new \BadMethodCallException(sprintf('Method %s::%s is not defined.', get_class($this), $method)); throw new \BadMethodCallException(sprintf('Method %s::%s is not defined.', get_class($this), $method));
} }
// registered tester object? // registered tester object?
$name = strtolower($matches[1]); $name = strtolower($matches[1]);
if (!$this->hasTester($name)) if (!$this->hasTester($name)) {
{
throw new \BadMethodCallException(sprintf('Method %s::%s is not defined (assert object "%s" is not defined).', get_class($this), $method, $name)); throw new \BadMethodCallException(sprintf('Method %s::%s is not defined (assert object "%s" is not defined).', get_class($this), $method, $name));
} }

View File

@ -126,8 +126,7 @@ class RequestTester extends Tester
*/ */
public function assertCookieEquals($name, $value) public function assertCookieEquals($name, $value)
{ {
if (!$this->request->cookies->has($name)) if (!$this->request->cookies->has($name)) {
{
return $this->test->fail(sprintf('Cookie "%s" does not exist.', $name)); return $this->test->fail(sprintf('Cookie "%s" does not exist.', $name));
} }
@ -142,8 +141,7 @@ class RequestTester extends Tester
*/ */
public function assertCookieRegExp($name, $regexp) public function assertCookieRegExp($name, $regexp)
{ {
if (!$this->request->cookies->has($name)) if (!$this->request->cookies->has($name)) {
{
return $this->test->fail(sprintf('cookie "%s" does not exist.', $name)); return $this->test->fail(sprintf('cookie "%s" does not exist.', $name));
} }
@ -158,8 +156,7 @@ class RequestTester extends Tester
*/ */
public function assertNotCookieRegExp($name, $regexp) public function assertNotCookieRegExp($name, $regexp)
{ {
if (!$this->request->cookies->has($name)) if (!$this->request->cookies->has($name)) {
{
return $this->test->fail(sprintf('Cookie "%s" does not exist.', $name)); return $this->test->fail(sprintf('Cookie "%s" does not exist.', $name));
} }

View File

@ -35,8 +35,7 @@ class ResponseTester extends Tester
{ {
$this->response = $response; $this->response = $response;
if (class_exists('Symfony\Components\DomCrawler\Crawler')) if (class_exists('Symfony\Components\DomCrawler\Crawler')) {
{
$this->crawler = new Crawler(); $this->crawler = new Crawler();
$this->crawler->addContent($this->response->getContent(), $this->response->headers->get('Content-Type')); $this->crawler->addContent($this->response->getContent(), $this->response->headers->get('Content-Type'));
} }
@ -51,8 +50,7 @@ class ResponseTester extends Tester
*/ */
public function assertSelectEquals($selector, $arguments, $expected) public function assertSelectEquals($selector, $arguments, $expected)
{ {
if (null === $this->crawler) if (null === $this->crawler) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__)); throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -69,8 +67,7 @@ class ResponseTester extends Tester
*/ */
public function assertSelectCount($selector, $count) public function assertSelectCount($selector, $count)
{ {
if (null === $this->crawler) if (null === $this->crawler) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__)); throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -86,8 +83,7 @@ class ResponseTester extends Tester
*/ */
public function assertSelectExists($selector) public function assertSelectExists($selector)
{ {
if (null === $this->crawler) if (null === $this->crawler) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__)); throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -103,8 +99,7 @@ class ResponseTester extends Tester
*/ */
public function assertNotSelectExists($selector) public function assertNotSelectExists($selector)
{ {
if (null === $this->crawler) if (null === $this->crawler) {
{
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__)); throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@ -122,8 +117,7 @@ class ResponseTester extends Tester
public function assertHeaderEquals($key, $value) public function assertHeaderEquals($key, $value)
{ {
$headers = explode(', ', $this->response->headers->get($key)); $headers = explode(', ', $this->response->headers->get($key));
foreach ($headers as $header) foreach ($headers as $header) {
{
if ($header == $value) if ($header == $value)
{ {
return $this->test->pass(sprintf('Response header "%s" is "%s" (%s)', $key, $value, $this->response->headers->get($key))); return $this->test->pass(sprintf('Response header "%s" is "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@ -142,8 +136,7 @@ class ResponseTester extends Tester
public function assertNotHeaderEquals($key, $value) public function assertNotHeaderEquals($key, $value)
{ {
$headers = explode(', ', $this->response->headers->get($key)); $headers = explode(', ', $this->response->headers->get($key));
foreach ($headers as $header) foreach ($headers as $header) {
{
if ($header == $value) if ($header == $value)
{ {
return $this->test->fail(sprintf('Response header "%s" is not "%s" (%s)', $key, $value, $this->response->headers->get($key))); return $this->test->fail(sprintf('Response header "%s" is not "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@ -162,8 +155,7 @@ class ResponseTester extends Tester
public function assertHeaderRegExp($key, $regex) public function assertHeaderRegExp($key, $regex)
{ {
$headers = explode(', ', $this->response->headers->get($key)); $headers = explode(', ', $this->response->headers->get($key));
foreach ($headers as $header) foreach ($headers as $header) {
{
if (preg_match($regex, $header)) if (preg_match($regex, $header))
{ {
return $this->test->pass(sprintf('Response header "%s" matches "%s" (%s)', $key, $value, $this->response->headers->get($key))); return $this->test->pass(sprintf('Response header "%s" matches "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@ -182,8 +174,7 @@ class ResponseTester extends Tester
public function assertNotHeaderRegExp($key, $regex) public function assertNotHeaderRegExp($key, $regex)
{ {
$headers = explode(', ', $this->response->headers->get($key)); $headers = explode(', ', $this->response->headers->get($key));
foreach ($headers as $header) foreach ($headers as $header) {
{
if (!preg_match($regex, $header)) if (!preg_match($regex, $header))
{ {
return $this->test->pass(sprintf('Response header "%s" matches "%s" (%s)', $key, $value, $this->response->headers->get($key))); return $this->test->pass(sprintf('Response header "%s" matches "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@ -202,21 +193,16 @@ class ResponseTester extends Tester
*/ */
public function assertCookie($name, $value = null, $attributes = array()) public function assertCookie($name, $value = null, $attributes = array())
{ {
foreach ($this->response->getCookies() as $cookie) foreach ($this->response->getCookies() as $cookie) {
{
if ($name == $cookie['name']) if ($name == $cookie['name'])
{ {
if (null === $value) if (null === $value) {
{
$this->test->pass(sprintf('Response sets cookie "%s"', $name)); $this->test->pass(sprintf('Response sets cookie "%s"', $name));
} } else {
else
{
$this->test->assertTrue($value == $cookie['value'], sprintf('Response sets cookie "%s" to "%s"', $name, $value)); $this->test->assertTrue($value == $cookie['value'], sprintf('Response sets cookie "%s" to "%s"', $name, $value));
} }
foreach ($attributes as $attributeName => $attributeValue) foreach ($attributes as $attributeName => $attributeValue) {
{
if (!array_key_exists($attributeName, $cookie)) if (!array_key_exists($attributeName, $cookie))
{ {
throw new \LogicException(sprintf('The cookie attribute "%s" is not valid.', $attributeName)); throw new \LogicException(sprintf('The cookie attribute "%s" is not valid.', $attributeName));
@ -335,8 +321,7 @@ class ResponseTester extends Tester
{ {
$this->test->assertTrue(in_array($this->response->getStatusCode(), array(301, 302, 303, 307)), 'Status code is a redirect'); $this->test->assertTrue(in_array($this->response->getStatusCode(), array(301, 302, 303, 307)), 'Status code is a redirect');
if (null !== $location) if (null !== $location) {
{
$this->test->assertEquals($location, $this->response->headers->get('Location'), sprintf('Page redirected to "%s"', $location)); $this->test->assertEquals($location, $this->response->headers->get('Location'), sprintf('Page redirected to "%s"', $location));
} }
} }

View File

@ -51,8 +51,7 @@ abstract class Escaper
*/ */
public function __construct($escaper, $value) public function __construct($escaper, $value)
{ {
if (null === self::$escapers) if (null === self::$escapers) {
{
self::initializeEscapers(); self::initializeEscapers();
} }
@ -90,34 +89,28 @@ abstract class Escaper
*/ */
static public function escape($escaper, $value) static public function escape($escaper, $value)
{ {
if (null === $value) if (null === $value) {
{
return $value; return $value;
} }
if (null === self::$escapers) if (null === self::$escapers) {
{
self::initializeEscapers(); self::initializeEscapers();
} }
if (is_string($escaper) && isset(self::$escapers[$escaper])) if (is_string($escaper) && isset(self::$escapers[$escaper])) {
{
$escaper = self::$escapers[$escaper]; $escaper = self::$escapers[$escaper];
} }
// Scalars are anything other than arrays, objects and resources. // Scalars are anything other than arrays, objects and resources.
if (is_scalar($value)) if (is_scalar($value)) {
{
return call_user_func($escaper, $value); return call_user_func($escaper, $value);
} }
if (is_array($value)) if (is_array($value)) {
{
return new ArrayDecorator($escaper, $value); return new ArrayDecorator($escaper, $value);
} }
if (is_object($value)) if (is_object($value)) {
{
if ($value instanceof Escaper) if ($value instanceof Escaper)
{ {
// avoid double decoration // avoid double decoration
@ -128,22 +121,19 @@ abstract class Escaper
return $copy; return $copy;
} }
if (self::isClassMarkedAsSafe(get_class($value))) if (self::isClassMarkedAsSafe(get_class($value))) {
{
// the class or one of its children is marked as safe // the class or one of its children is marked as safe
// return the unescaped object // return the unescaped object
return $value; return $value;
} }
if ($value instanceof SafeDecorator) if ($value instanceof SafeDecorator) {
{
// do not escape objects marked as safe // do not escape objects marked as safe
// return the original object // return the original object
return $value->getValue(); return $value->getValue();
} }
if ($value instanceof \Traversable) if ($value instanceof \Traversable) {
{
return new IteratorDecorator($escaper, $value); return new IteratorDecorator($escaper, $value);
} }
@ -166,18 +156,15 @@ abstract class Escaper
*/ */
static public function unescape($value) static public function unescape($value)
{ {
if (null === $value || is_bool($value)) if (null === $value || is_bool($value)) {
{
return $value; return $value;
} }
if (is_scalar($value)) if (is_scalar($value)) {
{
return html_entity_decode($value, ENT_QUOTES, self::$charset); return html_entity_decode($value, ENT_QUOTES, self::$charset);
} }
if (is_array($value)) if (is_array($value)) {
{
foreach ($value as $name => $v) foreach ($value as $name => $v)
{ {
$value[$name] = self::unescape($v); $value[$name] = self::unescape($v);
@ -186,8 +173,7 @@ abstract class Escaper
return $value; return $value;
} }
if (is_object($value)) if (is_object($value)) {
{
return $value instanceof Escaper ? $value->getRawValue() : $value; return $value instanceof Escaper ? $value->getRawValue() : $value;
} }
@ -203,13 +189,11 @@ abstract class Escaper
*/ */
static public function isClassMarkedAsSafe($class) static public function isClassMarkedAsSafe($class)
{ {
if (in_array($class, self::$safeClasses)) if (in_array($class, self::$safeClasses)) {
{
return true; return true;
} }
foreach (self::$safeClasses as $safeClass) foreach (self::$safeClasses as $safeClass) {
{
if (is_subclass_of($class, $safeClass)) if (is_subclass_of($class, $safeClass))
{ {
return true; return true;

View File

@ -47,8 +47,7 @@ abstract class GetterDecorator extends Escaper
*/ */
public function get($key, $escaper = null) public function get($key, $escaper = null)
{ {
if (!$escaper) if (!$escaper) {
{
$escaper = $this->escaper; $escaper = $this->escaper;
} }

View File

@ -46,22 +46,16 @@ class ObjectDecorator extends GetterDecorator
*/ */
public function __call($method, $args) public function __call($method, $args)
{ {
if (count($args) > 0) if (count($args) > 0) {
{
$escaper = $args[count($args) - 1]; $escaper = $args[count($args) - 1];
if (is_string($escaper) && 'esc_' === substr($escaper, 0, 4)) if (is_string($escaper) && 'esc_' === substr($escaper, 0, 4)) {
{
$escaper = substr($escaper, 4); $escaper = substr($escaper, 4);
array_pop($args); array_pop($args);
} } else {
else
{
$escaper = $this->escaper; $escaper = $this->escaper;
} }
} } else {
else
{
$escaper = $this->escaper; $escaper = $this->escaper;
} }
@ -84,8 +78,7 @@ class ObjectDecorator extends GetterDecorator
*/ */
public function getRaw($key) public function getRaw($key)
{ {
if (!is_callable(array($this->value, 'get'))) if (!is_callable(array($this->value, 'get'))) {
{
throw new \LogicException('Object does not have a callable get() method.'); throw new \LogicException('Object does not have a callable get() method.');
} }

View File

@ -31,8 +31,7 @@ class SafeDecorator extends \ArrayIterator
{ {
$this->value = $value; $this->value = $value;
if (is_array($value) || is_object($value)) if (is_array($value) || is_object($value)) {
{
parent::__construct($value); parent::__construct($value);
} }
} }

View File

@ -52,8 +52,7 @@ class PhpProcess extends Process
*/ */
public function run($callback = null) public function run($callback = null)
{ {
if (null === $this->commandline) if (null === $this->commandline) {
{
$this->commandline = $this->getPhpBinary(); $this->commandline = $this->getPhpBinary();
} }
@ -69,8 +68,7 @@ class PhpProcess extends Process
*/ */
static public function getPhpBinary() static public function getPhpBinary()
{ {
if (getenv('PHP_PATH')) if (getenv('PHP_PATH')) {
{
if (!is_executable($php = getenv('PHP_PATH'))) if (!is_executable($php = getenv('PHP_PATH')))
{ {
throw new \RuntimeException('The defined PHP_PATH environment variable is not a valid PHP executable.'); throw new \RuntimeException('The defined PHP_PATH environment variable is not a valid PHP executable.');
@ -80,8 +78,7 @@ class PhpProcess extends Process
} }
$suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : array('.exe', '.bat', '.cmd', '.com')) : array(''); $suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : array('.exe', '.bat', '.cmd', '.com')) : array('');
foreach ($suffixes as $suffix) foreach ($suffixes as $suffix) {
{
if (is_executable($php = PHP_BINDIR.DIRECTORY_SEPARATOR.'php'.$suffix)) if (is_executable($php = PHP_BINDIR.DIRECTORY_SEPARATOR.'php'.$suffix))
{ {
return $php; return $php;

View File

@ -46,16 +46,14 @@ class Process
*/ */
public function __construct($commandline, $cwd, array $env = array(), $stdin = null, $timeout = 60, array $options = array()) public function __construct($commandline, $cwd, array $env = array(), $stdin = null, $timeout = 60, array $options = array())
{ {
if (!function_exists('proc_open')) if (!function_exists('proc_open')) {
{
throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.'); throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
} }
$this->commandline = $commandline; $this->commandline = $commandline;
$this->cwd = null === $cwd ? getcwd() : $cwd; $this->cwd = null === $cwd ? getcwd() : $cwd;
$this->env = array(); $this->env = array();
foreach ($env as $key => $value) foreach ($env as $key => $value) {
{
$this->env[(binary) $key] = (binary) $value; $this->env[(binary) $key] = (binary) $value;
} }
$this->stdin = $stdin; $this->stdin = $stdin;
@ -82,19 +80,15 @@ class Process
*/ */
public function run($callback = null) public function run($callback = null)
{ {
if (null === $callback) if (null === $callback) {
{
$this->stdout = ''; $this->stdout = '';
$this->stderr = ''; $this->stderr = '';
$that = $this; $that = $this;
$callback = function ($type, $line) use ($that) $callback = function ($type, $line) use ($that)
{ {
if ('out' == $type) if ('out' == $type) {
{
$that->addOutput($line); $that->addOutput($line);
} } else {
else
{
$that->addErrorOutput($line); $that->addErrorOutput($line);
} }
}; };
@ -107,62 +101,49 @@ class Process
stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false); stream_set_blocking($pipes[2], false);
if (!is_resource($process)) if (!is_resource($process)) {
{
throw new \RuntimeException('Unable to launch a new process.'); throw new \RuntimeException('Unable to launch a new process.');
} }
if (null !== $this->stdin) if (null !== $this->stdin) {
{
fwrite($pipes[0], (binary) $this->stdin); fwrite($pipes[0], (binary) $this->stdin);
} }
fclose($pipes[0]); fclose($pipes[0]);
while (true) while (true) {
{
$r = $pipes; $r = $pipes;
$w = null; $w = null;
$e = null; $e = null;
$n = @stream_select($r, $w, $e, $this->timeout); $n = @stream_select($r, $w, $e, $this->timeout);
if ($n === false) if ($n === false) {
{
break; break;
} } elseif ($n === 0) {
elseif ($n === 0)
{
proc_terminate($process); proc_terminate($process);
throw new \RuntimeException('The process timed out.'); throw new \RuntimeException('The process timed out.');
} } elseif ($n > 0) {
elseif ($n > 0)
{
$called = false; $called = false;
while (true) while (true) {
{
$c = false; $c = false;
if ($line = (binary) fgets($pipes[1], 1024)) if ($line = (binary) fgets($pipes[1], 1024)) {
{
$called = $c = true; $called = $c = true;
call_user_func($callback, 'out', $line); call_user_func($callback, 'out', $line);
} }
if ($line = fgets($pipes[2], 1024)) if ($line = fgets($pipes[2], 1024)) {
{
$called = $c = true; $called = $c = true;
call_user_func($callback, 'err', $line); call_user_func($callback, 'err', $line);
} }
if (!$c) if (!$c) {
{
break; break;
} }
} }
if (!$called) if (!$called) {
{
break; break;
} }
} }
@ -172,8 +153,7 @@ class Process
proc_close($process); proc_close($process);
if ($this->status['signaled']) if ($this->status['signaled']) {
{
throw new \RuntimeException(sprintf('The process stopped because of a "%s" signal.', $this->status['stopsig'])); throw new \RuntimeException(sprintf('The process stopped because of a "%s" signal.', $this->status['stopsig']));
} }

View File

@ -51,8 +51,7 @@ class FileResource implements ResourceInterface
*/ */
public function isUptodate($timestamp) public function isUptodate($timestamp)
{ {
if (!file_exists($this->resource)) if (!file_exists($this->resource)) {
{
return false; return false;
} }

View File

@ -53,8 +53,7 @@ class PhpGeneratorDumper extends GeneratorDumper
{ {
$methods = array(); $methods = array();
foreach ($this->routes->getRoutes() as $name => $route) foreach ($this->routes->getRoutes() as $name => $route) {
{
$compiledRoute = $route->compile(); $compiledRoute = $route->compile();
$variables = str_replace("\n", '', var_export($compiledRoute->getVariables(), true)); $variables = str_replace("\n", '', var_export($compiledRoute->getVariables(), true));
@ -78,8 +77,7 @@ EOF
public function generate(\$name, array \$parameters, \$absolute = false) public function generate(\$name, array \$parameters, \$absolute = false)
{ {
if (!method_exists(\$this, \$method = 'get'.\$name.'RouteInfo')) if (!method_exists(\$this, \$method = 'get'.\$name.'RouteInfo')) {
{
throw new \InvalidArgumentException(sprintf('Route "%s" does not exist.', \$name)); throw new \InvalidArgumentException(sprintf('Route "%s" does not exist.', \$name));
} }

View File

@ -56,13 +56,11 @@ class UrlGenerator implements UrlGeneratorInterface
*/ */
public function generate($name, array $parameters, $absolute = false) public function generate($name, array $parameters, $absolute = false)
{ {
if (null === $route = $this->routes->getRoute($name)) if (null === $route = $this->routes->getRoute($name)) {
{
throw new \InvalidArgumentException(sprintf('Route "%s" does not exist.', $name)); throw new \InvalidArgumentException(sprintf('Route "%s" does not exist.', $name));
} }
if (!isset($this->cache[$name])) if (!isset($this->cache[$name])) {
{
$this->cache[$name] = $route->compile(); $this->cache[$name] = $route->compile();
} }
@ -78,60 +76,48 @@ class UrlGenerator implements UrlGeneratorInterface
$tparams = array_merge($defaults, $parameters); $tparams = array_merge($defaults, $parameters);
// all params must be given // all params must be given
if ($diff = array_diff_key($variables, $tparams)) if ($diff = array_diff_key($variables, $tparams)) {
{
throw new \InvalidArgumentException(sprintf('The "%s" route has some missing mandatory parameters (%s).', $name, implode(', ', $diff))); throw new \InvalidArgumentException(sprintf('The "%s" route has some missing mandatory parameters (%s).', $name, implode(', ', $diff)));
} }
$url = ''; $url = '';
$optional = true; $optional = true;
foreach ($tokens as $token) foreach ($tokens as $token) {
{
if ('variable' === $token[0]) if ('variable' === $token[0])
{ {
if (false === $optional || !isset($defaults[$token[3]]) || (isset($parameters[$token[3]]) && $parameters[$token[3]] != $defaults[$token[3]])) if (false === $optional || !isset($defaults[$token[3]]) || (isset($parameters[$token[3]]) && $parameters[$token[3]] != $defaults[$token[3]])) {
{
// check requirement // check requirement
if (isset($requirements[$token[3]]) && !preg_match('#^'.$requirements[$token[3]].'$#', $tparams[$token[3]])) if (isset($requirements[$token[3]]) && !preg_match('#^'.$requirements[$token[3]].'$#', $tparams[$token[3]])) {
{
throw new \InvalidArgumentException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $requirements[$token[3]], $tparams[$token[3]])); throw new \InvalidArgumentException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $requirements[$token[3]], $tparams[$token[3]]));
} }
$url = $token[1].urlencode($tparams[$token[3]]).$url; $url = $token[1].urlencode($tparams[$token[3]]).$url;
$optional = false; $optional = false;
} }
} } elseif ('text' === $token[0]) {
elseif ('text' === $token[0])
{
$url = $token[1].$token[2].$url; $url = $token[1].$token[2].$url;
$optional = false; $optional = false;
} } else {
else
{
// handle custom tokens // handle custom tokens
if ($segment = call_user_func_array(array($this, 'generateFor'.ucfirst(array_shift($token))), array_merge(array($optional, $tparams), $token))) if ($segment = call_user_func_array(array($this, 'generateFor'.ucfirst(array_shift($token))), array_merge(array($optional, $tparams), $token))) {
{
$url = $segment.$url; $url = $segment.$url;
$optional = false; $optional = false;
} }
} }
} }
if (!$url) if (!$url) {
{
$url = '/'; $url = '/';
} }
// add a query string if needed // add a query string if needed
if ($extra = array_diff_key($parameters, $variables, $defaults)) if ($extra = array_diff_key($parameters, $variables, $defaults)) {
{
$url .= '?'.http_build_query($extra); $url .= '?'.http_build_query($extra);
} }
$url = (isset($this->context['base_url']) ? $this->context['base_url'] : '').$url; $url = (isset($this->context['base_url']) ? $this->context['base_url'] : '').$url;
if ($absolute && isset($this->context['host'])) if ($absolute && isset($this->context['host'])) {
{
$url = 'http'.(isset($this->context['is_secure']) && $this->context['is_secure'] ? 's' : '').'://'.$this->context['host'].$url; $url = 'http'.(isset($this->context['is_secure']) && $this->context['is_secure'] ? 's' : '').'://'.$this->context['host'].$url;
} }

View File

@ -29,8 +29,7 @@ abstract class FileLoader implements LoaderInterface
*/ */
public function __construct($paths = array()) public function __construct($paths = array())
{ {
if (!is_array($paths)) if (!is_array($paths)) {
{
$paths = array($paths); $paths = array($paths);
} }
@ -43,8 +42,7 @@ abstract class FileLoader implements LoaderInterface
protected function findFile($file) protected function findFile($file)
{ {
$path = $this->getAbsolutePath($file); $path = $this->getAbsolutePath($file);
if (!file_exists($path)) if (!file_exists($path)) {
{
throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $file, implode(', ', $this->paths))); throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s).', $file, implode(', ', $this->paths)));
} }
@ -53,20 +51,14 @@ abstract class FileLoader implements LoaderInterface
protected function getAbsolutePath($file, $currentPath = null) protected function getAbsolutePath($file, $currentPath = null)
{ {
if (self::isAbsolutePath($file)) if (self::isAbsolutePath($file)) {
{
return $file; return $file;
} } else if (null !== $currentPath && file_exists($currentPath.DIRECTORY_SEPARATOR.$file)) {
else if (null !== $currentPath && file_exists($currentPath.DIRECTORY_SEPARATOR.$file))
{
return $currentPath.DIRECTORY_SEPARATOR.$file; return $currentPath.DIRECTORY_SEPARATOR.$file;
} } else {
else
{
foreach ($this->paths as $path) foreach ($this->paths as $path)
{ {
if (file_exists($path.DIRECTORY_SEPARATOR.$file)) if (file_exists($path.DIRECTORY_SEPARATOR.$file)) {
{
return $path.DIRECTORY_SEPARATOR.$file; return $path.DIRECTORY_SEPARATOR.$file;
} }
} }

View File

@ -43,15 +43,13 @@ class XmlFileLoader extends FileLoader
$collection->addResource(new FileResource($path)); $collection->addResource(new FileResource($path));
// process routes and imports // process routes and imports
foreach ($xml->documentElement->childNodes as $node) foreach ($xml->documentElement->childNodes as $node) {
{
if (!$node instanceof \DOMElement) if (!$node instanceof \DOMElement)
{ {
continue; continue;
} }
switch ($node->tagName) switch ($node->tagName) {
{
case 'route': case 'route':
$this->parseRoute($collection, $node, $path); $this->parseRoute($collection, $node, $path);
break; break;
@ -72,15 +70,13 @@ class XmlFileLoader extends FileLoader
$requirements = array(); $requirements = array();
$options = array(); $options = array();
foreach ($definition->childNodes as $node) foreach ($definition->childNodes as $node) {
{
if (!$node instanceof \DOMElement) if (!$node instanceof \DOMElement)
{ {
continue; continue;
} }
switch ($node->tagName) switch ($node->tagName) {
{
case 'default': case 'default':
$defaults[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue); $defaults[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
break; break;
@ -103,15 +99,11 @@ class XmlFileLoader extends FileLoader
protected function parseImport(RouteCollection $collection, $node, $file) protected function parseImport(RouteCollection $collection, $node, $file)
{ {
$class = null; $class = null;
if ($node->hasAttribute('class') && $import->getAttribute('class') !== get_class($this)) if ($node->hasAttribute('class') && $import->getAttribute('class') !== get_class($this)) {
{
$class = (string) $node->getAttribute('class'); $class = (string) $node->getAttribute('class');
} } else {
else
{
// try to detect loader with the extension // try to detect loader with the extension
switch (pathinfo((string) $node->getAttribute('resource'), PATHINFO_EXTENSION)) switch (pathinfo((string) $node->getAttribute('resource'), PATHINFO_EXTENSION)) {
{
case 'yml': case 'yml':
$class = 'Symfony\\Components\\Routing\\Loader\\YamlFileLoader'; $class = 'Symfony\\Components\\Routing\\Loader\\YamlFileLoader';
break; break;
@ -132,8 +124,7 @@ class XmlFileLoader extends FileLoader
{ {
$dom = new \DOMDocument(); $dom = new \DOMDocument();
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
if (!$dom->load($path, LIBXML_COMPACT)) if (!$dom->load($path, LIBXML_COMPACT)) {
{
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors())); throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
} }
$dom->validateOnParse = true; $dom->validateOnParse = true;
@ -150,8 +141,7 @@ class XmlFileLoader extends FileLoader
protected function validate($dom, $file) protected function validate($dom, $file)
{ {
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
if (!$dom->schemaValidate(__DIR__.'/schema/routing/routing-1.0.xsd')) if (!$dom->schemaValidate(__DIR__.'/schema/routing/routing-1.0.xsd')) {
{
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors())); throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
} }
libxml_use_internal_errors(false); libxml_use_internal_errors(false);
@ -160,8 +150,7 @@ class XmlFileLoader extends FileLoader
protected function getXmlErrors() protected function getXmlErrors()
{ {
$errors = array(); $errors = array();
foreach (libxml_get_errors() as $error) foreach (libxml_get_errors() as $error) {
{
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code, $error->code,

View File

@ -43,18 +43,13 @@ class YamlFileLoader extends FileLoader
$collection = new RouteCollection(); $collection = new RouteCollection();
$collection->addResource(new FileResource($path)); $collection->addResource(new FileResource($path));
foreach ($config as $name => $config) foreach ($config as $name => $config) {
{
if (isset($config['resource'])) if (isset($config['resource']))
{ {
$this->parseImport($collection, $name, $config, $path); $this->parseImport($collection, $name, $config, $path);
} } elseif (isset($config['pattern'])) {
elseif (isset($config['pattern']))
{
$this->parseRoute($collection, $name, $config, $path); $this->parseRoute($collection, $name, $config, $path);
} } else {
else
{
throw new \InvalidArgumentException(sprintf('Unable to parse the "%s" route.', $name)); throw new \InvalidArgumentException(sprintf('Unable to parse the "%s" route.', $name));
} }
} }
@ -71,8 +66,7 @@ class YamlFileLoader extends FileLoader
$requirements = isset($config['requirements']) ? $config['requirements'] : array(); $requirements = isset($config['requirements']) ? $config['requirements'] : array();
$options = isset($config['options']) ? $config['options'] : array(); $options = isset($config['options']) ? $config['options'] : array();
if (!isset($config['pattern'])) if (!isset($config['pattern'])) {
{
throw new \InvalidArgumentException(sprintf('You must define a "pattern" for the "%s" route.', $name)); throw new \InvalidArgumentException(sprintf('You must define a "pattern" for the "%s" route.', $name));
} }
@ -86,21 +80,16 @@ class YamlFileLoader extends FileLoader
*/ */
protected function parseImport(RouteCollection $collection, $name, $import, $file) protected function parseImport(RouteCollection $collection, $name, $import, $file)
{ {
if (!isset($import['resource'])) if (!isset($import['resource'])) {
{
throw new \InvalidArgumentException(sprintf('You must define a "resource" when importing (%s).', $name)); throw new \InvalidArgumentException(sprintf('You must define a "resource" when importing (%s).', $name));
} }
$class = null; $class = null;
if (isset($import['class']) && $import['class'] !== get_class($this)) if (isset($import['class']) && $import['class'] !== get_class($this)) {
{
$class = $import['class']; $class = $import['class'];
} } else {
else
{
// try to detect loader with the extension // try to detect loader with the extension
switch (pathinfo($import['resource'], PATHINFO_EXTENSION)) switch (pathinfo($import['resource'], PATHINFO_EXTENSION)) {
{
case 'xml': case 'xml':
$class = 'Symfony\\Components\\Routing\\Loader\\XmlFileLoader'; $class = 'Symfony\\Components\\Routing\\Loader\\XmlFileLoader';
break; break;

View File

@ -49,15 +49,13 @@ class ApacheUrlMatcher extends UrlMatcher
*/ */
public function match($url) public function match($url)
{ {
if (!isset($_SERVER['_ROUTING__route'])) if (!isset($_SERVER['_ROUTING__route'])) {
{
// fall-back to the default UrlMatcher // fall-back to the default UrlMatcher
return parent::match($url); return parent::match($url);
} }
$parameters = array(); $parameters = array();
foreach ($_SERVER as $key => $value) foreach ($_SERVER as $key => $value) {
{
if ('_ROUTING_' === substr($key, 0, 9)) if ('_ROUTING_' === substr($key, 0, 9))
{ {
$parameters[substr($key, 9)] = $value; $parameters[substr($key, 9)] = $value;

View File

@ -43,32 +43,27 @@ class ApacheMatcherDumper extends MatcherDumper
$regexes = array(); $regexes = array();
foreach ($this->routes->getRoutes() as $name => $route) foreach ($this->routes->getRoutes() as $name => $route) {
{
$compiledRoute = $route->compile(); $compiledRoute = $route->compile();
// Apache "only" supports 9 variables // Apache "only" supports 9 variables
if (count($compiledRoute->getVariables()) > 9) if (count($compiledRoute->getVariables()) > 9) {
{
throw new \RuntimeException(sprintf('Unable to dump a route collection as route "%s" has more than 9 variables', $name)); throw new \RuntimeException(sprintf('Unable to dump a route collection as route "%s" has more than 9 variables', $name));
} }
$regex = preg_replace('/\?P<.+?>/', '', substr($compiledRoute->getRegex(), 1, -2)); $regex = preg_replace('/\?P<.+?>/', '', substr($compiledRoute->getRegex(), 1, -2));
$variables = array('E=_ROUTING__route:'.$name); $variables = array('E=_ROUTING__route:'.$name);
foreach (array_keys($compiledRoute->getVariables()) as $i => $variable) foreach (array_keys($compiledRoute->getVariables()) as $i => $variable) {
{
$variables[] = 'E=_ROUTING_'.$variable.':%'.($i + 1); $variables[] = 'E=_ROUTING_'.$variable.':%'.($i + 1);
} }
foreach ($route->getDefaults() as $key => $value) foreach ($route->getDefaults() as $key => $value) {
{
$variables[] = 'E=_ROUTING_'.$key.':'.$value; $variables[] = 'E=_ROUTING_'.$key.':'.$value;
} }
$variables = implode(',', $variables); $variables = implode(',', $variables);
$conditions = array(); $conditions = array();
foreach ((array) $route->getRequirement('_method') as $method) foreach ((array) $route->getRequirement('_method') as $method) {
{
$conditions[] = sprintf('RewriteCond %%{REQUEST_METHOD} =%s', strtoupper($method)); $conditions[] = sprintf('RewriteCond %%{REQUEST_METHOD} =%s', strtoupper($method));
} }

View File

@ -53,21 +53,18 @@ class PhpMatcherDumper extends MatcherDumper
{ {
$code = array(); $code = array();
foreach ($this->routes->getRoutes() as $name => $route) foreach ($this->routes->getRoutes() as $name => $route) {
{
$compiledRoute = $route->compile(); $compiledRoute = $route->compile();
$conditions = array(); $conditions = array();
if ($req = $route->getRequirement('_method')) if ($req = $route->getRequirement('_method')) {
{
$req = array_map('strtolower', (array) $req); $req = array_map('strtolower', (array) $req);
$conditions[] = sprintf("isset(\$this->context['method']) && in_array(strtolower(\$this->context['method']), %s)", str_replace("\n", '', var_export($req, true))); $conditions[] = sprintf("isset(\$this->context['method']) && in_array(strtolower(\$this->context['method']), %s)", str_replace("\n", '', var_export($req, true)));
} }
if ($compiledRoute->getStaticPrefix()) if ($compiledRoute->getStaticPrefix()) {
{
$conditions[] = sprintf("0 === strpos(\$url, '%s')", $compiledRoute->getStaticPrefix()); $conditions[] = sprintf("0 === strpos(\$url, '%s')", $compiledRoute->getStaticPrefix());
} }

View File

@ -54,24 +54,20 @@ class UrlMatcher implements UrlMatcherInterface
{ {
$url = $this->normalizeUrl($url); $url = $this->normalizeUrl($url);
foreach ($this->routes->getRoutes() as $name => $route) foreach ($this->routes->getRoutes() as $name => $route) {
{
$compiledRoute = $route->compile(); $compiledRoute = $route->compile();
// check HTTP method requirement // check HTTP method requirement
if (isset($this->context['method']) && (($req = $route->getRequirement('_method')) && !in_array(strtolower($this->context['method']), array_map('strtolower', (array) $req)))) if (isset($this->context['method']) && (($req = $route->getRequirement('_method')) && !in_array(strtolower($this->context['method']), array_map('strtolower', (array) $req)))) {
{
continue; continue;
} }
// check the static prefix of the URL first. Only use the more expensive preg_match when it matches // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($url, $compiledRoute->getStaticPrefix())) if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($url, $compiledRoute->getStaticPrefix())) {
{
continue; continue;
} }
if (!preg_match($compiledRoute->getRegex(), $url, $matches)) if (!preg_match($compiledRoute->getRegex(), $url, $matches)) {
{
continue; continue;
} }
@ -84,8 +80,7 @@ class UrlMatcher implements UrlMatcherInterface
protected function mergeDefaults($params, $defaults) protected function mergeDefaults($params, $defaults)
{ {
$parameters = array_merge($this->defaults, $defaults); $parameters = array_merge($this->defaults, $defaults);
foreach ($params as $key => $value) foreach ($params as $key => $value) {
{
if (!is_int($key)) if (!is_int($key))
{ {
$parameters[$key] = urldecode($value); $parameters[$key] = urldecode($value);
@ -98,14 +93,12 @@ class UrlMatcher implements UrlMatcherInterface
protected function normalizeUrl($url) protected function normalizeUrl($url)
{ {
// ensure that the URL starts with a / // ensure that the URL starts with a /
if ('/' !== substr($url, 0, 1)) if ('/' !== substr($url, 0, 1)) {
{
$url = '/'.$url; $url = '/'.$url;
} }
// remove the query string // remove the query string
if (false !== $pos = strpos($url, '?')) if (false !== $pos = strpos($url, '?')) {
{
$url = substr($url, 0, $pos); $url = substr($url, 0, $pos);
} }

View File

@ -76,8 +76,7 @@ class Route
$this->pattern = trim($pattern); $this->pattern = trim($pattern);
// a route must start with a slash // a route must start with a slash
if (empty($this->pattern) || '/' !== $this->pattern[0]) if (empty($this->pattern) || '/' !== $this->pattern[0]) {
{
$this->pattern = '/'.$this->pattern; $this->pattern = '/'.$this->pattern;
} }
@ -188,15 +187,13 @@ class Route
public function setRequirements(array $requirements) public function setRequirements(array $requirements)
{ {
$this->requirements = array(); $this->requirements = array();
foreach ($requirements as $key => $regex) foreach ($requirements as $key => $regex) {
{
if ('^' == $regex[0]) if ('^' == $regex[0])
{ {
$regex = substr($regex, 1); $regex = substr($regex, 1);
} }
if ('$' == substr($regex, -1)) if ('$' == substr($regex, -1)) {
{
$regex = substr($regex, 0, -1); $regex = substr($regex, 0, -1);
} }
@ -223,15 +220,13 @@ class Route
*/ */
public function compile() public function compile()
{ {
if (null !== $this->compiled) if (null !== $this->compiled) {
{
return $this->compiled; return $this->compiled;
} }
$class = $this->getOption('compiler_class'); $class = $this->getOption('compiler_class');
if (!isset(static::$compilers[$class])) if (!isset(static::$compilers[$class])) {
{
static::$compilers[$class] = new $class; static::$compilers[$class] = new $class;
} }

View File

@ -42,8 +42,7 @@ class RouteCollection
*/ */
public function addRoute($name, Route $route) public function addRoute($name, Route $route)
{ {
if (!preg_match('/^[a-z0-9A-Z_]+$/', $name)) if (!preg_match('/^[a-z0-9A-Z_]+$/', $name)) {
{
throw new \InvalidArgumentException(sprintf('Name "%s" contains non valid characters for a route name.', $name)); throw new \InvalidArgumentException(sprintf('Name "%s" contains non valid characters for a route name.', $name));
} }
@ -82,8 +81,7 @@ class RouteCollection
{ {
$collection->addPrefix($prefix); $collection->addPrefix($prefix);
foreach ($collection->getResources() as $resource) foreach ($collection->getResources() as $resource) {
{
$this->addResource($resource); $this->addResource($resource);
} }
@ -97,13 +95,11 @@ class RouteCollection
*/ */
public function addPrefix($prefix) public function addPrefix($prefix)
{ {
if (!$prefix) if (!$prefix) {
{
return; return;
} }
foreach ($this->getRoutes() as $route) foreach ($this->getRoutes() as $route) {
{
$route->setPattern($prefix.$route->getPattern()); $route->setPattern($prefix.$route->getPattern());
} }
} }

View File

@ -51,16 +51,14 @@ class RouteCompiler implements RouteCompilerInterface
$this->tokenize(); $this->tokenize();
foreach ($this->tokens as $token) foreach ($this->tokens as $token) {
{
call_user_func_array(array($this, 'compileFor'.ucfirst(array_shift($token))), $token); call_user_func_array(array($this, 'compileFor'.ucfirst(array_shift($token))), $token);
} }
$this->postCompile(); $this->postCompile();
$separator = ''; $separator = '';
if (count($this->tokens)) if (count($this->tokens)) {
{
$lastToken = $this->tokens[count($this->tokens) - 1]; $lastToken = $this->tokens[count($this->tokens) - 1];
$separator = 'separator' == $lastToken[0] ? $lastToken[2] : ''; $separator = 'separator' == $lastToken[0] ? $lastToken[2] : '';
} }
@ -69,15 +67,12 @@ class RouteCompiler implements RouteCompilerInterface
// optimize tokens for generation // optimize tokens for generation
$tokens = array(); $tokens = array();
foreach ($this->tokens as $i => $token) foreach ($this->tokens as $i => $token) {
{
if ($i + 1 === count($this->tokens) && 'separator' === $token[0]) if ($i + 1 === count($this->tokens) && 'separator' === $token[0])
{ {
// trailing / // trailing /
$tokens[] = array('text', $token[2], '', null); $tokens[] = array('text', $token[2], '', null);
} } elseif ('separator' !== $token[0]) {
elseif ('separator' !== $token[0])
{
$tokens[] = $token; $tokens[] = $token;
} }
} }
@ -101,15 +96,13 @@ class RouteCompiler implements RouteCompilerInterface
{ {
// all segments after the last static segment are optional // all segments after the last static segment are optional
// be careful, the n-1 is optional only if n is empty // be careful, the n-1 is optional only if n is empty
for ($i = $this->firstOptional, $max = count($this->segments); $i < $max; $i++) for ($i = $this->firstOptional, $max = count($this->segments); $i < $max; $i++) {
{
$this->segments[$i] = (0 == $i ? '/?' : '').str_repeat(' ', $i - $this->firstOptional).'(?:'.$this->segments[$i]; $this->segments[$i] = (0 == $i ? '/?' : '').str_repeat(' ', $i - $this->firstOptional).'(?:'.$this->segments[$i];
$this->segments[] = str_repeat(' ', $max - $i - 1).')?'; $this->segments[] = str_repeat(' ', $max - $i - 1).')?';
} }
$this->staticPrefix = ''; $this->staticPrefix = '';
foreach ($this->tokens as $token) foreach ($this->tokens as $token) {
{
switch ($token[0]) switch ($token[0])
{ {
case 'separator': case 'separator':
@ -138,47 +131,36 @@ class RouteCompiler implements RouteCompilerInterface
$currentSeparator = ''; $currentSeparator = '';
// a route is an array of (separator + variable) or (separator + text) segments // a route is an array of (separator + variable) or (separator + text) segments
while (strlen($buffer)) while (strlen($buffer)) {
{
if (false !== $this->tokenizeBufferBefore($buffer, $tokens, $afterASeparator, $currentSeparator)) if (false !== $this->tokenizeBufferBefore($buffer, $tokens, $afterASeparator, $currentSeparator))
{ {
// a custom token // a custom token
$this->customToken = true; $this->customToken = true;
} } else if ($afterASeparator && preg_match('#^'.$this->options['variable_prefix_regex'].'('.$this->options['variable_regex'].')#', $buffer, $match)) {
else if ($afterASeparator && preg_match('#^'.$this->options['variable_prefix_regex'].'('.$this->options['variable_regex'].')#', $buffer, $match))
{
// a variable // a variable
$this->tokens[] = array('variable', $currentSeparator, $match[0], $match[1]); $this->tokens[] = array('variable', $currentSeparator, $match[0], $match[1]);
$currentSeparator = ''; $currentSeparator = '';
$buffer = substr($buffer, strlen($match[0])); $buffer = substr($buffer, strlen($match[0]));
$afterASeparator = false; $afterASeparator = false;
} } else if ($afterASeparator && preg_match('#^('.$this->options['text_regex'].')(?:'.$this->options['segment_separators_regex'].'|$)#', $buffer, $match)) {
else if ($afterASeparator && preg_match('#^('.$this->options['text_regex'].')(?:'.$this->options['segment_separators_regex'].'|$)#', $buffer, $match))
{
// a text // a text
$this->tokens[] = array('text', $currentSeparator, $match[1], null); $this->tokens[] = array('text', $currentSeparator, $match[1], null);
$currentSeparator = ''; $currentSeparator = '';
$buffer = substr($buffer, strlen($match[1])); $buffer = substr($buffer, strlen($match[1]));
$afterASeparator = false; $afterASeparator = false;
} } else if (!$afterASeparator && preg_match('#^'.$this->options['segment_separators_regex'].'#', $buffer, $match)) {
else if (!$afterASeparator && preg_match('#^'.$this->options['segment_separators_regex'].'#', $buffer, $match))
{
// a separator // a separator
$this->tokens[] = array('separator', $currentSeparator, $match[0], null); $this->tokens[] = array('separator', $currentSeparator, $match[0], null);
$currentSeparator = $match[0]; $currentSeparator = $match[0];
$buffer = substr($buffer, strlen($match[0])); $buffer = substr($buffer, strlen($match[0]));
$afterASeparator = true; $afterASeparator = true;
} } else if (false !== $this->tokenizeBufferAfter($buffer, $tokens, $afterASeparator, $currentSeparator)) {
else if (false !== $this->tokenizeBufferAfter($buffer, $tokens, $afterASeparator, $currentSeparator))
{
// a custom token // a custom token
$this->customToken = true; $this->customToken = true;
} } else {
else
{
// parsing problem // parsing problem
throw new \InvalidArgumentException(sprintf('Unable to parse "%s" route near "%s".', $this->route->getPattern(), $buffer)); throw new \InvalidArgumentException(sprintf('Unable to parse "%s" route near "%s".', $this->route->getPattern(), $buffer));
} }
@ -228,16 +210,14 @@ class RouteCompiler implements RouteCompilerInterface
protected function compileForVariable($separator, $name, $variable) protected function compileForVariable($separator, $name, $variable)
{ {
if (null === $requirement = $this->route->getRequirement($variable)) if (null === $requirement = $this->route->getRequirement($variable)) {
{
$requirement = $this->options['variable_content_regex']; $requirement = $this->options['variable_content_regex'];
} }
$this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$requirement.')'; $this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$requirement.')';
$this->variables[$variable] = $name; $this->variables[$variable] = $name;
if (!$this->route->getDefault($variable)) if (!$this->route->getDefault($variable)) {
{
$this->firstOptional = count($this->segments); $this->firstOptional = count($this->segments);
} }
} }

View File

@ -63,8 +63,7 @@ class Router implements RouterInterface
); );
// check option names // check option names
if ($diff = array_diff(array_keys($options), array_keys($this->options))) if ($diff = array_diff(array_keys($options), array_keys($this->options))) {
{
throw new \InvalidArgumentException(sprintf('The Router does not support the following options: \'%s\'.', implode('\', \'', $diff))); throw new \InvalidArgumentException(sprintf('The Router does not support the following options: \'%s\'.', implode('\', \'', $diff)));
} }
@ -78,8 +77,7 @@ class Router implements RouterInterface
*/ */
public function getRouteCollection() public function getRouteCollection()
{ {
if (null === $this->collection) if (null === $this->collection) {
{
$this->collection = call_user_func($this->loader); $this->collection = call_user_func($this->loader);
} }
@ -141,19 +139,16 @@ class Router implements RouterInterface
*/ */
public function getMatcher() public function getMatcher()
{ {
if (null !== $this->matcher) if (null !== $this->matcher) {
{
return $this->matcher; return $this->matcher;
} }
if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
{
return $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context, $this->defaults); return $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context, $this->defaults);
} }
$class = $this->options['matcher_cache_class']; $class = $this->options['matcher_cache_class'];
if ($this->needsReload($class)) if ($this->needsReload($class)) {
{
$dumper = new $this->options['matcher_dumper_class']($this->getRouteCollection()); $dumper = new $this->options['matcher_dumper_class']($this->getRouteCollection());
$options = array( $options = array(
@ -176,19 +171,16 @@ class Router implements RouterInterface
*/ */
public function getGenerator() public function getGenerator()
{ {
if (null !== $this->generator) if (null !== $this->generator) {
{
return $this->generator; return $this->generator;
} }
if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
{
return $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->defaults); return $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->defaults);
} }
$class = $this->options['generator_cache_class']; $class = $this->options['generator_cache_class'];
if ($this->needsReload($class)) if ($this->needsReload($class)) {
{
$dumper = new $this->options['generator_dumper_class']($this->getRouteCollection()); $dumper = new $this->options['generator_dumper_class']($this->getRouteCollection());
$options = array( $options = array(
@ -208,8 +200,7 @@ class Router implements RouterInterface
{ {
$this->writeCacheFile($this->getCacheFile($class), $dump); $this->writeCacheFile($this->getCacheFile($class), $dump);
if ($this->options['debug']) if ($this->options['debug']) {
{
$this->writeCacheFile($this->getCacheFile($class, 'meta'), serialize($this->getRouteCollection()->getResources())); $this->writeCacheFile($this->getCacheFile($class, 'meta'), serialize($this->getRouteCollection()->getResources()));
} }
} }
@ -217,26 +208,22 @@ class Router implements RouterInterface
protected function needsReload($class) protected function needsReload($class)
{ {
$file = $this->getCacheFile($class); $file = $this->getCacheFile($class);
if (!file_exists($file)) if (!file_exists($file)) {
{
return true; return true;
} }
if (!$this->options['debug']) if (!$this->options['debug']) {
{
return false; return false;
} }
$metadata = $this->getCacheFile($class, 'meta'); $metadata = $this->getCacheFile($class, 'meta');
if (!file_exists($metadata)) if (!file_exists($metadata)) {
{
return true; return true;
} }
$time = filemtime($file); $time = filemtime($file);
$meta = unserialize(file_get_contents($metadata)); $meta = unserialize(file_get_contents($metadata));
foreach ($meta as $resource) foreach ($meta as $resource) {
{
if (!$resource->isUptodate($time)) if (!$resource->isUptodate($time))
{ {
return true; return true;
@ -257,16 +244,14 @@ class Router implements RouterInterface
protected function writeCacheFile($file, $content) protected function writeCacheFile($file, $content)
{ {
$tmpFile = tempnam(dirname($file), basename($file)); $tmpFile = tempnam(dirname($file), basename($file));
if (!$fp = @fopen($tmpFile, 'wb')) if (!$fp = @fopen($tmpFile, 'wb')) {
{
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $tmpFile)); throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $tmpFile));
} }
@fwrite($fp, $content); @fwrite($fp, $content);
@fclose($fp); @fclose($fp);
if ($content != file_get_contents($tmpFile)) if ($content != file_get_contents($tmpFile)) {
{
throw new \RuntimeException(sprintf('Failed to write cache file "%s" (cache corrupted).', $tmpFile)); throw new \RuntimeException(sprintf('Failed to write cache file "%s" (cache corrupted).', $tmpFile));
} }

View File

@ -53,13 +53,11 @@ class Engine
$this->addHelpers($helpers); $this->addHelpers($helpers);
if (!isset($this->renderers['php'])) if (!isset($this->renderers['php'])) {
{
$this->renderers['php'] = new PhpRenderer(); $this->renderers['php'] = new PhpRenderer();
} }
foreach ($this->renderers as $renderer) foreach ($this->renderers as $renderer) {
{
$renderer->setEngine($this); $renderer->setEngine($this);
} }
} }
@ -83,19 +81,15 @@ class Engine
*/ */
public function render($name, array $parameters = array()) public function render($name, array $parameters = array())
{ {
if (isset($this->cache[$name])) if (isset($this->cache[$name])) {
{
list($name, $options, $template) = $this->cache[$name]; list($name, $options, $template) = $this->cache[$name];
} } else {
else
{
list($name, $options) = $this->splitTemplateName($old = $name); list($name, $options) = $this->splitTemplateName($old = $name);
// load // load
$template = $this->loader->load($name, $options); $template = $this->loader->load($name, $options);
if (false === $template) if (false === $template) {
{
throw new \InvalidArgumentException(sprintf('The template "%s" does not exist (renderer: %s).', $name, $options['renderer'])); throw new \InvalidArgumentException(sprintf('The template "%s" does not exist (renderer: %s).', $name, $options['renderer']));
} }
@ -108,20 +102,17 @@ class Engine
// renderer // renderer
$renderer = $template->getRenderer() ? $template->getRenderer() : $options['renderer']; $renderer = $template->getRenderer() ? $template->getRenderer() : $options['renderer'];
if (!isset($this->renderers[$options['renderer']])) if (!isset($this->renderers[$options['renderer']])) {
{
throw new \InvalidArgumentException(sprintf('The renderer "%s" is not registered.', $renderer)); throw new \InvalidArgumentException(sprintf('The renderer "%s" is not registered.', $renderer));
} }
// render // render
if (false === $content = $this->renderers[$renderer]->evaluate($template, $parameters)) if (false === $content = $this->renderers[$renderer]->evaluate($template, $parameters)) {
{
throw new \RuntimeException(sprintf('The template "%s" cannot be rendered (renderer: %s).', $name, $renderer)); throw new \RuntimeException(sprintf('The template "%s" cannot be rendered (renderer: %s).', $name, $renderer));
} }
// decorator // decorator
if ($this->parents[$name]) if ($this->parents[$name]) {
{
$slots = $this->get('slots'); $slots = $this->get('slots');
$this->stack[] = $slots->get('_content'); $this->stack[] = $slots->get('_content');
$slots->set('_content', $content); $slots->set('_content', $content);
@ -166,8 +157,7 @@ class Engine
*/ */
public function addHelpers(array $helpers = array()) public function addHelpers(array $helpers = array())
{ {
foreach ($helpers as $alias => $helper) foreach ($helpers as $alias => $helper) {
{
$this->set($helper, is_int($alias) ? null : $alias); $this->set($helper, is_int($alias) ? null : $alias);
} }
} }
@ -181,8 +171,7 @@ class Engine
public function set(HelperInterface $helper, $alias = null) public function set(HelperInterface $helper, $alias = null)
{ {
$this->helpers[$helper->getName()] = $helper; $this->helpers[$helper->getName()] = $helper;
if (null !== $alias) if (null !== $alias) {
{
$this->helpers[$alias] = $helper; $this->helpers[$alias] = $helper;
} }
@ -212,8 +201,7 @@ class Engine
*/ */
public function get($name) public function get($name)
{ {
if (!isset($this->helpers[$name])) if (!isset($this->helpers[$name])) {
{
throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name)); throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
} }
@ -286,13 +274,10 @@ class Engine
protected function splitTemplateName($name) protected function splitTemplateName($name)
{ {
if (false !== $pos = strpos($name, ':')) if (false !== $pos = strpos($name, ':')) {
{
$renderer = substr($name, $pos + 1); $renderer = substr($name, $pos + 1);
$name = substr($name, 0, $pos); $name = substr($name, 0, $pos);
} } else {
else
{
$renderer = 'php'; $renderer = 'php';
} }

Some files were not shown because too many files have changed in this diff Show More