diff --git a/src/Symfony/Components/BrowserKit/Client.php b/src/Symfony/Components/BrowserKit/Client.php
index 7b886492860c..7483beef6bf8 100644
--- a/src/Symfony/Components/BrowserKit/Client.php
+++ b/src/Symfony/Components/BrowserKit/Client.php
@@ -75,8 +75,7 @@ public function followRedirects($followRedirect = true)
*/
public function insulate($insulated = true)
{
- if (!class_exists('Symfony\\Components\\Process\\Process'))
- {
+ if (!class_exists('Symfony\\Components\\Process\\Process')) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.');
// @codeCoverageIgnoreEnd
@@ -189,8 +188,7 @@ public function request($method, $uri, $parameters = array(), $headers = array()
$uri = $this->getAbsoluteUri($uri);
$server = array_merge($this->server, $server);
- if (!$this->history->isEmpty())
- {
+ if (!$this->history->isEmpty()) {
$server['HTTP_REFERER'] = $this->history->current()->getUri();
}
$server['HTTP_HOST'] = parse_url($uri, PHP_URL_HOST);
@@ -200,17 +198,13 @@ public function request($method, $uri, $parameters = array(), $headers = array()
$this->request = $this->filterRequest($request);
- if (true === $changeHistory)
- {
+ if (true === $changeHistory) {
$this->history->add($request);
}
- if ($this->insulated)
- {
+ if ($this->insulated) {
$this->response = $this->doRequestInProcess($this->request);
- }
- else
- {
+ } else {
$this->response = $this->doRequest($this->request);
}
@@ -220,8 +214,7 @@ public function request($method, $uri, $parameters = array(), $headers = array()
$this->redirect = $response->getHeader('Location');
- if ($this->followRedirects && $this->redirect)
- {
+ if ($this->followRedirects && $this->redirect) {
return $this->crawler = $this->followRedirect();
}
@@ -242,8 +235,7 @@ protected function doRequestInProcess($request)
$process = new PhpProcess($this->getScript($request));
$process->run();
- if ($process->getExitCode() > 0)
- {
+ if ($process->getExitCode() > 0) {
throw new \RuntimeException($process->getErrorOutput());
}
@@ -324,8 +316,7 @@ public function reload()
*/
public function followRedirect()
{
- if (empty($this->redirect))
- {
+ if (empty($this->redirect)) {
throw new \LogicException('The request was not redirected.');
}
@@ -346,17 +337,13 @@ public function restart()
protected function getAbsoluteUri($uri)
{
// already absolute?
- if ('http' === substr($uri, 0, 4))
- {
+ if ('http' === substr($uri, 0, 4)) {
return $uri;
}
- if (!$this->history->isEmpty())
- {
+ if (!$this->history->isEmpty()) {
$currentUri = $this->history->current()->getUri();
- }
- else
- {
+ } else {
$currentUri = sprintf('http%s://%s/',
isset($this->server['HTTPS']) ? 's' : '',
isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
@@ -364,17 +351,14 @@ protected function getAbsoluteUri($uri)
}
// anchor?
- if (!$uri || '#' == $uri[0])
- {
+ if (!$uri || '#' == $uri[0]) {
return preg_replace('/#.*?$/', '', $currentUri).$uri;
}
- if ('/' !== $uri[0])
- {
+ if ('/' !== $uri[0]) {
$path = parse_url($currentUri, PHP_URL_PATH);
- if ('/' !== substr($path, -1))
- {
+ if ('/' !== substr($path, -1)) {
$path = substr($path, 0, strrpos($path, '/') + 1);
}
diff --git a/src/Symfony/Components/BrowserKit/CookieJar.php b/src/Symfony/Components/BrowserKit/CookieJar.php
index 25237d2406f0..fc88fdb81189 100644
--- a/src/Symfony/Components/BrowserKit/CookieJar.php
+++ b/src/Symfony/Components/BrowserKit/CookieJar.php
@@ -71,8 +71,7 @@ public function clear()
*/
public function updateFromResponse(Response $response)
{
- foreach ($response->getCookies() as $name => $cookie)
- {
+ foreach ($response->getCookies() as $name => $cookie) {
$this->set(new Cookie(
$name,
isset($cookie['value']) ? $cookie['value'] : '',
@@ -110,20 +109,17 @@ public function getValues($uri)
$parts = parse_url($uri);
$cookies = array();
- foreach ($this->cookieJar as $cookie)
- {
+ foreach ($this->cookieJar as $cookie) {
if ($cookie->getDomain() && $cookie->getDomain() != substr($parts['host'], -strlen($cookie->getDomain())))
{
continue;
}
- if ($cookie->getPath() != substr($parts['path'], 0, strlen($cookie->getPath())))
- {
+ if ($cookie->getPath() != substr($parts['path'], 0, strlen($cookie->getPath()))) {
continue;
}
- if ($cookie->isSecure() && 'https' != $parts['scheme'])
- {
+ if ($cookie->isSecure() && 'https' != $parts['scheme']) {
continue;
}
@@ -139,8 +135,7 @@ public function getValues($uri)
public function flushExpiredCookies()
{
$cookies = $this->cookieJar;
- foreach ($cookies as $name => $cookie)
- {
+ foreach ($cookies as $name => $cookie) {
if ($cookie->isExpired())
{
unset($this->cookieJar[$name]);
diff --git a/src/Symfony/Components/BrowserKit/History.php b/src/Symfony/Components/BrowserKit/History.php
index 91f2497072ae..511b7af300a1 100644
--- a/src/Symfony/Components/BrowserKit/History.php
+++ b/src/Symfony/Components/BrowserKit/History.php
@@ -71,8 +71,7 @@ public function isEmpty()
*/
public function back()
{
- if ($this->position < 1)
- {
+ if ($this->position < 1) {
throw new \LogicException('You are already on the first page.');
}
@@ -88,8 +87,7 @@ public function back()
*/
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.');
}
@@ -105,8 +103,7 @@ public function forward()
*/
public function current()
{
- if (-1 == $this->position)
- {
+ if (-1 == $this->position) {
throw new \LogicException('The page history is empty.');
}
diff --git a/src/Symfony/Components/BrowserKit/Response.php b/src/Symfony/Components/BrowserKit/Response.php
index d495b9ef701f..4c892a56ea7b 100644
--- a/src/Symfony/Components/BrowserKit/Response.php
+++ b/src/Symfony/Components/BrowserKit/Response.php
@@ -44,12 +44,10 @@ public function __construct($content = '', $status = 200, $headers = array(), $c
public function __toString()
{
$headers = '';
- foreach ($this->headers as $name => $value)
- {
+ foreach ($this->headers as $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']);
}
@@ -95,8 +93,7 @@ public function getHeaders()
*/
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)))
{
return $value;
diff --git a/src/Symfony/Components/Console/Application.php b/src/Symfony/Components/Console/Application.php
index 922509ab24ce..5dca831b92d9 100644
--- a/src/Symfony/Components/Console/Application.php
+++ b/src/Symfony/Components/Console/Application.php
@@ -104,22 +104,17 @@ public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
*/
public function run(InputInterface $input = null, OutputInterface $output = null)
{
- if (null === $input)
- {
+ if (null === $input) {
$input = new ArgvInput();
}
- if (null === $output)
- {
+ if (null === $output) {
$output = new ConsoleOutput();
}
- try
- {
+ try {
$statusCode = $this->doRun($input, $output);
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
if (!$this->catchExceptions)
{
throw $e;
@@ -131,14 +126,11 @@ public function run(InputInterface $input = null, OutputInterface $output = null
$statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
}
- if ($this->autoExit)
- {
+ if ($this->autoExit) {
// @codeCoverageIgnoreStart
exit($statusCode);
// @codeCoverageIgnoreEnd
- }
- else
- {
+ } else {
return $statusCode;
}
}
@@ -155,47 +147,37 @@ public function doRun(InputInterface $input, OutputInterface $output)
{
$name = $input->getFirstArgument('command');
- if (true === $input->hasParameterOption(array('--color', '-c')))
- {
+ if (true === $input->hasParameterOption(array('--color', '-c'))) {
$output->setDecorated(true);
}
- if (true === $input->hasParameterOption(array('--help', '-H')))
- {
+ if (true === $input->hasParameterOption(array('--help', '-H'))) {
if (!$name)
{
$name = 'help';
$input = new ArrayInput(array('command' => 'help'));
- }
- else
- {
+ } else {
$this->wantHelps = true;
}
}
- if (true === $input->hasParameterOption(array('--no-interaction', '-n')))
- {
+ if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
$input->setInteractive(false);
}
- if (true === $input->hasParameterOption(array('--quiet', '-q')))
- {
+ if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
$output->setVerbosity(Output::VERBOSITY_QUIET);
- }
- elseif (true === $input->hasParameterOption(array('--verbose', '-v')))
- {
+ } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
$output->setVerbosity(Output::VERBOSITY_VERBOSE);
}
- if (true === $input->hasParameterOption(array('--version', '-V')))
- {
+ if (true === $input->hasParameterOption(array('--version', '-V'))) {
$output->writeln($this->getLongVersion());
return 0;
}
- if (!$name)
- {
+ if (!$name) {
$name = 'list';
$input = new ArrayInput(array('command' => 'list'));
}
@@ -255,8 +237,7 @@ public function getHelp()
'Options:',
);
- foreach ($this->definition->getOptions() as $option)
- {
+ foreach ($this->definition->getOptions() as $option) {
$messages[] = sprintf(' %-29s %s %s',
'--'.$option->getName().'',
$option->getShortcut() ? '-'.$option->getShortcut().'' : ' ',
@@ -334,12 +315,9 @@ public function setVersion($version)
*/
public function getLongVersion()
{
- if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion())
- {
+ if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
return sprintf('%s version %s', $this->getName(), $this->getVersion());
- }
- else
- {
+ } else {
return 'Console Tool';
}
}
@@ -363,8 +341,7 @@ public function register($name)
*/
public function addCommands(array $commands)
{
- foreach ($commands as $command)
- {
+ foreach ($commands as $command) {
$this->addCommand($command);
}
}
@@ -384,8 +361,7 @@ public function addCommand(Command $command)
$this->commands[$command->getFullName()] = $command;
- foreach ($command->getAliases() as $alias)
- {
+ foreach ($command->getAliases() as $alias) {
$this->aliases[$alias] = $command;
}
@@ -403,15 +379,13 @@ public function addCommand(Command $command)
*/
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));
}
$command = isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
- if ($this->wantHelps)
- {
+ if ($this->wantHelps) {
$this->wantHelps = false;
$helpCommand = $this->getCommand('help');
@@ -445,8 +419,7 @@ public function hasCommand($name)
public function getNamespaces()
{
$namespaces = array();
- foreach ($this->commands as $command)
- {
+ foreach ($this->commands as $command) {
if ($command->getNamespace())
{
$namespaces[$command->getNamespace()] = true;
@@ -467,13 +440,11 @@ public function findNamespace($namespace)
{
$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));
}
- 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])));
}
@@ -496,8 +467,7 @@ public function findCommand($name)
{
// namespace
$namespace = '';
- if (false !== $pos = strrpos($name, ':'))
- {
+ if (false !== $pos = strrpos($name, ':')) {
$namespace = $this->findNamespace(substr($name, 0, $pos));
$name = substr($name, $pos + 1);
}
@@ -506,8 +476,7 @@ public function findCommand($name)
// name
$commands = array();
- foreach ($this->commands as $command)
- {
+ foreach ($this->commands as $command) {
if ($command->getNamespace() == $namespace)
{
$commands[] = $command->getName();
@@ -515,13 +484,11 @@ public function findCommand($name)
}
$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]);
}
- 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]));
throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $suggestions));
@@ -529,13 +496,11 @@ public function findCommand($name)
// 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));
}
- if (count($abbrevs[$fullName]) > 1)
- {
+ if (count($abbrevs[$fullName]) > 1) {
throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $this->getAbbreviationSuggestions($abbrevs[$fullName])));
}
@@ -553,14 +518,12 @@ public function findCommand($name)
*/
public function getCommands($namespace = null)
{
- if (null === $namespace)
- {
+ if (null === $namespace) {
return $this->commands;
}
$commands = array();
- foreach ($this->commands as $name => $command)
- {
+ foreach ($this->commands as $name => $command) {
if ($namespace === $command->getNamespace())
{
$commands[$name] = $command;
@@ -580,25 +543,20 @@ public function getCommands($namespace = null)
static public function getAbbreviations($names)
{
$abbrevs = array();
- foreach ($names as $name)
- {
+ foreach ($names as $name) {
for ($len = strlen($name) - 1; $len > 0; --$len)
{
$abbrev = substr($name, 0, $len);
- if (!isset($abbrevs[$abbrev]))
- {
+ if (!isset($abbrevs[$abbrev])) {
$abbrevs[$abbrev] = array($name);
- }
- else
- {
+ } else {
$abbrevs[$abbrev][] = $name;
}
}
}
// Non-abbreviations always get entered, even if they aren't unique
- foreach ($names as $name)
- {
+ foreach ($names as $name) {
$abbrevs[$name] = array($name);
}
@@ -617,32 +575,26 @@ public function asText($namespace = null)
$commands = $namespace ? $this->getCommands($this->findNamespace($namespace)) : $this->commands;
$messages = array($this->getHelp(), '');
- if ($namespace)
- {
+ if ($namespace) {
$messages[] = sprintf("Available commands for the \"%s\" namespace:", $namespace);
- }
- else
- {
+ } else {
$messages[] = 'Available commands:';
}
$width = 0;
- foreach ($commands as $command)
- {
+ foreach ($commands as $command) {
$width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
}
$width += 2;
// add commands by namespace
- foreach ($this->sortCommands($commands) as $space => $commands)
- {
+ foreach ($this->sortCommands($commands) as $space => $commands) {
if (!$namespace && '_global' !== $space)
{
$messages[] = ''.$space.'';
}
- foreach ($commands as $command)
- {
+ foreach ($commands as $command) {
$aliases = $command->getAliases() ? ' ('.implode(', ', $command->getAliases()).')' : '';
$messages[] = sprintf(" %-${width}s %s%s", ($command->getNamespace() ? ':' : '').$command->getName(), $command->getDescription(), $aliases);
@@ -670,26 +622,21 @@ public function asXml($namespace = null, $asDom = false)
$xml->appendChild($commandsXML = $dom->createElement('commands'));
- if ($namespace)
- {
+ if ($namespace) {
$commandsXML->setAttribute('namespace', $namespace);
- }
- else
- {
+ } else {
$xml->appendChild($namespacesXML = $dom->createElement('namespaces'));
}
// add commands by namespace
- foreach ($this->sortCommands($commands) as $space => $commands)
- {
+ foreach ($this->sortCommands($commands) as $space => $commands) {
if (!$namespace)
{
$namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace'));
$namespaceArrayXML->setAttribute('id', $space);
}
- foreach ($commands as $command)
- {
+ foreach ($commands as $command) {
if (!$namespace)
{
$namespaceArrayXML->appendChild($commandXML = $dom->createElement('command'));
@@ -725,36 +672,31 @@ public function renderException($e, $output)
$title = sprintf(' [%s] ', get_class($e));
$len = $strlen($title);
$lines = array();
- foreach (explode("\n", $e->getMessage()) as $line)
- {
+ foreach (explode("\n", $e->getMessage()) as $line) {
$lines[] = sprintf(' %s ', $line);
$len = max($strlen($line) + 4, $len);
}
$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[] = str_repeat(' ', $len);
$output->writeln("\n");
- foreach ($messages as $message)
- {
+ foreach ($messages as $message) {
$output->writeln(''.$message.'');
}
$output->writeln("\n");
- if (null !== $this->runningCommand)
- {
+ if (null !== $this->runningCommand) {
$output->writeln(sprintf('%s', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
$output->writeln("\n");
}
- if (Output::VERBOSITY_VERBOSE === $output->getVerbosity())
- {
+ if (Output::VERBOSITY_VERBOSE === $output->getVerbosity()) {
$output->writeln('Exception trace:');
// exception related properties
@@ -766,8 +708,7 @@ public function renderException($e, $output)
'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'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function'];
@@ -784,12 +725,10 @@ public function renderException($e, $output)
private function sortCommands($commands)
{
$namespacedCommands = array();
- foreach ($commands as $name => $command)
- {
+ foreach ($commands as $name => $command) {
$key = $command->getNamespace() ? $command->getNamespace() : '_global';
- if (!isset($namespacedCommands[$key]))
- {
+ if (!isset($namespacedCommands[$key])) {
$namespacedCommands[$key] = array();
}
@@ -797,8 +736,7 @@ private function sortCommands($commands)
}
ksort($namespacedCommands);
- foreach ($namespacedCommands as $name => &$commands)
- {
+ foreach ($namespacedCommands as $name => &$commands) {
ksort($commands);
}
diff --git a/src/Symfony/Components/Console/Command/Command.php b/src/Symfony/Components/Console/Command/Command.php
index ae029e8d2f28..9f68bd2a670e 100644
--- a/src/Symfony/Components/Console/Command/Command.php
+++ b/src/Symfony/Components/Console/Command/Command.php
@@ -53,15 +53,13 @@ public function __construct($name = null)
$this->applicationDefinitionMerged = false;
$this->aliases = array();
- if (null !== $name)
- {
+ if (null !== $name) {
$this->setName($name);
}
$this->configure();
- if (!$this->name)
- {
+ if (!$this->name) {
throw new \LogicException('The command name cannot be empty.');
}
}
@@ -133,12 +131,9 @@ public function run(InputInterface $input, OutputInterface $output)
$this->mergeApplicationDefinition();
// bind the input against the command specific arguments/options
- try
- {
+ try {
$input->bind($this->definition);
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
if (!$this->ignoreValidationErrors)
{
throw $e;
@@ -147,19 +142,15 @@ public function run(InputInterface $input, OutputInterface $output)
$this->initialize($input, $output);
- if ($input->isInteractive())
- {
+ if ($input->isInteractive()) {
$this->interact($input, $output);
}
$input->validate();
- if ($this->code)
- {
+ if ($this->code) {
return call_user_func($this->code, $input, $output);
- }
- else
- {
+ } else {
return $this->execute($input, $output);
}
}
@@ -183,8 +174,7 @@ public function setCode(\Closure $code)
*/
protected function mergeApplicationDefinition()
{
- if (null === $this->application || true === $this->applicationDefinitionMerged)
- {
+ if (null === $this->application || true === $this->applicationDefinitionMerged) {
return;
}
@@ -207,12 +197,9 @@ protected function mergeApplicationDefinition()
*/
public function setDefinition($definition)
{
- if ($definition instanceof InputDefinition)
- {
+ if ($definition instanceof InputDefinition) {
$this->definition = $definition;
- }
- else
- {
+ } else {
$this->definition->setDefinition($definition);
}
@@ -282,18 +269,14 @@ public function addOption($name, $shortcut = null, $mode = null, $description =
*/
public function setName($name)
{
- if (false !== $pos = strrpos($name, ':'))
- {
+ if (false !== $pos = strrpos($name, ':')) {
$namespace = substr($name, 0, $pos);
$name = substr($name, $pos + 1);
- }
- else
- {
+ } else {
$namespace = $this->namespace;
}
- if (!$name)
- {
+ if (!$name) {
throw new \InvalidArgumentException('A command name cannot be empty.');
}
@@ -478,15 +461,13 @@ public function asText()
'',
);
- if ($this->getAliases())
- {
+ if ($this->getAliases()) {
$messages[] = 'Aliases: '.implode(', ', $this->getAliases()).'';
}
$messages[] = $this->definition->asText();
- if ($help = $this->getProcessedHelp())
- {
+ if ($help = $this->getProcessedHelp()) {
$messages[] = 'Help:';
$messages[] = ' '.implode("\n ", explode("\n", $help))."\n";
}
@@ -521,8 +502,7 @@ public function asXml($asDom = false)
$helpXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $help))));
$commandXML->appendChild($aliasesXML = $dom->createElement('aliases'));
- foreach ($this->getAliases() as $alias)
- {
+ foreach ($this->getAliases() as $alias) {
$aliasesXML->appendChild($aliasXML = $dom->createElement('alias'));
$aliasXML->appendChild($dom->createTextNode($alias));
}
diff --git a/src/Symfony/Components/Console/Command/HelpCommand.php b/src/Symfony/Components/Console/Command/HelpCommand.php
index 38c8ad197e28..032faecbe133 100644
--- a/src/Symfony/Components/Console/Command/HelpCommand.php
+++ b/src/Symfony/Components/Console/Command/HelpCommand.php
@@ -66,17 +66,13 @@ public function setCommand(Command $command)
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
- if (null === $this->command)
- {
+ if (null === $this->command) {
$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);
- }
- else
- {
+ } else {
$output->writeln($this->command->asText());
}
}
diff --git a/src/Symfony/Components/Console/Command/ListCommand.php b/src/Symfony/Components/Console/Command/ListCommand.php
index efceb4a4b3d8..fd82c1768c98 100644
--- a/src/Symfony/Components/Console/Command/ListCommand.php
+++ b/src/Symfony/Components/Console/Command/ListCommand.php
@@ -60,12 +60,9 @@ protected function configure()
*/
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);
- }
- else
- {
+ } else {
$output->writeln($this->application->asText($input->getArgument('namespace')));
}
}
diff --git a/src/Symfony/Components/Console/Helper/DialogHelper.php b/src/Symfony/Components/Console/Helper/DialogHelper.php
index 2e19a9953ac0..c499c612e188 100644
--- a/src/Symfony/Components/Console/Helper/DialogHelper.php
+++ b/src/Symfony/Components/Console/Helper/DialogHelper.php
@@ -57,17 +57,13 @@ public function askConfirmation(OutputInterface $output, $question, $default = t
{
// @codeCoverageIgnoreStart
$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);
}
- if (false === $default)
- {
+ if (false === $default) {
return $answer && 'y' == strtolower($answer[0]);
- }
- else
- {
+ } else {
return !$answer || 'y' == strtolower($answer[0]);
}
// @codeCoverageIgnoreEnd
@@ -89,8 +85,7 @@ public function askAndValidate(OutputInterface $output, $question, \Closure $val
{
// @codeCoverageIgnoreStart
$error = null;
- while (false === $attempts || $attempts--)
- {
+ while (false === $attempts || $attempts--) {
if (null !== $error)
{
$output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'));
@@ -98,12 +93,9 @@ public function askAndValidate(OutputInterface $output, $question, \Closure $val
$value = $this->ask($output, $question, null);
- try
- {
+ try {
return $validator($value);
- }
- catch (\Exception $error)
- {
+ } catch (\Exception $error) {
}
}
diff --git a/src/Symfony/Components/Console/Helper/FormatterHelper.php b/src/Symfony/Components/Console/Helper/FormatterHelper.php
index 5689b1ec117f..9c640d801f2e 100644
--- a/src/Symfony/Components/Console/Helper/FormatterHelper.php
+++ b/src/Symfony/Components/Console/Helper/FormatterHelper.php
@@ -43,31 +43,26 @@ public function formatSection($section, $message, $style = 'info')
*/
public function formatBlock($messages, $style, $large = false)
{
- if (!is_array($messages))
- {
+ if (!is_array($messages)) {
$messages = array($messages);
}
$len = 0;
$lines = array();
- foreach ($messages as $message)
- {
+ foreach ($messages as $message) {
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
$len = max($this->strlen($message) + ($large ? 4 : 2), $len);
}
$messages = $large ? array(str_repeat(' ', $len)) : array();
- foreach ($lines as $line)
- {
+ foreach ($lines as $line) {
$messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
}
- if ($large)
- {
+ if ($large) {
$messages[] = str_repeat(' ', $len);
}
- foreach ($messages as &$message)
- {
+ foreach ($messages as &$message) {
$message = sprintf('<%s>%s%s>', $style, $message, $style);
}
diff --git a/src/Symfony/Components/Console/Helper/HelperSet.php b/src/Symfony/Components/Console/Helper/HelperSet.php
index 2398fc1ffaeb..ea76c4d99433 100644
--- a/src/Symfony/Components/Console/Helper/HelperSet.php
+++ b/src/Symfony/Components/Console/Helper/HelperSet.php
@@ -31,8 +31,7 @@ class HelperSet
*/
public function __construct(array $helpers = array())
{
- foreach ($helpers as $alias => $helper)
- {
+ foreach ($helpers as $alias => $helper) {
$this->set($helper, is_int($alias) ? null : $alias);
}
}
@@ -46,8 +45,7 @@ public function __construct(array $helpers = array())
public function set(HelperInterface $helper, $alias = null)
{
$this->helpers[$helper->getName()] = $helper;
- if (null !== $alias)
- {
+ if (null !== $alias) {
$this->helpers[$alias] = $helper;
}
@@ -77,8 +75,7 @@ public function has($name)
*/
public function get($name)
{
- if (!$this->has($name))
- {
+ if (!$this->has($name)) {
throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
}
diff --git a/src/Symfony/Components/Console/Input/ArgvInput.php b/src/Symfony/Components/Console/Input/ArgvInput.php
index db32cf6b2977..c813ec40017d 100644
--- a/src/Symfony/Components/Console/Input/ArgvInput.php
+++ b/src/Symfony/Components/Console/Input/ArgvInput.php
@@ -51,8 +51,7 @@ class ArgvInput extends Input
*/
public function __construct(array $argv = null, InputDefinition $definition = null)
{
- if (null === $argv)
- {
+ if (null === $argv) {
$argv = $_SERVER['argv'];
}
@@ -70,18 +69,13 @@ public function __construct(array $argv = null, InputDefinition $definition = nu
protected function parse()
{
$this->parsed = $this->tokens;
- while (null !== $token = array_shift($this->parsed))
- {
+ while (null !== $token = array_shift($this->parsed)) {
if ('--' === substr($token, 0, 2))
{
$this->parseLongOption($token);
- }
- elseif ('-' === $token[0])
- {
+ } elseif ('-' === $token[0]) {
$this->parseShortOption($token);
- }
- else
- {
+ } else {
$this->parseArgument($token);
}
}
@@ -96,20 +90,15 @@ protected function parseShortOption($token)
{
$name = substr($token, 1);
- if (strlen($name) > 1)
- {
+ if (strlen($name) > 1) {
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptParameter())
{
// an option with a value (with no space)
$this->addShortOption($name[0], substr($name, 1));
- }
- else
- {
+ } else {
$this->parseShortOptionSet($name);
}
- }
- else
- {
+ } else {
$this->addShortOption($name, null);
}
}
@@ -124,22 +113,18 @@ protected function parseShortOption($token)
protected function parseShortOptionSet($name)
{
$len = strlen($name);
- for ($i = 0; $i < $len; $i++)
- {
+ for ($i = 0; $i < $len; $i++) {
if (!$this->definition->hasShortcut($name[$i]))
{
throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
}
$option = $this->definition->getOptionForShortcut($name[$i]);
- if ($option->acceptParameter())
- {
+ if ($option->acceptParameter()) {
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
break;
- }
- else
- {
+ } else {
$this->addLongOption($option->getName(), true);
}
}
@@ -154,12 +139,9 @@ protected function parseLongOption($token)
{
$name = substr($token, 2);
- if (false !== $pos = strpos($name, '='))
- {
+ if (false !== $pos = strpos($name, '=')) {
$this->addLongOption(substr($name, 0, $pos), substr($name, $pos + 1));
- }
- else
- {
+ } else {
$this->addLongOption($name, null);
}
}
@@ -173,8 +155,7 @@ protected function parseLongOption($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.');
}
@@ -191,8 +172,7 @@ protected function parseArgument($token)
*/
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));
}
@@ -209,30 +189,24 @@ protected function addShortOption($shortcut, $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));
}
$option = $this->definition->getOption($name);
- if (null === $value && $option->acceptParameter())
- {
+ if (null === $value && $option->acceptParameter()) {
// if option accepts an optional or mandatory argument
// let's see if there is one provided
$next = array_shift($this->parsed);
- if ('-' !== $next[0])
- {
+ if ('-' !== $next[0]) {
$value = $next;
- }
- else
- {
+ } else {
array_unshift($this->parsed, $next);
}
}
- if (null === $value)
- {
+ if (null === $value) {
if ($option->isParameterRequired())
{
throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
@@ -251,8 +225,7 @@ protected function addLongOption($name, $value)
*/
public function getFirstArgument()
{
- foreach ($this->tokens as $token)
- {
+ foreach ($this->tokens as $token) {
if ($token && '-' === $token[0])
{
continue;
@@ -274,13 +247,11 @@ public function getFirstArgument()
*/
public function hasParameterOption($values)
{
- if (!is_array($values))
- {
+ if (!is_array($values)) {
$values = array($values);
}
- foreach ($this->tokens as $v)
- {
+ foreach ($this->tokens as $v) {
if (in_array($v, $values))
{
return true;
diff --git a/src/Symfony/Components/Console/Input/ArrayInput.php b/src/Symfony/Components/Console/Input/ArrayInput.php
index 308baff345a0..46b2221b5d4f 100644
--- a/src/Symfony/Components/Console/Input/ArrayInput.php
+++ b/src/Symfony/Components/Console/Input/ArrayInput.php
@@ -46,8 +46,7 @@ public function __construct(array $parameters, InputDefinition $definition = nul
*/
public function getFirstArgument()
{
- foreach ($this->parameters as $key => $value)
- {
+ foreach ($this->parameters as $key => $value) {
if ($key && '-' === $key[0])
{
continue;
@@ -69,20 +68,17 @@ public function getFirstArgument()
*/
public function hasParameterOption($values)
{
- if (!is_array($values))
- {
+ if (!is_array($values)) {
$values = array($values);
}
- foreach ($this->parameters as $k => $v)
- {
+ foreach ($this->parameters as $k => $v) {
if (!is_int($k))
{
$v = $k;
}
- if (in_array($v, $values))
- {
+ if (in_array($v, $values)) {
return true;
}
}
@@ -95,18 +91,13 @@ public function hasParameterOption($values)
*/
protected function parse()
{
- foreach ($this->parameters as $key => $value)
- {
+ foreach ($this->parameters as $key => $value) {
if ('--' === substr($key, 0, 2))
{
$this->addLongOption(substr($key, 2), $value);
- }
- elseif ('-' === $key[0])
- {
+ } elseif ('-' === $key[0]) {
$this->addShortOption(substr($key, 1), $value);
- }
- else
- {
+ } else {
$this->addArgument($key, $value);
}
}
@@ -122,8 +113,7 @@ protected function parse()
*/
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));
}
@@ -141,15 +131,13 @@ protected function addShortOption($shortcut, $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));
}
$option = $this->definition->getOption($name);
- if (null === $value)
- {
+ if (null === $value) {
if ($option->isParameterRequired())
{
throw new \InvalidArgumentException(sprintf('The "--%s" option requires a value.', $name));
@@ -171,8 +159,7 @@ protected function addLongOption($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));
}
diff --git a/src/Symfony/Components/Console/Input/Input.php b/src/Symfony/Components/Console/Input/Input.php
index 50d3d67db9c1..e7fcff3d1206 100644
--- a/src/Symfony/Components/Console/Input/Input.php
+++ b/src/Symfony/Components/Console/Input/Input.php
@@ -38,12 +38,9 @@ abstract class Input implements InputInterface
*/
public function __construct(InputDefinition $definition = null)
{
- if (null === $definition)
- {
+ if (null === $definition) {
$this->definition = new InputDefinition();
- }
- else
- {
+ } else {
$this->bind($definition);
$this->validate();
}
@@ -73,8 +70,7 @@ abstract protected function parse();
*/
public function validate()
{
- if (count($this->arguments) < $this->definition->getArgumentRequiredCount())
- {
+ if (count($this->arguments) < $this->definition->getArgumentRequiredCount()) {
throw new \RuntimeException('Not enough arguments.');
}
}
@@ -110,8 +106,7 @@ public function getArguments()
*/
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));
}
@@ -128,8 +123,7 @@ public function getArgument($name)
*/
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));
}
@@ -169,8 +163,7 @@ public function getOptions()
*/
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));
}
@@ -187,8 +180,7 @@ public function getOption($name)
*/
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));
}
diff --git a/src/Symfony/Components/Console/Input/InputArgument.php b/src/Symfony/Components/Console/Input/InputArgument.php
index de4222f35b37..e2498e01d751 100644
--- a/src/Symfony/Components/Console/Input/InputArgument.php
+++ b/src/Symfony/Components/Console/Input/InputArgument.php
@@ -41,12 +41,9 @@ class InputArgument
*/
public function __construct($name, $mode = null, $description = '', $default = null)
{
- if (null === $mode)
- {
+ if (null === $mode) {
$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));
}
@@ -96,19 +93,15 @@ public function isArray()
*/
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.');
}
- if ($this->isArray())
- {
+ if ($this->isArray()) {
if (null === $default)
{
$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.');
}
}
diff --git a/src/Symfony/Components/Console/Input/InputDefinition.php b/src/Symfony/Components/Console/Input/InputDefinition.php
index 0a4af589bc1e..0dc893bc3d90 100644
--- a/src/Symfony/Components/Console/Input/InputDefinition.php
+++ b/src/Symfony/Components/Console/Input/InputDefinition.php
@@ -48,14 +48,11 @@ public function setDefinition(array $definition)
{
$arguments = array();
$options = array();
- foreach ($definition as $item)
- {
+ foreach ($definition as $item) {
if ($item instanceof InputOption)
{
$options[] = $item;
- }
- else
- {
+ } else {
$arguments[] = $item;
}
}
@@ -84,8 +81,7 @@ public function setArguments($arguments = array())
*/
public function addArguments($arguments = array())
{
- if (null !== $arguments)
- {
+ if (null !== $arguments) {
foreach ($arguments as $argument)
{
$this->addArgument($argument);
@@ -102,32 +98,25 @@ public function addArguments($arguments = array())
*/
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()));
}
- if ($this->hasAnArrayArgument)
- {
+ if ($this->hasAnArrayArgument) {
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.');
}
- if ($argument->isArray())
- {
+ if ($argument->isArray()) {
$this->hasAnArrayArgument = true;
}
- if ($argument->isRequired())
- {
+ if ($argument->isRequired()) {
++$this->requiredCount;
- }
- else
- {
+ } else {
$this->hasOptional = true;
}
@@ -147,8 +136,7 @@ public function getArgument($name)
{
$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));
}
@@ -207,8 +195,7 @@ public function getArgumentRequiredCount()
public function getArgumentDefaults()
{
$values = array();
- foreach ($this->arguments as $argument)
- {
+ foreach ($this->arguments as $argument) {
$values[$argument->getName()] = $argument->getDefault();
}
@@ -234,8 +221,7 @@ public function setOptions($options = array())
*/
public function addOptions($options = array())
{
- foreach ($options as $option)
- {
+ foreach ($options as $option) {
$this->addOption($option);
}
}
@@ -249,18 +235,14 @@ public function addOptions($options = array())
*/
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()));
- }
- 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()));
}
$this->options[$option->getName()] = $option;
- if ($option->getShortcut())
- {
+ if ($option->getShortcut()) {
$this->shortcuts[$option->getShortcut()] = $option->getName();
}
}
@@ -274,8 +256,7 @@ public function addOption(InputOption $option)
*/
public function getOption($name)
{
- if (!$this->hasOption($name))
- {
+ if (!$this->hasOption($name)) {
throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
}
@@ -334,8 +315,7 @@ public function getOptionForShortcut($shortcut)
public function getOptionDefaults()
{
$values = array();
- foreach ($this->options as $option)
- {
+ foreach ($this->options as $option) {
$values[$option->getName()] = $option->getDefault();
}
@@ -353,8 +333,7 @@ public function getOptionDefaults()
*/
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));
}
@@ -369,18 +348,15 @@ protected function shortcutToName($shortcut)
public function getSynopsis()
{
$elements = array();
- foreach ($this->getOptions() as $option)
- {
+ foreach ($this->getOptions() as $option) {
$shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
$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' : ''));
- if ($argument->isArray())
- {
+ if ($argument->isArray()) {
$elements[] = sprintf('... [%sN]', $argument->getName());
}
}
@@ -397,29 +373,23 @@ public function asText()
{
// find the largest option or argument name
$max = 0;
- foreach ($this->getOptions() as $option)
- {
+ foreach ($this->getOptions() as $option) {
$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;
$text = array();
- if ($this->getArguments())
- {
+ if ($this->getArguments()) {
$text[] = 'Arguments:';
- foreach ($this->getArguments() as $argument)
- {
+ foreach ($this->getArguments() as $argument) {
if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault())))
{
$default = sprintf(' (default: %s)', is_array($argument->getDefault()) ? str_replace("\n", '', var_export($argument->getDefault(), true)): $argument->getDefault());
- }
- else
- {
+ } else {
$default = '';
}
@@ -429,18 +399,14 @@ public function asText()
$text[] = '';
}
- if ($this->getOptions())
- {
+ if ($this->getOptions()) {
$text[] = 'Options:';
- foreach ($this->getOptions() as $option)
- {
+ foreach ($this->getOptions() as $option) {
if ($option->acceptParameter() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault())))
{
$default = sprintf(' (default: %s)', is_array($option->getDefault()) ? str_replace("\n", '', print_r($option->getDefault(), true)): $option->getDefault());
- }
- else
- {
+ } else {
$default = '';
}
@@ -468,8 +434,7 @@ public function asXml($asDom = false)
$dom->appendChild($definitionXML = $dom->createElement('definition'));
$definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
- foreach ($this->getArguments() as $argument)
- {
+ foreach ($this->getArguments() as $argument) {
$argumentsXML->appendChild($argumentXML = $dom->createElement('argument'));
$argumentXML->setAttribute('name', $argument->getName());
$argumentXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0);
@@ -479,16 +444,14 @@ public function asXml($asDom = false)
$argumentXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$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'));
$defaultXML->appendChild($dom->createTextNode($default));
}
}
$definitionXML->appendChild($optionsXML = $dom->createElement('options'));
- foreach ($this->getOptions() as $option)
- {
+ foreach ($this->getOptions() as $option) {
$optionsXML->appendChild($optionXML = $dom->createElement('option'));
$optionXML->setAttribute('name', '--'.$option->getName());
$optionXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : '');
@@ -498,12 +461,10 @@ public function asXml($asDom = false)
$optionXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
- if ($option->acceptParameter())
- {
+ if ($option->acceptParameter()) {
$optionXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$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'));
$defaultXML->appendChild($dom->createTextNode($default));
}
diff --git a/src/Symfony/Components/Console/Input/InputOption.php b/src/Symfony/Components/Console/Input/InputOption.php
index 0c00bff9847b..4bc0738ec610 100644
--- a/src/Symfony/Components/Console/Input/InputOption.php
+++ b/src/Symfony/Components/Console/Input/InputOption.php
@@ -44,30 +44,24 @@ class InputOption
*/
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);
}
- if (empty($shortcut))
- {
+ if (empty($shortcut)) {
$shortcut = null;
}
- if (null !== $shortcut)
- {
+ if (null !== $shortcut) {
if ('-' === $shortcut[0])
{
$shortcut = substr($shortcut, 1);
}
}
- if (null === $mode)
- {
+ if (null === $mode) {
$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));
}
@@ -76,8 +70,7 @@ public function __construct($name, $shortcut = null, $mode = null, $description
$this->mode = $mode;
$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.');
}
@@ -151,19 +144,15 @@ public function isArray()
*/
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.');
}
- if ($this->isArray())
- {
+ if ($this->isArray()) {
if (null === $default)
{
$default = array();
- }
- elseif (!is_array($default))
- {
+ } elseif (!is_array($default)) {
throw new \LogicException('A default value for an array option must be an array.');
}
}
diff --git a/src/Symfony/Components/Console/Input/StringInput.php b/src/Symfony/Components/Console/Input/StringInput.php
index 1e8d13107cb8..e4c17284edd2 100644
--- a/src/Symfony/Components/Console/Input/StringInput.php
+++ b/src/Symfony/Components/Console/Input/StringInput.php
@@ -50,25 +50,16 @@ protected function tokenize($input)
$tokens = array();
$length = strlen($input);
$cursor = 0;
- while ($cursor < $length)
- {
+ while ($cursor < $length) {
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)));
- }
- 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));
- }
- 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]);
- }
- else
- {
+ } else {
// should never happen
// @codeCoverageIgnoreStart
throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
diff --git a/src/Symfony/Components/Console/Output/Output.php b/src/Symfony/Components/Console/Output/Output.php
index 166291b322f5..691752ad20d3 100644
--- a/src/Symfony/Components/Console/Output/Output.php
+++ b/src/Symfony/Components/Console/Output/Output.php
@@ -132,18 +132,15 @@ public function writeln($messages, $type = 0)
*/
public function write($messages, $newline = false, $type = 0)
{
- if (self::VERBOSITY_QUIET === $this->verbosity)
- {
+ if (self::VERBOSITY_QUIET === $this->verbosity) {
return;
}
- if (!is_array($messages))
- {
+ if (!is_array($messages)) {
$messages = array($messages);
}
- foreach ($messages as $message)
- {
+ foreach ($messages as $message) {
switch ($type)
{
case Output::OUTPUT_NORMAL:
@@ -189,31 +186,26 @@ protected function format($message)
*/
protected function replaceStartStyle($match)
{
- if (!$this->decorated)
- {
+ if (!$this->decorated) {
return '';
}
- if (!isset(static::$styles[strtolower($match[1])]))
- {
+ if (!isset(static::$styles[strtolower($match[1])])) {
throw new \InvalidArgumentException(sprintf('Unknown style "%s".', $match[1]));
}
$parameters = static::$styles[strtolower($match[1])];
$codes = array();
- if (isset($parameters['fg']))
- {
+ if (isset($parameters['fg'])) {
$codes[] = static::$foreground[$parameters['fg']];
}
- if (isset($parameters['bg']))
- {
+ if (isset($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])
{
$codes[] = $value;
@@ -225,8 +217,7 @@ protected function replaceStartStyle($match)
protected function replaceEndStyle($match)
{
- if (!$this->decorated)
- {
+ if (!$this->decorated) {
return '';
}
diff --git a/src/Symfony/Components/Console/Output/StreamOutput.php b/src/Symfony/Components/Console/Output/StreamOutput.php
index fe3c4b2b2651..6c21f38341f1 100644
--- a/src/Symfony/Components/Console/Output/StreamOutput.php
+++ b/src/Symfony/Components/Console/Output/StreamOutput.php
@@ -41,15 +41,13 @@ class StreamOutput extends Output
*/
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.');
}
$this->stream = $stream;
- if (null === $decorated)
- {
+ if (null === $decorated) {
$decorated = $this->hasColorSupport($decorated);
}
@@ -76,8 +74,7 @@ public function getStream()
*/
public function doWrite($message, $newline)
{
- if (false === @fwrite($this->stream, $message.($newline ? PHP_EOL : '')))
- {
+ if (false === @fwrite($this->stream, $message.($newline ? PHP_EOL : ''))) {
// @codeCoverageIgnoreStart
// should never happen
throw new \RuntimeException('Unable to write output.');
@@ -100,12 +97,9 @@ public function doWrite($message, $newline)
protected function hasColorSupport()
{
// @codeCoverageIgnoreStart
- if (DIRECTORY_SEPARATOR == '\\')
- {
+ if (DIRECTORY_SEPARATOR == '\\') {
return false !== getenv('ANSICON');
- }
- else
- {
+ } else {
return function_exists('posix_isatty') && @posix_isatty($this->stream);
}
// @codeCoverageIgnoreEnd
diff --git a/src/Symfony/Components/Console/Shell.php b/src/Symfony/Components/Console/Shell.php
index b897e41d35ec..5701cbf3a28d 100644
--- a/src/Symfony/Components/Console/Shell.php
+++ b/src/Symfony/Components/Console/Shell.php
@@ -43,8 +43,7 @@ class Shell
*/
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.');
}
@@ -65,12 +64,10 @@ public function run()
readline_completion_function(array($this, 'autocompleter'));
$this->output->writeln($this->getHeader());
- while (true)
- {
+ while (true) {
$command = readline($this->application->getName().' > ');
- if (false === $command)
- {
+ if (false === $command) {
$this->output->writeln("\n");
break;
@@ -79,8 +76,7 @@ public function run()
readline_add_history($command);
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('The command terminated with an error status (%s)', $ret));
}
}
@@ -97,30 +93,24 @@ protected function autocompleter($text, $position)
$info = readline_info();
$text = substr($info['line_buffer'], 0, $info['end']);
- if ($info['point'] !== $info['end'])
- {
+ if ($info['point'] !== $info['end']) {
return true;
}
// task name?
- if (false === strpos($text, ' ') || !$text)
- {
+ if (false === strpos($text, ' ') || !$text) {
return array_keys($this->application->getCommands());
}
// options and arguments?
- try
- {
+ try {
$command = $this->application->findCommand(substr($text, 0, strpos($text, ' ')));
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
return true;
}
$list = array('--help');
- foreach ($command->getDefinition()->getOptions() as $option)
- {
+ foreach ($command->getDefinition()->getOptions() as $option) {
$list[] = '--'.$option->getName();
}
diff --git a/src/Symfony/Components/Console/Tester/ApplicationTester.php b/src/Symfony/Components/Console/Tester/ApplicationTester.php
index efe3b17a797e..beb207bfb05f 100644
--- a/src/Symfony/Components/Console/Tester/ApplicationTester.php
+++ b/src/Symfony/Components/Console/Tester/ApplicationTester.php
@@ -52,18 +52,15 @@ public function __construct(Application $application)
public function run(array $input, $options = array())
{
$this->input = new ArrayInput($input);
- if (isset($options['interactive']))
- {
+ if (isset($options['interactive'])) {
$this->input->setInteractive($options['interactive']);
}
$this->output = new StreamOutput(fopen('php://memory', 'w', false));
- if (isset($options['decorated']))
- {
+ if (isset($options['decorated'])) {
$this->output->setDecorated($options['decorated']);
}
- if (isset($options['verbosity']))
- {
+ if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
diff --git a/src/Symfony/Components/Console/Tester/CommandTester.php b/src/Symfony/Components/Console/Tester/CommandTester.php
index 475820961b57..59994357b411 100644
--- a/src/Symfony/Components/Console/Tester/CommandTester.php
+++ b/src/Symfony/Components/Console/Tester/CommandTester.php
@@ -52,18 +52,15 @@ public function __construct(Command $command)
public function execute(array $input, array $options = array())
{
$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->output = new StreamOutput(fopen('php://memory', 'w', false));
- if (isset($options['decorated']))
- {
+ if (isset($options['decorated'])) {
$this->output->setDecorated($options['decorated']);
}
- if (isset($options['verbosity']))
- {
+ if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
diff --git a/src/Symfony/Components/CssSelector/Node/AttribNode.php b/src/Symfony/Components/CssSelector/Node/AttribNode.php
index d410b1819a13..04632718e175 100644
--- a/src/Symfony/Components/CssSelector/Node/AttribNode.php
+++ b/src/Symfony/Components/CssSelector/Node/AttribNode.php
@@ -43,12 +43,9 @@ public function __construct($selector, $namespace, $attrib, $operator, $value)
public function __toString()
{
- if ($this->operator == 'exists')
- {
+ if ($this->operator == 'exists') {
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);
}
}
@@ -61,52 +58,32 @@ public function toXpath()
$path = $this->selector->toXpath();
$attrib = $this->xpathAttrib();
$value = $this->value;
- if ($this->operator == 'exists')
- {
+ if ($this->operator == 'exists') {
$path->addCondition($attrib);
- }
- elseif ($this->operator == '=')
- {
+ } elseif ($this->operator == '=') {
$path->addCondition(sprintf('%s = %s', $attrib, XPathExpr::xpathLiteral($value)));
- }
- elseif ($this->operator == '!=')
- {
+ } elseif ($this->operator == '!=') {
// FIXME: this seems like a weird hack...
- if ($value)
- {
+ if ($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('%s != %s' % (attrib, xpathLiteral(value)))
- }
- elseif ($this->operator == '~=')
- {
+ } elseif ($this->operator == '~=') {
$path->addCondition(sprintf("contains(concat(' ', normalize-space(%s), ' '), %s)", $attrib, XPathExpr::xpathLiteral(' '.$value.' ')));
- }
- elseif ($this->operator == '|=')
- {
+ } elseif ($this->operator == '|=') {
// Weird, but true...
$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)));
- }
- elseif ($this->operator == '$=')
- {
+ } elseif ($this->operator == '$=') {
// 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)));
- }
- elseif ($this->operator == '*=')
- {
+ } elseif ($this->operator == '*=') {
// FIXME: case sensitive?
$path->addCondition(sprintf('contains(%s, %s)', $attrib, XPathExpr::xpathLiteral($value)));
- }
- else
- {
+ } else {
throw new SyntaxError(sprintf('Unknown operator: %s', $this->operator));
}
@@ -116,8 +93,7 @@ public function toXpath()
protected function xpathAttrib()
{
// FIXME: if attrib is *?
- if ($this->namespace == '*')
- {
+ if ($this->namespace == '*') {
return '@'.$this->attrib;
}
@@ -126,8 +102,7 @@ protected function xpathAttrib()
protected function formatAttrib()
{
- if ($this->namespace == '*')
- {
+ if ($this->namespace == '*') {
return $this->attrib;
}
diff --git a/src/Symfony/Components/CssSelector/Node/CombinedSelectorNode.php b/src/Symfony/Components/CssSelector/Node/CombinedSelectorNode.php
index 97ff27e51b64..45b79d8568f4 100644
--- a/src/Symfony/Components/CssSelector/Node/CombinedSelectorNode.php
+++ b/src/Symfony/Components/CssSelector/Node/CombinedSelectorNode.php
@@ -55,8 +55,7 @@ public function __toString()
*/
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));
}
diff --git a/src/Symfony/Components/CssSelector/Node/ElementNode.php b/src/Symfony/Components/CssSelector/Node/ElementNode.php
index 090983aabb6f..111307646e66 100644
--- a/src/Symfony/Components/CssSelector/Node/ElementNode.php
+++ b/src/Symfony/Components/CssSelector/Node/ElementNode.php
@@ -41,8 +41,7 @@ public function __toString()
public function formatElement()
{
- if ($this->namespace == '*')
- {
+ if ($this->namespace == '*') {
return $this->element;
}
@@ -51,12 +50,9 @@ public function formatElement()
public function toXpath()
{
- if ($this->namespace == '*')
- {
+ if ($this->namespace == '*') {
$el = strtolower($this->element);
- }
- else
- {
+ } else {
// FIXME: Should we lowercase here?
$el = sprintf('%s:%s', $this->namespace, $this->element);
}
diff --git a/src/Symfony/Components/CssSelector/Node/FunctionNode.php b/src/Symfony/Components/CssSelector/Node/FunctionNode.php
index 6f9bfc691202..b9f3259fef7e 100644
--- a/src/Symfony/Components/CssSelector/Node/FunctionNode.php
+++ b/src/Symfony/Components/CssSelector/Node/FunctionNode.php
@@ -52,13 +52,11 @@ public function __toString()
public function 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));
}
$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));
}
@@ -68,22 +66,19 @@ public function toXpath()
protected function _xpath_nth_child($xpath, $expr, $last = false, $addNameTest = true)
{
list($a, $b) = $this->parseSeries($expr);
- if (!$a && !$b && !$last)
- {
+ if (!$a && !$b && !$last) {
// a=0 means nothing is returned...
$xpath->addCondition('false() and position() = 0');
return $xpath;
}
- if ($addNameTest)
- {
+ if ($addNameTest) {
$xpath->addNameTest();
}
$xpath->addStarPrefix();
- if ($a == 0)
- {
+ if ($a == 0) {
if ($last)
{
$b = sprintf('last() - %s', $b);
@@ -93,43 +88,32 @@ protected function _xpath_nth_child($xpath, $expr, $last = false, $addNameTest =
return $xpath;
}
- if ($last)
- {
+ if ($last) {
// FIXME: I'm not sure if this is right
$a = -$a;
$b = -$b;
}
- if ($b > 0)
- {
+ if ($b > 0) {
$b_neg = -$b;
- }
- else
- {
+ } else {
$b_neg = sprintf('+%s', -$b);
}
- if ($a != 1)
- {
+ if ($a != 1) {
$expr = array(sprintf('(position() %s) mod %s = 0', $b_neg, $a));
- }
- else
- {
+ } else {
$expr = array();
}
- if ($b >= 0)
- {
+ if ($b >= 0) {
$expr[] = sprintf('position() >= %s', $b);
- }
- elseif ($b < 0 && $last)
- {
+ } elseif ($b < 0 && $last) {
$expr[] = sprintf('position() < (last() %s)', $b);
}
$expr = implode($expr, ' and ');
- if ($expr)
- {
+ if ($expr) {
$xpath->addCondition($expr);
}
@@ -150,8 +134,7 @@ protected function _xpath_nth_last_child($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');
}
@@ -166,8 +149,7 @@ protected function _xpath_nth_last_of_type($xpath, $expr)
protected function _xpath_contains($xpath, $expr)
{
// text content, minus tags, must contain expr
- if ($expr instanceof ElementNode)
- {
+ if ($expr instanceof ElementNode) {
$expr = $expr->formatElement();
}
@@ -194,69 +176,52 @@ protected function _xpath_not($xpath, $expr)
// Parses things like '1n+2', or 'an+b' generally, returning (a, b)
protected function parseSeries($s)
{
- if ($s instanceof ElementNode)
- {
+ if ($s instanceof ElementNode) {
$s = $s->formatElement();
}
- if (!$s || $s == '*')
- {
+ if (!$s || $s == '*') {
// Happens when there's nothing, which the CSS parser thinks of as *
return array(0, 0);
}
- if (is_string($s))
- {
+ if (is_string($s)) {
// Happens when you just get a number
return array(0, $s);
}
- if ($s == 'odd')
- {
+ if ($s == 'odd') {
return array(2, 1);
}
- if ($s == 'even')
- {
+ if ($s == 'even') {
return array(2, 0);
}
- if ($s == 'n')
- {
+ if ($s == 'n') {
return array(1, 0);
}
- if (false === strpos($s, 'n'))
- {
+ if (false === strpos($s, 'n')) {
// Just a b
return array(0, intval((string) $s));
}
list($a, $b) = explode('n', $s);
- if (!$a)
- {
+ if (!$a) {
$a = 1;
- }
- elseif ($a == '-' || $a == '+')
- {
+ } elseif ($a == '-' || $a == '+') {
$a = intval($a.'1');
- }
- else
- {
+ } else {
$a = intval($a);
}
- if (!$b)
- {
+ if (!$b) {
$b = 0;
- }
- elseif ($b == '-' || $b == '+')
- {
+ } elseif ($b == '-' || $b == '+') {
$b = intval($b.'1');
- }
- else
- {
+ } else {
$b = intval($b);
}
diff --git a/src/Symfony/Components/CssSelector/Node/OrNode.php b/src/Symfony/Components/CssSelector/Node/OrNode.php
index 10c0be943c48..fd4f67361765 100644
--- a/src/Symfony/Components/CssSelector/Node/OrNode.php
+++ b/src/Symfony/Components/CssSelector/Node/OrNode.php
@@ -40,8 +40,7 @@ public function __toString()
public function toXpath()
{
$paths = array();
- foreach ($this->items as $item)
- {
+ foreach ($this->items as $item) {
$paths[] = $item->toXpath();
}
diff --git a/src/Symfony/Components/CssSelector/Node/PseudoNode.php b/src/Symfony/Components/CssSelector/Node/PseudoNode.php
index 19951fb89b0c..aded2b9778c9 100644
--- a/src/Symfony/Components/CssSelector/Node/PseudoNode.php
+++ b/src/Symfony/Components/CssSelector/Node/PseudoNode.php
@@ -42,8 +42,7 @@ public function __construct($element, $type, $ident)
{
$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));
}
@@ -63,13 +62,11 @@ public function 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));
}
$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));
}
@@ -113,8 +110,7 @@ protected function xpath_last_child($xpath)
protected function xpath_first_of_type($xpath)
{
- if ($xpath->getElement() == '*')
- {
+ if ($xpath->getElement() == '*') {
throw new SyntaxError('*:first-of-type is not implemented');
}
$xpath->addStarPrefix();
@@ -128,8 +124,7 @@ protected function xpath_first_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');
}
$xpath->addStarPrefix();
@@ -152,8 +147,7 @@ protected function xpath_only_child($xpath)
*/
protected function xpath_only_of_type($xpath)
{
- if ($xpath->getElement() == '*')
- {
+ if ($xpath->getElement() == '*') {
throw new SyntaxError('*:only-of-type is not implemented');
}
$xpath->addCondition('last() = 1');
diff --git a/src/Symfony/Components/CssSelector/Parser.php b/src/Symfony/Components/CssSelector/Parser.php
index 693342c6d492..42757cbe998b 100644
--- a/src/Symfony/Components/CssSelector/Parser.php
+++ b/src/Symfony/Components/CssSelector/Parser.php
@@ -31,20 +31,17 @@ class Parser
*/
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))
{
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]);
}
- 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]);
}
@@ -55,14 +52,12 @@ static public function cssToXpath($cssExpr, $prefix = 'descendant-or-self::')
$expr = $cssExpr->toXpath();
// @codeCoverageIgnoreStart
- if (!$expr)
- {
+ if (!$expr) {
throw new SyntaxError(sprintf('Got None for xpath expression from %s.', $cssExpr));
}
// @codeCoverageIgnoreEnd
- if ($prefix)
- {
+ if ($prefix) {
$expr->addPrefix($prefix);
}
@@ -78,12 +73,9 @@ public function parse($string)
$stream = new TokenStream($tokenizer->tokenize($string), $string);
- try
- {
+ try {
return $this->parseSelectorGroup($stream);
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
$class = get_class($e);
throw new $class(sprintf('%s at %s -> %s', $e->getMessage(), implode($stream->getUsed(), ''), $stream->peek()));
@@ -93,21 +85,16 @@ public function parse($string)
protected function parseSelectorGroup($stream)
{
$result = array();
- while (1)
- {
+ while (1) {
$result[] = $this->parseSelector($stream);
- if ($stream->peek() == ',')
- {
+ if ($stream->peek() == ',') {
$stream->next();
- }
- else
- {
+ } else {
break;
}
}
- if (count($result) == 1)
- {
+ if (count($result) == 1) {
return $result[0];
}
@@ -121,26 +108,19 @@ protected function parseSelector($stream)
{
$result = $this->parseSimpleSelector($stream);
- while (1)
- {
+ while (1) {
$peek = $stream->peek();
- if ($peek == ',' || $peek === null)
- {
+ if ($peek == ',' || $peek === null) {
return $result;
- }
- elseif (in_array($peek, array('+', '>', '~')))
- {
+ } elseif (in_array($peek, array('+', '>', '~'))) {
// A combinator
$combinator = (string) $stream->next();
- }
- else
- {
+ } else {
$combinator = ' ';
}
$consumed = count($stream->getUsed());
$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()));
}
@@ -156,30 +136,22 @@ protected function parseSelector($stream)
protected function parseSimpleSelector($stream)
{
$peek = $stream->peek();
- if ($peek != '*' && !$peek->isType('Symbol'))
- {
+ if ($peek != '*' && !$peek->isType('Symbol')) {
$element = $namespace = '*';
- }
- else
- {
+ } else {
$next = $stream->next();
- if ($next != '*' && !$next->isType('Symbol'))
- {
+ if ($next != '*' && !$next->isType('Symbol')) {
throw new SyntaxError(sprintf("Expected symbol, got '%s'", $next));
}
- if ($stream->peek() == '|')
- {
+ if ($stream->peek() == '|') {
$namespace = $next;
$stream->next();
$element = $stream->next();
- if ($element != '*' && !$next->isType('Symbol'))
- {
+ if ($element != '*' && !$next->isType('Symbol')) {
throw new SyntaxError(sprintf("Expected symbol, got '%s'", $next));
}
- }
- else
- {
+ } else {
$namespace = '*';
$element = $next;
}
@@ -187,11 +159,9 @@ protected function parseSimpleSelector($stream)
$result = new Node\ElementNode($namespace, $element);
$has_hash = false;
- while (1)
- {
+ while (1) {
$peek = $stream->peek();
- if ($peek == '#')
- {
+ if ($peek == '#') {
if ($has_hash)
{
/* You can't have two hashes
@@ -205,69 +175,50 @@ protected function parseSimpleSelector($stream)
$has_hash = true;
continue;
- }
- elseif ($peek == '.')
- {
+ } elseif ($peek == '.') {
$stream->next();
$result = new Node\ClassNode($result, $stream->next());
continue;
- }
- elseif ($peek == '[')
- {
+ } elseif ($peek == '[') {
$stream->next();
$result = $this->parseAttrib($result, $stream);
$next = $stream->next();
- if ($next != ']')
- {
+ if ($next != ']') {
throw new SyntaxError(sprintf("] expected, got '%s'", $next));
}
continue;
- }
- elseif ($peek == ':' || $peek == '::')
- {
+ } elseif ($peek == ':' || $peek == '::') {
$type = $stream->next();
$ident = $stream->next();
- if (!$ident || !$ident->isType('Symbol'))
- {
+ if (!$ident || !$ident->isType('Symbol')) {
throw new SyntaxError(sprintf("Expected symbol, got '%s'", $ident));
}
- if ($stream->peek() == '(')
- {
+ if ($stream->peek() == '(') {
$stream->next();
$peek = $stream->peek();
- if ($peek->isType('String'))
- {
+ if ($peek->isType('String')) {
$selector = $stream->next();
- }
- elseif ($peek->isType('Symbol') && is_int($peek))
- {
+ } elseif ($peek->isType('Symbol') && is_int($peek)) {
$selector = intval($stream->next());
- }
- else
- {
+ } else {
// FIXME: parseSimpleSelector, or selector, or...?
$selector = $this->parseSimpleSelector($stream);
}
$next = $stream->next();
- if ($next != ')')
- {
+ if ($next != ')') {
throw new SyntaxError(sprintf("Expected ')', got '%s' and '%s'", $next, $selector));
}
$result = new Node\FunctionNode($result, $type, $ident, $selector);
- }
- else
- {
+ } else {
$result = new Node\PseudoNode($result, $type, $ident);
}
continue;
- }
- else
- {
+ } else {
if ($peek == ' ')
{
$stream->next();
@@ -287,31 +238,25 @@ protected function parseSimpleSelector($stream)
protected function parseAttrib($selector, $stream)
{
$attrib = $stream->next();
- if ($stream->peek() == '|')
- {
+ if ($stream->peek() == '|') {
$namespace = $attrib;
$stream->next();
$attrib = $stream->next();
- }
- else
- {
+ } else {
$namespace = '*';
}
- if ($stream->peek() == ']')
- {
+ if ($stream->peek() == ']') {
return new Node\AttribNode($selector, $namespace, $attrib, 'exists', null);
}
$op = $stream->next();
- if (!in_array($op, array('^=', '$=', '*=', '=', '~=', '|=', '!=')))
- {
+ if (!in_array($op, array('^=', '$=', '*=', '=', '~=', '|=', '!='))) {
throw new SyntaxError(sprintf("Operator expected, got '%s'", $op));
}
$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));
}
diff --git a/src/Symfony/Components/CssSelector/TokenStream.php b/src/Symfony/Components/CssSelector/TokenStream.php
index e896281799cd..adab2cd2c3a8 100644
--- a/src/Symfony/Components/CssSelector/TokenStream.php
+++ b/src/Symfony/Components/CssSelector/TokenStream.php
@@ -45,16 +45,14 @@ public function getUsed()
public function next()
{
- if ($this->peeking)
- {
+ if ($this->peeking) {
$this->peeking = false;
$this->used[] = $this->peeked;
return $this->peeked;
}
- if (!count($this->tokens))
- {
+ if (!count($this->tokens)) {
return null;
}
@@ -66,8 +64,7 @@ public function next()
public function peek()
{
- if (!$this->peeking)
- {
+ if (!$this->peeking) {
if (!count($this->tokens))
{
return null;
diff --git a/src/Symfony/Components/CssSelector/Tokenizer.php b/src/Symfony/Components/CssSelector/Tokenizer.php
index b536b9c08c84..9e056abbcb2c 100644
--- a/src/Symfony/Components/CssSelector/Tokenizer.php
+++ b/src/Symfony/Components/CssSelector/Tokenizer.php
@@ -25,8 +25,7 @@ class Tokenizer
{
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();
mb_internal_encoding('ASCII');
}
@@ -35,20 +34,16 @@ public function tokenize($s)
$pos = 0;
$s = preg_replace('#/\*.*?\*/#s', '', $s);
- while (1)
- {
+ while (1) {
if (preg_match('#\s+#A', $s, $match, 0, $pos))
{
$preceding_whitespace_pos = $pos;
$pos += strlen($match[0]);
- }
- else
- {
+ } else {
$preceding_whitespace_pos = 0;
}
- if ($pos >= strlen($s))
- {
+ if ($pos >= strlen($s)) {
if (isset($mbEncoding))
{
mb_internal_encoding($mbEncoding);
@@ -57,8 +52,7 @@ public function tokenize($s)
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]));
$tokens[] = new Token('Symbol', $sym, $pos);
$pos += strlen($match[0]);
@@ -68,16 +62,14 @@ public function tokenize($s)
$c = $s[$pos];
$c2 = substr($s, $pos, 2);
- if (in_array($c2, array('~=', '|=', '^=', '$=', '*=', '::', '!=')))
- {
+ if (in_array($c2, array('~=', '|=', '^=', '$=', '*=', '::', '!='))) {
$tokens[] = new Token('Token', $c2, $pos);
$pos += 2;
continue;
}
- if (in_array($c, array('>', '+', '~', ',', '.', '*', '=', '[', ']', '(', ')', '|', ':', '#')))
- {
+ if (in_array($c, array('>', '+', '~', ',', '.', '*', '=', '[', ']', '(', ')', '|', ':', '#'))) {
if (in_array($c, array('.', '#', '[')) && $preceding_whitespace_pos > 0)
{
$tokens[] = new Token('Token', ' ', $preceding_whitespace_pos);
@@ -88,8 +80,7 @@ public function tokenize($s)
continue;
}
- if ($c === '"' || $c === "'")
- {
+ if ($c === '"' || $c === "'") {
// Quoted string
$old_pos = $pos;
list($sym, $pos) = $this->tokenizeEscapedString($s, $pos);
@@ -117,24 +108,20 @@ protected function tokenizeEscapedString($s, $pos)
$pos = $pos + 1;
$start = $pos;
- while (1)
- {
+ while (1) {
$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)));
}
$result = substr($s, $start, $next - $start);
- if ('\\' === $result[strlen($result) - 1])
- {
+ if ('\\' === $result[strlen($result) - 1]) {
// next quote character is escaped
$pos = $next + 1;
$continue;
}
- if (false !== strpos($result, '\\'))
- {
+ if (false !== strpos($result, '\\')) {
$result = $this->unescapeStringLiteral($result);
}
@@ -149,16 +136,12 @@ protected function unescapeStringLiteral($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);
- 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]));
}
- }
- else
- {
+ } else {
throw new SyntaxError(sprintf('Invalid escape sequence %s in string %s', $matches[0], $literal));
}
}, $literal);
@@ -171,16 +154,14 @@ protected function tokenizeSymbol($s, $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
return array(substr($s, $start), strlen($s));
}
$matchStart = $match[0][1];
- if ($matchStart == $pos)
- {
+ if ($matchStart == $pos) {
throw new SyntaxError(sprintf('Unexpected symbol: %s at %s', $s[$pos], $pos));
}
diff --git a/src/Symfony/Components/CssSelector/XPathExpr.php b/src/Symfony/Components/CssSelector/XPathExpr.php
index 251cd6eab5d1..7763ae31b03f 100644
--- a/src/Symfony/Components/CssSelector/XPathExpr.php
+++ b/src/Symfony/Components/CssSelector/XPathExpr.php
@@ -66,20 +66,17 @@ public function getCondition()
public function __toString()
{
$path = '';
- if (null !== $this->prefix)
- {
+ if (null !== $this->prefix) {
$path .= $this->prefix;
}
- if (null !== $this->path)
- {
+ if (null !== $this->path) {
$path .= $this->path;
}
$path .= $this->element;
- if ($this->condition)
- {
+ if ($this->condition) {
$path .= sprintf('[%s]', $this->condition);
}
@@ -88,32 +85,25 @@ public function __toString()
public function addCondition($condition)
{
- if ($this->condition)
- {
+ if ($this->condition) {
$this->condition = sprintf('%s and (%s)', $this->condition, $condition);
- }
- else
- {
+ } else {
$this->condition = $condition;
}
}
public function addPrefix($prefix)
{
- if ($this->prefix)
- {
+ if ($this->prefix) {
$this->prefix = $prefix.$this->prefix;
- }
- else
- {
+ } else {
$this->prefix = $prefix;
}
}
public function addNameTest()
{
- if ($this->element == '*')
- {
+ if ($this->element == '*') {
// We weren't doing a test anyway
return;
}
@@ -128,12 +118,9 @@ public function addStarPrefix()
Adds a /* prefix if there is no prefix. This is when you need
to keep context's constrained to a single parent.
*/
- if ($this->path)
- {
+ if ($this->path) {
$this->path .= '*/';
- }
- else
- {
+ } else {
$this->path = '*/';
}
@@ -149,8 +136,7 @@ public function join($combiner, $other)
/* We don't need a star prefix if we are joining to this other
prefix; so we'll get rid of it */
- if ($other->hasStarPrefix() && $path == '*/')
- {
+ if ($other->hasStarPrefix() && $path == '*/') {
$path = '';
}
$this->prefix = $prefix;
@@ -161,38 +147,30 @@ public function join($combiner, $other)
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...
$s = $s->formatElement();
- }
- else
- {
+ } else {
$s = (string) $s;
}
- if (false === strpos($s, "'"))
- {
+ if (false === strpos($s, "'")) {
return sprintf("'%s'", $s);
}
- if (false === strpos($s, '"'))
- {
+ if (false === strpos($s, '"')) {
return sprintf('"%s"', $s);
}
$string = $s;
$parts = array();
- while (true)
- {
+ while (true) {
if (false !== $pos = strpos($string, "'"))
{
$parts[] = sprintf("'%s'", substr($string, 0, $pos));
$parts[] = "\"'\"";
$string = substr($string, $pos + 1);
- }
- else
- {
+ } else {
$parts[] = "'$string'";
break;
}
diff --git a/src/Symfony/Components/CssSelector/XPathExprOr.php b/src/Symfony/Components/CssSelector/XPathExprOr.php
index 5f8a83c5699e..54234b0408c5 100644
--- a/src/Symfony/Components/CssSelector/XPathExprOr.php
+++ b/src/Symfony/Components/CssSelector/XPathExprOr.php
@@ -36,8 +36,7 @@ public function __toString()
$prefix = $this->prefix;
$tmp = array();
- foreach ($this->items as $i)
- {
+ foreach ($this->items as $i) {
$tmp[] = sprintf('%s%s', $prefix, $i);
}
diff --git a/src/Symfony/Components/DependencyInjection/Builder.php b/src/Symfony/Components/DependencyInjection/Builder.php
index acd157d91f87..3fb0f7a42f9e 100644
--- a/src/Symfony/Components/DependencyInjection/Builder.php
+++ b/src/Symfony/Components/DependencyInjection/Builder.php
@@ -65,28 +65,21 @@ public function hasService($id)
*/
public function getService($id, $invalidBehavior = Container::EXCEPTION_ON_INVALID_REFERENCE)
{
- try
- {
+ try {
return parent::getService($id, Container::EXCEPTION_ON_INVALID_REFERENCE);
- }
- catch (\InvalidArgumentException $e)
- {
+ } catch (\InvalidArgumentException $e) {
if (isset($this->loading[$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]);
}
- try
- {
+ try {
$definition = $this->getDefinition($id);
- }
- catch (\InvalidArgumentException $e)
- {
+ } catch (\InvalidArgumentException $e) {
if (Container::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior)
{
return null;
@@ -125,8 +118,7 @@ public function getService($id, $invalidBehavior = Container::EXCEPTION_ON_INVAL
*/
public function merge(BuilderConfiguration $configuration = null)
{
- if (null === $configuration)
- {
+ if (null === $configuration) {
return;
}
@@ -134,14 +126,12 @@ public function merge(BuilderConfiguration $configuration = null)
$this->addAliases($configuration->getAliases());
$currentParameters = $this->getParameters();
- foreach ($configuration->getParameters() as $key => $value)
- {
+ foreach ($configuration->getParameters() as $key => $value) {
$this->setParameter($key, $value);
}
$this->addParameters($currentParameters);
- foreach ($this->parameters as $key => $value)
- {
+ foreach ($this->parameters as $key => $value) {
$this->parameters[$key] = self::resolveValue($value, $this->parameters);
}
}
@@ -163,8 +153,7 @@ public function getServiceIds()
*/
public function addAliases(array $aliases)
{
- foreach ($aliases as $alias => $id)
- {
+ foreach ($aliases as $alias => $id) {
$this->setAlias($alias, $id);
}
}
@@ -226,8 +215,7 @@ public function getAliases()
*/
public function getAlias($id)
{
- if (!$this->hasAlias($id))
- {
+ if (!$this->hasAlias($id)) {
throw new \InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
}
@@ -257,8 +245,7 @@ public function register($id, $class)
*/
public function addDefinitions(array $definitions)
{
- foreach ($definitions as $id => $definition)
- {
+ foreach ($definitions as $id => $definition) {
$this->setDefinition($id, $definition);
}
}
@@ -320,8 +307,7 @@ public function hasDefinition($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));
}
@@ -340,8 +326,7 @@ public function getDefinition($id)
*/
protected function createService(Definition $definition, $id)
{
- if (null !== $definition->getFile())
- {
+ if (null !== $definition->getFile()) {
require_once self::resolveValue($definition->getFile(), $this->parameters);
}
@@ -349,27 +334,21 @@ protected function createService(Definition $definition, $id)
$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);
- }
- else
- {
+ } else {
$service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
}
- if ($definition->isShared())
- {
+ if ($definition->isShared()) {
$this->services[$id] = $service;
}
- foreach ($definition->getMethodCalls() as $call)
- {
+ foreach ($definition->getMethodCalls() as $call) {
$services = self::getServiceConditionals($call[1]);
$ok = true;
- foreach ($services as $s)
- {
+ foreach ($services as $s) {
if (!$this->hasService($s))
{
$ok = false;
@@ -377,25 +356,20 @@ protected function createService(Definition $definition, $id)
}
}
- if ($ok)
- {
+ if ($ok) {
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)
{
$callable[0] = $this->getService((string) $callable[0]);
- }
- elseif (is_array($callable))
- {
+ } elseif (is_array($callable)) {
$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)));
}
@@ -416,35 +390,27 @@ protected function createService(Definition $definition, $id)
*/
static public function resolveValue($value, $parameters)
{
- if (is_array($value))
- {
+ if (is_array($value)) {
$args = array();
- foreach ($value as $k => $v)
- {
+ foreach ($value as $k => $v) {
$args[self::resolveValue($k, $parameters)] = self::resolveValue($v, $parameters);
}
$value = $args;
- }
- else if (is_string($value))
- {
+ } else if (is_string($value)) {
if (preg_match('/^%([^%]+)%$/', $value, $match))
{
// we do this to deal with non string values (boolean, integer, ...)
// 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));
}
$value = $parameters[$name];
- }
- else
- {
+ } else {
$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));
}
@@ -467,15 +433,12 @@ static public function resolveValue($value, $parameters)
*/
public function resolveServices($value)
{
- if (is_array($value))
- {
+ if (is_array($value)) {
foreach ($value as &$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());
}
@@ -492,8 +455,7 @@ public function resolveServices($value)
public function findAnnotatedServiceIds($name)
{
$annotations = array();
- foreach ($this->getDefinitions() as $id => $definition)
- {
+ foreach ($this->getDefinitions() as $id => $definition) {
if ($definition->getAnnotation($name))
{
$annotations[$id] = $definition->getAnnotation($name);
@@ -507,15 +469,12 @@ static public function getServiceConditionals($value)
{
$services = array();
- if (is_array($value))
- {
+ if (is_array($value)) {
foreach ($value as $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;
}
diff --git a/src/Symfony/Components/DependencyInjection/BuilderConfiguration.php b/src/Symfony/Components/DependencyInjection/BuilderConfiguration.php
index 81d26bc96fbb..69001f80aa62 100644
--- a/src/Symfony/Components/DependencyInjection/BuilderConfiguration.php
+++ b/src/Symfony/Components/DependencyInjection/BuilderConfiguration.php
@@ -66,8 +66,7 @@ public function addResource(ResourceInterface $resource)
*/
public function merge(BuilderConfiguration $configuration = null)
{
- if (null === $configuration)
- {
+ if (null === $configuration) {
return;
}
@@ -75,8 +74,7 @@ public function merge(BuilderConfiguration $configuration = null)
$this->addAliases($configuration->getAliases());
$this->addParameters($configuration->getParameters());
- foreach ($configuration->getResources() as $resource)
- {
+ foreach ($configuration->getResources() as $resource) {
$this->addResource($resource);
}
@@ -112,8 +110,7 @@ public function mergeExtension($key, array $values = array())
public function setParameters(array $parameters)
{
$this->parameters = array();
- foreach ($parameters as $key => $value)
- {
+ foreach ($parameters as $key => $value) {
$this->parameters[strtolower($key)] = $value;
}
@@ -167,8 +164,7 @@ public function hasParameter($name)
*/
public function getParameter($name)
{
- if (!$this->hasParameter($name))
- {
+ if (!$this->hasParameter($name)) {
throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
}
@@ -216,8 +212,7 @@ public function setAlias($alias, $id)
*/
public function addAliases(array $aliases)
{
- foreach ($aliases as $alias => $id)
- {
+ foreach ($aliases as $alias => $id) {
$this->setAlias($alias, $id);
}
@@ -257,8 +252,7 @@ public function hasAlias($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));
}
@@ -291,8 +285,7 @@ public function setDefinition($id, Definition $definition)
*/
public function addDefinitions(array $definitions)
{
- foreach ($definitions as $id => $definition)
- {
+ foreach ($definitions as $id => $definition) {
$this->setDefinition($id, $definition);
}
@@ -347,8 +340,7 @@ public function hasDefinition($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));
}
@@ -368,8 +360,7 @@ public function getDefinition($id)
*/
public function findDefinition($id)
{
- if ($this->hasAlias($id))
- {
+ if ($this->hasAlias($id)) {
return $this->findDefinition($this->getAlias($id));
}
diff --git a/src/Symfony/Components/DependencyInjection/Container.php b/src/Symfony/Components/DependencyInjection/Container.php
index 425f7e60fb1c..d3afeb8a07ca 100644
--- a/src/Symfony/Components/DependencyInjection/Container.php
+++ b/src/Symfony/Components/DependencyInjection/Container.php
@@ -78,8 +78,7 @@ public function __construct(array $parameters = array())
public function setParameters(array $parameters)
{
$this->parameters = array();
- foreach ($parameters as $key => $value)
- {
+ foreach ($parameters as $key => $value) {
$this->parameters[strtolower($key)] = $value;
}
}
@@ -117,8 +116,7 @@ public function getParameter($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));
}
@@ -188,27 +186,21 @@ public function hasService($id)
*/
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))));
}
- if (isset($this->services[$id]))
- {
+ if (isset($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();
}
- 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));
- }
- else
- {
+ } else {
return null;
}
}
@@ -222,8 +214,7 @@ public function getServiceIds()
{
$ids = array();
$r = new \ReflectionClass($this);
- foreach ($r->getMethods() as $method)
- {
+ foreach ($r->getMethods() as $method) {
if (preg_match('/^get(.+)Service$/', $name = $method->getName(), $match))
{
$ids[] = self::underscore($match[1]);
@@ -337,8 +328,7 @@ public function __unset($id)
*/
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));
}
diff --git a/src/Symfony/Components/DependencyInjection/Definition.php b/src/Symfony/Components/DependencyInjection/Definition.php
index 8d715bf38daf..d2d990bcf31b 100644
--- a/src/Symfony/Components/DependencyInjection/Definition.php
+++ b/src/Symfony/Components/DependencyInjection/Definition.php
@@ -140,8 +140,7 @@ public function getArguments()
public function setMethodCalls(array $calls = array())
{
$this->calls = array();
- foreach ($calls as $call)
- {
+ foreach ($calls as $call) {
$this->addMethodCall($call[0], $call[1]);
}
@@ -192,8 +191,7 @@ public function getAnnotations()
*/
public function getAnnotation($name)
{
- if (!isset($this->annotations[$name]))
- {
+ if (!isset($this->annotations[$name])) {
$this->annotations[$name] = array();
}
@@ -210,8 +208,7 @@ public function getAnnotation($name)
*/
public function addAnnotation($name, array $attributes = array())
{
- if (!isset($this->annotations[$name]))
- {
+ if (!isset($this->annotations[$name])) {
$this->annotations[$name] = array();
}
diff --git a/src/Symfony/Components/DependencyInjection/Dumper/GraphvizDumper.php b/src/Symfony/Components/DependencyInjection/Dumper/GraphvizDumper.php
index 2d22c66b5a38..7dd6b00b8e70 100644
--- a/src/Symfony/Components/DependencyInjection/Dumper/GraphvizDumper.php
+++ b/src/Symfony/Components/DependencyInjection/Dumper/GraphvizDumper.php
@@ -59,8 +59,7 @@ public function dump(array $options = array())
'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]))
{
$this->options[$key] = array_merge($this->options[$key], $options[$key]);
@@ -70,12 +69,10 @@ public function dump(array $options = array())
$this->nodes = $this->findNodes();
$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, '');
- foreach ($definition->getMethodCalls() as $call)
- {
+ foreach ($definition->getMethodCalls() as $call) {
$this->edges[$id] = array_merge(
$this->edges[$id],
$this->findEdges($id, $call[1], false, $call[0].'()')
@@ -89,8 +86,7 @@ public function dump(array $options = array())
protected function addNodes()
{
$code = '';
- foreach ($this->nodes as $id => $node)
- {
+ foreach ($this->nodes as $id => $node) {
$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']));
@@ -102,8 +98,7 @@ protected function addNodes()
protected function addEdges()
{
$code = '';
- foreach ($this->edges as $id => $edges)
- {
+ foreach ($this->edges as $id => $edges) {
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');
@@ -116,28 +111,22 @@ protected function addEdges()
protected function findEdges($id, $arguments, $required, $name)
{
$edges = array();
- foreach ($arguments as $argument)
- {
+ foreach ($arguments as $argument) {
if (is_object($argument) && $argument instanceof Parameter)
{
$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;
}
- if ($argument instanceof Reference)
- {
+ if ($argument instanceof Reference) {
if (!$this->container->hasService((string) $argument))
{
$this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']);
}
$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));
}
}
@@ -151,24 +140,20 @@ protected function findNodes()
$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')));
$container->setDefinition($id, new Definition('stdClass'));
}
- foreach ($container->getServiceIds() as $id)
- {
+ foreach ($container->getServiceIds() as $id) {
$service = $container->getService($id);
- if (in_array($id, array_keys($container->getAliases())))
- {
+ if (in_array($id, array_keys($container->getAliases()))) {
continue;
}
- if (!$container->hasDefinition($id))
- {
+ if (!$container->hasDefinition($id)) {
$nodes[$id] = array('class' => str_replace('\\', '\\\\', get_class($service)), 'attributes' => $this->options['node.instance']);
}
}
@@ -200,8 +185,7 @@ protected function endDot()
protected function addAttributes($attributes)
{
$code = array();
- foreach ($attributes as $k => $v)
- {
+ foreach ($attributes as $k => $v) {
$code[] = sprintf('%s="%s"', $k, $v);
}
@@ -211,8 +195,7 @@ protected function addAttributes($attributes)
protected function addOptions($options)
{
$code = array();
- foreach ($options as $k => $v)
- {
+ foreach ($options as $k => $v) {
$code[] = sprintf('%s="%s"', $k, $v);
}
@@ -227,8 +210,7 @@ protected function dotize($id)
protected function getAliases($id)
{
$aliases = array();
- foreach ($this->container->getAliases() as $alias => $origin)
- {
+ foreach ($this->container->getAliases() as $alias => $origin) {
if ($id == $origin)
{
$aliases[] = $alias;
diff --git a/src/Symfony/Components/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Components/DependencyInjection/Dumper/PhpDumper.php
index 6f2f7e070cd3..12302a69b296 100644
--- a/src/Symfony/Components/DependencyInjection/Dumper/PhpDumper.php
+++ b/src/Symfony/Components/DependencyInjection/Dumper/PhpDumper.php
@@ -56,16 +56,14 @@ public function dump(array $options = array())
protected function addServiceInclude($id, $definition)
{
- if (null !== $definition->getFile())
- {
+ if (null !== $definition->getFile()) {
return sprintf(" require_once %s;\n\n", $this->dumpValue($definition->getFile()));
}
}
protected function addServiceShared($id, $definition)
{
- if ($definition->isShared())
- {
+ if ($definition->isShared()) {
return <<shared['$id'])) return \$this->shared['$id'];
@@ -89,26 +87,19 @@ protected function addServiceInstance($id, $definition)
$class = $this->dumpValue($definition->getClass());
$arguments = array();
- foreach ($definition->getArguments() as $value)
- {
+ foreach ($definition->getArguments() as $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) : '');
- }
- 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));
- }
- else
- {
+ } else {
$code = sprintf(" \$instance = new %s(%s);\n", $definition->getClass(), implode(', ', $arguments));
}
- if ($definition->isShared())
- {
+ if ($definition->isShared()) {
$code .= sprintf(" \$this->shared['$id'] = \$instance;\n");
}
@@ -118,11 +109,9 @@ protected function addServiceInstance($id, $definition)
protected function addServiceMethodCalls($id, $definition)
{
$calls = '';
- foreach ($definition->getMethodCalls() as $call)
- {
+ foreach ($definition->getMethodCalls() as $call) {
$arguments = array();
- foreach ($call[1] as $value)
- {
+ foreach ($call[1] as $value) {
$arguments[] = $this->dumpValue($value);
}
@@ -134,24 +123,18 @@ protected function addServiceMethodCalls($id, $definition)
protected function addServiceConfigurator($id, $definition)
{
- if (!$callable = $definition->getConfigurator())
- {
+ if (!$callable = $definition->getConfigurator()) {
return '';
}
- if (is_array($callable))
- {
+ if (is_array($callable)) {
if (is_object($callable[0]) && $callable[0] instanceof Reference)
{
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]);
}
- }
- else
- {
+ } else {
return sprintf(" %s(\$instance);\n", $callable);
}
}
@@ -163,8 +146,7 @@ protected function addService($id, $definition)
$type = 0 === strpos($class, '%') ? 'Object' : $class;
$doc = '';
- if ($definition->isShared())
- {
+ if ($definition->isShared()) {
$doc = <<container->hasDefinition($id))
- {
+ if ($this->container->hasDefinition($id)) {
$class = $this->container->getDefinition($id)->getClass();
$type = 0 === strpos($class, '%') ? 'Object' : $class;
}
@@ -226,13 +207,11 @@ protected function get{$name}Service()
protected function addServices()
{
$code = '';
- foreach ($this->container->getDefinitions() as $id => $definition)
- {
+ foreach ($this->container->getDefinitions() as $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);
}
@@ -242,12 +221,10 @@ protected function addServices()
protected function addAnnotations()
{
$annotations = array();
- foreach ($this->container->getDefinitions() as $id => $definition)
- {
+ foreach ($this->container->getDefinitions() as $id => $definition) {
foreach ($definition->getAnnotations() as $name => $ann)
{
- if (!isset($annotations[$name]))
- {
+ if (!isset($annotations[$name])) {
$annotations[$name] = array();
}
@@ -278,17 +255,14 @@ public function findAnnotatedServiceIds(\$name)
protected function startClass($class, $baseClass)
{
$properties = array();
- foreach ($this->container->getDefinitions() as $id => $definition)
- {
+ foreach ($this->container->getDefinitions() as $id => $definition) {
$type = 0 === strpos($definition->getClass(), '%') ? 'Object' : $definition->getClass();
$properties[] = sprintf(' * @property %s $%s', $type, $id);
}
- foreach ($this->container->getAliases() as $alias => $id)
- {
+ foreach ($this->container->getAliases() as $alias => $id) {
$type = 'Object';
- if ($this->container->hasDefinition($id))
- {
+ if ($this->container->hasDefinition($id)) {
$sclass = $this->container->getDefinition($id)->getClass();
$type = 0 === strpos($sclass, '%') ? 'Object' : $sclass;
}
@@ -296,8 +270,7 @@ protected function startClass($class, $baseClass)
$properties[] = sprintf(' * @property %s $%s', $type, $alias);
}
$properties = implode("\n", $properties);
- if ($properties)
- {
+ if ($properties) {
$properties = "\n *\n".$properties;
}
@@ -323,8 +296,7 @@ class $class extends $baseClass
protected function addConstructor()
{
- if (!$this->container->getParameters())
- {
+ if (!$this->container->getParameters()) {
return '';
}
@@ -345,8 +317,7 @@ public function __construct()
protected function addDefaultParametersMethod()
{
- if (!$this->container->getParameters())
- {
+ if (!$this->container->getParameters()) {
return '';
}
@@ -370,18 +341,13 @@ protected function getDefaultParameters()
protected function exportParameters($parameters, $indent = 12)
{
$php = array();
- foreach ($parameters as $key => $value)
- {
+ foreach ($parameters as $key => $value) {
if (is_array($value))
{
$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));
- }
- else
- {
+ } else {
$value = var_export($value, true);
}
@@ -401,53 +367,41 @@ protected function endClass()
protected function wrapServiceConditionals($value, $code)
{
- if (!$services = Builder::getServiceConditionals($value))
- {
+ if (!$services = Builder::getServiceConditionals($value)) {
return $code;
}
$conditions = array();
- foreach ($services as $service)
- {
+ foreach ($services as $service) {
$conditions[] = sprintf("\$this->hasService('%s')", $service);
}
// re-indent the wrapped 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)
{
- if (is_array($value))
- {
+ if (is_array($value)) {
$code = array();
- foreach ($value as $k => $v)
- {
+ foreach ($value as $k => $v) {
$code[] = sprintf('%s => %s', $this->dumpValue($k), $this->dumpValue($v));
}
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);
- }
- elseif (is_object($value) && $value instanceof Parameter)
- {
+ } elseif (is_object($value) && $value instanceof Parameter) {
return sprintf("\$this->getParameter('%s')", strtolower($value));
- }
- elseif (is_string($value))
- {
+ } elseif (is_string($value)) {
if (preg_match('/^%([^%]+)%$/', $value, $match))
{
// we do this to deal with non string values (boolean, integer, ...)
// the preg_replace_callback converts them to strings
return sprintf("\$this->getParameter('%s')", strtolower($match[1]));
- }
- else
- {
+ } else {
$replaceParameters = function ($match)
{
return sprintf("'.\$this->getParameter('%s').'", strtolower($match[2]));
@@ -460,37 +414,28 @@ protected function dumpValue($value)
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.');
- }
- else
- {
+ } else {
return var_export($value, true);
}
}
protected function getServiceCall($id, Reference $reference = null)
{
- if ('service_container' === $id)
- {
+ if ('service_container' === $id) {
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);
- }
- else
- {
+ } else {
if ($this->container->hasAlias($id))
{
$id = $this->container->getAlias($id);
}
- if ($this->container->hasDefinition($id))
- {
+ if ($this->container->hasDefinition($id)) {
return sprintf('$this->get%sService()', Container::camelize($id));
}
diff --git a/src/Symfony/Components/DependencyInjection/Dumper/XmlDumper.php b/src/Symfony/Components/DependencyInjection/Dumper/XmlDumper.php
index a64b1a090e87..53532cec3e40 100644
--- a/src/Symfony/Components/DependencyInjection/Dumper/XmlDumper.php
+++ b/src/Symfony/Components/DependencyInjection/Dumper/XmlDumper.php
@@ -38,8 +38,7 @@ public function dump(array $options = array())
protected function addParameters()
{
- if (!$this->container->getParameters())
- {
+ if (!$this->container->getParameters()) {
return '';
}
@@ -55,13 +54,11 @@ protected function addService($id, $definition)
!$definition->isShared() ? ' shared="false"' : ''
);
- foreach ($definition->getAnnotations() as $name => $annotations)
- {
+ foreach ($definition->getAnnotations() as $name => $annotations) {
foreach ($annotations as $attributes)
{
$att = array();
- foreach ($attributes as $key => $value)
- {
+ foreach ($attributes as $key => $value) {
$att[] = sprintf('%s="%s"', $key, $value);
}
$att = $att ? ' '.implode(' ', $att) : '';
@@ -70,43 +67,32 @@ protected function addService($id, $definition)
}
}
- if ($definition->getFile())
- {
+ if ($definition->getFile()) {
$code .= sprintf(" %s\n", $definition->getFile());
}
- if ($definition->getArguments())
- {
+ if ($definition->getArguments()) {
$code .= $this->convertParameters($definition->getArguments(), 'argument', 6);
}
- foreach ($definition->getMethodCalls() as $call)
- {
+ foreach ($definition->getMethodCalls() as $call) {
if (count($call[1]))
{
$code .= sprintf(" \n%s \n", $call[0], $this->convertParameters($call[1], 'argument', 8));
- }
- else
- {
+ } else {
$code .= sprintf(" \n", $call[0]);
}
}
- if ($callable = $definition->getConfigurator())
- {
+ if ($callable = $definition->getConfigurator()) {
if (is_array($callable))
{
- if (is_object($callable[0]) && $callable[0] instanceof Reference)
- {
+ if (is_object($callable[0]) && $callable[0] instanceof Reference) {
$code .= sprintf(" \n", $callable[0], $callable[1]);
- }
- else
- {
+ } else {
$code .= sprintf(" \n", $callable[0], $callable[1]);
}
- }
- else
- {
+ } else {
$code .= sprintf(" \n", $callable);
}
}
@@ -123,19 +109,16 @@ protected function addServiceAlias($alias, $id)
protected function addServices()
{
- if (!$this->container->getDefinitions())
- {
+ if (!$this->container->getDefinitions()) {
return '';
}
$code = '';
- foreach ($this->container->getDefinitions() as $id => $definition)
- {
+ foreach ($this->container->getDefinitions() as $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);
}
@@ -147,22 +130,17 @@ protected function convertParameters($parameters, $type='parameter', $depth = 2)
$white = str_repeat(' ', $depth);
$xml = '';
$withKeys = array_keys($parameters) !== range(0, count($parameters) - 1);
- foreach ($parameters as $key => $value)
- {
+ foreach ($parameters as $key => $value) {
$attributes = '';
$key = $withKeys ? sprintf(' key="%s"', $key) : '';
- if (is_array($value))
- {
+ if (is_array($value)) {
$value = "\n".$this->convertParameters($value, $type, $depth + 2).$white;
$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));
- }
- else
- {
+ } else {
if (in_array($value, array('null', 'true', 'false'), true))
{
$attributes = ' type="string"';
@@ -194,8 +172,7 @@ protected function endXml()
protected function getXmlInvalidBehavior(Reference $reference)
{
- switch ($reference->getInvalidBehavior())
- {
+ switch ($reference->getInvalidBehavior()) {
case Container::NULL_ON_INVALID_REFERENCE:
return 'on-invalid="null" ';
case Container::IGNORE_ON_INVALID_REFERENCE:
@@ -208,18 +185,13 @@ protected function getXmlInvalidBehavior(Reference $reference)
protected function escape($arguments)
{
$args = array();
- foreach ($arguments as $k => $v)
- {
+ foreach ($arguments as $k => $v) {
if (is_array($v))
{
$args[$k] = $this->escape($v);
- }
- elseif (is_string($v))
- {
+ } elseif (is_string($v)) {
$args[$k] = str_replace('%', '%%', $v);
- }
- else
- {
+ } else {
$args[$k] = $v;
}
}
@@ -232,8 +204,7 @@ protected function escape($arguments)
*/
static public function phpToXml($value)
{
- switch (true)
- {
+ switch (true) {
case null === $value:
return 'null';
case true === $value:
diff --git a/src/Symfony/Components/DependencyInjection/Dumper/YamlDumper.php b/src/Symfony/Components/DependencyInjection/Dumper/YamlDumper.php
index a71cd53980d5..9580e067952e 100644
--- a/src/Symfony/Components/DependencyInjection/Dumper/YamlDumper.php
+++ b/src/Symfony/Components/DependencyInjection/Dumper/YamlDumper.php
@@ -43,13 +43,11 @@ protected function addService($id, $definition)
$code .= sprintf(" class: %s\n", $definition->getClass());
$annotationsCode = '';
- foreach ($definition->getAnnotations() as $name => $annotations)
- {
+ foreach ($definition->getAnnotations() as $name => $annotations) {
foreach ($annotations as $attributes)
{
$att = array();
- foreach ($attributes as $key => $value)
- {
+ foreach ($attributes as $key => $value) {
$att[] = sprintf('%s: %s', Yaml::dump($key), Yaml::dump($value));
}
$att = $att ? ', '.implode(' ', $att) : '';
@@ -57,46 +55,36 @@ protected function addService($id, $definition)
$annotationsCode .= sprintf(" - { name: %s%s }\n", Yaml::dump($name), $att);
}
}
- if ($annotationsCode)
- {
+ if ($annotationsCode) {
$code .= " annotations:\n".$annotationsCode;
}
- if ($definition->getFile())
- {
+ if ($definition->getFile()) {
$code .= sprintf(" file: %s\n", $definition->getFile());
}
- if ($definition->getConstructor())
- {
+ if ($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));
}
- if ($definition->getMethodCalls())
- {
+ if ($definition->getMethodCalls()) {
$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";
}
- if ($callable = $definition->getConfigurator())
- {
+ if ($callable = $definition->getConfigurator()) {
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]);
- }
- else
- {
+ } else {
$callable = array($callable[0], $callable[1]);
}
}
@@ -114,19 +102,16 @@ protected function addServiceAlias($alias, $id)
protected function addServices()
{
- if (!$this->container->getDefinitions())
- {
+ if (!$this->container->getDefinitions()) {
return '';
}
$code = "services:\n";
- foreach ($this->container->getDefinitions() as $id => $definition)
- {
+ foreach ($this->container->getDefinitions() as $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);
}
@@ -135,8 +120,7 @@ protected function addServices()
protected function addParameters()
{
- if (!$this->container->getParameters())
- {
+ if (!$this->container->getParameters()) {
return '';
}
@@ -148,42 +132,29 @@ protected function addParameters()
*/
protected function dumpValue($value)
{
- if (is_array($value))
- {
+ if (is_array($value)) {
$code = array();
- foreach ($value as $k => $v)
- {
+ foreach ($value as $k => $v) {
$code[$k] = $this->dumpValue($v);
}
return $code;
- }
- elseif (is_object($value) && $value instanceof Reference)
- {
+ } elseif (is_object($value) && $value instanceof Reference) {
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);
- }
- 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.');
- }
- else
- {
+ } else {
return $value;
}
}
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);
- }
- else
- {
+ } else {
return sprintf('@%s', $id);
}
}
@@ -196,14 +167,11 @@ protected function getParameterCall($id)
protected function prepareParameters($parameters)
{
$filtered = array();
- foreach ($parameters as $key => $value)
- {
+ foreach ($parameters as $key => $value) {
if (is_array($value))
{
$value = $this->prepareParameters($value);
- }
- elseif ($value instanceof Reference)
- {
+ } elseif ($value instanceof Reference) {
$value = '@'.$value;
}
@@ -216,18 +184,13 @@ protected function prepareParameters($parameters)
protected function escape($arguments)
{
$args = array();
- foreach ($arguments as $k => $v)
- {
+ foreach ($arguments as $k => $v) {
if (is_array($v))
{
$args[$k] = $this->escape($v);
- }
- elseif (is_string($v))
- {
+ } elseif (is_string($v)) {
$args[$k] = str_replace('%', '%%', $v);
- }
- else
- {
+ } else {
$args[$k] = $v;
}
}
diff --git a/src/Symfony/Components/DependencyInjection/FileResource.php b/src/Symfony/Components/DependencyInjection/FileResource.php
index 21b96009b710..cb4ed80bebf8 100644
--- a/src/Symfony/Components/DependencyInjection/FileResource.php
+++ b/src/Symfony/Components/DependencyInjection/FileResource.php
@@ -51,8 +51,7 @@ public function getResource()
*/
public function isUptodate($timestamp)
{
- if (!file_exists($this->resource))
- {
+ if (!file_exists($this->resource)) {
return false;
}
diff --git a/src/Symfony/Components/DependencyInjection/Loader/FileLoader.php b/src/Symfony/Components/DependencyInjection/Loader/FileLoader.php
index d01db14e390d..c27ec64fb75d 100644
--- a/src/Symfony/Components/DependencyInjection/Loader/FileLoader.php
+++ b/src/Symfony/Components/DependencyInjection/Loader/FileLoader.php
@@ -29,8 +29,7 @@ abstract class FileLoader extends Loader
*/
public function __construct($paths = array())
{
- if (!is_array($paths))
- {
+ if (!is_array($paths)) {
$paths = array($paths);
}
@@ -43,8 +42,7 @@ public function __construct($paths = array())
protected function findFile($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)));
}
@@ -53,20 +51,14 @@ protected function findFile($file)
protected function getAbsolutePath($file, $currentPath = null)
{
- if (self::isAbsolutePath($file))
- {
+ if (self::isAbsolutePath($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;
- }
- else
- {
+ } else {
foreach ($this->paths as $path)
{
- if (file_exists($path.DIRECTORY_SEPARATOR.$file))
- {
+ if (file_exists($path.DIRECTORY_SEPARATOR.$file)) {
return $path.DIRECTORY_SEPARATOR.$file;
}
}
diff --git a/src/Symfony/Components/DependencyInjection/Loader/IniFileLoader.php b/src/Symfony/Components/DependencyInjection/Loader/IniFileLoader.php
index d65455fa2c8e..bb201168f50f 100644
--- a/src/Symfony/Components/DependencyInjection/Loader/IniFileLoader.php
+++ b/src/Symfony/Components/DependencyInjection/Loader/IniFileLoader.php
@@ -41,13 +41,11 @@ public function load($file)
$configuration->addResource(new FileResource($path));
$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));
}
- if (isset($result['parameters']) && is_array($result['parameters']))
- {
+ if (isset($result['parameters']) && is_array($result['parameters'])) {
foreach ($result['parameters'] as $key => $value)
{
$configuration->setParameter(strtolower($key), $value);
diff --git a/src/Symfony/Components/DependencyInjection/Loader/LoaderExtension.php b/src/Symfony/Components/DependencyInjection/Loader/LoaderExtension.php
index e288e2df6610..1da9ea636481 100644
--- a/src/Symfony/Components/DependencyInjection/Loader/LoaderExtension.php
+++ b/src/Symfony/Components/DependencyInjection/Loader/LoaderExtension.php
@@ -45,8 +45,7 @@ public function setConfiguration($name, $resource)
*/
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()));
}
diff --git a/src/Symfony/Components/DependencyInjection/Loader/XmlFileLoader.php b/src/Symfony/Components/DependencyInjection/Loader/XmlFileLoader.php
index 85afb66aa022..1837b00ec92a 100644
--- a/src/Symfony/Components/DependencyInjection/Loader/XmlFileLoader.php
+++ b/src/Symfony/Components/DependencyInjection/Loader/XmlFileLoader.php
@@ -63,8 +63,7 @@ public function load($file)
protected function parseParameters(BuilderConfiguration $configuration, $xml, $file)
{
- if (!$xml->parameters)
- {
+ if (!$xml->parameters) {
return;
}
@@ -73,13 +72,11 @@ protected function parseParameters(BuilderConfiguration $configuration, $xml, $f
protected function parseImports(BuilderConfiguration $configuration, $xml, $file)
{
- if (!$xml->imports)
- {
+ if (!$xml->imports) {
return;
}
- foreach ($xml->imports->import as $import)
- {
+ foreach ($xml->imports->import as $import) {
$configuration->merge($this->parseImport($import, $file));
}
}
@@ -87,15 +84,11 @@ protected function parseImports(BuilderConfiguration $configuration, $xml, $file
protected function parseImport($import, $file)
{
$class = null;
- if (isset($import['class']) && $import['class'] !== get_class($this))
- {
+ if (isset($import['class']) && $import['class'] !== get_class($this)) {
$class = (string) $import['class'];
- }
- else
- {
+ } else {
// try to detect loader with the extension
- switch (pathinfo((string) $import['resource'], PATHINFO_EXTENSION))
- {
+ switch (pathinfo((string) $import['resource'], PATHINFO_EXTENSION)) {
case 'yml':
$class = 'Symfony\\Components\\DependencyInjection\\Loader\\YamlFileLoader';
break;
@@ -114,21 +107,18 @@ protected function parseImport($import, $file)
protected function parseDefinitions(BuilderConfiguration $configuration, $xml, $file)
{
- if (!$xml->services)
- {
+ if (!$xml->services) {
return;
}
- foreach ($xml->services->service as $service)
- {
+ foreach ($xml->services->service as $service) {
$this->parseDefinition($configuration, (string) $service['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']);
return;
@@ -136,8 +126,7 @@ protected function parseDefinition(BuilderConfiguration $configuration, $id, $se
$definition = new Definition((string) $service['class']);
- foreach (array('shared', 'constructor') as $key)
- {
+ foreach (array('shared', 'constructor') as $key) {
if (isset($service[$key]))
{
$method = 'set'.ucfirst($key);
@@ -145,27 +134,21 @@ protected function parseDefinition(BuilderConfiguration $configuration, $id, $se
}
}
- if ($service->file)
- {
+ if ($service->file) {
$definition->setFile((string) $service->file);
}
$definition->setArguments($service->getArgumentsAsPhp('argument'));
- if (isset($service->configurator))
- {
+ if (isset($service->configurator)) {
if (isset($service->configurator['function']))
{
$definition->setConfigurator((string) $service->configurator['function']);
- }
- else
- {
+ } else {
if (isset($service->configurator['service']))
{
$class = new Reference((string) $service->configurator['service']);
- }
- else
- {
+ } else {
$class = (string) $service->configurator['class'];
}
@@ -173,16 +156,13 @@ protected function parseDefinition(BuilderConfiguration $configuration, $id, $se
}
}
- foreach ($service->call as $call)
- {
+ foreach ($service->call as $call) {
$definition->addMethodCall((string) $call['method'], $call->getArgumentsAsPhp('argument'));
}
- foreach ($service->annotation as $annotation)
- {
+ foreach ($service->annotation as $annotation) {
$parameters = array();
- foreach ($annotation->attributes() as $name => $value)
- {
+ foreach ($annotation->attributes() as $name => $value) {
if ('name' === $name)
{
continue;
@@ -204,8 +184,7 @@ protected function parseFile($file)
{
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
- if (!$dom->load($file, LIBXML_COMPACT))
- {
+ if (!$dom->load($file, LIBXML_COMPACT)) {
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
}
$dom->validateOnParse = true;
@@ -224,8 +203,7 @@ protected function processAnonymousServices(BuilderConfiguration $configuration,
// find anonymous service definitions
$xml->registerXPathNamespace('container', 'http://www.symfony-project.org/schema/dic/services');
$nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]');
- foreach ($nodes as $node)
- {
+ foreach ($nodes as $node) {
// give it a unique names
$node['id'] = sprintf('_%s_%d', md5($file), ++$count);
@@ -235,8 +213,7 @@ protected function processAnonymousServices(BuilderConfiguration $configuration,
// resolve definitions
krsort($definitions);
- foreach ($definitions as $id => $def)
- {
+ foreach ($definitions as $id => $def) {
$this->parseDefinition($configuration, $id, $def[0], $def[1]);
$oNode = dom_import_simplexml($def[0]);
@@ -260,17 +237,14 @@ protected function validateSchema($dom, $file)
{
$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);
- 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]))
{
$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));
}
@@ -280,8 +254,7 @@ protected function validateSchema($dom, $file)
}
$imports = '';
- foreach ($schemaLocations as $namespace => $location)
- {
+ foreach ($schemaLocations as $namespace => $location) {
$imports .= sprintf(' '."\n", $namespace, $location);
}
@@ -299,8 +272,7 @@ protected function validateSchema($dom, $file)
;
libxml_use_internal_errors(true);
- if (!$dom->schemaValidateSource($source))
- {
+ if (!$dom->schemaValidateSource($source)) {
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
}
libxml_use_internal_errors(false);
@@ -311,21 +283,18 @@ protected function validateSchema($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')))
{
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));
}
// 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));
}
}
@@ -334,8 +303,7 @@ protected function validateExtensions($dom, $file)
protected function getXmlErrors()
{
$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)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code,
@@ -353,8 +321,7 @@ protected function getXmlErrors()
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')
{
continue;
@@ -393,35 +360,27 @@ static public function convertDomElementToArray(\DomElement $element)
{
$empty = true;
$config = array();
- foreach ($element->attributes as $name => $node)
- {
+ foreach ($element->attributes as $name => $node) {
$config[$name] = SimpleXMLElement::phpize($node->value);
$empty = false;
}
$nodeValue = false;
- foreach ($element->childNodes as $node)
- {
+ foreach ($element->childNodes as $node) {
if ($node instanceof \DOMText)
{
- if (trim($node->nodeValue))
- {
+ if (trim($node->nodeValue)) {
$nodeValue = trim($node->nodeValue);
$empty = false;
}
- }
- elseif (!$node instanceof \DOMComment)
- {
+ } elseif (!$node instanceof \DOMComment) {
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][] = static::convertDomElementToArray($node);
- }
- else
- {
+ } else {
$config[$node->localName] = static::convertDomElementToArray($node);
}
@@ -429,15 +388,11 @@ static public function convertDomElementToArray(\DomElement $element)
}
}
- if (false !== $nodeValue)
- {
+ if (false !== $nodeValue) {
$value = SimpleXMLElement::phpize($nodeValue);
- if (count($config))
- {
+ if (count($config)) {
$config['value'] = $value;
- }
- else
- {
+ } else {
$config = $value;
}
}
diff --git a/src/Symfony/Components/DependencyInjection/Loader/YamlFileLoader.php b/src/Symfony/Components/DependencyInjection/Loader/YamlFileLoader.php
index f366d4a17cfd..2f6ffe84097c 100644
--- a/src/Symfony/Components/DependencyInjection/Loader/YamlFileLoader.php
+++ b/src/Symfony/Components/DependencyInjection/Loader/YamlFileLoader.php
@@ -46,8 +46,7 @@ public function load($file)
$configuration->addResource(new FileResource($path));
- if (!$content)
- {
+ if (!$content) {
return $configuration;
}
@@ -55,8 +54,7 @@ public function load($file)
$this->parseImports($configuration, $content, $file);
// parameters
- if (isset($content['parameters']))
- {
+ if (isset($content['parameters'])) {
foreach ($content['parameters'] as $key => $value)
{
$configuration->setParameter(strtolower($key), $this->resolveServices($value));
@@ -74,13 +72,11 @@ public function load($file)
protected function parseImports(BuilderConfiguration $configuration, $content, $file)
{
- if (!isset($content['imports']))
- {
+ if (!isset($content['imports'])) {
return;
}
- foreach ($content['imports'] as $import)
- {
+ foreach ($content['imports'] as $import) {
$configuration->merge($this->parseImport($import, $file));
}
}
@@ -88,15 +84,11 @@ protected function parseImports(BuilderConfiguration $configuration, $content, $
protected function parseImport($import, $file)
{
$class = null;
- if (isset($import['class']) && $import['class'] !== get_class($this))
- {
+ if (isset($import['class']) && $import['class'] !== get_class($this)) {
$class = $import['class'];
- }
- else
- {
+ } else {
// try to detect loader with the extension
- switch (pathinfo($import['resource'], PATHINFO_EXTENSION))
- {
+ switch (pathinfo($import['resource'], PATHINFO_EXTENSION)) {
case 'xml':
$class = 'Symfony\\Components\\DependencyInjection\\Loader\\XmlFileLoader';
break;
@@ -115,21 +107,18 @@ protected function parseImport($import, $file)
protected function parseDefinitions(BuilderConfiguration $configuration, $content, $file)
{
- if (!isset($content['services']))
- {
+ if (!isset($content['services'])) {
return;
}
- foreach ($content['services'] as $id => $service)
- {
+ foreach ($content['services'] as $id => $service) {
$this->parseDefinition($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));
return;
@@ -137,48 +126,39 @@ protected function parseDefinition(BuilderConfiguration $configuration, $id, $se
$definition = new Definition($service['class']);
- if (isset($service['shared']))
- {
+ if (isset($service['shared'])) {
$definition->setShared($service['shared']);
}
- if (isset($service['constructor']))
- {
+ if (isset($service['constructor'])) {
$definition->setConstructor($service['constructor']);
}
- if (isset($service['file']))
- {
+ if (isset($service['file'])) {
$definition->setFile($service['file']);
}
- if (isset($service['arguments']))
- {
+ if (isset($service['arguments'])) {
$definition->setArguments($this->resolveServices($service['arguments']));
}
- if (isset($service['configurator']))
- {
+ if (isset($service['configurator'])) {
if (is_string($service['configurator']))
{
$definition->setConfigurator($service['configurator']);
- }
- else
- {
+ } else {
$definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1]));
}
}
- if (isset($service['calls']))
- {
+ if (isset($service['calls'])) {
foreach ($service['calls'] as $call)
{
$definition->addMethodCall($call[0], $this->resolveServices($call[1]));
}
}
- if (isset($service['annotations']))
- {
+ if (isset($service['annotations'])) {
foreach ($service['annotations'] as $annotation)
{
$name = $annotation['name'];
@@ -201,29 +181,24 @@ protected function loadFile($file)
*/
protected function validate($content, $file)
{
- if (null === $content)
- {
+ if (null === $content) {
return $content;
}
- if (!is_array($content))
- {
+ if (!is_array($content)) {
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')))
{
continue;
}
// can it be handled by an extension?
- if (false !== strpos($key, '.'))
- {
+ if (false !== strpos($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));
}
@@ -238,16 +213,11 @@ protected function validate($content, $file)
protected function resolveServices($value)
{
- if (is_array($value))
- {
+ if (is_array($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);
- }
- else if (is_string($value) && 0 === strpos($value, '@'))
- {
+ } else if (is_string($value) && 0 === strpos($value, '@')) {
$value = new Reference(substr($value, 1));
}
@@ -256,8 +226,7 @@ protected function resolveServices($value)
protected function loadFromExtensions(BuilderConfiguration $configuration, $content)
{
- foreach ($content as $key => $values)
- {
+ foreach ($content as $key => $values) {
if (in_array($key, array('imports', 'parameters', 'services')))
{
continue;
@@ -265,8 +234,7 @@ protected function loadFromExtensions(BuilderConfiguration $configuration, $cont
list($namespace, $tag) = explode('.', $key);
- if (!is_array($values))
- {
+ if (!is_array($values)) {
$values = array();
}
diff --git a/src/Symfony/Components/DependencyInjection/SimpleXMLElement.php b/src/Symfony/Components/DependencyInjection/SimpleXMLElement.php
index be20c3cb3276..596eaa9bc63b 100644
--- a/src/Symfony/Components/DependencyInjection/SimpleXMLElement.php
+++ b/src/Symfony/Components/DependencyInjection/SimpleXMLElement.php
@@ -28,26 +28,20 @@ public function getAttributeAsPhp($name)
public function getArgumentsAsPhp($name)
{
$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);
// parameter keys are case insensitive
- if ('parameter' == $name)
- {
+ if ('parameter' == $name) {
$key = strtolower($key);
}
- switch ($arg['type'])
- {
+ switch ($arg['type']) {
case 'service':
$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;
- }
- elseif (isset($arg['on-invalid']) && 'null' == $arg['on-invalid'])
- {
+ } elseif (isset($arg['on-invalid']) && 'null' == $arg['on-invalid']) {
$invalidBehavior = Container::NULL_ON_INVALID_REFERENCE;
}
$arguments[$key] = new Reference((string) $arg['id'], $invalidBehavior);
@@ -74,8 +68,7 @@ static public function phpize($value)
$value = (string) $value;
$lowercaseValue = strtolower($value);
- switch (true)
- {
+ switch (true) {
case 'null' === $lowercaseValue:
return null;
case ctype_digit($value):
diff --git a/src/Symfony/Components/DomCrawler/Crawler.php b/src/Symfony/Components/DomCrawler/Crawler.php
index 3b92b9aab8b9..e7858dd494bb 100644
--- a/src/Symfony/Components/DomCrawler/Crawler.php
+++ b/src/Symfony/Components/DomCrawler/Crawler.php
@@ -58,45 +58,34 @@ public function clear()
*/
public function add($node)
{
- if ($node instanceof \DOMNodeList)
- {
+ if ($node instanceof \DOMNodeList) {
$this->addNodeList($node);
- }
- elseif (is_array($node))
- {
+ } elseif (is_array($node)) {
$this->addNodes($node);
- }
- elseif (null !== $node)
- {
+ } elseif (null !== $node) {
$this->addNode($node);
}
}
public function addContent($content, $type = null)
{
- if (empty($type))
- {
+ if (empty($type)) {
$type = 'text/html';
}
// 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;
}
$charset = 'ISO-8859-1';
- if (false !== $pos = strpos($type, 'charset='))
- {
+ if (false !== $pos = strpos($type, 'charset=')) {
$charset = substr($type, $pos + 8);
}
- if ('x' === $matches[1])
- {
+ if ('x' === $matches[1]) {
$this->addXmlContent($content, $charset);
- }
- else
- {
+ } else {
$this->addHtmlContent($content, $charset);
}
}
@@ -139,8 +128,7 @@ public function addXmlContent($content, $charset = 'UTF-8')
*/
public function addDocument(\DOMDocument $dom)
{
- if ($dom->documentElement)
- {
+ if ($dom->documentElement) {
$this->addNode($dom->documentElement);
}
}
@@ -152,8 +140,7 @@ public function addDocument(\DOMDocument $dom)
*/
public function addNodeList(\DOMNodeList $nodes)
{
- foreach ($nodes as $node)
- {
+ foreach ($nodes as $node) {
$this->addNode($node);
}
}
@@ -165,8 +152,7 @@ public function addNodeList(\DOMNodeList $nodes)
*/
public function addNodes(array $nodes)
{
- foreach ($nodes as $node)
- {
+ foreach ($nodes as $node) {
$this->add($node);
}
}
@@ -178,12 +164,9 @@ public function addNodes(array $nodes)
*/
public function addNode(\DOMNode $node)
{
- if ($node instanceof \DOMDocument)
- {
+ if ($node instanceof \DOMDocument) {
$this->attach($node->documentElement);
- }
- else
- {
+ } else {
$this->attach($node);
}
}
@@ -207,8 +190,7 @@ public function isEmpty()
*/
public function eq($position)
{
- foreach ($this as $i => $node)
- {
+ foreach ($this as $i => $node) {
if ($i == $position)
{
return new static($node, $this->uri);
@@ -237,8 +219,7 @@ public function eq($position)
public function each(\Closure $closure)
{
$data = array();
- foreach ($this as $i => $node)
- {
+ foreach ($this as $i => $node) {
$data[] = $closure($node, $i);
}
@@ -257,8 +238,7 @@ public function each(\Closure $closure)
public function reduce(\Closure $closure)
{
$nodes = array();
- foreach ($this as $i => $node)
- {
+ foreach ($this as $i => $node) {
if (false !== $closure($node, $i))
{
$nodes[] = $node;
@@ -297,8 +277,7 @@ public function last()
*/
public function siblings()
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -314,8 +293,7 @@ public function siblings()
*/
public function nextAll()
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -329,8 +307,7 @@ public function nextAll()
*/
public function previousAll()
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -346,16 +323,14 @@ public function previousAll()
*/
public function parents()
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$node = $this->getNode(0);
$nodes = array();
- while ($node = $node->parentNode)
- {
+ while ($node = $node->parentNode) {
if (1 === $node->nodeType && '_root' !== $node->nodeName)
{
$nodes[] = $node;
@@ -374,8 +349,7 @@ public function parents()
*/
public function children()
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -393,8 +367,7 @@ public function children()
*/
public function attr($attribute)
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -410,8 +383,7 @@ public function attr($attribute)
*/
public function text()
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -433,23 +405,18 @@ public function text()
*/
public function extract($attributes)
{
- if (!is_array($attributes))
- {
+ if (!is_array($attributes)) {
$attributes = array($attributes);
}
$data = array();
- foreach ($this as $node)
- {
+ foreach ($this as $node) {
$elements = array();
- foreach ($attributes as $attribute)
- {
+ foreach ($attributes as $attribute) {
if ('_text' === $attribute)
{
$elements[] = $node->nodeValue;
- }
- else
- {
+ } else {
$elements[] = $node->getAttribute($attribute);
}
}
@@ -471,8 +438,7 @@ public function filterXPath($xpath)
{
$document = new \DOMDocument('1.0', 'UTF-8');
$root = $document->appendChild($document->createElement('_root'));
- foreach ($this as $node)
- {
+ foreach ($this as $node) {
$root->appendChild($document->importNode($node, true));
}
@@ -494,8 +460,7 @@ public function filterXPath($xpath)
*/
public function filter($selector)
{
- if (!class_exists('Symfony\\Components\\CssSelector\\Parser'))
- {
+ if (!class_exists('Symfony\\Components\\CssSelector\\Parser')) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector is not installed (you can use filterXPath instead).');
// @codeCoverageIgnoreEnd
@@ -546,8 +511,7 @@ public function selectButton($value)
*/
public function link($method = 'get')
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
@@ -564,8 +528,7 @@ public function link($method = 'get')
public function links()
{
$links = array();
- foreach ($this as $node)
- {
+ foreach ($this as $node) {
$links[] = new Link($node, 'get', $this->host, $this->path);
}
@@ -584,15 +547,13 @@ public function links()
*/
public function form(array $values = null, $method = null)
{
- if (!count($this))
- {
+ if (!count($this)) {
throw new \InvalidArgumentException('The current node list is empty.');
}
$form = new Form($this->getNode(0), $method, $this->host, $this->path);
- if (null !== $values)
- {
+ if (null !== $values) {
$form->setValues($values);
}
@@ -601,8 +562,7 @@ public function form(array $values = null, $method = null)
protected function getNode($position)
{
- foreach ($this as $i => $node)
- {
+ foreach ($this as $i => $node) {
if ($i == $position)
{
return $node;
@@ -616,15 +576,13 @@ protected function getNode($position)
protected function parseUri($uri)
{
- if ('http' !== substr($uri, 0, 4))
- {
+ if ('http' !== substr($uri, 0, 4)) {
return array(null, '/');
}
$path = parse_url($uri, PHP_URL_PATH);
- if ('/' !== substr($path, -1))
- {
+ if ('/' !== substr($path, -1)) {
$path = substr($path, 0, strrpos($path, '/') + 1);
}
@@ -635,42 +593,35 @@ protected function sibling($node, $siblingDir = 'nextSibling')
{
$nodes = array();
- do
- {
+ do {
if ($node !== $this->getNode(0) && $node->nodeType === 1)
{
$nodes[] = $node;
}
- }
- while($node = $node->$siblingDir);
+ } while($node = $node->$siblingDir);
return $nodes;
}
static public function xpathLiteral($s)
{
- if (false === strpos($s, "'"))
- {
+ if (false === strpos($s, "'")) {
return sprintf("'%s'", $s);
}
- if (false === strpos($s, '"'))
- {
+ if (false === strpos($s, '"')) {
return sprintf('"%s"', $s);
}
$string = $s;
$parts = array();
- while (true)
- {
+ while (true) {
if (false !== $pos = strpos($string, "'"))
{
$parts[] = sprintf("'%s'", substr($string, 0, $pos));
$parts[] = "\"'\"";
$string = substr($string, $pos + 1);
- }
- else
- {
+ } else {
$parts[] = "'$string'";
break;
}
diff --git a/src/Symfony/Components/DomCrawler/Field/ChoiceFormField.php b/src/Symfony/Components/DomCrawler/Field/ChoiceFormField.php
index f1eddf0f09b2..c292c9eff25a 100644
--- a/src/Symfony/Components/DomCrawler/Field/ChoiceFormField.php
+++ b/src/Symfony/Components/DomCrawler/Field/ChoiceFormField.php
@@ -34,8 +34,7 @@ class ChoiceFormField extends FormField
public function hasValue()
{
// 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;
}
@@ -51,49 +50,36 @@ public function hasValue()
*/
public function setValue($value)
{
- if ('checkbox' == $this->type && false === $value)
- {
+ if ('checkbox' == $this->type && false === $value) {
// uncheck
$this->value = null;
- }
- elseif ('checkbox' == $this->type && true === $value)
- {
+ } elseif ('checkbox' == $this->type && true === $value) {
// check
$this->value = $this->options[0];
- }
- else
- {
+ } else {
if (is_array($value))
{
- if (!$this->multiple)
- {
+ if (!$this->multiple) {
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))
{
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)));
}
- if ($this->multiple && !is_array($value))
- {
+ if ($this->multiple && !is_array($value)) {
$value = array($value);
}
- if (is_array($value))
- {
+ if (is_array($value)) {
$this->value = $value;
- }
- else
- {
+ } else {
parent::setValue($value);
}
}
@@ -110,15 +96,13 @@ public function setValue($value)
*/
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));
}
$this->options[] = $value = $node->hasAttribute('value') ? $node->getAttribute('value') : '1';
- if ($node->getAttribute('checked'))
- {
+ if ($node->getAttribute('checked')) {
$this->value = $value;
}
}
@@ -150,13 +134,11 @@ public function isMultiple()
*/
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));
}
- 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')));
}
@@ -164,40 +146,30 @@ protected function initialize()
$this->options = array();
$this->multiple = false;
- if ('input' == $this->node->nodeName)
- {
+ if ('input' == $this->node->nodeName) {
$this->type = $this->node->getAttribute('type');
$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;
}
- }
- else
- {
+ } else {
$this->type = 'select';
- if ($this->node->hasAttribute('multiple'))
- {
+ if ($this->node->hasAttribute('multiple')) {
$this->multiple = true;
$this->value = array();
$this->name = str_replace('[]', '', $this->name);
}
$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');
- if ($option->getAttribute('selected'))
- {
+ if ($option->getAttribute('selected')) {
$found = true;
- if ($this->multiple)
- {
+ if ($this->multiple) {
$this->value[] = $option->getAttribute('value');
- }
- else
- {
+ } else {
$this->value = $option->getAttribute('value');
}
}
@@ -205,8 +177,7 @@ protected function initialize()
// 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);
- if (!$found && !$this->multiple && $option instanceof \DOMElement)
- {
+ if (!$found && !$this->multiple && $option instanceof \DOMElement) {
$this->value = $option->getAttribute('value');
}
}
diff --git a/src/Symfony/Components/DomCrawler/Field/FileFormField.php b/src/Symfony/Components/DomCrawler/Field/FileFormField.php
index 3588af24bb0b..64a06290e4d2 100644
--- a/src/Symfony/Components/DomCrawler/Field/FileFormField.php
+++ b/src/Symfony/Components/DomCrawler/Field/FileFormField.php
@@ -30,8 +30,7 @@ class FileFormField extends FormField
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);
- if (!in_array($error, $codes))
- {
+ if (!in_array($error, $codes)) {
throw new \InvalidArgumentException(sprintf('The error code %s is not valid.', $error));
}
@@ -45,13 +44,10 @@ public function setErrorCode($error)
*/
public function setValue($value)
{
- if (null !== $value && is_readable($value))
- {
+ if (null !== $value && is_readable($value)) {
$error = UPLOAD_ERR_OK;
$size = filesize($value);
- }
- else
- {
+ } else {
$error = UPLOAD_ERR_NO_FILE;
$size = 0;
$value = '';
@@ -67,13 +63,11 @@ public function setValue($value)
*/
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));
}
- 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')));
}
diff --git a/src/Symfony/Components/DomCrawler/Field/InputFormField.php b/src/Symfony/Components/DomCrawler/Field/InputFormField.php
index 37380db9a048..706b5055b096 100644
--- a/src/Symfony/Components/DomCrawler/Field/InputFormField.php
+++ b/src/Symfony/Components/DomCrawler/Field/InputFormField.php
@@ -30,18 +30,15 @@ class InputFormField extends FormField
*/
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));
}
- if ('checkbox' == $this->node->getAttribute('type'))
- {
+ if ('checkbox' == $this->node->getAttribute('type')) {
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.');
}
diff --git a/src/Symfony/Components/DomCrawler/Field/TextareaFormField.php b/src/Symfony/Components/DomCrawler/Field/TextareaFormField.php
index f9d33c816551..e78123c4b25f 100644
--- a/src/Symfony/Components/DomCrawler/Field/TextareaFormField.php
+++ b/src/Symfony/Components/DomCrawler/Field/TextareaFormField.php
@@ -27,14 +27,12 @@ class TextareaFormField extends FormField
*/
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));
}
$this->value = null;
- foreach ($this->node->childNodes as $node)
- {
+ foreach ($this->node->childNodes as $node) {
$this->value .= $this->document->saveXML($node);
}
}
diff --git a/src/Symfony/Components/DomCrawler/Form.php b/src/Symfony/Components/DomCrawler/Form.php
index 266933aa275a..2fb8c0439a32 100644
--- a/src/Symfony/Components/DomCrawler/Form.php
+++ b/src/Symfony/Components/DomCrawler/Form.php
@@ -41,20 +41,15 @@ class Form
public function __construct(\DOMNode $node, $method = null, $host = null, $path = '/')
{
$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
{
// 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.');
}
- }
- while ('form' != $node->nodeName);
- }
- else
- {
+ } while ('form' != $node->nodeName);
+ } else {
throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
}
$this->node = $node;
@@ -84,8 +79,7 @@ public function getFormNode()
*/
public function getValue($name)
{
- if (!$this->hasField($name))
- {
+ if (!$this->hasField($name)) {
throw new \InvalidArgumentException(sprintf('The form field "%s" does not exist', $name));
}
@@ -102,8 +96,7 @@ public function getValue($name)
*/
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));
}
@@ -119,8 +112,7 @@ public function setValue($name, $value)
*/
public function setValues(array $values)
{
- foreach ($values as $name => $value)
- {
+ foreach ($values as $name => $value) {
$this->setValue($name, $value);
}
@@ -137,8 +129,7 @@ public function setValues(array $values)
public function getValues()
{
$values = array();
- foreach ($this->fields as $name => $field)
- {
+ foreach ($this->fields as $name => $field) {
if (!$field instanceof Field\FileFormField && $field->hasValue())
{
$values[$name] = $field->getValue();
@@ -155,14 +146,12 @@ public function getValues()
*/
public function getFiles()
{
- if (!in_array($this->getMethod(), array('post', 'put', 'delete')))
- {
+ if (!in_array($this->getMethod(), array('post', 'put', 'delete'))) {
return array();
}
$files = array();
- foreach ($this->fields as $name => $field)
- {
+ foreach ($this->fields as $name => $field) {
if ($field instanceof Field\FileFormField)
{
$files[$name] = $field->getValue();
@@ -219,19 +208,16 @@ public function getUri($absolute = true)
{
$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, '?') ? '?' : '&';
$uri .= $sep.$queryString;
}
- if ($uri && '/' !== $uri[0])
- {
+ if ($uri && '/' !== $uri[0]) {
$uri = $this->path.$uri;
}
- if ($absolute && null !== $this->host)
- {
+ if ($absolute && null !== $this->host) {
return $this->host.$uri;
}
@@ -247,8 +233,7 @@ public function getUri($absolute = true)
*/
public function getMethod()
{
- if (null !== $this->method)
- {
+ if (null !== $this->method) {
return $this->method;
}
@@ -278,8 +263,7 @@ public function hasField($name)
*/
public function getField($name)
{
- if (!$this->hasField($name))
- {
+ if (!$this->hasField($name)) {
throw new \InvalidArgumentException(sprintf('The form has no "%s" field', $name));
}
@@ -320,8 +304,7 @@ protected function initialize()
$root->appendChild($button);
$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'))
{
continue;
@@ -329,35 +312,22 @@ protected function initialize()
$nodeName = $node->nodeName;
- if ($node === $button)
- {
+ if ($node === $button) {
$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));
- }
- elseif ('input' == $nodeName && 'radio' == $node->getAttribute('type'))
- {
+ } elseif ('input' == $nodeName && 'radio' == $node->getAttribute('type')) {
if ($this->hasField($node->getAttribute('name')))
{
$this->getField($node->getAttribute('name'))->addChoice($node);
- }
- else
- {
+ } else {
$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));
- }
- 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));
- }
- elseif ('textarea' == $nodeName)
- {
+ } elseif ('textarea' == $nodeName) {
$this->setField(new Field\TextareaFormField($node));
}
}
diff --git a/src/Symfony/Components/DomCrawler/Link.php b/src/Symfony/Components/DomCrawler/Link.php
index e8837454ff43..4499bf6a19c2 100644
--- a/src/Symfony/Components/DomCrawler/Link.php
+++ b/src/Symfony/Components/DomCrawler/Link.php
@@ -37,8 +37,7 @@ class Link
*/
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));
}
@@ -69,13 +68,11 @@ public function getUri($absolute = true)
{
$uri = $this->node->getAttribute('href');
- if ($uri && '/' !== $uri[0])
- {
+ if ($uri && '/' !== $uri[0]) {
$uri = $this->path.$uri;
}
- if ($absolute && null !== $this->host)
- {
+ if ($absolute && null !== $this->host) {
return $this->host.$uri;
}
diff --git a/src/Symfony/Components/EventDispatcher/Event.php b/src/Symfony/Components/EventDispatcher/Event.php
index 424a24c4fd09..db32c817b3c9 100644
--- a/src/Symfony/Components/EventDispatcher/Event.php
+++ b/src/Symfony/Components/EventDispatcher/Event.php
@@ -132,8 +132,7 @@ public function hasParameter($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));
}
@@ -172,8 +171,7 @@ public function offsetExists($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));
}
diff --git a/src/Symfony/Components/EventDispatcher/EventDispatcher.php b/src/Symfony/Components/EventDispatcher/EventDispatcher.php
index 9ee74f433fe6..adbad0dfdfaf 100644
--- a/src/Symfony/Components/EventDispatcher/EventDispatcher.php
+++ b/src/Symfony/Components/EventDispatcher/EventDispatcher.php
@@ -31,8 +31,7 @@ class EventDispatcher
*/
public function connect($name, $listener)
{
- if (!isset($this->listeners[$name]))
- {
+ if (!isset($this->listeners[$name])) {
$this->listeners[$name] = array();
}
@@ -49,13 +48,11 @@ public function connect($name, $listener)
*/
public function disconnect($name, $listener)
{
- if (!isset($this->listeners[$name]))
- {
+ if (!isset($this->listeners[$name])) {
return false;
}
- foreach ($this->listeners[$name] as $i => $callable)
- {
+ foreach ($this->listeners[$name] as $i => $callable) {
if ($listener === $callable)
{
unset($this->listeners[$name][$i]);
@@ -72,8 +69,7 @@ public function disconnect($name, $listener)
*/
public function notify(Event $event)
{
- foreach ($this->getListeners($event->getName()) as $listener)
- {
+ foreach ($this->getListeners($event->getName()) as $listener) {
call_user_func($listener, $event);
}
@@ -89,8 +85,7 @@ public function notify(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))
{
$event->setProcessed(true);
@@ -111,8 +106,7 @@ public function notifyUntil(Event $event)
*/
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);
}
@@ -130,8 +124,7 @@ public function filter(Event $event, $value)
*/
public function hasListeners($name)
{
- if (!isset($this->listeners[$name]))
- {
+ if (!isset($this->listeners[$name])) {
$this->listeners[$name] = array();
}
@@ -147,8 +140,7 @@ public function hasListeners($name)
*/
public function getListeners($name)
{
- if (!isset($this->listeners[$name]))
- {
+ if (!isset($this->listeners[$name])) {
return array();
}
diff --git a/src/Symfony/Components/Finder/Finder.php b/src/Symfony/Components/Finder/Finder.php
index 6cb42ca7012a..8a7dcf89c60a 100644
--- a/src/Symfony/Components/Finder/Finder.php
+++ b/src/Symfony/Components/Finder/Finder.php
@@ -287,13 +287,11 @@ public function followLinks()
*/
public function in($dirs)
{
- if (!is_array($dirs))
- {
+ if (!is_array($dirs)) {
$dirs = array($dirs);
}
- foreach ($dirs as $dir)
- {
+ foreach ($dirs as $dir) {
if (!is_dir($dir))
{
throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
@@ -316,19 +314,16 @@ public function in($dirs)
*/
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.');
}
- if (1 === count($this->dirs))
- {
+ if (1 === count($this->dirs)) {
return $this->searchInDirectory($this->dirs[0]);
}
$iterator = new \AppendIterator();
- foreach ($this->dirs as $dir)
- {
+ foreach ($this->dirs as $dir) {
$iterator->append($this->searchInDirectory($dir));
}
@@ -339,50 +334,41 @@ protected function searchInDirectory($dir)
{
$flags = \FilesystemIterator::SKIP_DOTS;
- if ($this->followLinks)
- {
+ if ($this->followLinks) {
$flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
}
$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);
}
- if ($this->mode)
- {
+ if ($this->mode) {
$iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
}
- if ($this->exclude)
- {
+ if ($this->exclude) {
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
}
- if ($this->ignoreVCS)
- {
+ if ($this->ignoreVCS) {
$iterator = new Iterator\IgnoreVcsFilterIterator($iterator);
}
- if ($this->names || $this->notNames)
- {
+ if ($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);
}
- if ($this->filters)
- {
+ if ($this->filters) {
$iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
}
- if ($this->sort)
- {
+ if ($this->sort) {
$iterator = new Iterator\SortableIterator($iterator, $this->sort);
}
diff --git a/src/Symfony/Components/Finder/Glob.php b/src/Symfony/Components/Finder/Glob.php
index 79eb651044b4..c01958eb2cc3 100644
--- a/src/Symfony/Components/Finder/Glob.php
+++ b/src/Symfony/Components/Finder/Glob.php
@@ -51,11 +51,9 @@ static public function toRegex($glob, $strictLeadingDot = true, $strictWildcardS
$inCurlies = 0;
$regex = '';
$sizeGlob = strlen($glob);
- for ($i = 0; $i < $sizeGlob; $i++)
- {
+ for ($i = 0; $i < $sizeGlob; $i++) {
$car = $glob[$i];
- if ($firstByte)
- {
+ if ($firstByte) {
if ($strictLeadingDot && $car !== '.')
{
$regex .= '(?=[^\.])';
@@ -64,59 +62,39 @@ static public function toRegex($glob, $strictLeadingDot = true, $strictWildcardS
$firstByte = false;
}
- if ($car === '/')
- {
+ if ($car === '/') {
$firstByte = true;
}
- if ($car === '.' || $car === '(' || $car === ')' || $car === '|' || $car === '+' || $car === '^' || $car === '$')
- {
+ if ($car === '.' || $car === '(' || $car === ')' || $car === '|' || $car === '+' || $car === '^' || $car === '$') {
$regex .= "\\$car";
- }
- elseif ($car === '*')
- {
+ } elseif ($car === '*') {
$regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
- }
- elseif ($car === '?')
- {
+ } elseif ($car === '?') {
$regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
- }
- elseif ($car === '{')
- {
+ } elseif ($car === '{') {
$regex .= $escaping ? '\\{' : '(';
- if (!$escaping)
- {
+ if (!$escaping) {
++$inCurlies;
}
- }
- elseif ($car === '}' && $inCurlies)
- {
+ } elseif ($car === '}' && $inCurlies) {
$regex .= $escaping ? '}' : ')';
- if (!$escaping)
- {
+ if (!$escaping) {
--$inCurlies;
}
- }
- elseif ($car === ',' && $inCurlies)
- {
+ } elseif ($car === ',' && $inCurlies) {
$regex .= $escaping ? ',' : '|';
- }
- elseif ($car === '\\')
- {
+ } elseif ($car === '\\') {
if ($escaping)
{
$regex .= '\\\\';
$escaping = false;
- }
- else
- {
+ } else {
$escaping = true;
}
continue;
- }
- else
- {
+ } else {
$regex .= $car;
}
$escaping = false;
diff --git a/src/Symfony/Components/Finder/Iterator/CustomFilterIterator.php b/src/Symfony/Components/Finder/Iterator/CustomFilterIterator.php
index e706fba82839..d750ef611bfe 100644
--- a/src/Symfony/Components/Finder/Iterator/CustomFilterIterator.php
+++ b/src/Symfony/Components/Finder/Iterator/CustomFilterIterator.php
@@ -47,8 +47,7 @@ public function accept()
{
$fileinfo = $this->getInnerIterator()->current();
- foreach ($this->filters as $filter)
- {
+ foreach ($this->filters as $filter) {
if (false === $filter($fileinfo))
{
return false;
diff --git a/src/Symfony/Components/Finder/Iterator/ExcludeDirectoryFilterIterator.php b/src/Symfony/Components/Finder/Iterator/ExcludeDirectoryFilterIterator.php
index f7f1263eb665..6a082488d25f 100644
--- a/src/Symfony/Components/Finder/Iterator/ExcludeDirectoryFilterIterator.php
+++ b/src/Symfony/Components/Finder/Iterator/ExcludeDirectoryFilterIterator.php
@@ -31,8 +31,7 @@ class ExcludeDirectoryFilterIterator extends \FilterIterator
public function __construct(\Iterator $iterator, array $directories)
{
$this->patterns = array();
- foreach ($directories as $directory)
- {
+ foreach ($directories as $directory) {
$this->patterns[] = '#/'.preg_quote($directory, '#').'(/|$)#';
}
@@ -48,16 +47,13 @@ public function accept()
{
$fileinfo = $this->getInnerIterator()->current();
- foreach ($this->patterns as $pattern)
- {
+ foreach ($this->patterns as $pattern) {
$path = $fileinfo->getPathname();
- if ($fileinfo->isDir())
- {
+ if ($fileinfo->isDir()) {
$path .= '/';
}
- if (preg_match($pattern, $path))
- {
+ if (preg_match($pattern, $path)) {
return false;
}
}
diff --git a/src/Symfony/Components/Finder/Iterator/FileTypeFilterIterator.php b/src/Symfony/Components/Finder/Iterator/FileTypeFilterIterator.php
index 0e1eca58dd81..f1649dbcc849 100644
--- a/src/Symfony/Components/Finder/Iterator/FileTypeFilterIterator.php
+++ b/src/Symfony/Components/Finder/Iterator/FileTypeFilterIterator.php
@@ -47,12 +47,9 @@ public function accept()
{
$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;
- }
- elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir())
- {
+ } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) {
return false;
}
diff --git a/src/Symfony/Components/Finder/Iterator/FilenameFilterIterator.php b/src/Symfony/Components/Finder/Iterator/FilenameFilterIterator.php
index 183a84c54cc0..f6990aa9bed7 100644
--- a/src/Symfony/Components/Finder/Iterator/FilenameFilterIterator.php
+++ b/src/Symfony/Components/Finder/Iterator/FilenameFilterIterator.php
@@ -35,14 +35,12 @@ class FilenameFilterIterator extends \FilterIterator
public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
{
$this->matchRegexps = array();
- foreach ($matchPatterns as $pattern)
- {
+ foreach ($matchPatterns as $pattern) {
$this->matchRegexps[] = $this->toRegex($pattern);
}
$this->noMatchRegexps = array();
- foreach ($noMatchPatterns as $pattern)
- {
+ foreach ($noMatchPatterns as $pattern) {
$this->noMatchRegexps[] = $this->toRegex($pattern);
}
@@ -59,38 +57,30 @@ public function accept()
$fileinfo = $this->getInnerIterator()->current();
// should at least match one rule
- if ($this->matchRegexps)
- {
+ if ($this->matchRegexps) {
$match = false;
- foreach ($this->matchRegexps as $regex)
- {
+ foreach ($this->matchRegexps as $regex) {
if (preg_match($regex, $fileinfo->getFilename()))
{
$match = true;
break;
}
}
- }
- else
- {
+ } else {
$match = true;
}
// should at least not match one rule to exclude
- if ($this->noMatchRegexps)
- {
+ if ($this->noMatchRegexps) {
$exclude = false;
- foreach ($this->noMatchRegexps as $regex)
- {
+ foreach ($this->noMatchRegexps as $regex) {
if (preg_match($regex, $fileinfo->getFilename()))
{
$exclude = true;
break;
}
}
- }
- else
- {
+ } else {
$exclude = false;
}
@@ -99,8 +89,7 @@ public function accept()
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;
}
diff --git a/src/Symfony/Components/Finder/Iterator/SizeRangeFilterIterator.php b/src/Symfony/Components/Finder/Iterator/SizeRangeFilterIterator.php
index cce137e4bfa6..ea389355a372 100644
--- a/src/Symfony/Components/Finder/Iterator/SizeRangeFilterIterator.php
+++ b/src/Symfony/Components/Finder/Iterator/SizeRangeFilterIterator.php
@@ -44,14 +44,12 @@ public function accept()
{
$fileinfo = $this->getInnerIterator()->current();
- if (!$fileinfo->isFile())
- {
+ if (!$fileinfo->isFile()) {
return true;
}
$filesize = $fileinfo->getSize();
- foreach ($this->patterns as $compare)
- {
+ foreach ($this->patterns as $compare) {
if (!$compare->test($filesize))
{
return false;
diff --git a/src/Symfony/Components/Finder/Iterator/SortableIterator.php b/src/Symfony/Components/Finder/Iterator/SortableIterator.php
index 59bc72ac170f..d06f4c57d331 100644
--- a/src/Symfony/Components/Finder/Iterator/SortableIterator.php
+++ b/src/Symfony/Components/Finder/Iterator/SortableIterator.php
@@ -31,31 +31,23 @@ class SortableIterator extends \ArrayIterator
*/
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)
{
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)
{
- if ($a->isDir() && $b->isFile())
- {
+ if ($a->isDir() && $b->isFile()) {
return -1;
- }
- elseif ($a->isFile() && $b->isDir())
- {
+ } elseif ($a->isFile() && $b->isDir()) {
return 1;
}
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));
}
diff --git a/src/Symfony/Components/Finder/NumberCompare.php b/src/Symfony/Components/Finder/NumberCompare.php
index 15afc84125eb..39f5dc7cb337 100644
--- a/src/Symfony/Components/Finder/NumberCompare.php
+++ b/src/Symfony/Components/Finder/NumberCompare.php
@@ -45,8 +45,7 @@ class NumberCompare
*/
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));
}
@@ -54,8 +53,7 @@ public function __construct($test)
$this->comparison = isset($matches[1]) ? $matches[1] : '==';
$magnitude = strtolower(isset($matches[3]) ? $matches[3] : '');
- switch ($magnitude)
- {
+ switch ($magnitude) {
case 'k':
$this->target *= 1000;
break;
@@ -84,23 +82,19 @@ public function __construct($test)
*/
public function test($number)
{
- if ($this->comparison === '>')
- {
+ if ($this->comparison === '>') {
return ($number > $this->target);
}
- if ($this->comparison === '>=')
- {
+ if ($this->comparison === '>=') {
return ($number >= $this->target);
}
- if ($this->comparison === '<')
- {
+ if ($this->comparison === '<') {
return ($number < $this->target);
}
- if ($this->comparison === '<=')
- {
+ if ($this->comparison === '<=') {
return ($number <= $this->target);
}
diff --git a/src/Symfony/Components/HttpKernel/CacheControl.php b/src/Symfony/Components/HttpKernel/CacheControl.php
index fe3dbcc0ae3b..e9671dda7285 100644
--- a/src/Symfony/Components/HttpKernel/CacheControl.php
+++ b/src/Symfony/Components/HttpKernel/CacheControl.php
@@ -36,8 +36,7 @@ class CacheControl
*/
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));
}
$this->type = $type;
@@ -50,14 +49,11 @@ public function __toString()
{
$parts = array();
ksort($this->attributes);
- foreach ($this->attributes as $key => $value)
- {
+ foreach ($this->attributes as $key => $value) {
if (true === $value)
{
$parts[] = $key;
- }
- else
- {
+ } else {
if (preg_match('#[^a-zA-Z0-9._-]#', $value))
{
$value = '"'.$value.'"';
@@ -245,8 +241,7 @@ protected function parse($header)
{
$attributes = array();
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);
}
@@ -255,12 +250,9 @@ protected function parse($header)
protected function setValue($key, $value, $isBoolean = false)
{
- if (false === $value)
- {
+ if (false === $value) {
unset($this->attributes[$key]);
- }
- else
- {
+ } else {
$this->attributes[$key] = $isBoolean ? true : $value;
}
@@ -269,8 +261,7 @@ protected function setValue($key, $value, $isBoolean = false)
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));
}
}
diff --git a/src/Symfony/Components/HttpKernel/Exception/ForbiddenHttpException.php b/src/Symfony/Components/HttpKernel/Exception/ForbiddenHttpException.php
index 57f6d707a714..b45c5fbdfc1e 100644
--- a/src/Symfony/Components/HttpKernel/Exception/ForbiddenHttpException.php
+++ b/src/Symfony/Components/HttpKernel/Exception/ForbiddenHttpException.php
@@ -22,8 +22,7 @@ class ForbiddenHttpException extends HttpException
{
public function __construct($message = '')
{
- if (!$message)
- {
+ if (!$message) {
$message = 'Forbidden';
}
diff --git a/src/Symfony/Components/HttpKernel/Exception/NotFoundHttpException.php b/src/Symfony/Components/HttpKernel/Exception/NotFoundHttpException.php
index eab3390f1fa0..47672e2af8f7 100644
--- a/src/Symfony/Components/HttpKernel/Exception/NotFoundHttpException.php
+++ b/src/Symfony/Components/HttpKernel/Exception/NotFoundHttpException.php
@@ -22,8 +22,7 @@ class NotFoundHttpException extends HttpException
{
public function __construct($message = '')
{
- if (!$message)
- {
+ if (!$message) {
$message = 'Not Found';
}
diff --git a/src/Symfony/Components/HttpKernel/Exception/UnauthorizedHttpException.php b/src/Symfony/Components/HttpKernel/Exception/UnauthorizedHttpException.php
index 5e3eb3acb244..8ebd5e53a9d2 100644
--- a/src/Symfony/Components/HttpKernel/Exception/UnauthorizedHttpException.php
+++ b/src/Symfony/Components/HttpKernel/Exception/UnauthorizedHttpException.php
@@ -22,8 +22,7 @@ class UnauthorizedHttpException extends HttpException
{
public function __construct($message = '')
{
- if (!$message)
- {
+ if (!$message) {
$message = 'Unauthorized';
}
diff --git a/src/Symfony/Components/HttpKernel/HeaderBag.php b/src/Symfony/Components/HttpKernel/HeaderBag.php
index 3ea4fbd9ab6a..2e6de8fde979 100644
--- a/src/Symfony/Components/HttpKernel/HeaderBag.php
+++ b/src/Symfony/Components/HttpKernel/HeaderBag.php
@@ -33,8 +33,7 @@ public function __construct(array $parameters = array(), $type = null)
{
$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));
}
$this->type = $type;
@@ -49,8 +48,7 @@ public function replace(array $parameters = array())
{
$this->cacheControl = null;
$this->parameters = array();
- foreach ($parameters as $key => $value)
- {
+ foreach ($parameters as $key => $value) {
$this->parameters[strtr(strtolower($key), '_', '-')] = $value;
}
}
@@ -79,8 +77,7 @@ public function set($key, $value, $replace = true)
{
$key = strtr(strtolower($key), '_', '-');
- if (false === $replace)
- {
+ if (false === $replace) {
$current = $this->get($key, '');
$value = ($current ? $current.', ' : '').$value;
}
@@ -117,8 +114,7 @@ public function delete($key)
*/
public function getCacheControl()
{
- if (null === $this->cacheControl)
- {
+ if (null === $this->cacheControl) {
$this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type);
}
diff --git a/src/Symfony/Components/HttpKernel/HttpKernel.php b/src/Symfony/Components/HttpKernel/HttpKernel.php
index 5f09fecfc0fc..36e34bc53d42 100644
--- a/src/Symfony/Components/HttpKernel/HttpKernel.php
+++ b/src/Symfony/Components/HttpKernel/HttpKernel.php
@@ -65,22 +65,17 @@ public function handle(Request $request = null, $main = true, $raw = false)
{
$main = (Boolean) $main;
- if (null === $request)
- {
+ if (null === $request) {
$request = new Request();
}
- if (true === $main)
- {
+ if (true === $main) {
$this->request = $request;
}
- try
- {
+ try {
return $this->handleRaw($request, $main);
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
if (true === $raw)
{
throw $e;
@@ -88,8 +83,7 @@ public function handle(Request $request = null, $main = true, $raw = false)
// exception
$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);
}
@@ -116,41 +110,33 @@ protected function handleRaw(Request $request, $main = true)
// 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);
}
// load controller
$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.');
}
list($controller, $arguments) = $event->getReturnValue();
// 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)));
}
// controller
$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
{
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();
}
- }
- else
- {
+ } else {
// call controller
$retval = call_user_func_array($controller, $arguments);
}
@@ -173,16 +159,14 @@ protected function handleRaw(Request $request, $main = true)
*/
protected function filterResponse($response, $request, $message, $main)
{
- if (!$response instanceof Response)
- {
+ if (!$response instanceof Response) {
throw new \RuntimeException($message);
}
$event = $this->dispatcher->filter(new Event($this, 'core.response', array('main_request' => $main, 'request' => $request)), $response);
$response = $event->getReturnValue();
- if (!$response instanceof Response)
- {
+ if (!$response instanceof Response) {
throw new \RuntimeException('A "core.response" listener returned a non response object.');
}
diff --git a/src/Symfony/Components/HttpKernel/ParameterBag.php b/src/Symfony/Components/HttpKernel/ParameterBag.php
index ea46120edfad..afeb1b5147a8 100644
--- a/src/Symfony/Components/HttpKernel/ParameterBag.php
+++ b/src/Symfony/Components/HttpKernel/ParameterBag.php
@@ -150,13 +150,11 @@ public function getInt($key, $default = 0)
public function getDate($key, \DateTime $default = null)
{
- if (null === $value = $this->get($key))
- {
+ if (null === $value = $this->get($key)) {
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));
}
diff --git a/src/Symfony/Components/HttpKernel/Request.php b/src/Symfony/Components/HttpKernel/Request.php
index f826498df6b7..96ed94d9181e 100644
--- a/src/Symfony/Components/HttpKernel/Request.php
+++ b/src/Symfony/Components/HttpKernel/Request.php
@@ -117,22 +117,18 @@ static public function create($uri, $method = 'get', $parameters = array(), $coo
'SCRIPT_FILENAME' => '',
);
- if (in_array(strtolower($method), array('post', 'put', 'delete')))
- {
+ if (in_array(strtolower($method), array('post', 'put', 'delete'))) {
$request = $parameters;
$query = array();
$defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
- }
- else
- {
+ } else {
$request = array();
$query = $parameters;
}
$queryString = false !== ($pos = strpos($uri, '?')) ? html_entity_decode(substr($uri, $pos + 1)) : '';
parse_str($queryString, $qs);
- if (is_array($qs))
- {
+ if (is_array($qs)) {
$query = array_replace($qs, $query);
}
@@ -204,8 +200,7 @@ public function getScriptName()
public function getPathInfo()
{
- if (null === $this->pathInfo)
- {
+ if (null === $this->pathInfo) {
$this->pathInfo = $this->preparePathInfo();
}
@@ -214,8 +209,7 @@ public function getPathInfo()
public function getBasePath()
{
- if (null === $this->basePath)
- {
+ if (null === $this->basePath) {
$this->basePath = $this->prepareBasePath();
}
@@ -224,8 +218,7 @@ public function getBasePath()
public function getBaseUrl()
{
- if (null === $this->baseUrl)
- {
+ if (null === $this->baseUrl) {
$this->baseUrl = $this->prepareBaseUrl();
}
@@ -245,8 +238,7 @@ public function getPort()
public function getHttpHost()
{
$host = $this->headers->get('HOST');
- if (!empty($host))
- {
+ if (!empty($host)) {
return $host;
}
@@ -254,20 +246,16 @@ public function getHttpHost()
$name = $this->server->get('SERVER_NAME');
$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;
- }
- else
- {
+ } else {
return $name.':'.$port;
}
}
public function getRequestUri()
{
- if (null === $this->requestUri)
- {
+ if (null === $this->requestUri) {
$this->requestUri = $this->prepareRequestUri();
}
@@ -292,14 +280,11 @@ public function isSecure()
*/
public function getHost()
{
- if ($host = $this->headers->get('X_FORWARDED_HOST'))
- {
+ if ($host = $this->headers->get('X_FORWARDED_HOST')) {
$elements = implode(',', $host);
return trim($elements[count($elements) - 1]);
- }
- else
- {
+ } else {
return $this->headers->get('HOST', $this->server->get('SERVER_NAME', $this->server->get('SERVER_ADDR', '')));
}
}
@@ -317,8 +302,7 @@ public function setMethod($method)
*/
public function getMethod()
{
- if (null === $this->method)
- {
+ if (null === $this->method) {
switch ($this->server->get('REQUEST_METHOD', 'GET'))
{
case 'POST':
@@ -354,8 +338,7 @@ public function getMethod()
*/
public function getMimeType($format)
{
- if (null === static::$formats)
- {
+ if (null === static::$formats) {
static::initializeFormats();
}
@@ -371,13 +354,11 @@ public function getMimeType($format)
*/
public function getFormat($mimeType)
{
- if (null === static::$formats)
- {
+ if (null === static::$formats) {
static::initializeFormats();
}
- foreach (static::$formats as $format => $mimeTypes)
- {
+ foreach (static::$formats as $format => $mimeTypes) {
if (in_array($mimeType, (array) $mimeTypes))
{
return $format;
@@ -395,8 +376,7 @@ public function getFormat($mimeType)
*/
public function setFormat($format, $mimeTypes)
{
- if (null === static::$formats)
- {
+ if (null === static::$formats) {
static::initializeFormats();
}
@@ -416,8 +396,7 @@ public function setFormat($format, $mimeTypes)
*/
public function getRequestFormat()
{
- if (null === $this->format)
- {
+ if (null === $this->format) {
$this->format = $this->get('_format', 'html');
}
@@ -445,13 +424,11 @@ public function getPreferredLanguage(array $cultures = null)
{
$preferredLanguages = $this->getLanguages();
- if (null === $cultures)
- {
+ if (null === $cultures) {
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
}
- if (!$preferredLanguages)
- {
+ if (!$preferredLanguages) {
return $cultures[0];
}
@@ -467,37 +444,28 @@ public function getPreferredLanguage(array $cultures = null)
*/
public function getLanguages()
{
- if (null !== $this->languages)
- {
+ if (null !== $this->languages) {
return $this->languages;
}
$languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
- foreach ($languages as $lang)
- {
+ foreach ($languages as $lang) {
if (strstr($lang, '-'))
{
$codes = explode('-', $lang);
- if ($codes[0] == 'i')
- {
+ if ($codes[0] == 'i') {
// Language not listed in ISO 639 that are not variants
// of any listed language, which can be registered with the
// i-prefix, such as i-cherokee
- if (count($codes) > 1)
- {
+ if (count($codes) > 1) {
$lang = $codes[1];
}
- }
- else
- {
+ } else {
for ($i = 0, $max = count($codes); $i < $max; $i++)
{
- if ($i == 0)
- {
+ if ($i == 0) {
$lang = strtolower($codes[0]);
- }
- else
- {
+ } else {
$lang .= '_'.strtoupper($codes[$i]);
}
}
@@ -517,8 +485,7 @@ public function getLanguages()
*/
public function getCharsets()
{
- if (null !== $this->charsets)
- {
+ if (null !== $this->charsets) {
return $this->charsets;
}
@@ -532,8 +499,7 @@ public function getCharsets()
*/
public function getAcceptableContentTypes()
{
- if (null !== $this->acceptableContentTypes)
- {
+ if (null !== $this->acceptableContentTypes) {
return $this->acceptableContentTypes;
}
@@ -560,27 +526,21 @@ public function isXmlHttpRequest()
*/
public function splitHttpAcceptHeader($header)
{
- if (!$header)
- {
+ if (!$header) {
return 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
- if ($pos = strpos($value, ';'))
- {
+ if ($pos = strpos($value, ';')) {
$q = (float) trim(substr($value, strpos($value, '=') + 1));
$value = trim(substr($value, 0, $pos));
- }
- else
- {
+ } else {
$q = 1;
}
- if (0 < $q)
- {
+ if (0 < $q) {
$values[trim($value)] = $q;
}
}
@@ -602,32 +562,23 @@ protected function prepareRequestUri()
{
$requestUri = '';
- if ($this->headers->has('X_REWRITE_URL'))
- {
+ if ($this->headers->has('X_REWRITE_URL')) {
// check this first so IIS will catch
$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)
$requestUri = $this->server->get('UNENCODED_URL');
- }
- elseif ($this->server->has('REQUEST_URI'))
- {
+ } elseif ($this->server->has('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
$schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
- if (strpos($requestUri, $schemeAndHttpHost) === 0)
- {
+ if (strpos($requestUri, $schemeAndHttpHost) === 0) {
$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
$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');
}
}
@@ -641,20 +592,13 @@ protected function prepareBaseUrl()
$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');
- }
- elseif (basename($this->server->get('PHP_SELF')) === $filename)
- {
+ } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
$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
- }
- else
- {
+ } else {
// Backtrack up the script_filename to find the portion matching
// php_self
$path = $this->server->get('PHP_SELF', '');
@@ -664,8 +608,7 @@ protected function prepareBaseUrl()
$index = 0;
$last = count($segs);
$baseUrl = '';
- do
- {
+ do {
$seg = $segs[$index];
$baseUrl = '/'.$seg.$baseUrl;
++$index;
@@ -675,27 +618,23 @@ protected function prepareBaseUrl()
// Does the baseUrl have anything in common with the request_uri?
$requestUri = $this->getRequestUri();
- if ($baseUrl && 0 === strpos($requestUri, $baseUrl))
- {
+ if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
// full $baseUrl matches
return $baseUrl;
}
- if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl)))
- {
+ if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
// directory portion of $baseUrl matches
return rtrim(dirname($baseUrl), '/');
}
$truncatedRequestUri = $requestUri;
- if (($pos = strpos($requestUri, '?')) !== false)
- {
+ if (($pos = strpos($requestUri, '?')) !== false) {
$truncatedRequestUri = substr($requestUri, 0, $pos);
}
$basename = basename($baseUrl);
- if (empty($basename) || !strpos($truncatedRequestUri, $basename))
- {
+ if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
// no match whatsoever; set it blank
return '';
}
@@ -703,8 +642,7 @@ protected function prepareBaseUrl()
// If using mod_rewrite or ISAPI_Rewrite strip the script filename
// out of baseUrl. $pos !== 0 makes sure it is not matching a value
// 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));
}
@@ -716,22 +654,17 @@ protected function prepareBasePath()
$basePath = '';
$filename = basename($this->server->get('SCRIPT_FILENAME'));
$baseUrl = $this->getBaseUrl();
- if (empty($baseUrl))
- {
+ if (empty($baseUrl)) {
return '';
}
- if (basename($baseUrl) === $filename)
- {
+ if (basename($baseUrl) === $filename) {
$basePath = dirname($baseUrl);
- }
- else
- {
+ } else {
$basePath = $baseUrl;
}
- if ('\\' === DIRECTORY_SEPARATOR)
- {
+ if ('\\' === DIRECTORY_SEPARATOR) {
$basePath = str_replace('\\', '/', $basePath);
}
@@ -742,26 +675,21 @@ protected function preparePathInfo()
{
$baseUrl = $this->getBaseUrl();
- if (null === ($requestUri = $this->getRequestUri()))
- {
+ if (null === ($requestUri = $this->getRequestUri())) {
return '';
}
$pathInfo = '';
// Remove the query string from REQUEST_URI
- if ($pos = strpos($requestUri, '?'))
- {
+ if ($pos = strpos($requestUri, '?')) {
$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
return '';
- }
- elseif (null === $baseUrl)
- {
+ } elseif (null === $baseUrl) {
return $requestUri;
}
@@ -780,8 +708,7 @@ protected function preparePathInfo()
protected function convertFileInformation(array $taintedFiles)
{
$files = array();
- foreach ($taintedFiles as $key => $data)
- {
+ foreach ($taintedFiles as $key => $data) {
$files[$key] = $this->fixPhpFilesArray($data);
}
@@ -791,8 +718,7 @@ protected function convertFileInformation(array $taintedFiles)
protected function initializeHeaders()
{
$headers = array();
- foreach ($this->server->all() as $key => $value)
- {
+ foreach ($this->server->all() as $key => $value) {
if ('http_' === strtolower(substr($key, 0, 5)))
{
$headers[substr($key, 5)] = $value;
@@ -821,18 +747,15 @@ static protected function fixPhpFilesArray($data)
$keys = array_keys($data);
sort($keys);
- if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name']))
- {
+ if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
return $data;
}
$files = $data;
- foreach ($fileKeys as $k)
- {
+ foreach ($fileKeys as $k) {
unset($files[$k]);
}
- foreach (array_keys($data['name']) as $key)
- {
+ foreach (array_keys($data['name']) as $key) {
$files[$key] = self::fixPhpFilesArray(array(
'error' => $data['error'][$key],
'name' => $data['name'][$key],
diff --git a/src/Symfony/Components/HttpKernel/Response.php b/src/Symfony/Components/HttpKernel/Response.php
index 0f07021b1c7a..739fc28738d4 100644
--- a/src/Symfony/Components/HttpKernel/Response.php
+++ b/src/Symfony/Components/HttpKernel/Response.php
@@ -112,8 +112,7 @@ public function __clone()
*/
public function sendHeaders()
{
- if (!$this->headers->has('Content-Type'))
- {
+ if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html');
}
@@ -121,14 +120,12 @@ public function sendHeaders()
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
// headers
- foreach ($this->headers->all() as $name => $value)
- {
+ foreach ($this->headers->all() as $name => $value) {
header($name.': '.$value);
}
// 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']);
}
}
@@ -205,17 +202,13 @@ public function getProtocolVersion()
*/
public function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false)
{
- if (null !== $expire)
- {
+ if (null !== $expire) {
if (is_numeric($expire))
{
$expire = (int) $expire;
- }
- else
- {
+ } else {
$expire = strtotime($expire);
- if (false === $expire || -1 == $expire)
- {
+ if (false === $expire || -1 == $expire) {
throw new \InvalidArgumentException('The cookie expire parameter is not valid.');
}
}
@@ -253,8 +246,7 @@ public function getCookies()
public function setStatusCode($code, $text = null)
{
$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));
}
@@ -284,13 +276,11 @@ public function getStatusCode()
*/
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;
}
- if ($this->headers->getCacheControl()->isNoStore() || $this->headers->getCacheControl()->isPrivate())
- {
+ if ($this->headers->getCacheControl()->isNoStore() || $this->headers->getCacheControl()->isPrivate()) {
return false;
}
@@ -362,8 +352,7 @@ public function mustRevalidate()
*/
public function getDate()
{
- if (null === $date = $this->headers->getDate('Date'))
- {
+ if (null === $date = $this->headers->getDate('Date')) {
$date = new \DateTime();
$this->headers->set('Date', $date->format(DATE_RFC2822));
}
@@ -378,8 +367,7 @@ public function getDate()
*/
public function getAge()
{
- if ($age = $this->headers->get('Age'))
- {
+ if ($age = $this->headers->get('Age')) {
return $age;
}
@@ -391,8 +379,7 @@ public function getAge()
*/
public function expire()
{
- if ($this->isFresh())
- {
+ if ($this->isFresh()) {
$this->headers->set('Age', $this->getMaxAge());
}
}
@@ -416,12 +403,9 @@ public function getExpires()
*/
public function setExpires(\DateTime $date = null)
{
- if (null === $date)
- {
+ if (null === $date) {
$this->headers->delete('Expires');
- }
- else
- {
+ } else {
$this->headers->set('Expires', $date->format(DATE_RFC2822));
}
}
@@ -437,18 +421,15 @@ public function setExpires(\DateTime $date = null)
*/
public function getMaxAge()
{
- if ($age = $this->headers->getCacheControl()->getSharedMaxAge())
- {
+ if ($age = $this->headers->getCacheControl()->getSharedMaxAge()) {
return $age;
}
- if ($age = $this->headers->getCacheControl()->getMaxAge())
- {
+ if ($age = $this->headers->getCacheControl()->getMaxAge()) {
return $age;
}
- if (null !== $this->getExpires())
- {
+ if (null !== $this->getExpires()) {
return $this->getExpires()->format('U') - $this->getDate()->format('U');
}
@@ -491,8 +472,7 @@ public function setSharedMaxAge($value)
*/
public function getTtl()
{
- if ($maxAge = $this->getMaxAge())
- {
+ if ($maxAge = $this->getMaxAge()) {
return $maxAge - $this->getAge();
}
@@ -542,12 +522,9 @@ public function getLastModified()
*/
public function setLastModified(\DateTime $date = null)
{
- if (null === $date)
- {
+ if (null === $date) {
$this->headers->delete('Last-Modified');
- }
- else
- {
+ } else {
$this->headers->set('Last-Modified', $date->format(DATE_RFC2822));
}
@@ -565,12 +542,9 @@ public function getEtag()
public function setEtag($etag = null)
{
- if (null === $etag)
- {
+ if (null === $etag) {
$this->headers->delete('Etag');
- }
- else
- {
+ } else {
$this->headers->set('ETag', $etag);
}
}
@@ -589,8 +563,7 @@ public function setNotModified()
$this->setContent(null);
// 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);
}
}
@@ -612,8 +585,7 @@ public function hasVary()
*/
public function getVary()
{
- if (!$vary = $this->headers->get('Vary'))
- {
+ if (!$vary = $this->headers->get('Vary')) {
return array();
}
@@ -635,19 +607,15 @@ public function isNotModified(Request $request)
{
$lastModified = $request->headers->get('If-Modified-Since');
$notModified = false;
- if ($etags = $request->headers->get('If-None-Match'))
- {
+ if ($etags = $request->headers->get('If-None-Match')) {
$etags = preg_split('/\s*,\s*/', $etags);
$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');
}
- if ($notModified)
- {
+ if ($notModified) {
$this->setNotModified();
}
diff --git a/src/Symfony/Components/HttpKernel/Test/Client.php b/src/Symfony/Components/HttpKernel/Test/Client.php
index 1005d1b1ad06..85b53e4229d0 100644
--- a/src/Symfony/Components/HttpKernel/Test/Client.php
+++ b/src/Symfony/Components/HttpKernel/Test/Client.php
@@ -92,8 +92,7 @@ public function addTester($name, TesterInterface $tester)
*/
public function getTester($name)
{
- if (!isset($this->testers[$name]))
- {
+ if (!isset($this->testers[$name])) {
throw new \InvalidArgumentException(sprintf('Tester "%s" does not exist.', $name));
}
@@ -151,8 +150,7 @@ protected function getScript($request)
protected function filterRequest(DomRequest $request)
{
$uri = $request->getUri();
- if (preg_match('#^https?\://([^/]+)/(.*)$#', $uri, $matches))
- {
+ if (preg_match('#^https?\://([^/]+)/(.*)$#', $uri, $matches)) {
$uri = '/'.$matches[2];
}
@@ -181,26 +179,22 @@ protected function filterResponse($response)
*/
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));
}
// 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);
}
- 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));
}
// registered tester object?
$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));
}
diff --git a/src/Symfony/Components/HttpKernel/Test/RequestTester.php b/src/Symfony/Components/HttpKernel/Test/RequestTester.php
index b2a58e3001f4..280ca60d05d7 100644
--- a/src/Symfony/Components/HttpKernel/Test/RequestTester.php
+++ b/src/Symfony/Components/HttpKernel/Test/RequestTester.php
@@ -126,8 +126,7 @@ public function assertNotCookieExists($name)
*/
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));
}
@@ -142,8 +141,7 @@ public function assertCookieEquals($name, $value)
*/
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));
}
@@ -158,8 +156,7 @@ public function assertCookieRegExp($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));
}
diff --git a/src/Symfony/Components/HttpKernel/Test/ResponseTester.php b/src/Symfony/Components/HttpKernel/Test/ResponseTester.php
index a914f7a98470..02e18f91bba7 100644
--- a/src/Symfony/Components/HttpKernel/Test/ResponseTester.php
+++ b/src/Symfony/Components/HttpKernel/Test/ResponseTester.php
@@ -35,8 +35,7 @@ public function __construct(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->addContent($this->response->getContent(), $this->response->headers->get('Content-Type'));
}
@@ -51,8 +50,7 @@ public function __construct(Response $response)
*/
public function assertSelectEquals($selector, $arguments, $expected)
{
- if (null === $this->crawler)
- {
+ if (null === $this->crawler) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd
@@ -69,8 +67,7 @@ public function assertSelectEquals($selector, $arguments, $expected)
*/
public function assertSelectCount($selector, $count)
{
- if (null === $this->crawler)
- {
+ if (null === $this->crawler) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd
@@ -86,8 +83,7 @@ public function assertSelectCount($selector, $count)
*/
public function assertSelectExists($selector)
{
- if (null === $this->crawler)
- {
+ if (null === $this->crawler) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd
@@ -103,8 +99,7 @@ public function assertSelectExists($selector)
*/
public function assertNotSelectExists($selector)
{
- if (null === $this->crawler)
- {
+ if (null === $this->crawler) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to use %s() as the Symfony DomCrawler does not seem to be installed.', __METHOD__));
// @codeCoverageIgnoreEnd
@@ -122,8 +117,7 @@ public function assertNotSelectExists($selector)
public function assertHeaderEquals($key, $value)
{
$headers = explode(', ', $this->response->headers->get($key));
- foreach ($headers as $header)
- {
+ foreach ($headers as $header) {
if ($header == $value)
{
return $this->test->pass(sprintf('Response header "%s" is "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@@ -142,8 +136,7 @@ public function assertHeaderEquals($key, $value)
public function assertNotHeaderEquals($key, $value)
{
$headers = explode(', ', $this->response->headers->get($key));
- foreach ($headers as $header)
- {
+ foreach ($headers as $header) {
if ($header == $value)
{
return $this->test->fail(sprintf('Response header "%s" is not "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@@ -162,8 +155,7 @@ public function assertNotHeaderEquals($key, $value)
public function assertHeaderRegExp($key, $regex)
{
$headers = explode(', ', $this->response->headers->get($key));
- foreach ($headers as $header)
- {
+ foreach ($headers as $header) {
if (preg_match($regex, $header))
{
return $this->test->pass(sprintf('Response header "%s" matches "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@@ -182,8 +174,7 @@ public function assertHeaderRegExp($key, $regex)
public function assertNotHeaderRegExp($key, $regex)
{
$headers = explode(', ', $this->response->headers->get($key));
- foreach ($headers as $header)
- {
+ foreach ($headers as $header) {
if (!preg_match($regex, $header))
{
return $this->test->pass(sprintf('Response header "%s" matches "%s" (%s)', $key, $value, $this->response->headers->get($key)));
@@ -202,21 +193,16 @@ public function assertNotHeaderRegExp($key, $regex)
*/
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 (null === $value)
- {
+ if (null === $value) {
$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));
}
- foreach ($attributes as $attributeName => $attributeValue)
- {
+ foreach ($attributes as $attributeName => $attributeValue) {
if (!array_key_exists($attributeName, $cookie))
{
throw new \LogicException(sprintf('The cookie attribute "%s" is not valid.', $attributeName));
@@ -335,8 +321,7 @@ public function assertStatusCodeRedirect($location = null)
{
$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));
}
}
diff --git a/src/Symfony/Components/OutputEscaper/Escaper.php b/src/Symfony/Components/OutputEscaper/Escaper.php
index 0167abc045ca..e489a6b20231 100644
--- a/src/Symfony/Components/OutputEscaper/Escaper.php
+++ b/src/Symfony/Components/OutputEscaper/Escaper.php
@@ -51,8 +51,7 @@ abstract class Escaper
*/
public function __construct($escaper, $value)
{
- if (null === self::$escapers)
- {
+ if (null === self::$escapers) {
self::initializeEscapers();
}
@@ -90,34 +89,28 @@ public function __construct($escaper, $value)
*/
static public function escape($escaper, $value)
{
- if (null === $value)
- {
+ if (null === $value) {
return $value;
}
- if (null === self::$escapers)
- {
+ if (null === self::$escapers) {
self::initializeEscapers();
}
- if (is_string($escaper) && isset(self::$escapers[$escaper]))
- {
+ if (is_string($escaper) && isset(self::$escapers[$escaper])) {
$escaper = self::$escapers[$escaper];
}
// Scalars are anything other than arrays, objects and resources.
- if (is_scalar($value))
- {
+ if (is_scalar($value)) {
return call_user_func($escaper, $value);
}
- if (is_array($value))
- {
+ if (is_array($value)) {
return new ArrayDecorator($escaper, $value);
}
- if (is_object($value))
- {
+ if (is_object($value)) {
if ($value instanceof Escaper)
{
// avoid double decoration
@@ -128,22 +121,19 @@ static public function escape($escaper, $value)
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
// return the unescaped object
return $value;
}
- if ($value instanceof SafeDecorator)
- {
+ if ($value instanceof SafeDecorator) {
// do not escape objects marked as safe
// return the original object
return $value->getValue();
}
- if ($value instanceof \Traversable)
- {
+ if ($value instanceof \Traversable) {
return new IteratorDecorator($escaper, $value);
}
@@ -166,18 +156,15 @@ static public function escape($escaper, $value)
*/
static public function unescape($value)
{
- if (null === $value || is_bool($value))
- {
+ if (null === $value || is_bool($value)) {
return $value;
}
- if (is_scalar($value))
- {
+ if (is_scalar($value)) {
return html_entity_decode($value, ENT_QUOTES, self::$charset);
}
- if (is_array($value))
- {
+ if (is_array($value)) {
foreach ($value as $name => $v)
{
$value[$name] = self::unescape($v);
@@ -186,8 +173,7 @@ static public function unescape($value)
return $value;
}
- if (is_object($value))
- {
+ if (is_object($value)) {
return $value instanceof Escaper ? $value->getRawValue() : $value;
}
@@ -203,13 +189,11 @@ static public function unescape($value)
*/
static public function isClassMarkedAsSafe($class)
{
- if (in_array($class, self::$safeClasses))
- {
+ if (in_array($class, self::$safeClasses)) {
return true;
}
- foreach (self::$safeClasses as $safeClass)
- {
+ foreach (self::$safeClasses as $safeClass) {
if (is_subclass_of($class, $safeClass))
{
return true;
diff --git a/src/Symfony/Components/OutputEscaper/GetterDecorator.php b/src/Symfony/Components/OutputEscaper/GetterDecorator.php
index 434e48804876..1ab3c24032cf 100644
--- a/src/Symfony/Components/OutputEscaper/GetterDecorator.php
+++ b/src/Symfony/Components/OutputEscaper/GetterDecorator.php
@@ -47,8 +47,7 @@ public abstract function getRaw($key);
*/
public function get($key, $escaper = null)
{
- if (!$escaper)
- {
+ if (!$escaper) {
$escaper = $this->escaper;
}
diff --git a/src/Symfony/Components/OutputEscaper/ObjectDecorator.php b/src/Symfony/Components/OutputEscaper/ObjectDecorator.php
index 3252bc35f8dc..3a8bf6a771c8 100644
--- a/src/Symfony/Components/OutputEscaper/ObjectDecorator.php
+++ b/src/Symfony/Components/OutputEscaper/ObjectDecorator.php
@@ -46,22 +46,16 @@ class ObjectDecorator extends GetterDecorator
*/
public function __call($method, $args)
{
- if (count($args) > 0)
- {
+ if (count($args) > 0) {
$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);
array_pop($args);
- }
- else
- {
+ } else {
$escaper = $this->escaper;
}
- }
- else
- {
+ } else {
$escaper = $this->escaper;
}
@@ -84,8 +78,7 @@ public function __call($method, $args)
*/
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.');
}
diff --git a/src/Symfony/Components/OutputEscaper/SafeDecorator.php b/src/Symfony/Components/OutputEscaper/SafeDecorator.php
index 156cf9472c98..7188f0f4a764 100644
--- a/src/Symfony/Components/OutputEscaper/SafeDecorator.php
+++ b/src/Symfony/Components/OutputEscaper/SafeDecorator.php
@@ -31,8 +31,7 @@ public function __construct($value)
{
$this->value = $value;
- if (is_array($value) || is_object($value))
- {
+ if (is_array($value) || is_object($value)) {
parent::__construct($value);
}
}
diff --git a/src/Symfony/Components/Process/PhpProcess.php b/src/Symfony/Components/Process/PhpProcess.php
index 6921fcfe4c65..5b86d8eb9a4c 100644
--- a/src/Symfony/Components/Process/PhpProcess.php
+++ b/src/Symfony/Components/Process/PhpProcess.php
@@ -52,8 +52,7 @@ public function setPhpBinary($php)
*/
public function run($callback = null)
{
- if (null === $this->commandline)
- {
+ if (null === $this->commandline) {
$this->commandline = $this->getPhpBinary();
}
@@ -69,8 +68,7 @@ public function run($callback = null)
*/
static public function getPhpBinary()
{
- if (getenv('PHP_PATH'))
- {
+ if (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.');
@@ -80,8 +78,7 @@ static public function getPhpBinary()
}
$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))
{
return $php;
diff --git a/src/Symfony/Components/Process/Process.php b/src/Symfony/Components/Process/Process.php
index 54249d660a12..c537122bdad0 100644
--- a/src/Symfony/Components/Process/Process.php
+++ b/src/Symfony/Components/Process/Process.php
@@ -46,16 +46,14 @@ class Process
*/
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.');
}
$this->commandline = $commandline;
$this->cwd = null === $cwd ? getcwd() : $cwd;
$this->env = array();
- foreach ($env as $key => $value)
- {
+ foreach ($env as $key => $value) {
$this->env[(binary) $key] = (binary) $value;
}
$this->stdin = $stdin;
@@ -82,19 +80,15 @@ public function __construct($commandline, $cwd, array $env = array(), $stdin = n
*/
public function run($callback = null)
{
- if (null === $callback)
- {
+ if (null === $callback) {
$this->stdout = '';
$this->stderr = '';
$that = $this;
$callback = function ($type, $line) use ($that)
{
- if ('out' == $type)
- {
+ if ('out' == $type) {
$that->addOutput($line);
- }
- else
- {
+ } else {
$that->addErrorOutput($line);
}
};
@@ -107,62 +101,49 @@ public function run($callback = null)
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
- if (!is_resource($process))
- {
+ if (!is_resource($process)) {
throw new \RuntimeException('Unable to launch a new process.');
}
- if (null !== $this->stdin)
- {
+ if (null !== $this->stdin) {
fwrite($pipes[0], (binary) $this->stdin);
}
fclose($pipes[0]);
- while (true)
- {
+ while (true) {
$r = $pipes;
$w = null;
$e = null;
$n = @stream_select($r, $w, $e, $this->timeout);
- if ($n === false)
- {
+ if ($n === false) {
break;
- }
- elseif ($n === 0)
- {
+ } elseif ($n === 0) {
proc_terminate($process);
throw new \RuntimeException('The process timed out.');
- }
- elseif ($n > 0)
- {
+ } elseif ($n > 0) {
$called = false;
- while (true)
- {
+ while (true) {
$c = false;
- if ($line = (binary) fgets($pipes[1], 1024))
- {
+ if ($line = (binary) fgets($pipes[1], 1024)) {
$called = $c = true;
call_user_func($callback, 'out', $line);
}
- if ($line = fgets($pipes[2], 1024))
- {
+ if ($line = fgets($pipes[2], 1024)) {
$called = $c = true;
call_user_func($callback, 'err', $line);
}
- if (!$c)
- {
+ if (!$c) {
break;
}
}
- if (!$called)
- {
+ if (!$called) {
break;
}
}
@@ -172,8 +153,7 @@ public function run($callback = null)
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']));
}
diff --git a/src/Symfony/Components/Routing/FileResource.php b/src/Symfony/Components/Routing/FileResource.php
index 2f8c80cad0cd..b5afb3316354 100644
--- a/src/Symfony/Components/Routing/FileResource.php
+++ b/src/Symfony/Components/Routing/FileResource.php
@@ -51,8 +51,7 @@ public function getResource()
*/
public function isUptodate($timestamp)
{
- if (!file_exists($this->resource))
- {
+ if (!file_exists($this->resource)) {
return false;
}
diff --git a/src/Symfony/Components/Routing/Generator/Dumper/PhpGeneratorDumper.php b/src/Symfony/Components/Routing/Generator/Dumper/PhpGeneratorDumper.php
index 2d784b354448..ec3d5678caba 100644
--- a/src/Symfony/Components/Routing/Generator/Dumper/PhpGeneratorDumper.php
+++ b/src/Symfony/Components/Routing/Generator/Dumper/PhpGeneratorDumper.php
@@ -53,8 +53,7 @@ protected function addGenerator()
{
$methods = array();
- foreach ($this->routes->getRoutes() as $name => $route)
- {
+ foreach ($this->routes->getRoutes() as $name => $route) {
$compiledRoute = $route->compile();
$variables = str_replace("\n", '', var_export($compiledRoute->getVariables(), true));
@@ -78,8 +77,7 @@ protected function get{$name}RouteInfo()
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));
}
diff --git a/src/Symfony/Components/Routing/Generator/UrlGenerator.php b/src/Symfony/Components/Routing/Generator/UrlGenerator.php
index 40ce7daab7d7..4caa4571a4b4 100644
--- a/src/Symfony/Components/Routing/Generator/UrlGenerator.php
+++ b/src/Symfony/Components/Routing/Generator/UrlGenerator.php
@@ -56,13 +56,11 @@ public function __construct(RouteCollection $routes, array $context = array(), a
*/
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));
}
- if (!isset($this->cache[$name]))
- {
+ if (!isset($this->cache[$name])) {
$this->cache[$name] = $route->compile();
}
@@ -78,60 +76,48 @@ protected function doGenerate($variables, $defaults, $requirements, $tokens, $pa
$tparams = array_merge($defaults, $parameters);
// 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)));
}
$url = '';
$optional = true;
- foreach ($tokens as $token)
- {
+ foreach ($tokens as $token) {
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
- 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]]));
}
$url = $token[1].urlencode($tparams[$token[3]]).$url;
$optional = false;
}
- }
- elseif ('text' === $token[0])
- {
+ } elseif ('text' === $token[0]) {
$url = $token[1].$token[2].$url;
$optional = false;
- }
- else
- {
+ } else {
// 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;
$optional = false;
}
}
}
- if (!$url)
- {
+ if (!$url) {
$url = '/';
}
// 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 = (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;
}
diff --git a/src/Symfony/Components/Routing/Loader/FileLoader.php b/src/Symfony/Components/Routing/Loader/FileLoader.php
index 780f677da463..427256106d3a 100644
--- a/src/Symfony/Components/Routing/Loader/FileLoader.php
+++ b/src/Symfony/Components/Routing/Loader/FileLoader.php
@@ -29,8 +29,7 @@ abstract class FileLoader implements LoaderInterface
*/
public function __construct($paths = array())
{
- if (!is_array($paths))
- {
+ if (!is_array($paths)) {
$paths = array($paths);
}
@@ -43,8 +42,7 @@ public function __construct($paths = array())
protected function findFile($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)));
}
@@ -53,20 +51,14 @@ protected function findFile($file)
protected function getAbsolutePath($file, $currentPath = null)
{
- if (self::isAbsolutePath($file))
- {
+ if (self::isAbsolutePath($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;
- }
- else
- {
+ } else {
foreach ($this->paths as $path)
{
- if (file_exists($path.DIRECTORY_SEPARATOR.$file))
- {
+ if (file_exists($path.DIRECTORY_SEPARATOR.$file)) {
return $path.DIRECTORY_SEPARATOR.$file;
}
}
diff --git a/src/Symfony/Components/Routing/Loader/XmlFileLoader.php b/src/Symfony/Components/Routing/Loader/XmlFileLoader.php
index 29e46e1014a4..f8355226e774 100644
--- a/src/Symfony/Components/Routing/Loader/XmlFileLoader.php
+++ b/src/Symfony/Components/Routing/Loader/XmlFileLoader.php
@@ -43,15 +43,13 @@ public function load($file)
$collection->addResource(new FileResource($path));
// process routes and imports
- foreach ($xml->documentElement->childNodes as $node)
- {
+ foreach ($xml->documentElement->childNodes as $node) {
if (!$node instanceof \DOMElement)
{
continue;
}
- switch ($node->tagName)
- {
+ switch ($node->tagName) {
case 'route':
$this->parseRoute($collection, $node, $path);
break;
@@ -72,15 +70,13 @@ protected function parseRoute(RouteCollection $collection, $definition, $file)
$requirements = array();
$options = array();
- foreach ($definition->childNodes as $node)
- {
+ foreach ($definition->childNodes as $node) {
if (!$node instanceof \DOMElement)
{
continue;
}
- switch ($node->tagName)
- {
+ switch ($node->tagName) {
case 'default':
$defaults[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
@@ -103,15 +99,11 @@ protected function parseRoute(RouteCollection $collection, $definition, $file)
protected function parseImport(RouteCollection $collection, $node, $file)
{
$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');
- }
- else
- {
+ } else {
// 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':
$class = 'Symfony\\Components\\Routing\\Loader\\YamlFileLoader';
break;
@@ -132,8 +124,7 @@ protected function loadFile($path)
{
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
- if (!$dom->load($path, LIBXML_COMPACT))
- {
+ if (!$dom->load($path, LIBXML_COMPACT)) {
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
}
$dom->validateOnParse = true;
@@ -150,8 +141,7 @@ protected function loadFile($path)
protected function validate($dom, $file)
{
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()));
}
libxml_use_internal_errors(false);
@@ -160,8 +150,7 @@ protected function validate($dom, $file)
protected function getXmlErrors()
{
$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)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code,
diff --git a/src/Symfony/Components/Routing/Loader/YamlFileLoader.php b/src/Symfony/Components/Routing/Loader/YamlFileLoader.php
index 964275f3a474..c248a7123859 100644
--- a/src/Symfony/Components/Routing/Loader/YamlFileLoader.php
+++ b/src/Symfony/Components/Routing/Loader/YamlFileLoader.php
@@ -43,18 +43,13 @@ public function load($file)
$collection = new RouteCollection();
$collection->addResource(new FileResource($path));
- foreach ($config as $name => $config)
- {
+ foreach ($config as $name => $config) {
if (isset($config['resource']))
{
$this->parseImport($collection, $name, $config, $path);
- }
- elseif (isset($config['pattern']))
- {
+ } elseif (isset($config['pattern'])) {
$this->parseRoute($collection, $name, $config, $path);
- }
- else
- {
+ } else {
throw new \InvalidArgumentException(sprintf('Unable to parse the "%s" route.', $name));
}
}
@@ -71,8 +66,7 @@ protected function parseRoute(RouteCollection $collection, $name, $config, $file
$requirements = isset($config['requirements']) ? $config['requirements'] : 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));
}
@@ -86,21 +80,16 @@ protected function parseRoute(RouteCollection $collection, $name, $config, $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));
}
$class = null;
- if (isset($import['class']) && $import['class'] !== get_class($this))
- {
+ if (isset($import['class']) && $import['class'] !== get_class($this)) {
$class = $import['class'];
- }
- else
- {
+ } else {
// try to detect loader with the extension
- switch (pathinfo($import['resource'], PATHINFO_EXTENSION))
- {
+ switch (pathinfo($import['resource'], PATHINFO_EXTENSION)) {
case 'xml':
$class = 'Symfony\\Components\\Routing\\Loader\\XmlFileLoader';
break;
diff --git a/src/Symfony/Components/Routing/Matcher/ApacheUrlMatcher.php b/src/Symfony/Components/Routing/Matcher/ApacheUrlMatcher.php
index 9e8310f01986..5f2522abdc7d 100644
--- a/src/Symfony/Components/Routing/Matcher/ApacheUrlMatcher.php
+++ b/src/Symfony/Components/Routing/Matcher/ApacheUrlMatcher.php
@@ -49,15 +49,13 @@ public function __construct(array $context = array(), array $defaults = array())
*/
public function match($url)
{
- if (!isset($_SERVER['_ROUTING__route']))
- {
+ if (!isset($_SERVER['_ROUTING__route'])) {
// fall-back to the default UrlMatcher
return parent::match($url);
}
$parameters = array();
- foreach ($_SERVER as $key => $value)
- {
+ foreach ($_SERVER as $key => $value) {
if ('_ROUTING_' === substr($key, 0, 9))
{
$parameters[substr($key, 9)] = $value;
diff --git a/src/Symfony/Components/Routing/Matcher/Dumper/ApacheMatcherDumper.php b/src/Symfony/Components/Routing/Matcher/Dumper/ApacheMatcherDumper.php
index cb370d8f848f..d1579280a0a7 100644
--- a/src/Symfony/Components/Routing/Matcher/Dumper/ApacheMatcherDumper.php
+++ b/src/Symfony/Components/Routing/Matcher/Dumper/ApacheMatcherDumper.php
@@ -43,32 +43,27 @@ public function dump(array $options = array())
$regexes = array();
- foreach ($this->routes->getRoutes() as $name => $route)
- {
+ foreach ($this->routes->getRoutes() as $name => $route) {
$compiledRoute = $route->compile();
// 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));
}
$regex = preg_replace('/\?P<.+?>/', '', substr($compiledRoute->getRegex(), 1, -2));
$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);
}
- foreach ($route->getDefaults() as $key => $value)
- {
+ foreach ($route->getDefaults() as $key => $value) {
$variables[] = 'E=_ROUTING_'.$key.':'.$value;
}
$variables = implode(',', $variables);
$conditions = array();
- foreach ((array) $route->getRequirement('_method') as $method)
- {
+ foreach ((array) $route->getRequirement('_method') as $method) {
$conditions[] = sprintf('RewriteCond %%{REQUEST_METHOD} =%s', strtoupper($method));
}
diff --git a/src/Symfony/Components/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Components/Routing/Matcher/Dumper/PhpMatcherDumper.php
index 2a826d2faf4d..eef2d87bbba2 100644
--- a/src/Symfony/Components/Routing/Matcher/Dumper/PhpMatcherDumper.php
+++ b/src/Symfony/Components/Routing/Matcher/Dumper/PhpMatcherDumper.php
@@ -53,21 +53,18 @@ protected function addMatcher()
{
$code = array();
- foreach ($this->routes->getRoutes() as $name => $route)
- {
+ foreach ($this->routes->getRoutes() as $name => $route) {
$compiledRoute = $route->compile();
$conditions = array();
- if ($req = $route->getRequirement('_method'))
- {
+ if ($req = $route->getRequirement('_method')) {
$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)));
}
- if ($compiledRoute->getStaticPrefix())
- {
+ if ($compiledRoute->getStaticPrefix()) {
$conditions[] = sprintf("0 === strpos(\$url, '%s')", $compiledRoute->getStaticPrefix());
}
diff --git a/src/Symfony/Components/Routing/Matcher/UrlMatcher.php b/src/Symfony/Components/Routing/Matcher/UrlMatcher.php
index 3aacccec7406..3d61adbdc0a3 100644
--- a/src/Symfony/Components/Routing/Matcher/UrlMatcher.php
+++ b/src/Symfony/Components/Routing/Matcher/UrlMatcher.php
@@ -54,24 +54,20 @@ public function match($url)
{
$url = $this->normalizeUrl($url);
- foreach ($this->routes->getRoutes() as $name => $route)
- {
+ foreach ($this->routes->getRoutes() as $name => $route) {
$compiledRoute = $route->compile();
// 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;
}
// 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;
}
- if (!preg_match($compiledRoute->getRegex(), $url, $matches))
- {
+ if (!preg_match($compiledRoute->getRegex(), $url, $matches)) {
continue;
}
@@ -84,8 +80,7 @@ public function match($url)
protected function mergeDefaults($params, $defaults)
{
$parameters = array_merge($this->defaults, $defaults);
- foreach ($params as $key => $value)
- {
+ foreach ($params as $key => $value) {
if (!is_int($key))
{
$parameters[$key] = urldecode($value);
@@ -98,14 +93,12 @@ protected function mergeDefaults($params, $defaults)
protected function normalizeUrl($url)
{
// ensure that the URL starts with a /
- if ('/' !== substr($url, 0, 1))
- {
+ if ('/' !== substr($url, 0, 1)) {
$url = '/'.$url;
}
// remove the query string
- if (false !== $pos = strpos($url, '?'))
- {
+ if (false !== $pos = strpos($url, '?')) {
$url = substr($url, 0, $pos);
}
diff --git a/src/Symfony/Components/Routing/Route.php b/src/Symfony/Components/Routing/Route.php
index 7777ab73de46..4508271562c2 100644
--- a/src/Symfony/Components/Routing/Route.php
+++ b/src/Symfony/Components/Routing/Route.php
@@ -76,8 +76,7 @@ public function setPattern($pattern)
$this->pattern = trim($pattern);
// 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;
}
@@ -188,15 +187,13 @@ public function getRequirements()
public function setRequirements(array $requirements)
{
$this->requirements = array();
- foreach ($requirements as $key => $regex)
- {
+ foreach ($requirements as $key => $regex) {
if ('^' == $regex[0])
{
$regex = substr($regex, 1);
}
- if ('$' == substr($regex, -1))
- {
+ if ('$' == substr($regex, -1)) {
$regex = substr($regex, 0, -1);
}
@@ -223,15 +220,13 @@ public function getRequirement($key)
*/
public function compile()
{
- if (null !== $this->compiled)
- {
+ if (null !== $this->compiled) {
return $this->compiled;
}
$class = $this->getOption('compiler_class');
- if (!isset(static::$compilers[$class]))
- {
+ if (!isset(static::$compilers[$class])) {
static::$compilers[$class] = new $class;
}
diff --git a/src/Symfony/Components/Routing/RouteCollection.php b/src/Symfony/Components/Routing/RouteCollection.php
index 9576ecafec7e..3299f4807cb5 100644
--- a/src/Symfony/Components/Routing/RouteCollection.php
+++ b/src/Symfony/Components/Routing/RouteCollection.php
@@ -42,8 +42,7 @@ public function __construct()
*/
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));
}
@@ -82,8 +81,7 @@ public function addCollection(RouteCollection $collection, $prefix = '')
{
$collection->addPrefix($prefix);
- foreach ($collection->getResources() as $resource)
- {
+ foreach ($collection->getResources() as $resource) {
$this->addResource($resource);
}
@@ -97,13 +95,11 @@ public function addCollection(RouteCollection $collection, $prefix = '')
*/
public function addPrefix($prefix)
{
- if (!$prefix)
- {
+ if (!$prefix) {
return;
}
- foreach ($this->getRoutes() as $route)
- {
+ foreach ($this->getRoutes() as $route) {
$route->setPattern($prefix.$route->getPattern());
}
}
diff --git a/src/Symfony/Components/Routing/RouteCompiler.php b/src/Symfony/Components/Routing/RouteCompiler.php
index c38780564135..3924642887f3 100644
--- a/src/Symfony/Components/Routing/RouteCompiler.php
+++ b/src/Symfony/Components/Routing/RouteCompiler.php
@@ -51,16 +51,14 @@ public function compile(Route $route)
$this->tokenize();
- foreach ($this->tokens as $token)
- {
+ foreach ($this->tokens as $token) {
call_user_func_array(array($this, 'compileFor'.ucfirst(array_shift($token))), $token);
}
$this->postCompile();
$separator = '';
- if (count($this->tokens))
- {
+ if (count($this->tokens)) {
$lastToken = $this->tokens[count($this->tokens) - 1];
$separator = 'separator' == $lastToken[0] ? $lastToken[2] : '';
}
@@ -69,15 +67,12 @@ public function compile(Route $route)
// optimize tokens for generation
$tokens = array();
- foreach ($this->tokens as $i => $token)
- {
+ foreach ($this->tokens as $i => $token) {
if ($i + 1 === count($this->tokens) && 'separator' === $token[0])
{
// trailing /
$tokens[] = array('text', $token[2], '', null);
- }
- elseif ('separator' !== $token[0])
- {
+ } elseif ('separator' !== $token[0]) {
$tokens[] = $token;
}
}
@@ -101,15 +96,13 @@ protected function postCompile()
{
// all segments after the last static segment are optional
// 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[] = str_repeat(' ', $max - $i - 1).')?';
}
$this->staticPrefix = '';
- foreach ($this->tokens as $token)
- {
+ foreach ($this->tokens as $token) {
switch ($token[0])
{
case 'separator':
@@ -138,47 +131,36 @@ protected function tokenize()
$currentSeparator = '';
// 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))
{
// a custom token
$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
$this->tokens[] = array('variable', $currentSeparator, $match[0], $match[1]);
$currentSeparator = '';
$buffer = substr($buffer, strlen($match[0]));
$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
$this->tokens[] = array('text', $currentSeparator, $match[1], null);
$currentSeparator = '';
$buffer = substr($buffer, strlen($match[1]));
$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
$this->tokens[] = array('separator', $currentSeparator, $match[0], null);
$currentSeparator = $match[0];
$buffer = substr($buffer, strlen($match[0]));
$afterASeparator = true;
- }
- else if (false !== $this->tokenizeBufferAfter($buffer, $tokens, $afterASeparator, $currentSeparator))
- {
+ } else if (false !== $this->tokenizeBufferAfter($buffer, $tokens, $afterASeparator, $currentSeparator)) {
// a custom token
$this->customToken = true;
- }
- else
- {
+ } else {
// parsing problem
throw new \InvalidArgumentException(sprintf('Unable to parse "%s" route near "%s".', $this->route->getPattern(), $buffer));
}
@@ -228,16 +210,14 @@ protected function compileForText($separator, $text)
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'];
}
$this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$requirement.')';
$this->variables[$variable] = $name;
- if (!$this->route->getDefault($variable))
- {
+ if (!$this->route->getDefault($variable)) {
$this->firstOptional = count($this->segments);
}
}
diff --git a/src/Symfony/Components/Routing/Router.php b/src/Symfony/Components/Routing/Router.php
index 7426aa368714..2908f583dc69 100644
--- a/src/Symfony/Components/Routing/Router.php
+++ b/src/Symfony/Components/Routing/Router.php
@@ -63,8 +63,7 @@ public function __construct($loader, array $options = array(), array $context =
);
// 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)));
}
@@ -78,8 +77,7 @@ public function __construct($loader, array $options = array(), array $context =
*/
public function getRouteCollection()
{
- if (null === $this->collection)
- {
+ if (null === $this->collection) {
$this->collection = call_user_func($this->loader);
}
@@ -141,19 +139,16 @@ public function match($url)
*/
public function getMatcher()
{
- if (null !== $this->matcher)
- {
+ if (null !== $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);
}
$class = $this->options['matcher_cache_class'];
- if ($this->needsReload($class))
- {
+ if ($this->needsReload($class)) {
$dumper = new $this->options['matcher_dumper_class']($this->getRouteCollection());
$options = array(
@@ -176,19 +171,16 @@ public function getMatcher()
*/
public function getGenerator()
{
- if (null !== $this->generator)
- {
+ if (null !== $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);
}
$class = $this->options['generator_cache_class'];
- if ($this->needsReload($class))
- {
+ if ($this->needsReload($class)) {
$dumper = new $this->options['generator_dumper_class']($this->getRouteCollection());
$options = array(
@@ -208,8 +200,7 @@ protected function updateCache($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()));
}
}
@@ -217,26 +208,22 @@ protected function updateCache($class, $dump)
protected function needsReload($class)
{
$file = $this->getCacheFile($class);
- if (!file_exists($file))
- {
+ if (!file_exists($file)) {
return true;
}
- if (!$this->options['debug'])
- {
+ if (!$this->options['debug']) {
return false;
}
$metadata = $this->getCacheFile($class, 'meta');
- if (!file_exists($metadata))
- {
+ if (!file_exists($metadata)) {
return true;
}
$time = filemtime($file);
$meta = unserialize(file_get_contents($metadata));
- foreach ($meta as $resource)
- {
+ foreach ($meta as $resource) {
if (!$resource->isUptodate($time))
{
return true;
@@ -257,16 +244,14 @@ protected function getCacheFile($class, $extension = 'php')
protected function writeCacheFile($file, $content)
{
$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));
}
@fwrite($fp, $content);
@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));
}
diff --git a/src/Symfony/Components/Templating/Engine.php b/src/Symfony/Components/Templating/Engine.php
index a0b6067ceb06..d32d66b9c4a5 100644
--- a/src/Symfony/Components/Templating/Engine.php
+++ b/src/Symfony/Components/Templating/Engine.php
@@ -53,13 +53,11 @@ public function __construct(LoaderInterface $loader, array $renderers = array(),
$this->addHelpers($helpers);
- if (!isset($this->renderers['php']))
- {
+ if (!isset($this->renderers['php'])) {
$this->renderers['php'] = new PhpRenderer();
}
- foreach ($this->renderers as $renderer)
- {
+ foreach ($this->renderers as $renderer) {
$renderer->setEngine($this);
}
}
@@ -83,19 +81,15 @@ public function __construct(LoaderInterface $loader, array $renderers = 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];
- }
- else
- {
+ } else {
list($name, $options) = $this->splitTemplateName($old = $name);
// load
$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']));
}
@@ -108,20 +102,17 @@ public function render($name, array $parameters = array())
// 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));
}
// 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));
}
// decorator
- if ($this->parents[$name])
- {
+ if ($this->parents[$name]) {
$slots = $this->get('slots');
$this->stack[] = $slots->get('_content');
$slots->set('_content', $content);
@@ -166,8 +157,7 @@ public function __get($name)
*/
public function addHelpers(array $helpers = array())
{
- foreach ($helpers as $alias => $helper)
- {
+ foreach ($helpers as $alias => $helper) {
$this->set($helper, is_int($alias) ? null : $alias);
}
}
@@ -181,8 +171,7 @@ public function addHelpers(array $helpers = array())
public function set(HelperInterface $helper, $alias = null)
{
$this->helpers[$helper->getName()] = $helper;
- if (null !== $alias)
- {
+ if (null !== $alias) {
$this->helpers[$alias] = $helper;
}
@@ -212,8 +201,7 @@ public function has($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));
}
@@ -286,13 +274,10 @@ public function setRenderer($name, RendererInterface $renderer)
protected function splitTemplateName($name)
{
- if (false !== $pos = strpos($name, ':'))
- {
+ if (false !== $pos = strpos($name, ':')) {
$renderer = substr($name, $pos + 1);
$name = substr($name, 0, $pos);
- }
- else
- {
+ } else {
$renderer = 'php';
}
diff --git a/src/Symfony/Components/Templating/Helper/AssetsHelper.php b/src/Symfony/Components/Templating/Helper/AssetsHelper.php
index 9a8fa0b8c223..97b946343168 100644
--- a/src/Symfony/Components/Templating/Helper/AssetsHelper.php
+++ b/src/Symfony/Components/Templating/Helper/AssetsHelper.php
@@ -81,8 +81,7 @@ public function getBasePath()
*/
public function setBasePath($basePath)
{
- if (strlen($basePath) && '/' != $basePath[0])
- {
+ if (strlen($basePath) && '/' != $basePath[0]) {
$basePath = '/'.$basePath;
}
@@ -100,13 +99,11 @@ public function getBaseURL($path)
{
$count = count($this->baseURLs);
- if (0 === $count)
- {
+ if (0 === $count) {
return '';
}
- if (1 === $count)
- {
+ if (1 === $count) {
return $this->baseURLs[0];
}
@@ -134,14 +131,12 @@ public function getBaseURLs()
*/
public function setBaseURLs($baseURLs)
{
- if (!is_array($baseURLs))
- {
+ if (!is_array($baseURLs)) {
$baseURLs = array($baseURLs);
}
$this->baseURLs = array();
- foreach ($baseURLs as $URL)
- {
+ foreach ($baseURLs as $URL) {
$this->baseURLs[] = rtrim($URL, '/');
}
}
@@ -155,13 +150,11 @@ public function setBaseURLs($baseURLs)
*/
public function getUrl($path)
{
- if (strpos($path, '://'))
- {
+ if (strpos($path, '://')) {
return $path;
}
- if (0 !== strpos($path, '/'))
- {
+ if (0 !== strpos($path, '/')) {
$path = $this->basePath.$path;
}
diff --git a/src/Symfony/Components/Templating/Helper/JavascriptsHelper.php b/src/Symfony/Components/Templating/Helper/JavascriptsHelper.php
index 7838b8d6cdb6..2bff3a882e92 100644
--- a/src/Symfony/Components/Templating/Helper/JavascriptsHelper.php
+++ b/src/Symfony/Components/Templating/Helper/JavascriptsHelper.php
@@ -69,11 +69,9 @@ public function get()
public function render()
{
$html = '';
- foreach ($this->javascripts as $path => $attributes)
- {
+ foreach ($this->javascripts as $path => $attributes) {
$atts = '';
- foreach ($attributes as $key => $value)
- {
+ foreach ($attributes as $key => $value) {
$atts .= ' '.sprintf('%s="%s"', $key, htmlspecialchars($value, ENT_QUOTES, $this->charset));
}
diff --git a/src/Symfony/Components/Templating/Helper/SlotsHelper.php b/src/Symfony/Components/Templating/Helper/SlotsHelper.php
index a186ad6549f1..e10f6fbcacc3 100644
--- a/src/Symfony/Components/Templating/Helper/SlotsHelper.php
+++ b/src/Symfony/Components/Templating/Helper/SlotsHelper.php
@@ -35,8 +35,7 @@ class SlotsHelper extends Helper
*/
public function start($name)
{
- if (in_array($name, $this->openSlots))
- {
+ if (in_array($name, $this->openSlots)) {
throw new \InvalidArgumentException(sprintf('A slot named "%s" is already started.', $name));
}
@@ -56,8 +55,7 @@ public function stop()
{
$content = ob_get_clean();
- if (!$this->openSlots)
- {
+ if (!$this->openSlots) {
throw new \LogicException('No slot started.');
}
@@ -110,8 +108,7 @@ public function set($name, $content)
*/
public function output($name, $default = false)
{
- if (!isset($this->slots[$name]))
- {
+ if (!isset($this->slots[$name])) {
if (false !== $default)
{
echo $default;
diff --git a/src/Symfony/Components/Templating/Helper/StylesheetsHelper.php b/src/Symfony/Components/Templating/Helper/StylesheetsHelper.php
index c19c9e92ab42..10f3eab18127 100644
--- a/src/Symfony/Components/Templating/Helper/StylesheetsHelper.php
+++ b/src/Symfony/Components/Templating/Helper/StylesheetsHelper.php
@@ -69,11 +69,9 @@ public function get()
public function render()
{
$html = '';
- foreach ($this->stylesheets as $path => $attributes)
- {
+ foreach ($this->stylesheets as $path => $attributes) {
$atts = '';
- foreach ($attributes as $key => $value)
- {
+ foreach ($attributes as $key => $value) {
$atts .= ' '.sprintf('%s="%s"', $key, htmlspecialchars($value, ENT_QUOTES, $this->charset));
}
diff --git a/src/Symfony/Components/Templating/Loader/CacheLoader.php b/src/Symfony/Components/Templating/Loader/CacheLoader.php
index 155912320c7e..91989472c10c 100644
--- a/src/Symfony/Components/Templating/Loader/CacheLoader.php
+++ b/src/Symfony/Components/Templating/Loader/CacheLoader.php
@@ -61,13 +61,11 @@ public function load($template, array $options = array())
$file = substr($tmp, 2);
$path = $dir.DIRECTORY_SEPARATOR.$file;
- if ($this->loader instanceof CompilableLoaderInterface)
- {
+ if ($this->loader instanceof CompilableLoaderInterface) {
$options['renderer'] = 'php';
}
- if (file_exists($path))
- {
+ if (file_exists($path)) {
if (null !== $this->debugger)
{
$this->debugger->log(sprintf('Fetching template "%s" from cache', $template));
@@ -76,27 +74,23 @@ public function load($template, array $options = array())
return new FileStorage($path, $options['renderer']);
}
- if (false === $storage = $this->loader->load($template, $options))
- {
+ if (false === $storage = $this->loader->load($template, $options)) {
return false;
}
$content = $storage->getContent();
- if ($this->loader instanceof CompilableLoaderInterface)
- {
+ if ($this->loader instanceof CompilableLoaderInterface) {
$content = $this->loader->compile($content);
}
- if (!file_exists($dir))
- {
+ if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($path, $content);
- if (null !== $this->debugger)
- {
+ if (null !== $this->debugger) {
$this->debugger->log(sprintf('Storing template "%s" in cache', $template));
}
diff --git a/src/Symfony/Components/Templating/Loader/ChainLoader.php b/src/Symfony/Components/Templating/Loader/ChainLoader.php
index eab0b933e85e..7dd3948d1248 100644
--- a/src/Symfony/Components/Templating/Loader/ChainLoader.php
+++ b/src/Symfony/Components/Templating/Loader/ChainLoader.php
@@ -32,8 +32,7 @@ class ChainLoader extends Loader
public function __construct(array $loaders = array())
{
$this->loaders = array();
- foreach ($loaders as $loader)
- {
+ foreach ($loaders as $loader) {
$this->addLoader($loader);
}
@@ -60,8 +59,7 @@ public function addLoader(Loader $loader)
*/
public function load($template, array $options = array())
{
- foreach ($this->loaders as $loader)
- {
+ foreach ($this->loaders as $loader) {
if (false !== $ret = $loader->load($template, $options))
{
return $ret;
diff --git a/src/Symfony/Components/Templating/Loader/FilesystemLoader.php b/src/Symfony/Components/Templating/Loader/FilesystemLoader.php
index b4c9cfec22c2..a1e29d274c86 100644
--- a/src/Symfony/Components/Templating/Loader/FilesystemLoader.php
+++ b/src/Symfony/Components/Templating/Loader/FilesystemLoader.php
@@ -32,8 +32,7 @@ class FilesystemLoader extends Loader
*/
public function __construct($templatePathPatterns)
{
- if (!is_array($templatePathPatterns))
- {
+ if (!is_array($templatePathPatterns)) {
$templatePathPatterns = array($templatePathPatterns);
}
@@ -52,8 +51,7 @@ public function __construct($templatePathPatterns)
*/
public function load($template, array $options = array())
{
- if (self::isAbsolutePath($template) && file_exists($template))
- {
+ if (self::isAbsolutePath($template) && file_exists($template)) {
return new FileStorage($template);
}
@@ -61,32 +59,27 @@ public function load($template, array $options = array())
$options['name'] = $template;
$replacements = array();
- foreach ($options as $key => $value)
- {
+ foreach ($options as $key => $value) {
$replacements['%'.$key.'%'] = $value;
}
$logs = array();
- foreach ($this->templatePathPatterns as $templatePathPattern)
- {
+ foreach ($this->templatePathPatterns as $templatePathPattern) {
if (is_file($file = strtr($templatePathPattern, $replacements)))
{
- if (null !== $this->debugger)
- {
+ if (null !== $this->debugger) {
$this->debugger->log(sprintf('Loaded template file "%s" (renderer: %s)', $file, $options['renderer']));
}
return new FileStorage($file);
}
- if (null !== $this->debugger)
- {
+ if (null !== $this->debugger) {
$logs[] = sprintf('Failed loading template file "%s" (renderer: %s)', $file, $options['renderer']);
}
}
- if (null !== $this->debugger)
- {
+ if (null !== $this->debugger) {
foreach ($logs as $log)
{
$this->debugger->log($log);
diff --git a/src/Symfony/Components/Templating/Renderer/PhpRenderer.php b/src/Symfony/Components/Templating/Renderer/PhpRenderer.php
index da881636ebd7..3e83c4708fc0 100644
--- a/src/Symfony/Components/Templating/Renderer/PhpRenderer.php
+++ b/src/Symfony/Components/Templating/Renderer/PhpRenderer.php
@@ -34,17 +34,14 @@ class PhpRenderer extends Renderer
*/
public function evaluate(Storage $template, array $parameters = array())
{
- if ($template instanceof FileStorage)
- {
+ if ($template instanceof FileStorage) {
extract($parameters);
$view = $this->engine;
ob_start();
require $template;
return ob_get_clean();
- }
- else if ($template instanceof StringStorage)
- {
+ } else if ($template instanceof StringStorage) {
extract($parameters);
$view = $this->engine;
ob_start();
diff --git a/src/Symfony/Components/Yaml/Dumper.php b/src/Symfony/Components/Yaml/Dumper.php
index 3fcd390b1384..ab44f7a444fd 100644
--- a/src/Symfony/Components/Yaml/Dumper.php
+++ b/src/Symfony/Components/Yaml/Dumper.php
@@ -33,16 +33,12 @@ public function dump($input, $inline = 0, $indent = 0)
$output = '';
$prefix = $indent ? str_repeat(' ', $indent) : '';
- if ($inline <= 0 || !is_array($input) || empty($input))
- {
+ if ($inline <= 0 || !is_array($input) || empty($input)) {
$output .= $prefix.Inline::dump($input);
- }
- else
- {
+ } else {
$isAHash = array_keys($input) !== range(0, count($input) - 1);
- foreach ($input as $key => $value)
- {
+ foreach ($input as $key => $value) {
$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
$output .= sprintf('%s%s%s%s',
diff --git a/src/Symfony/Components/Yaml/Inline.php b/src/Symfony/Components/Yaml/Inline.php
index 10d99cd1c165..f1a2f5f41a99 100644
--- a/src/Symfony/Components/Yaml/Inline.php
+++ b/src/Symfony/Components/Yaml/Inline.php
@@ -32,19 +32,16 @@ static public function load($value)
{
$value = trim($value);
- if (0 == strlen($value))
- {
+ if (0 == strlen($value)) {
return '';
}
- 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();
mb_internal_encoding('ASCII');
}
- switch ($value[0])
- {
+ switch ($value[0]) {
case '[':
$result = self::parseSequence($value);
break;
@@ -55,8 +52,7 @@ static public function load($value)
$result = self::parseScalar($value);
}
- if (isset($mbEncoding))
- {
+ if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
@@ -77,8 +73,7 @@ static public function dump($value)
$trueValues = '1.1' == Yaml::getSpecVersion() ? array('true', 'on', '+', 'yes', 'y') : array('true');
$falseValues = '1.1' == Yaml::getSpecVersion() ? array('false', 'off', '-', 'no', 'n') : array('false');
- switch (true)
- {
+ switch (true) {
case is_resource($value):
throw new Exception('Unable to dump PHP resources in a YAML file.');
case is_object($value):
@@ -131,8 +126,7 @@ static protected function dumpArray($value)
(count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (integer) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2))
{
$output = array();
- foreach ($value as $val)
- {
+ foreach ($value as $val) {
$output[] = self::dump($val);
}
@@ -141,8 +135,7 @@ static protected function dumpArray($value)
// mapping
$output = array();
- foreach ($value as $key => $val)
- {
+ foreach ($value as $key => $val) {
$output[] = sprintf('%s: %s', self::dump($key), self::dump($val));
}
@@ -164,32 +157,23 @@ static protected function dumpArray($value)
*/
static public function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true)
{
- if (in_array($scalar[$i], $stringDelimiters))
- {
+ if (in_array($scalar[$i], $stringDelimiters)) {
// quoted scalar
$output = self::parseQuotedScalar($scalar, $i);
- }
- else
- {
+ } else {
// "normal" string
- if (!$delimiters)
- {
+ if (!$delimiters) {
$output = substr($scalar, $i);
$i += strlen($output);
// remove comments
- if (false !== $strpos = strpos($output, ' #'))
- {
+ if (false !== $strpos = strpos($output, ' #')) {
$output = rtrim(substr($output, 0, $strpos));
}
- }
- else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match))
- {
+ } else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
$output = $match[1];
$i += strlen($output);
- }
- else
- {
+ } else {
throw new ParserException(sprintf('Malformed inline YAML string (%s).', $scalar));
}
@@ -211,20 +195,16 @@ static public function parseScalar($scalar, $delimiters = null, $stringDelimiter
*/
static protected function parseQuotedScalar($scalar, &$i)
{
- if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/A', substr($scalar, $i), $match))
- {
+ if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/A', substr($scalar, $i), $match)) {
throw new ParserException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
}
$output = substr($match[0], 1, strlen($match[0]) - 2);
- if ('"' == $scalar[$i])
- {
+ if ('"' == $scalar[$i]) {
// evaluate the string
$output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output);
- }
- else
- {
+ } else {
// unescape '
$output = str_replace('\'\'', '\'', $output);
}
@@ -251,8 +231,7 @@ static protected function parseSequence($sequence, &$i = 0)
$i += 1;
// [foo, bar, ...]
- while ($i < $len)
- {
+ while ($i < $len) {
switch ($sequence[$i])
{
case '[':
@@ -272,15 +251,11 @@ static protected function parseSequence($sequence, &$i = 0)
$isQuoted = in_array($sequence[$i], array('"', "'"));
$value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i);
- if (!$isQuoted && false !== strpos($value, ': '))
- {
+ if (!$isQuoted && false !== strpos($value, ': ')) {
// embedded mapping?
- try
- {
+ try {
$value = self::parseMapping('{'.$value.'}');
- }
- catch (\InvalidArgumentException $e)
- {
+ } catch (\InvalidArgumentException $e) {
// no, it's not
}
}
@@ -313,8 +288,7 @@ static protected function parseMapping($mapping, &$i = 0)
$i += 1;
// {foo: bar, bar:foo, ...}
- while ($i < $len)
- {
+ while ($i < $len) {
switch ($mapping[$i])
{
case ' ':
@@ -330,8 +304,7 @@ static protected function parseMapping($mapping, &$i = 0)
// value
$done = false;
- while ($i < $len)
- {
+ while ($i < $len) {
switch ($mapping[$i])
{
case '[':
@@ -355,8 +328,7 @@ static protected function parseMapping($mapping, &$i = 0)
++$i;
- if ($done)
- {
+ if ($done) {
continue 2;
}
}
@@ -379,8 +351,7 @@ static protected function evaluateScalar($scalar)
$trueValues = '1.1' == Yaml::getSpecVersion() ? array('true', 'on', '+', 'yes', 'y') : array('true');
$falseValues = '1.1' == Yaml::getSpecVersion() ? array('false', 'off', '-', 'no', 'n') : array('false');
- switch (true)
- {
+ switch (true) {
case 'null' == strtolower($scalar):
case '' == $scalar:
case '~' == $scalar:
diff --git a/src/Symfony/Components/Yaml/Parser.php b/src/Symfony/Components/Yaml/Parser.php
index b4fc9f200da1..66b20af57ead 100644
--- a/src/Symfony/Components/Yaml/Parser.php
+++ b/src/Symfony/Components/Yaml/Parser.php
@@ -50,29 +50,25 @@ public function parse($value)
$this->currentLine = '';
$this->lines = explode("\n", $this->cleanup($value));
- 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();
mb_internal_encoding('ASCII');
}
$data = array();
- while ($this->moveToNextLine())
- {
+ while ($this->moveToNextLine()) {
if ($this->isCurrentLineEmpty())
{
continue;
}
// tab?
- if (preg_match('#^\t+#', $this->currentLine))
- {
+ if (preg_match('#^\t+#', $this->currentLine)) {
throw new ParserException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
}
$isRef = $isInPlace = $isProcessed = false;
- if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#', $this->currentLine, $values))
- {
+ if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#', $this->currentLine, $values)) {
if (isset($values['value']) && preg_match('#^&(?P[[^ ]+) *(?P.*)#', $values['value'], $matches))
{
$isRef = $matches['ref'];
@@ -80,15 +76,12 @@ public function parse($value)
}
// array
- if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
- {
+ if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
$c = $this->getRealCurrentLineNb() + 1;
$parser = new Parser($c);
$parser->refs =& $this->refs;
$data[] = $parser->parse($this->getNextEmbedBlock());
- }
- else
- {
+ } else {
if (isset($values['leadspaces'])
&& ' ' == $values['leadspaces']
&& preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#', $values['value'], $matches))
@@ -99,41 +92,30 @@ public function parse($value)
$parser->refs =& $this->refs;
$block = $values['value'];
- if (!$this->isNextLineIndented())
- {
+ if (!$this->isNextLineIndented()) {
$block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2);
}
$data[] = $parser->parse($block);
- }
- else
- {
+ } else {
$data[] = $this->parseValue($values['value']);
}
}
- }
- else if (preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#', $this->currentLine, $values))
- {
+ } else if (preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#', $this->currentLine, $values)) {
$key = Inline::parseScalar($values['key']);
- if ('<<' === $key)
- {
+ if ('<<' === $key) {
if (isset($values['value']) && '*' === substr($values['value'], 0, 1))
{
$isInPlace = substr($values['value'], 1);
- if (!array_key_exists($isInPlace, $this->refs))
- {
+ if (!array_key_exists($isInPlace, $this->refs)) {
throw new ParserException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine));
}
- }
- else
- {
+ } else {
if (isset($values['value']) && $values['value'] !== '')
{
$value = $values['value'];
- }
- else
- {
+ } else {
$value = $this->getNextEmbedBlock();
}
$c = $this->getRealCurrentLineNb() + 1;
@@ -142,100 +124,75 @@ public function parse($value)
$parsed = $parser->parse($value);
$merged = array();
- if (!is_array($parsed))
- {
+ if (!is_array($parsed)) {
throw new ParserException(sprintf('YAML merge keys used with a scalar value instead of an array at line %s (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
- }
- else if (isset($parsed[0]))
- {
+ } else if (isset($parsed[0])) {
// Numeric array, merge individual elements
- foreach (array_reverse($parsed) as $parsedItem)
- {
+ foreach (array_reverse($parsed) as $parsedItem) {
if (!is_array($parsedItem))
{
throw new ParserException(sprintf('Merge items must be arrays at line %s (%s).', $this->getRealCurrentLineNb() + 1, $parsedItem));
}
$merged = array_merge($parsedItem, $merged);
}
- }
- else
- {
+ } else {
// Associative array, merge
$merged = array_merge($merge, $parsed);
}
$isProcessed = $merged;
}
- }
- else if (isset($values['value']) && preg_match('#^&(?P][[^ ]+) *(?P.*)#', $values['value'], $matches))
- {
+ } else if (isset($values['value']) && preg_match('#^&(?P][[^ ]+) *(?P.*)#', $values['value'], $matches)) {
$isRef = $matches['ref'];
$values['value'] = $matches['value'];
}
- if ($isProcessed)
- {
+ if ($isProcessed) {
// Merge keys
$data = $isProcessed;
}
// hash
- else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
- {
+ else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
// if next line is less indented or equal, then it means that the current value is null
- if ($this->isNextLineIndented())
- {
+ if ($this->isNextLineIndented()) {
$data[$key] = null;
- }
- else
- {
+ } else {
$c = $this->getRealCurrentLineNb() + 1;
$parser = new Parser($c);
$parser->refs =& $this->refs;
$data[$key] = $parser->parse($this->getNextEmbedBlock());
}
- }
- else
- {
+ } else {
if ($isInPlace)
{
$data = $this->refs[$isInPlace];
- }
- else
- {
+ } else {
$data[$key] = $this->parseValue($values['value']);
}
}
- }
- else
- {
+ } else {
// 1-liner followed by newline
- if (2 == count($this->lines) && empty($this->lines[1]))
- {
+ if (2 == count($this->lines) && empty($this->lines[1])) {
$value = Inline::load($this->lines[0]);
- if (is_array($value))
- {
+ if (is_array($value)) {
$first = reset($value);
- if ('*' === substr($first, 0, 1))
- {
+ if ('*' === substr($first, 0, 1)) {
$data = array();
- foreach ($value as $alias)
- {
+ foreach ($value as $alias) {
$data[] = $this->refs[substr($alias, 1)];
}
$value = $data;
}
}
- if (isset($mbEncoding))
- {
+ if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
return $value;
}
- switch (preg_last_error())
- {
+ switch (preg_last_error()) {
case PREG_INTERNAL_ERROR:
$error = 'Internal PCRE error on line';
break;
@@ -258,14 +215,12 @@ public function parse($value)
throw new ParserException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine));
}
- if ($isRef)
- {
+ if ($isRef) {
$this->refs[$isRef] = end($data);
}
}
- if (isset($mbEncoding))
- {
+ if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
@@ -305,28 +260,22 @@ protected function getNextEmbedBlock($indentation = null)
{
$this->moveToNextLine();
- if (null === $indentation)
- {
+ if (null === $indentation) {
$newIndent = $this->getCurrentLineIndentation();
- if (!$this->isCurrentLineEmpty() && 0 == $newIndent)
- {
+ if (!$this->isCurrentLineEmpty() && 0 == $newIndent) {
throw new ParserException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
}
- }
- else
- {
+ } else {
$newIndent = $indentation;
}
$data = array(substr($this->currentLine, $newIndent));
- while ($this->moveToNextLine())
- {
+ while ($this->moveToNextLine()) {
if ($this->isCurrentLineEmpty())
{
- if ($this->isCurrentLineBlank())
- {
+ if ($this->isCurrentLineBlank()) {
$data[] = substr($this->currentLine, $newIndent);
}
@@ -335,23 +284,16 @@ protected function getNextEmbedBlock($indentation = null)
$indent = $this->getCurrentLineIndentation();
- if (preg_match('#^(?P *)$#', $this->currentLine, $match))
- {
+ if (preg_match('#^(?P *)$#', $this->currentLine, $match)) {
// empty line
$data[] = $match['text'];
- }
- else if ($indent >= $newIndent)
- {
+ } else if ($indent >= $newIndent) {
$data[] = substr($this->currentLine, $newIndent);
- }
- else if (0 == $indent)
- {
+ } else if (0 == $indent) {
$this->moveToPreviousLine();
break;
- }
- else
- {
+ } else {
throw new ParserException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
}
}
@@ -364,8 +306,7 @@ protected function getNextEmbedBlock($indentation = null)
*/
protected function moveToNextLine()
{
- if ($this->currentLineNb >= count($this->lines) - 1)
- {
+ if ($this->currentLineNb >= count($this->lines) - 1) {
return false;
}
@@ -393,32 +334,25 @@ protected function moveToPreviousLine()
*/
protected function parseValue($value)
{
- if ('*' === substr($value, 0, 1))
- {
+ if ('*' === substr($value, 0, 1)) {
if (false !== $pos = strpos($value, '#'))
{
$value = substr($value, 1, $pos - 2);
- }
- else
- {
+ } else {
$value = substr($value, 1);
}
- if (!array_key_exists($value, $this->refs))
- {
+ if (!array_key_exists($value, $this->refs)) {
throw new ParserException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine));
}
return $this->refs[$value];
}
- if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches))
- {
+ if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
- }
- else
- {
+ } else {
return Inline::load($value);
}
}
@@ -439,20 +373,17 @@ protected function parseFoldedScalar($separator, $indicator = '', $indentation =
$notEOF = $this->moveToNextLine();
- while ($notEOF && $this->isCurrentLineBlank())
- {
+ while ($notEOF && $this->isCurrentLineBlank()) {
$text .= "\n";
$notEOF = $this->moveToNextLine();
}
- if (!$notEOF)
- {
+ if (!$notEOF) {
return '';
}
- if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#', $this->currentLine, $matches))
- {
+ if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#', $this->currentLine, $matches)) {
$this->moveToPreviousLine();
return '';
@@ -462,12 +393,10 @@ protected function parseFoldedScalar($separator, $indicator = '', $indentation =
$previousIndent = 0;
$text .= $matches['text'].$separator;
- while ($this->currentLineNb + 1 < count($this->lines))
- {
+ while ($this->currentLineNb + 1 < count($this->lines)) {
$this->moveToNextLine();
- if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#', $this->currentLine, $matches))
- {
+ if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#', $this->currentLine, $matches)) {
if (' ' == $separator && $previousIndent != $matches['indent'])
{
$text = substr($text, 0, -1)."\n";
@@ -475,27 +404,21 @@ protected function parseFoldedScalar($separator, $indicator = '', $indentation =
$previousIndent = $matches['indent'];
$text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
- }
- else if (preg_match('#^(?P *)$#', $this->currentLine, $matches))
- {
+ } else if (preg_match('#^(?P *)$#', $this->currentLine, $matches)) {
$text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
- }
- else
- {
+ } else {
$this->moveToPreviousLine();
break;
}
}
- if (' ' == $separator)
- {
+ if (' ' == $separator) {
// replace last separator by a newline
$text = preg_replace('/ (\n*)$/', "\n$1", $text);
}
- switch ($indicator)
- {
+ switch ($indicator) {
case '':
$text = preg_replace('#\n+$#s', "\n", $text);
break;
@@ -519,19 +442,16 @@ protected function isNextLineIndented()
$currentIndentation = $this->getCurrentLineIndentation();
$notEOF = $this->moveToNextLine();
- while ($notEOF && $this->isCurrentLineEmpty())
- {
+ while ($notEOF && $this->isCurrentLineEmpty()) {
$notEOF = $this->moveToNextLine();
}
- if (false === $notEOF)
- {
+ if (false === $notEOF) {
return false;
}
$ret = false;
- if ($this->getCurrentLineIndentation() <= $currentIndentation)
- {
+ if ($this->getCurrentLineIndentation() <= $currentIndentation) {
$ret = true;
}
@@ -583,8 +503,7 @@ protected function cleanup($value)
{
$value = str_replace(array("\r\n", "\r"), "\n", $value);
- if (!preg_match("#\n$#", $value))
- {
+ if (!preg_match("#\n$#", $value)) {
$value .= "\n";
}
@@ -595,8 +514,7 @@ protected function cleanup($value)
// remove leading comments and/or ---
$trimmedValue = preg_replace('#^((\#.*?\n)|(\-\-\-.*?\n))*#s', '', $value, -1, $count);
- if ($count == 1)
- {
+ if ($count == 1) {
// items have been removed, update the offset
$this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
$value = $trimmedValue;
diff --git a/src/Symfony/Components/Yaml/Yaml.php b/src/Symfony/Components/Yaml/Yaml.php
index 8b7a1d29231c..fa0b806d9b1f 100644
--- a/src/Symfony/Components/Yaml/Yaml.php
+++ b/src/Symfony/Components/Yaml/Yaml.php
@@ -30,8 +30,7 @@ class Yaml
*/
static public function setSpecVersion($version)
{
- if (!in_array($version, array('1.1', '1.2')))
- {
+ if (!in_array($version, array('1.1', '1.2'))) {
throw new \InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version));
}
@@ -71,8 +70,7 @@ public static function load($input)
$file = '';
// if input is a file, process it
- if (strpos($input, "\n") === false && is_file($input))
- {
+ if (strpos($input, "\n") === false && is_file($input)) {
$file = $input;
ob_start();
@@ -84,19 +82,15 @@ public static function load($input)
}
// if an array is returned by the config file assume it's in plain php form else in YAML
- if (is_array($input))
- {
+ if (is_array($input)) {
return $input;
}
$yaml = new Parser();
- try
- {
+ try {
$ret = $yaml->parse($input);
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage()));
}
diff --git a/src/Symfony/Foundation/Bundle/Bundle.php b/src/Symfony/Foundation/Bundle/Bundle.php
index 8c4f38709758..6b33651589cc 100644
--- a/src/Symfony/Foundation/Bundle/Bundle.php
+++ b/src/Symfony/Foundation/Bundle/Bundle.php
@@ -37,18 +37,15 @@ public function shutdown(ContainerInterface $container)
public function registerCommands(Application $application)
{
- foreach ($application->getKernel()->getBundleDirs() as $dir)
- {
+ foreach ($application->getKernel()->getBundleDirs() as $dir) {
$bundleBase = dirname(str_replace('\\', '/', get_class($this)));
$commandDir = $dir.'/'.basename($bundleBase).'/Command';
- if (!is_dir($commandDir))
- {
+ if (!is_dir($commandDir)) {
continue;
}
// look for commands
- foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($commandDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file)
- {
+ foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($commandDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($file->isDir() || substr($file, -4) !== '.php')
{
continue;
@@ -58,8 +55,7 @@ public function registerCommands(Application $application)
$r = new \ReflectionClass($class);
- if ($r->isSubclassOf('Symfony\\Components\\Console\\Command\\Command') && !$r->isAbstract())
- {
+ if ($r->isSubclassOf('Symfony\\Components\\Console\\Command\\Command') && !$r->isAbstract()) {
$application->addCommand(new $class());
}
}
diff --git a/src/Symfony/Foundation/Bundle/KernelBundle.php b/src/Symfony/Foundation/Bundle/KernelBundle.php
index ca0b572df1a2..339a4ec4ee15 100644
--- a/src/Symfony/Foundation/Bundle/KernelBundle.php
+++ b/src/Symfony/Foundation/Bundle/KernelBundle.php
@@ -36,8 +36,7 @@ public function buildContainer(ContainerInterface $container)
$loader = new XmlFileLoader(array(__DIR__.'/../Resources/config', __DIR__.'/Resources/config'));
$configuration->merge($loader->load('services.xml'));
- if ($container->getParameter('kernel.debug'))
- {
+ if ($container->getParameter('kernel.debug')) {
$configuration->merge($loader->load('debug.xml'));
$configuration->setDefinition('event_dispatcher', $configuration->findDefinition('debug.event_dispatcher'));
}
@@ -50,8 +49,7 @@ public function boot(ContainerInterface $container)
$container->getErrorHandlerService();
// load core classes
- if ($container->getParameter('kernel.include_core_classes'))
- {
+ if ($container->getParameter('kernel.include_core_classes')) {
ClassCollectionLoader::load($container->getParameter('kernel.compiled_classes'), $container->getParameter('kernel.cache_dir'), 'classes', $container->getParameter('kernel.debug'));
}
}
diff --git a/src/Symfony/Foundation/Bundle/KernelExtension.php b/src/Symfony/Foundation/Bundle/KernelExtension.php
index b8037d7e5aa4..c9c9ed70ba1d 100644
--- a/src/Symfony/Foundation/Bundle/KernelExtension.php
+++ b/src/Symfony/Foundation/Bundle/KernelExtension.php
@@ -39,13 +39,11 @@ public function configLoad($config)
{
$configuration = new BuilderConfiguration();
- if (isset($config['charset']))
- {
+ if (isset($config['charset'])) {
$configuration->setParameter('kernel.charset', $config['charset']);
}
- if (!array_key_exists('compilation', $config))
- {
+ if (!array_key_exists('compilation', $config)) {
$classes = array(
'Symfony\\Components\\Routing\\Router',
'Symfony\\Components\\Routing\\RouterInterface',
@@ -70,12 +68,9 @@ public function configLoad($config)
'Symfony\\Framework\\WebBundle\\Listener\\ResponseFilter',
'Symfony\\Framework\\WebBundle\\Templating\\Engine',
);
- }
- else
- {
+ } else {
$classes = array();
- foreach (explode("\n", $config['compilation']) as $class)
- {
+ foreach (explode("\n", $config['compilation']) as $class) {
if ($class)
{
$classes[] = trim($class);
@@ -84,8 +79,7 @@ public function configLoad($config)
}
$configuration->setParameter('kernel.compiled_classes', $classes);
- if (array_key_exists('error_handler_level', $config))
- {
+ if (array_key_exists('error_handler_level', $config)) {
$configuration->setParameter('error_handler.level', $config['error_handler_level']);
}
diff --git a/src/Symfony/Foundation/ClassCollectionLoader.php b/src/Symfony/Foundation/ClassCollectionLoader.php
index 5b33bc4529bd..48c962541db0 100644
--- a/src/Symfony/Foundation/ClassCollectionLoader.php
+++ b/src/Symfony/Foundation/ClassCollectionLoader.php
@@ -29,28 +29,20 @@ static public function load($classes, $cacheDir, $name, $autoReload)
// auto-reload
$reload = false;
- if ($autoReload)
- {
+ if ($autoReload) {
$metadata = $cacheDir.'/'.$name.'.meta';
- if (!file_exists($metadata) || !file_exists($cache))
- {
+ if (!file_exists($metadata) || !file_exists($cache)) {
$reload = true;
- }
- else
- {
+ } else {
$time = filemtime($cache);
$meta = unserialize(file_get_contents($metadata));
- if ($meta[1] != $classes)
- {
+ if ($meta[1] != $classes) {
$reload = true;
- }
- else
- {
+ } else {
foreach ($meta[0] as $resource)
{
- if (!file_exists($resource) || filemtime($resource) > $time)
- {
+ if (!file_exists($resource) || filemtime($resource) > $time) {
$reload = true;
break;
@@ -60,8 +52,7 @@ static public function load($classes, $cacheDir, $name, $autoReload)
}
}
- if (!$reload && file_exists($cache))
- {
+ if (!$reload && file_exists($cache)) {
require_once $cache;
return;
@@ -69,8 +60,7 @@ static public function load($classes, $cacheDir, $name, $autoReload)
$files = array();
$content = '';
- foreach ($classes as $class)
- {
+ foreach ($classes as $class) {
if (!class_exists($class) && !interface_exists($class))
{
throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
@@ -83,14 +73,12 @@ static public function load($classes, $cacheDir, $name, $autoReload)
}
// cache the core classes
- if (!is_dir(dirname($cache)))
- {
+ if (!is_dir(dirname($cache))) {
mkdir(dirname($cache), 0777, true);
}
self::writeCacheFile($cache, Kernel::stripComments('level)
- {
+ if (0 === $this->level) {
return false;
}
- if (error_reporting() & $level && $this->level & $level)
- {
+ if (error_reporting() & $level && $this->level & $level) {
throw new \ErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line));
}
diff --git a/src/Symfony/Foundation/Debug/EventDispatcher.php b/src/Symfony/Foundation/Debug/EventDispatcher.php
index 024dde095854..256fadb2fbaa 100644
--- a/src/Symfony/Foundation/Debug/EventDispatcher.php
+++ b/src/Symfony/Foundation/Debug/EventDispatcher.php
@@ -49,8 +49,7 @@ public function __construct(ContainerInterface $container, LoggerInterface $logg
*/
public function notify(Event $event)
{
- foreach ($this->getListeners($event->getName()) as $listener)
- {
+ foreach ($this->getListeners($event->getName()) as $listener) {
if (null !== $this->logger)
{
$this->logger->debug(sprintf('Notifying event "%s" to listener "%s"', $event->getName(), $this->listenerToString($listener)));
@@ -71,15 +70,13 @@ public function notify(Event $event)
*/
public function notifyUntil(Event $event)
{
- foreach ($this->getListeners($event->getName()) as $listener)
- {
+ foreach ($this->getListeners($event->getName()) as $listener) {
if (null !== $this->logger)
{
$this->logger->debug(sprintf('Notifying (until) event "%s" to listener "%s"', $event->getName(), $this->listenerToString($listener)));
}
- if (call_user_func($listener, $event))
- {
+ if (call_user_func($listener, $event)) {
if (null !== $this->logger)
{
$this->logger->debug(sprintf('Listener "%s" processed the event "%s"', $this->listenerToString($listener), $event->getName()));
@@ -103,8 +100,7 @@ public function notifyUntil(Event $event)
*/
public function filter(Event $event, $value)
{
- foreach ($this->getListeners($event->getName()) as $listener)
- {
+ foreach ($this->getListeners($event->getName()) as $listener) {
if (null !== $this->logger)
{
$this->logger->debug(sprintf('Notifying (filter) event "%s" to listener "%s"', $event->getName(), $this->listenerToString($listener)));
@@ -120,18 +116,15 @@ public function filter(Event $event, $value)
protected function listenerToString($listener)
{
- if (is_object($listener) && $listener instanceof \Closure)
- {
+ if (is_object($listener) && $listener instanceof \Closure) {
return 'Closure';
}
- if (is_string($listener))
- {
+ if (is_string($listener)) {
return $listener;
}
- if (is_array($listener))
- {
+ if (is_array($listener)) {
return sprintf('(%s, %s)', is_object($listener[0]) ? get_class($listener[0]) : $listener[0], $listener[1]);
}
}
diff --git a/src/Symfony/Foundation/EventDispatcher.php b/src/Symfony/Foundation/EventDispatcher.php
index 3144b41520cd..ef7607a97362 100644
--- a/src/Symfony/Foundation/EventDispatcher.php
+++ b/src/Symfony/Foundation/EventDispatcher.php
@@ -35,12 +35,10 @@ public function __construct(ContainerInterface $container)
{
$this->container = $container;
- foreach ($container->findAnnotatedServiceIds('kernel.listener') as $id => $attributes)
- {
+ foreach ($container->findAnnotatedServiceIds('kernel.listener') as $id => $attributes) {
foreach ($attributes as $attribute)
{
- if (isset($attribute['event']))
- {
+ if (isset($attribute['event'])) {
$this->connect($attribute['event'], array($id, isset($attribute['method']) ? $attribute['method'] : 'handle'));
}
}
@@ -56,13 +54,11 @@ public function __construct(ContainerInterface $container)
*/
public function getListeners($name)
{
- if (!isset($this->listeners[$name]))
- {
+ if (!isset($this->listeners[$name])) {
return array();
}
- foreach ($this->listeners[$name] as $i => $listener)
- {
+ foreach ($this->listeners[$name] as $i => $listener) {
if (is_array($listener) && is_string($listener[0]))
{
$this->listeners[$name][$i] = array($this->container->getService($listener[0]), $listener[1]);
diff --git a/src/Symfony/Foundation/Kernel.php b/src/Symfony/Foundation/Kernel.php
index 1fb3352c09e8..4f40f5cbec51 100644
--- a/src/Symfony/Foundation/Kernel.php
+++ b/src/Symfony/Foundation/Kernel.php
@@ -56,15 +56,12 @@ public function __construct($environment, $debug)
$this->rootDir = realpath($this->registerRootDir());
$this->name = basename($this->rootDir);
- if ($this->debug)
- {
+ if ($this->debug) {
ini_set('display_errors', 1);
error_reporting(-1);
$this->startTime = microtime(true);
- }
- else
- {
+ } else {
ini_set('display_errors', 0);
}
}
@@ -101,8 +98,7 @@ public function isBooted()
*/
public function boot()
{
- if (true === $this->booted)
- {
+ if (true === $this->booted) {
throw new \LogicException('The kernel is already booted.');
}
@@ -114,8 +110,7 @@ public function boot()
$this->container->setService('kernel', $this);
// boot bundles
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$bundle->boot($this->container);
}
@@ -133,8 +128,7 @@ public function shutdown()
{
$this->booted = false;
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$bundle->shutdown($this->container);
}
@@ -175,22 +169,17 @@ public function getRequest()
*/
public function handle(Request $request = null, $main = true, $raw = false)
{
- if (false === $this->booted)
- {
+ if (false === $this->booted) {
$this->boot();
}
- if (null === $request)
- {
+ if (null === $request) {
$request = $this->container->getRequestService();
- }
- else
- {
+ } else {
$this->container->setService('request', $request);
}
- if (true === $main)
- {
+ if (true === $main) {
$this->request = $request;
}
@@ -253,8 +242,7 @@ protected function initializeContainer()
$location = $this->getCacheDir().'/'.$class;
$reload = $this->debug ? $this->needsReload($class, $location) : false;
- if ($reload || !file_exists($location.'.php'))
- {
+ if ($reload || !file_exists($location.'.php')) {
$this->buildContainer($class, $location.'.php');
}
@@ -266,8 +254,7 @@ protected function initializeContainer()
public function getKernelParameters()
{
$bundles = array();
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$bundles[] = get_class($bundle);
}
@@ -290,8 +277,7 @@ public function getKernelParameters()
protected function getEnvParameters()
{
$parameters = array();
- foreach ($_SERVER as $key => $value)
- {
+ foreach ($_SERVER as $key => $value) {
if ('SYMFONY__' === substr($key, 0, 9))
{
$parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
@@ -303,15 +289,13 @@ protected function getEnvParameters()
protected function needsReload($class, $location)
{
- if (!file_exists($location.'.meta') || !file_exists($location.'.php'))
- {
+ if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
return true;
}
$meta = unserialize(file_get_contents($location.'.meta'));
$time = filemtime($location.'.php');
- foreach ($meta as $resource)
- {
+ foreach ($meta as $resource) {
if (!$resource->isUptodate($time))
{
return true;
@@ -326,26 +310,21 @@ protected function buildContainer($class, $file)
$container = new Builder($this->getKernelParameters());
$configuration = new BuilderConfiguration();
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$configuration->merge($bundle->buildContainer($container));
}
$configuration->merge($this->registerContainerConfiguration());
$container->merge($configuration);
$this->optimizeContainer($container);
- foreach (array('cache', 'logs') as $name)
- {
+ foreach (array('cache', 'logs') as $name) {
$dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
- if (!is_dir($dir))
- {
+ if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true))
{
die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
}
- }
- elseif (!is_writable($dir))
- {
+ } elseif (!is_writable($dir)) {
die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
}
}
@@ -353,19 +332,16 @@ protected function buildContainer($class, $file)
// cache the container
$dumper = new PhpDumper($container);
$content = $dumper->dump(array('class' => $class));
- if (!$this->debug)
- {
+ if (!$this->debug) {
$content = self::stripComments($content);
}
$this->writeCacheFile($file, $content);
- if ($this->debug)
- {
+ if ($this->debug) {
// add the Kernel class hierarchy as resources
$parent = new \ReflectionObject($this);
$configuration->addResource(new FileResource($parent->getFileName()));
- while ($parent = $parent->getParentClass())
- {
+ while ($parent = $parent->getParentClass()) {
$configuration->addResource(new FileResource($parent->getFileName()));
}
@@ -377,8 +353,7 @@ protected function buildContainer($class, $file)
public function optimizeContainer(Builder $container)
{
// replace all classes with the real value
- foreach ($container->getDefinitions() as $definition)
- {
+ foreach ($container->getDefinitions() as $definition) {
if (false !== strpos($class = $definition->getClass(), '%'))
{
$definition->setClass(Builder::resolveValue($class, $container->getParameters()));
@@ -389,27 +364,21 @@ public function optimizeContainer(Builder $container)
static public function stripComments($source)
{
- if (!function_exists('token_get_all'))
- {
+ if (!function_exists('token_get_all')) {
return $source;
}
$ignore = array(T_COMMENT => true, T_DOC_COMMENT => true);
$output = '';
- foreach (token_get_all($source) as $token)
- {
+ foreach (token_get_all($source) as $token) {
// array
- if (isset($token[1]))
- {
+ if (isset($token[1])) {
// no action on comments
- if (!isset($ignore[$token[0]]))
- {
+ if (!isset($ignore[$token[0]])) {
// anything else -> output "as is"
$output .= $token[1];
}
- }
- else
- {
+ } else {
// simple 1-character token
$output .= $token;
}
@@ -421,15 +390,13 @@ static public function stripComments($source)
protected function writeCacheFile($file, $content)
{
$tmpFile = tempnam(dirname($file), basename($file));
- if (!$fp = @fopen($tmpFile, 'wb'))
- {
+ if (!$fp = @fopen($tmpFile, 'wb')) {
die(sprintf('Failed to write cache file "%s".', $tmpFile));
}
@fwrite($fp, $content);
@fclose($fp);
- if ($content != file_get_contents($tmpFile))
- {
+ if ($content != file_get_contents($tmpFile)) {
die(sprintf('Failed to write cache file "%s" (cache corrupted).', $tmpFile));
}
diff --git a/src/Symfony/Foundation/Test/Client.php b/src/Symfony/Foundation/Test/Client.php
index 6c4320dbc4c2..b02838c3dacd 100644
--- a/src/Symfony/Foundation/Test/Client.php
+++ b/src/Symfony/Foundation/Test/Client.php
@@ -75,8 +75,7 @@ public function getKernel()
*/
public function getTester($name)
{
- if (isset($this->testers[$name]) && !is_object($this->testers[$name]))
- {
+ if (isset($this->testers[$name]) && !is_object($this->testers[$name])) {
$this->container->setService('test.response', $this->getResponse());
return $this->container->getService($this->testers[$name]);
@@ -130,8 +129,7 @@ protected function getScript($request)
*/
protected function addTestersFromContainer()
{
- foreach ($this->container->findAnnotatedServiceIds('test.tester') as $id => $config)
- {
+ foreach ($this->container->findAnnotatedServiceIds('test.tester') as $id => $config) {
if (!isset($config[0]['alias']))
{
continue;
diff --git a/src/Symfony/Foundation/UniversalClassLoader.php b/src/Symfony/Foundation/UniversalClassLoader.php
index cfb3fdfe3033..cf5da93bd759 100644
--- a/src/Symfony/Foundation/UniversalClassLoader.php
+++ b/src/Symfony/Foundation/UniversalClassLoader.php
@@ -125,35 +125,28 @@ public function register()
*/
public function loadClass($class)
{
- if (false !== ($pos = strripos($class, '\\')))
- {
+ if (false !== ($pos = strripos($class, '\\'))) {
// namespaced class name
$namespace = substr($class, 0, $pos);
- foreach ($this->namespaces as $ns => $dir)
- {
+ foreach ($this->namespaces as $ns => $dir) {
if (0 === strpos($namespace, $ns))
{
$class = substr($class, $pos + 1);
$file = $dir.DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
- if (file_exists($file))
- {
+ if (file_exists($file)) {
require $file;
}
return;
}
}
- }
- else
- {
+ } else {
// PEAR-like class name
- foreach ($this->prefixes as $prefix => $dir)
- {
+ foreach ($this->prefixes as $prefix => $dir) {
if (0 === strpos($class, $prefix))
{
$file = $dir.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
- if (file_exists($file))
- {
+ if (file_exists($file)) {
require $file;
}
diff --git a/src/Symfony/Foundation/bootstrap.php b/src/Symfony/Foundation/bootstrap.php
index bf56c5db62df..08c3b25855da 100644
--- a/src/Symfony/Foundation/bootstrap.php
+++ b/src/Symfony/Foundation/bootstrap.php
@@ -24,17 +24,14 @@ public function shutdown(ContainerInterface $container)
public function registerCommands(Application $application)
{
- foreach ($application->getKernel()->getBundleDirs() as $dir)
- {
+ foreach ($application->getKernel()->getBundleDirs() as $dir) {
$bundleBase = dirname(str_replace('\\', '/', get_class($this)));
$commandDir = $dir.'/'.basename($bundleBase).'/Command';
- if (!is_dir($commandDir))
- {
+ if (!is_dir($commandDir)) {
continue;
}
- foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($commandDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file)
- {
+ foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($commandDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($file->isDir() || substr($file, -4) !== '.php')
{
continue;
@@ -44,8 +41,7 @@ public function registerCommands(Application $application)
$r = new \ReflectionClass($class);
- if ($r->isSubclassOf('Symfony\\Components\\Console\\Command\\Command') && !$r->isAbstract())
- {
+ if ($r->isSubclassOf('Symfony\\Components\\Console\\Command\\Command') && !$r->isAbstract()) {
$application->addCommand(new $class());
}
}
@@ -94,8 +90,7 @@ public function buildContainer(ContainerInterface $container)
$loader = new XmlFileLoader(array(__DIR__.'/../Resources/config', __DIR__.'/Resources/config'));
$configuration->merge($loader->load('services.xml'));
- if ($container->getParameter('kernel.debug'))
- {
+ if ($container->getParameter('kernel.debug')) {
$configuration->merge($loader->load('debug.xml'));
$configuration->setDefinition('event_dispatcher', $configuration->findDefinition('debug.event_dispatcher'));
}
@@ -107,8 +102,7 @@ public function boot(ContainerInterface $container)
{
$container->getErrorHandlerService();
- if ($container->getParameter('kernel.include_core_classes'))
- {
+ if ($container->getParameter('kernel.include_core_classes')) {
ClassCollectionLoader::load($container->getParameter('kernel.compiled_classes'), $container->getParameter('kernel.cache_dir'), 'classes', $container->getParameter('kernel.debug'));
}
}
@@ -141,13 +135,11 @@ public function configLoad($config)
{
$configuration = new BuilderConfiguration();
- if (isset($config['charset']))
- {
+ if (isset($config['charset'])) {
$configuration->setParameter('kernel.charset', $config['charset']);
}
- if (!array_key_exists('compilation', $config))
- {
+ if (!array_key_exists('compilation', $config)) {
$classes = array(
'Symfony\\Components\\Routing\\Router',
'Symfony\\Components\\Routing\\RouterInterface',
@@ -172,12 +164,9 @@ public function configLoad($config)
'Symfony\\Framework\\WebBundle\\Listener\\ResponseFilter',
'Symfony\\Framework\\WebBundle\\Templating\\Engine',
);
- }
- else
- {
+ } else {
$classes = array();
- foreach (explode("\n", $config['compilation']) as $class)
- {
+ foreach (explode("\n", $config['compilation']) as $class) {
if ($class)
{
$classes[] = trim($class);
@@ -186,8 +175,7 @@ public function configLoad($config)
}
$configuration->setParameter('kernel.compiled_classes', $classes);
- if (array_key_exists('error_handler_level', $config))
- {
+ if (array_key_exists('error_handler_level', $config)) {
$configuration->setParameter('error_handler.level', $config['error_handler_level']);
}
@@ -245,13 +233,11 @@ public function register()
public function handle($level, $message, $file, $line, $context)
{
- if (0 === $this->level)
- {
+ if (0 === $this->level) {
return false;
}
- if (error_reporting() & $level && $this->level & $level)
- {
+ if (error_reporting() & $level && $this->level & $level) {
throw new \ErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line));
}
@@ -273,28 +259,20 @@ static public function load($classes, $cacheDir, $name, $autoReload)
$cache = $cacheDir.'/'.$name.'.php';
$reload = false;
- if ($autoReload)
- {
+ if ($autoReload) {
$metadata = $cacheDir.'/'.$name.'.meta';
- if (!file_exists($metadata) || !file_exists($cache))
- {
+ if (!file_exists($metadata) || !file_exists($cache)) {
$reload = true;
- }
- else
- {
+ } else {
$time = filemtime($cache);
$meta = unserialize(file_get_contents($metadata));
- if ($meta[1] != $classes)
- {
+ if ($meta[1] != $classes) {
$reload = true;
- }
- else
- {
+ } else {
foreach ($meta[0] as $resource)
{
- if (!file_exists($resource) || filemtime($resource) > $time)
- {
+ if (!file_exists($resource) || filemtime($resource) > $time) {
$reload = true;
break;
@@ -304,8 +282,7 @@ static public function load($classes, $cacheDir, $name, $autoReload)
}
}
- if (!$reload && file_exists($cache))
- {
+ if (!$reload && file_exists($cache)) {
require_once $cache;
return;
@@ -313,8 +290,7 @@ static public function load($classes, $cacheDir, $name, $autoReload)
$files = array();
$content = '';
- foreach ($classes as $class)
- {
+ foreach ($classes as $class) {
if (!class_exists($class) && !interface_exists($class))
{
throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
@@ -326,14 +302,12 @@ static public function load($classes, $cacheDir, $name, $autoReload)
$content .= preg_replace(array('/^\s*<\?php/', '/\?>\s*$/'), '', file_get_contents($r->getFileName()));
}
- if (!is_dir(dirname($cache)))
- {
+ if (!is_dir(dirname($cache))) {
mkdir(dirname($cache), 0777, true);
}
self::writeCacheFile($cache, Kernel::stripComments('rootDir = realpath($this->registerRootDir());
$this->name = basename($this->rootDir);
- if ($this->debug)
- {
+ if ($this->debug) {
ini_set('display_errors', 1);
error_reporting(-1);
$this->startTime = microtime(true);
- }
- else
- {
+ } else {
ini_set('display_errors', 0);
}
}
@@ -428,8 +397,7 @@ public function isBooted()
public function boot()
{
- if (true === $this->booted)
- {
+ if (true === $this->booted) {
throw new \LogicException('The kernel is already booted.');
}
@@ -439,8 +407,7 @@ public function boot()
$this->container = $this->initializeContainer();
$this->container->setService('kernel', $this);
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$bundle->boot($this->container);
}
@@ -454,8 +421,7 @@ public function shutdown()
{
$this->booted = false;
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$bundle->shutdown($this->container);
}
@@ -478,22 +444,17 @@ public function getRequest()
public function handle(Request $request = null, $main = true, $raw = false)
{
- if (false === $this->booted)
- {
+ if (false === $this->booted) {
$this->boot();
}
- if (null === $request)
- {
+ if (null === $request) {
$request = $this->container->getRequestService();
- }
- else
- {
+ } else {
$this->container->setService('request', $request);
}
- if (true === $main)
- {
+ if (true === $main) {
$this->request = $request;
}
@@ -556,8 +517,7 @@ protected function initializeContainer()
$location = $this->getCacheDir().'/'.$class;
$reload = $this->debug ? $this->needsReload($class, $location) : false;
- if ($reload || !file_exists($location.'.php'))
- {
+ if ($reload || !file_exists($location.'.php')) {
$this->buildContainer($class, $location.'.php');
}
@@ -569,8 +529,7 @@ protected function initializeContainer()
public function getKernelParameters()
{
$bundles = array();
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$bundles[] = get_class($bundle);
}
@@ -593,8 +552,7 @@ public function getKernelParameters()
protected function getEnvParameters()
{
$parameters = array();
- foreach ($_SERVER as $key => $value)
- {
+ foreach ($_SERVER as $key => $value) {
if ('SYMFONY__' === substr($key, 0, 9))
{
$parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
@@ -606,15 +564,13 @@ protected function getEnvParameters()
protected function needsReload($class, $location)
{
- if (!file_exists($location.'.meta') || !file_exists($location.'.php'))
- {
+ if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
return true;
}
$meta = unserialize(file_get_contents($location.'.meta'));
$time = filemtime($location.'.php');
- foreach ($meta as $resource)
- {
+ foreach ($meta as $resource) {
if (!$resource->isUptodate($time))
{
return true;
@@ -629,44 +585,36 @@ protected function buildContainer($class, $file)
$container = new Builder($this->getKernelParameters());
$configuration = new BuilderConfiguration();
- foreach ($this->bundles as $bundle)
- {
+ foreach ($this->bundles as $bundle) {
$configuration->merge($bundle->buildContainer($container));
}
$configuration->merge($this->registerContainerConfiguration());
$container->merge($configuration);
$this->optimizeContainer($container);
- foreach (array('cache', 'logs') as $name)
- {
+ foreach (array('cache', 'logs') as $name) {
$dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
- if (!is_dir($dir))
- {
+ if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true))
{
die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
}
- }
- elseif (!is_writable($dir))
- {
+ } elseif (!is_writable($dir)) {
die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
}
}
$dumper = new PhpDumper($container);
$content = $dumper->dump(array('class' => $class));
- if (!$this->debug)
- {
+ if (!$this->debug) {
$content = self::stripComments($content);
}
$this->writeCacheFile($file, $content);
- if ($this->debug)
- {
+ if ($this->debug) {
$parent = new \ReflectionObject($this);
$configuration->addResource(new FileResource($parent->getFileName()));
- while ($parent = $parent->getParentClass())
- {
+ while ($parent = $parent->getParentClass()) {
$configuration->addResource(new FileResource($parent->getFileName()));
}
@@ -676,8 +624,7 @@ protected function buildContainer($class, $file)
public function optimizeContainer(Builder $container)
{
- foreach ($container->getDefinitions() as $definition)
- {
+ foreach ($container->getDefinitions() as $definition) {
if (false !== strpos($class = $definition->getClass(), '%'))
{
$definition->setClass(Builder::resolveValue($class, $container->getParameters()));
@@ -688,24 +635,19 @@ public function optimizeContainer(Builder $container)
static public function stripComments($source)
{
- if (!function_exists('token_get_all'))
- {
+ if (!function_exists('token_get_all')) {
return $source;
}
$ignore = array(T_COMMENT => true, T_DOC_COMMENT => true);
$output = '';
- foreach (token_get_all($source) as $token)
- {
+ foreach (token_get_all($source) as $token) {
if (isset($token[1]))
{
- if (!isset($ignore[$token[0]]))
- {
+ if (!isset($ignore[$token[0]])) {
$output .= $token[1];
}
- }
- else
- {
+ } else {
$output .= $token;
}
}
@@ -716,15 +658,13 @@ static public function stripComments($source)
protected function writeCacheFile($file, $content)
{
$tmpFile = tempnam(dirname($file), basename($file));
- if (!$fp = @fopen($tmpFile, 'wb'))
- {
+ if (!$fp = @fopen($tmpFile, 'wb')) {
die(sprintf('Failed to write cache file "%s".', $tmpFile));
}
@fwrite($fp, $content);
@fclose($fp);
- if ($content != file_get_contents($tmpFile))
- {
+ if ($content != file_get_contents($tmpFile)) {
die(sprintf('Failed to write cache file "%s" (cache corrupted).', $tmpFile));
}
@@ -764,12 +704,10 @@ public function __construct(ContainerInterface $container)
{
$this->container = $container;
- foreach ($container->findAnnotatedServiceIds('kernel.listener') as $id => $attributes)
- {
+ foreach ($container->findAnnotatedServiceIds('kernel.listener') as $id => $attributes) {
foreach ($attributes as $attribute)
{
- if (isset($attribute['event']))
- {
+ if (isset($attribute['event'])) {
$this->connect($attribute['event'], array($id, isset($attribute['method']) ? $attribute['method'] : 'handle'));
}
}
@@ -779,13 +717,11 @@ public function __construct(ContainerInterface $container)
public function getListeners($name)
{
- if (!isset($this->listeners[$name]))
- {
+ if (!isset($this->listeners[$name])) {
return array();
}
- foreach ($this->listeners[$name] as $i => $listener)
- {
+ foreach ($this->listeners[$name] as $i => $listener) {
if (is_array($listener) && is_string($listener[0]))
{
$this->listeners[$name][$i] = array($this->container->getService($listener[0]), $listener[1]);
diff --git a/src/Symfony/Framework/DoctrineBundle/Bundle.php b/src/Symfony/Framework/DoctrineBundle/Bundle.php
index edefc8651af5..6b5690983a5c 100644
--- a/src/Symfony/Framework/DoctrineBundle/Bundle.php
+++ b/src/Symfony/Framework/DoctrineBundle/Bundle.php
@@ -35,20 +35,17 @@ public function buildContainer(ContainerInterface $container)
$metadataDirs = array();
$entityDirs = array();
$bundleDirs = $container->getParameter('kernel.bundle_dirs');
- foreach ($container->getParameter('kernel.bundles') as $className)
- {
+ foreach ($container->getParameter('kernel.bundles') as $className) {
$tmp = dirname(str_replace('\\', '/', $className));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (isset($bundleDirs[$namespace]))
- {
+ if (isset($bundleDirs[$namespace])) {
if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Resources/config/doctrine/metadata'))
{
$metadataDirs[] = realpath($dir);
}
- if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Entities'))
- {
+ if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Entities')) {
$entityDirs[] = realpath($dir);
}
}
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/ConvertDoctrine1SchemaDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/ConvertDoctrine1SchemaDoctrineCommand.php
index 223d3c749805..f0fd0fbe4ed7 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/ConvertDoctrine1SchemaDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/ConvertDoctrine1SchemaDoctrineCommand.php
@@ -59,16 +59,14 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$bundleClass = null;
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
- foreach ($this->container->getKernelService()->getBundles() as $bundle)
- {
+ foreach ($this->container->getKernelService()->getBundles() as $bundle) {
if (strpos(get_class($bundle), $input->getArgument('bundle')) !== false)
{
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (isset($bundleDirs[$namespace]))
- {
+ if (isset($bundleDirs[$namespace])) {
$destPath = realpath($bundleDirs[$namespace]).'/'.$class;
$bundleClass = $class;
break;
@@ -77,20 +75,16 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
$type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
- if ($type === 'annotation')
- {
+ if ($type === 'annotation') {
$destPath .= '/Entities';
- }
- else
- {
+ } else {
$destPath .= '/Resources/config/doctrine/metadata';
}
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter($type);
- if ($type === 'annotation')
- {
+ if ($type === 'annotation') {
$entityGenerator = $this->getEntityGenerator();
$exporter->setEntityGenerator($entityGenerator);
}
@@ -98,19 +92,14 @@ protected function execute(InputInterface $input, OutputInterface $output)
$converter = new ConvertDoctrine1Schema($input->getArgument('d1-schema'));
$metadata = $converter->getMetadata();
- if ($metadata)
- {
+ if ($metadata) {
$output->writeln(sprintf('Converting Doctrine 1 schema "%s"', $input->getArgument('d1-schema')));
- foreach ($metadata as $class)
- {
+ foreach ($metadata as $class) {
$className = $class->name;
$class->name = $namespace.'\\'.$bundleClass.'\\Entities\\'.$className;
- if ($type === 'annotation')
- {
+ if ($type === 'annotation') {
$path = $destPath.'/'.$className.'.php';
- }
- else
- {
+ } else {
$path = $destPath.'/'.str_replace('\\', '.', $class->name).'.dcm.xml';
}
$output->writeln(sprintf(' > writing %s', $path));
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php
index d6a44e6848e6..d2aebea22307 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/CreateDatabaseDoctrineCommand.php
@@ -53,8 +53,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$found = false;
$connections = $this->getDoctrineConnections();
- foreach ($connections as $name => $connection)
- {
+ foreach ($connections as $name => $connection) {
if ($input->getOption('connection') && $name != $input->getOption('connection'))
{
continue;
@@ -62,14 +61,11 @@ protected function execute(InputInterface $input, OutputInterface $output)
$this->createDatabaseForConnection($connection, $output);
$found = true;
}
- if ($found === false)
- {
+ if ($found === false) {
if ($input->getOption('connection'))
{
throw new \InvalidArgumentException(sprintf('Could not find a connection named %s', $input->getOption('connection')));
- }
- else
- {
+ } else {
throw new \InvalidArgumentException(sprintf('Could not find any configured connections', $input->getOption('connection')));
}
}
@@ -84,7 +80,7 @@ protected function createDatabaseForConnection(Connection $connection, OutputInt
$tmpConnection = \Doctrine\DBAL\DriverManager::getConnection($params);
- try {
+ try {
$tmpConnection->getSchemaManager()->createDatabase($name);
$output->writeln(sprintf('Created database for connection named %s', $name));
} catch (\Exception $e) {
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/DoctrineCommand.php
index ddbfd9f1aa72..3ce4feb302ea 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/DoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/DoctrineCommand.php
@@ -60,8 +60,7 @@ public static function setApplicationEntityManager(Application $application, $em
$container = $application->getKernel()->getContainer();
$emName = $emName ? $emName : 'default';
$emServiceName = sprintf('doctrine.orm.%s_entity_manager', $emName);
- if (!$container->hasService($emServiceName))
- {
+ if (!$container->hasService($emServiceName)) {
throw new \InvalidArgumentException(sprintf('Could not find Doctrine EntityManager named "%s"', $emName));
}
@@ -76,8 +75,7 @@ public static function setApplicationConnection(Application $application, $connN
$container = $application->getKernel()->getContainer();
$connName = $connName ? $connName : 'default';
$connServiceName = sprintf('doctrine.dbal.%s_connection', $connName);
- if (!$container->hasService($connServiceName))
- {
+ if (!$container->hasService($connServiceName)) {
throw new \InvalidArgumentException(sprintf('Could not find Doctrine Connection named "%s"', $connName));
}
@@ -102,8 +100,7 @@ protected function getEntityManager($name = null)
{
$name = $name ? $name : 'default';
$serviceName = sprintf('doctrine.orm.%s_entity_manager', $name);
- if (!$this->container->hasService($serviceName))
- {
+ if (!$this->container->hasService($serviceName)) {
throw new \InvalidArgumentException(sprintf('Could not find Doctrine EntityManager named "%s"', $name));
}
@@ -129,11 +126,9 @@ protected function getDoctrineConnections()
{
$connections = array();
$ids = $this->container->getServiceIds();
- foreach ($ids as $id)
- {
+ foreach ($ids as $id) {
preg_match('/doctrine.dbal.(.*)_connection/', $id, $matches);
- if ($matches)
- {
+ if ($matches) {
$name = $matches[1];
$connections[$name] = $this->container->getService($id);
}
@@ -146,11 +141,9 @@ protected function getDoctrineEntityManagers()
{
$entityManagers = array();
$ids = $this->container->getServiceIds();
- foreach ($ids as $id)
- {
+ foreach ($ids as $id) {
preg_match('/doctrine.orm.(.*)_entity_manager/', $id, $matches);
- if ($matches)
- {
+ if ($matches) {
$name = $matches[1];
$entityManagers[$name] = $this->container->getService($id);
}
@@ -166,12 +159,10 @@ protected function getBundleMetadatas(Bundle $bundle)
$bundleMetadatas = array();
$entityManagers = $this->getDoctrineEntityManagers();
- foreach ($entityManagers as $key => $em)
- {
+ foreach ($entityManagers as $key => $em) {
$cmf = new SymfonyDisconnectedClassMetadataFactory($em);
$metadatas = $cmf->getAllMetadata();
- foreach ($metadatas as $metadata)
- {
+ foreach ($metadatas as $metadata) {
if (strpos($metadata->name, $namespace) !== false)
{
$bundleMetadatas[] = $metadata;
@@ -189,12 +180,9 @@ class SymfonyDisconnectedClassMetadataFactory extends DisconnectedClassMetadataF
*/
protected function _newClassMetadataInstance($className)
{
- if (class_exists($className))
- {
+ if (class_exists($className)) {
return new ClassMetadata($className);
- }
- else
- {
+ } else {
return new ClassMetadataInfo($className);
}
}
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php
index ad45c22989b5..7c9dcfb2dd7b 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/DropDatabaseDoctrineCommand.php
@@ -53,8 +53,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$found = false;
$connections = $this->getDoctrineConnections();
- foreach ($connections as $name => $connection)
- {
+ foreach ($connections as $name => $connection) {
if ($input->getOption('connection') && $name != $input->getOption('connection'))
{
continue;
@@ -62,14 +61,11 @@ protected function execute(InputInterface $input, OutputInterface $output)
$this->dropDatabaseForConnection($connection, $output);
$found = true;
}
- if ($found === false)
- {
+ if ($found === false) {
if ($input->getOption('connection'))
{
throw new \InvalidArgumentException(sprintf('Could not find a connection named %s', $input->getOption('connection')));
- }
- else
- {
+ } else {
throw new \InvalidArgumentException(sprintf('Could not find any configured connections', $input->getOption('connection')));
}
}
@@ -80,7 +76,7 @@ protected function dropDatabaseForConnection(Connection $connection, OutputInter
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path']:$params['dbname'];
- try {
+ try {
$connection->getSchemaManager()->dropDatabase($name);
$output->writeln(sprintf('Dropped database for connection named %s', $name));
} catch (\Exception $e) {
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php
index 2d6177b99116..5d1acaa65e52 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php
@@ -46,20 +46,16 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$entityGenerator = $this->getEntityGenerator();
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
- foreach ($this->container->getKernelService()->getBundles() as $bundle)
- {
+ foreach ($this->container->getKernelService()->getBundles() as $bundle) {
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (isset($bundleDirs[$namespace]))
- {
+ if (isset($bundleDirs[$namespace])) {
$destination = realpath($bundleDirs[$namespace].'/..');
- if ($metadatas = $this->getBundleMetadatas($bundle))
- {
+ if ($metadatas = $this->getBundleMetadatas($bundle)) {
$output->writeln(sprintf('Generating entities for "%s"', $class));
- foreach ($metadatas as $metadata)
- {
+ foreach ($metadatas as $metadata) {
$output->writeln(sprintf(' > generating %s', $metadata->name));
$entityGenerator->generate(array($metadata), $destination);
}
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntityDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntityDoctrineCommand.php
index 63744aee9163..d8045dd91717 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntityDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/GenerateEntityDoctrineCommand.php
@@ -58,8 +58,7 @@ protected function configure()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
- if (!preg_match('/Bundle$/', $bundle = $input->getArgument('bundle')))
- {
+ if (!preg_match('/Bundle$/', $bundle = $input->getArgument('bundle'))) {
throw new \InvalidArgumentException('The bundle name must end with Bundle. Example: "Bundle\MySampleBundle".');
}
@@ -69,8 +68,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$namespace = str_replace('/', '\\', dirname($tmp));
$bundle = basename($tmp);
- if (!isset($dirs[$namespace]))
- {
+ if (!isset($dirs[$namespace])) {
throw new \InvalidArgumentException(sprintf('Unable to initialize the bundle entity (%s not defined).', $namespace));
}
@@ -90,8 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
// Map the specified fields
$fields = $input->getOption('fields');
$e = explode(' ', $fields);
- foreach ($e as $value)
- {
+ foreach ($e as $value) {
$e = explode(':', $value);
$name = $e[0];
$type = isset($e[1]) ? $e[1] : 'string';
@@ -109,8 +106,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter($mappingType);
- if ($mappingType === 'annotation')
- {
+ if ($mappingType === 'annotation') {
$path = $dirs[$namespace].'/'.$bundle.'/Entities/'.str_replace($entityNamespace.'\\', null, $fullEntityClassName).'.php';
$exporter->setEntityGenerator($this->getEntityGenerator());
@@ -120,8 +116,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$code = $exporter->exportClassMetadata($class);
- if (!is_dir($dir = dirname($path)))
- {
+ if (!is_dir($dir = dirname($path))) {
mkdir($dir, 0777, true);
}
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php
index 8a7fbb404a65..ec95e04ee932 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/GenerateRepositoriesDoctrineCommand.php
@@ -44,20 +44,16 @@ protected function execute(InputInterface $input, OutputInterface $output)
$generator = new EntityRepositoryGenerator();
$kernel = $this->application->getKernel();
$bundleDirs = $kernel->getBundleDirs();
- foreach ($kernel->getBundles() as $bundle)
- {
+ foreach ($kernel->getBundles() as $bundle) {
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (isset($bundleDirs[$namespace]))
- {
+ if (isset($bundleDirs[$namespace])) {
$destination = realpath($bundleDirs[$namespace].'/..');
- if ($metadatas = $this->getBundleMetadatas($bundle))
- {
+ if ($metadatas = $this->getBundleMetadatas($bundle)) {
$output->writeln(sprintf('Generating entity repositories for "%s"', $class));
- foreach ($metadatas as $metadata)
- {
+ foreach ($metadatas as $metadata) {
if ($metadata->customRepositoryClassName)
{
$output->writeln(sprintf(' > generating %s', $metadata->customRepositoryClassName));
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/ImportMappingDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/ImportMappingDoctrineCommand.php
index a2642e47b4b6..581d5edb7255 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/ImportMappingDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/ImportMappingDoctrineCommand.php
@@ -57,16 +57,14 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$bundleClass = null;
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
- foreach ($this->container->getKernelService()->getBundles() as $bundle)
- {
+ foreach ($this->container->getKernelService()->getBundles() as $bundle) {
if (strpos(get_class($bundle), $input->getArgument('bundle')) !== false)
{
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (isset($bundleDirs[$namespace]))
- {
+ if (isset($bundleDirs[$namespace])) {
$destPath = realpath($bundleDirs[$namespace]).'/'.$class;
$bundleClass = $class;
break;
@@ -75,20 +73,16 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
$type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
- if ($type === 'annotation')
- {
+ if ($type === 'annotation') {
$destPath .= '/Entities';
- }
- else
- {
+ } else {
$destPath .= '/Resources/config/doctrine/metadata';
}
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter($type);
- if ($type === 'annotation')
- {
+ if ($type === 'annotation') {
$entityGenerator = $this->getEntityGenerator();
$exporter->setEntityGenerator($entityGenerator);
}
@@ -101,19 +95,14 @@ protected function execute(InputInterface $input, OutputInterface $output)
$cmf = new DisconnectedClassMetadataFactory($em);
$metadata = $cmf->getAllMetadata();
- if ($metadata)
- {
+ if ($metadata) {
$output->writeln(sprintf('Importing mapping information from "%s" entity manager', $emName));
- foreach ($metadata as $class)
- {
+ foreach ($metadata as $class) {
$className = $class->name;
$class->name = $namespace.'\\'.$bundleClass.'\\Entities\\'.$className;
- if ($type === 'annotation')
- {
+ if ($type === 'annotation') {
$path = $destPath.'/'.$className.'.php';
- }
- else
- {
+ } else {
$path = $destPath.'/'.str_replace('\\', '.', $class->name).'.dcm.xml';
}
$output->writeln(sprintf(' > writing %s', $path));
diff --git a/src/Symfony/Framework/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php b/src/Symfony/Framework/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php
index b3deac1ec1b4..efe93fec5ea0 100644
--- a/src/Symfony/Framework/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php
+++ b/src/Symfony/Framework/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php
@@ -60,28 +60,24 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$defaultEm = $this->container->getDoctrine_ORM_EntityManagerService();
$dirOrFile = $input->getOption('fixtures');
- if ($dirOrFile)
- {
+ if ($dirOrFile) {
$paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile);
} else {
$paths = array();
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
- foreach ($this->container->getKernelService()->getBundles() as $bundle)
- {
+ foreach ($this->container->getKernelService()->getBundles() as $bundle) {
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (isset($bundleDirs[$namespace]) && is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Resources/data/fixtures/doctrine'))
- {
+ if (isset($bundleDirs[$namespace]) && is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Resources/data/fixtures/doctrine')) {
$paths[] = $dir;
}
}
}
$files = array();
- foreach ($paths as $path)
- {
+ foreach ($paths as $path) {
if (is_dir($path))
{
$finder = new Finder();
@@ -89,9 +85,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
->files()
->name('*.php')
->in($path));
- }
- else
- {
+ } else {
$found = array($path);
}
$files = array_merge($files, $found);
@@ -100,8 +94,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$ems = array();
$emEntities = array();
$files = array_unique($files);
- foreach ($files as $file)
- {
+ foreach ($files as $file) {
$em = $defaultEm;
$output->writeln(sprintf('Loading data fixtures from "%s"', $file));
@@ -116,17 +109,14 @@ protected function execute(InputInterface $input, OutputInterface $output)
$emEntities[$emName] = array();
$variables = array_values($new);
- foreach ($variables as $variable)
- {
+ foreach ($variables as $variable) {
$value = $$variable;
- if (!is_object($value) || $value instanceof \Doctrine\ORM\EntityManager)
- {
+ if (!is_object($value) || $value instanceof \Doctrine\ORM\EntityManager) {
continue;
}
$emEntities[$emName][] = $value;
}
- foreach ($ems as $emName => $em)
- {
+ foreach ($ems as $emName => $em) {
if (!$input->getOption('append'))
{
$output->writeln(sprintf('Purging data from entity manager named "%s"', $emName));
@@ -137,8 +127,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$numEntities = count($entities);
$output->writeln(sprintf('Persisting "%s" '.($numEntities > 1 ? 'entities' : 'entity').'', count($entities)));
- foreach ($entities as $entity)
- {
+ foreach ($entities as $entity) {
$output->writeln(sprintf('Persisting "%s" entity:', get_class($entity)));
$output->writeln('');
$output->writeln(var_dump($entity));
@@ -156,8 +145,7 @@ protected function purgeEntityManager(EntityManager $em)
$classes = array();
$metadatas = $em->getMetadataFactory()->getAllMetadata();
- foreach ($metadatas as $metadata)
- {
+ foreach ($metadatas as $metadata) {
if (!$metadata->isMappedSuperclass)
{
$classes[] = $metadata;
@@ -165,11 +153,9 @@ protected function purgeEntityManager(EntityManager $em)
}
$cmf = $em->getMetadataFactory();
$classes = $this->getCommitOrder($em, $classes);
- for ($i = count($classes) - 1; $i >= 0; --$i)
- {
+ for ($i = count($classes) - 1; $i >= 0; --$i) {
$class = $classes[$i];
- if ($cmf->hasMetadataFor($class->name))
- {
+ if ($cmf->hasMetadataFor($class->name)) {
try {
$em->createQuery('DELETE FROM '.$class->name.' a')->execute();
} catch (Exception $e) {}
@@ -181,16 +167,14 @@ protected function getCommitOrder(EntityManager $em, array $classes)
{
$calc = new CommitOrderCalculator;
- foreach ($classes as $class)
- {
+ foreach ($classes as $class) {
$calc->addClass($class);
- foreach ($class->associationMappings as $assoc)
- {
+ foreach ($class->associationMappings as $assoc) {
if ($assoc->isOwningSide) {
$targetClass = $em->getClassMetadata($assoc->targetEntityName);
- if ( ! $calc->hasClass($targetClass->name)) {
+ if ( ! $calc->hasClass($targetClass->name)) {
$calc->addClass($targetClass);
}
diff --git a/src/Symfony/Framework/DoctrineBundle/Controller/DoctrineController.php b/src/Symfony/Framework/DoctrineBundle/Controller/DoctrineController.php
index 39ac3bd6d19c..6333f6a5465a 100644
--- a/src/Symfony/Framework/DoctrineBundle/Controller/DoctrineController.php
+++ b/src/Symfony/Framework/DoctrineBundle/Controller/DoctrineController.php
@@ -25,12 +25,9 @@ class DoctrineController extends Controller
{
public function getDatabaseConnection($name = null)
{
- if ($name)
- {
+ if ($name) {
return $this->container->getService(sprintf('doctrine.dbal.%s_connection', $name));
- }
- else
- {
+ } else {
return $this->container->getDatabaseConnectionService();
}
}
@@ -45,12 +42,9 @@ public function getDatabaseConnection($name = null)
*/
protected function getEntityManager($name = null)
{
- if ($name)
- {
+ if ($name) {
return $this->container->getService(sprintf('doctrine.orm.%s_entity_manager', $name));
- }
- else
- {
+ } else {
return $this->container->getDoctrine_ORM_EntityManagerService();
}
}
diff --git a/src/Symfony/Framework/DoctrineBundle/DataCollector/DoctrineDataCollector.php b/src/Symfony/Framework/DoctrineBundle/DataCollector/DoctrineDataCollector.php
index 5f51f5580615..7b92cc968ba1 100644
--- a/src/Symfony/Framework/DoctrineBundle/DataCollector/DoctrineDataCollector.php
+++ b/src/Symfony/Framework/DoctrineBundle/DataCollector/DoctrineDataCollector.php
@@ -25,8 +25,7 @@ class DoctrineDataCollector extends DataCollector
protected function collect()
{
$data = array();
- if ($this->container->hasService('doctrine.dbal.logger'))
- {
+ if ($this->container->hasService('doctrine.dbal.logger')) {
$data = array(
'queries' => $this->container->getDoctrine_Dbal_LoggerService()->queries,
);
diff --git a/src/Symfony/Framework/DoctrineBundle/DependencyInjection/DoctrineExtension.php b/src/Symfony/Framework/DoctrineBundle/DependencyInjection/DoctrineExtension.php
index f632cae777c5..712d67c36e85 100644
--- a/src/Symfony/Framework/DoctrineBundle/DependencyInjection/DoctrineExtension.php
+++ b/src/Symfony/Framework/DoctrineBundle/DependencyInjection/DoctrineExtension.php
@@ -79,20 +79,16 @@ public function dbalLoad($config)
$config['default_connection'] = isset($config['default_connection']) ? $config['default_connection'] : 'default';
$connections = array();
- if (isset($config['connections']))
- {
+ if (isset($config['connections'])) {
foreach ($config['connections'] as $name => $connection)
{
$connections[isset($connection['id']) ? $connection['id'] : $name] = $connection;
}
- }
- else
- {
+ } else {
$connections = array($config['default_connection'] => $config);
}
- foreach ($connections as $name => $connection)
- {
+ foreach ($connections as $name => $connection) {
$connection = array_merge($defaultConnection, $connection);
$configurationClass = isset($connection['configuration_class']) ?
$connection['configuration_class'] : 'Doctrine\DBAL\Configuration';
@@ -113,23 +109,19 @@ public function dbalLoad($config)
);
$driverOptions = array();
- if (isset($connection['driver']))
- {
+ if (isset($connection['driver'])) {
$driverOptions['driverClass'] = sprintf(
'Doctrine\\DBAL\\Driver\\%s\\Driver',
$connection['driver']
);
}
- if (isset($connection['wrapper_class']))
- {
+ if (isset($connection['wrapper_class'])) {
$driverOptions['wrapperClass'] = $connection['wrapper_class'];
}
- if (isset($connection['options']))
- {
+ if (isset($connection['options'])) {
$driverOptions['driverOptions'] = $connection['options'];
}
- foreach (array('dbname', 'host', 'user', 'password', 'path', 'port') as $key)
- {
+ foreach (array('dbname', 'host', 'user', 'password', 'path', 'port') as $key) {
if (isset($connection[$key]))
{
$driverOptions[$key] = $connection[$key];
@@ -169,8 +161,7 @@ public function ormLoad($config)
$configuration->merge($loader->load($this->resources['orm']));
$config['default_entity_manager'] = isset($config['default_entity_manager']) ? $config['default_entity_manager'] : 'default';
- foreach (array('metadata_driver', 'cache_driver') as $key)
- {
+ foreach (array('metadata_driver', 'cache_driver') as $key) {
if (isset($config[$key]))
{
$configuration->setParameter('doctrine.orm.'.$key, $config[$key]);
@@ -180,16 +171,14 @@ public function ormLoad($config)
$config['entity_managers'] = isset($config['entity_managers']) ?
$config['entity_managers'] : array($config['default_entity_manager'] => array())
;
- foreach ($config['entity_managers'] as $name => $connection)
- {
+ foreach ($config['entity_managers'] as $name => $connection) {
$ormConfigDef = new Definition('Doctrine\ORM\Configuration');
$configuration->setDefinition(
sprintf('doctrine.orm.%s_configuration', $name), $ormConfigDef
);
$drivers = array('metadata', 'query', 'result');
- foreach ($drivers as $driver)
- {
+ foreach ($drivers as $driver) {
$definition = $configuration->getDefinition(sprintf('doctrine.orm.cache.%s', $configuration->getParameter('doctrine.orm.cache_driver')));
$clone = clone $definition;
$clone->addMethodCall('setNamespace', array(sprintf('doctrine_%s_', $driver)));
@@ -201,25 +190,21 @@ public function ormLoad($config)
$bundleEntityMappings = array();
$bundleDirs = $this->bundleDirs;
$aliasMap = array();
- foreach (array_reverse($this->bundles) as $className)
- {
+ foreach (array_reverse($this->bundles) as $className) {
$tmp = dirname(str_replace('\\', '/', $className));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
- if (!isset($bundleDirs[$namespace]))
- {
+ if (!isset($bundleDirs[$namespace])) {
continue;
}
$type = false;
- if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Resources/config/doctrine/metadata'))
- {
+ if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Resources/config/doctrine/metadata')) {
$type = $this->detectMappingType($dir);
}
- if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Entities'))
- {
+ if (is_dir($dir = $bundleDirs[$namespace].'/'.$class.'/Entities')) {
if ($type === false)
{
$type = 'annotation';
@@ -227,8 +212,7 @@ public function ormLoad($config)
$aliasMap[$class] = $namespace.'\\'.$class.'\\Entities';
}
- if (false !== $type)
- {
+ if (false !== $type) {
$mappingDriverDef->addMethodCall('addDriver', array(
new Reference(sprintf('doctrine.orm.metadata_driver.%s', $type)),
$namespace.'\\'.$class.'\\Entities'
@@ -250,8 +234,7 @@ public function ormLoad($config)
'setAutoGenerateProxyClasses' => true
);
- foreach ($methods as $method => $arg)
- {
+ foreach ($methods as $method => $arg) {
$ormConfigDef->addMethodCall($method, array($arg));
}
@@ -270,8 +253,7 @@ public function ormLoad($config)
$ormEmDef
);
- if ($name == $config['default_entity_manager'])
- {
+ if ($name == $config['default_entity_manager']) {
$configuration->setAlias(
'doctrine.orm.entity_manager',
sprintf('doctrine.orm.%s_entity_manager', $name)
@@ -302,8 +284,7 @@ public function ormLoad($config)
protected function detectMappingType($dir)
{
$files = glob($dir.'/*.*');
- if (!$files)
- {
+ if (!$files) {
return 'annotation';
}
$info = pathinfo($files[0]);
diff --git a/src/Symfony/Framework/DoctrineBundle/Logger/DbalLogger.php b/src/Symfony/Framework/DoctrineBundle/Logger/DbalLogger.php
index 2fac241f62f6..7c21aaa17d1b 100644
--- a/src/Symfony/Framework/DoctrineBundle/Logger/DbalLogger.php
+++ b/src/Symfony/Framework/DoctrineBundle/Logger/DbalLogger.php
@@ -39,8 +39,7 @@ public function logSql($sql, array $params = null)
{
parent::logSql($sql, $params);
- if (null !== $this->logger)
- {
+ if (null !== $this->logger) {
$this->log($sql.' ('.str_replace("\n", '', var_export($params, true)).')');
}
}
diff --git a/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollector.php b/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollector.php
index 547ea67e606a..dccee575737d 100644
--- a/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollector.php
+++ b/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollector.php
@@ -33,8 +33,7 @@ public function __construct(ContainerInterface $container)
public function getData()
{
- if (null === $this->data)
- {
+ if (null === $this->data) {
$this->data = $this->collect();
}
diff --git a/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollectorManager.php b/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollectorManager.php
index be34e1079e32..c39c5545c953 100644
--- a/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollectorManager.php
+++ b/src/Symfony/Framework/ProfilerBundle/DataCollector/DataCollectorManager.php
@@ -49,26 +49,21 @@ public function register()
public function handle(Event $event, Response $response)
{
- if (!$event->getParameter('main_request'))
- {
+ if (!$event->getParameter('main_request')) {
return $response;
}
$this->response = $response;
$data = array();
- foreach ($this->collectors as $name => $collector)
- {
+ foreach ($this->collectors as $name => $collector) {
$data[$name] = $collector->getData();
}
- try
- {
+ try {
$this->profilerStorage->write($data);
$this->profilerStorage->purge($this->lifetime);
- }
- catch (\Exception $e)
- {
+ } catch (\Exception $e) {
$this->logger->err('Unable to store the profiler information.');
}
@@ -96,17 +91,13 @@ public function initCollectors()
$ids = array();
$coreCollectors = array();
$userCollectors = array();
- foreach ($config as $id => $attributes)
- {
+ foreach ($config as $id => $attributes) {
$collector = $this->container->getService($id);
$collector->setCollectorManager($this);
- if (isset($attributes[0]['core']) && $attributes[0]['core'])
- {
+ if (isset($attributes[0]['core']) && $attributes[0]['core']) {
$coreCollectors[$collector->getName()] = $collector;
- }
- else
- {
+ } else {
$userCollectors[$collector->getName()] = $collector;
}
}
diff --git a/src/Symfony/Framework/ProfilerBundle/DependencyInjection/ProfilerExtension.php b/src/Symfony/Framework/ProfilerBundle/DependencyInjection/ProfilerExtension.php
index 4754ebbd00bd..44a861f902b8 100644
--- a/src/Symfony/Framework/ProfilerBundle/DependencyInjection/ProfilerExtension.php
+++ b/src/Symfony/Framework/ProfilerBundle/DependencyInjection/ProfilerExtension.php
@@ -31,8 +31,7 @@ public function configLoad($config)
$loader = new XmlFileLoader(__DIR__.'/../Resources/config');
$configuration->merge($loader->load('collectors.xml'));
- if (isset($config['toolbar']) && $config['toolbar'])
- {
+ if (isset($config['toolbar']) && $config['toolbar']) {
$configuration->merge($loader->load('toolbar.xml'));
}
diff --git a/src/Symfony/Framework/ProfilerBundle/Listener/WebDebugToolbar.php b/src/Symfony/Framework/ProfilerBundle/Listener/WebDebugToolbar.php
index 91c3ef812167..e81ff07378d6 100644
--- a/src/Symfony/Framework/ProfilerBundle/Listener/WebDebugToolbar.php
+++ b/src/Symfony/Framework/ProfilerBundle/Listener/WebDebugToolbar.php
@@ -41,8 +41,7 @@ public function register()
public function handle(Event $event, Response $response)
{
- if (!$event->getParameter('main_request'))
- {
+ if (!$event->getParameter('main_request')) {
return $response;
}
@@ -76,8 +75,7 @@ public function handle(Event $event, Response $response)
protected function injectToolbar(Response $response)
{
$data = '';
- foreach ($this->collectorManager->getCollectors() as $name => $collector)
- {
+ foreach ($this->collectorManager->getCollectors() as $name => $collector) {
$data .= $collector->getSummary();
}
@@ -95,8 +93,7 @@ protected function injectToolbar(Response $response)
$toolbar = "\n".str_replace("\n", '', $toolbar)."\n";
$count = 0;
$content = str_ireplace(']