merged 2.0

This commit is contained in:
Fabien Potencier 2011-12-18 14:48:17 +01:00
commit 5d6a7d35b0
99 changed files with 870 additions and 184 deletions

View File

@ -93,6 +93,9 @@ foreach ($finder as $file) {
$new .= "\n";
}
// [Structure] elseif, not else if
$new = preg_replace('/} else if \(/', '} elseif (', $new);
if ($new != $old) {
$count++;

View File

@ -196,7 +196,7 @@ abstract class AbstractDoctrineExtension extends Extension
$args[0] = array_merge(array_values($driverPaths), $args[0]);
}
$mappingDriverDef->setArguments($args);
} else if ($driverType == 'annotation') {
} elseif ($driverType == 'annotation') {
$mappingDriverDef = new Definition('%'.$this->getObjectManagerElementName('metadata.'.$driverType.'.class%'), array(
new Reference($this->getObjectManagerElementName('metadata.annotation_reader')),
array_values($driverPaths)

View File

@ -150,7 +150,7 @@ class EntityChoiceList extends ArrayChoiceList
if (is_array($this->choices)) {
$entities = $this->choices;
} else if ($qb = $this->queryBuilder) {
} elseif ($qb = $this->queryBuilder) {
$entities = $qb->getQuery()->execute();
} else {
$entities = $this->em->getRepository($this->class)->findAll();
@ -305,9 +305,9 @@ class EntityChoiceList extends ArrayChoiceList
$entities = $this->getEntities();
return isset($entities[$key]) ? $entities[$key] : null;
} else if ($this->entities) {
} elseif ($this->entities) {
return isset($this->entities[$key]) ? $this->entities[$key] : null;
} else if ($qb = $this->queryBuilder) {
} elseif ($qb = $this->queryBuilder) {
// should we clone the builder?
$alias = $qb->getRootAlias();
$where = $qb->expr()->eq($alias.'.'.current($this->identifier), $key);

View File

@ -38,7 +38,7 @@ class MergeCollectionListener implements EventSubscriberInterface
if (!$collection) {
$collection = $data;
} else if (count($data) === 0) {
} elseif (count($data) === 0) {
$collection->clear();
} else {
// merge $data into $collection

View File

@ -0,0 +1,12 @@
Doctrine Bridge
===============
Provides integration for [Doctrine](http://www.doctrine-project.org/) with
various Symfony2 components.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Bridge/Doctrine

View File

@ -0,0 +1,11 @@
Monolog Bridge
==============
Provides integration for Monolog with various Symfony2 components.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Bridge/Monolog

View File

@ -0,0 +1,12 @@
Twig Bridge
===========
Provides integration for [Twig](http://twig.sensiolabs.org/) with various
Symfony2 components.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Bridge/Twig

View File

@ -88,7 +88,7 @@ class CodeHelper extends Helper
if (false !== strpos($method, '::')) {
list($class, $method) = explode('::', $method, 2);
$result = sprintf("%s::%s()", $this->abbrClass($class), $method);
} else if ('Closure' === $method) {
} elseif ('Closure' === $method) {
$result = sprintf("<abbr title=\"%s\">%s</abbr>", $method, $method);
} else {
$result = sprintf("<abbr title=\"%s\">%s</abbr>()", $method, $method);

View File

@ -45,7 +45,7 @@ class TemplateNameParser extends BaseTemplateNameParser
{
if ($name instanceof TemplateReferenceInterface) {
return $name;
} else if (isset($this->cache[$name])) {
} elseif (isset($this->cache[$name])) {
return $this->cache[$name];
}

View File

@ -240,7 +240,7 @@ class SecurityExtension extends Extension
$matcher = null;
if (isset($firewall['request_matcher'])) {
$matcher = new Reference($firewall['request_matcher']);
} else if (isset($firewall['pattern'])) {
} elseif (isset($firewall['pattern'])) {
$matcher = $this->createRequestMatcher($container, $firewall['pattern']);
}
@ -524,7 +524,7 @@ class SecurityExtension extends Extension
// access denied handler setup
if (isset($config['access_denied_handler'])) {
$listener->replaceArgument(5, new Reference($config['access_denied_handler']));
} else if (isset($config['access_denied_url'])) {
} elseif (isset($config['access_denied_url'])) {
$listener->replaceArgument(4, $config['access_denied_url']);
}

View File

@ -110,7 +110,7 @@ abstract class SecurityExtensionTest extends \PHPUnit_Framework_TestCase
if (1 === $i) {
$this->assertEquals(array('ROLE_USER'), $roles);
$this->assertEquals('https', $channel);
} else if (2 === $i) {
} elseif (2 === $i) {
$this->assertEquals(array('IS_AUTHENTICATED_ANONYMOUSLY'), $roles);
$this->assertNull($channel);
}

View File

@ -72,7 +72,7 @@ fieldset {
}
abbr {
border-bottom: 1px dotted #000000;
border-bottom: 1px dotted #000;
cursor: help;
}
@ -160,6 +160,7 @@ abbr {
background: #d1d1d1 url(../images/profiler/bg_submenu.gif) repeat-x 0 0;
}
#navigation div:first-child,
#menu_profiler li:first-child,
#menu_profiler li:first-child a,
#menu_profiler li:first-child a span.label {
@ -253,7 +254,7 @@ table th.value {
#content #main {
padding: 0;
background-color: #FFFFFF;
background-color: #FFF;
border: 1px solid #dfdfdf;
}
@ -316,7 +317,7 @@ td.main, td.menu {
margin-right: 10px;
font-size: 12px;
border: 1px solid #dadada;
background: #FFFFFF url(../images/profiler/input_bg.gif) repeat-x left top;
background: #FFF url(../images/profiler/input_bg.gif) repeat-x left top;
padding: 5px 6px;
color: #565656;
}
@ -372,6 +373,11 @@ td.main, td.menu {
background: transparent url(../images/profiler/btn_bg.png) repeat-x top left;
}
#navigation div:first-child {
margin: 0 0 20px;
border-top: 0;
}
#navigation .search {
padding-top: 15px;
float: none;

View File

@ -0,0 +1,17 @@
BrowserKit Component
====================
BrowserKit simulates the behavior of a web browser.
The component only provide an abstract client and does not provide any
"default" backend for the HTTP layer.
Resources
---------
For a simple implementation of a browser based on an HTTP layer, have a look
at [Goutte](https://github.com/fabpot/Goutte).
For an implementation based on HttpKernelInterface, have a look at the
[Client](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/Client.php)
provided by the HttpKernel component.

View File

@ -0,0 +1,60 @@
ClassLoader Component
=====================
ClassLoader loads your project classes automatically if they follow some
standard PHP conventions.
The Universal ClassLoader is able to autoload classes that implement the PSR-0
standard or the PEAR naming convention.
First, register the autoloader:
require_once __DIR__.'/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
use Symfony\Component\ClassLoader\UniversalClassLoader;
$loader = new UniversalClassLoader();
$loader->register();
Then, register some namespaces with the `registerNamespace()` method:
$loader->registerNamespace('Symfony', __DIR__.'/src');
$loader->registerNamespace('Monolog', __DIR__.'/vendor/monolog/src');
The `registerNamespace()` method takes a namespace prefix and a path where to
look for the classes as arguments.
You can also register a sub-namespaces:
$loader->registerNamespace('Doctrine\\Common', __DIR__.'/vendor/doctrine-common/lib');
The order of registration is significant and the first registered namespace
takes precedence over later registered one.
You can also register more than one path for a given namespace:
$loader->registerNamespace('Symfony', array(__DIR__.'/src', __DIR__.'/symfony/src'));
Alternatively, you can use the `registerNamespaces()` method to register more
than one namespace at once:
$loader->registerNamespaces(array(
'Symfony' => array(__DIR__.'/src', __DIR__.'/symfony/src'),
'Doctrine\\Common' => __DIR__.'/vendor/doctrine-common/lib',
'Doctrine' => __DIR__.'/vendor/doctrine/lib',
'Monolog' => __DIR__.'/vendor/monolog/src',
));
For better performance, you can use the APC based version of the universal
class loader:
require_once __DIR__.'/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
require_once __DIR__.'/src/Symfony/Component/ClassLoader/ApcUniversalClassLoader.php';
use Symfony\Component\ClassLoader\ApcUniversalClassLoader;
$loader = new ApcUniversalClassLoader('apc.prefix.');
Furthermore, the component provides tools to aggregate classes into a single
file, which is especially useful to improve performance on servers that do not
provide byte caches.

View File

@ -217,7 +217,7 @@ class PrototypedArrayNode extends ArrayNode
$ex->setPath($this->getPath());
throw $ex;
} else if (isset($v[$this->keyAttribute])) {
} elseif (isset($v[$this->keyAttribute])) {
$k = $v[$this->keyAttribute];
// remove the key attribute when required

View File

@ -0,0 +1,14 @@
Config Component
================
Config provides the infrastructure for loading configurations from different
data sources and optionally monitoring these data sources for changes. There
are additional tools for validating, normalizing and handling of defaults that
can optionally be used to convert from different formats to arrays.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Config

View File

@ -45,7 +45,7 @@ class InputArgument
{
if (null === $mode) {
$mode = self::OPTIONAL;
} else if (!is_int($mode) || $mode > 7 || $mode < 1) {
} elseif (!is_int($mode) || $mode > 7 || $mode < 1) {
throw new \InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode));
}
@ -102,7 +102,7 @@ class InputArgument
if ($this->isArray()) {
if (null === $default) {
$default = array();
} else if (!is_array($default)) {
} elseif (!is_array($default)) {
throw new \LogicException('A default value for an array argument must be an array.');
}
}

View File

@ -263,7 +263,7 @@ class InputDefinition
{
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()])) {
} elseif (isset($this->shortcuts[$option->getShortcut()])) {
throw new \LogicException(sprintf('An option with shortcut "%s" already exist.', $option->getShortcut()));
}

View File

@ -62,7 +62,7 @@ class InputOption
if (null === $mode) {
$mode = self::VALUE_NONE;
} else if (!is_int($mode) || $mode > 15 || $mode < 1) {
} elseif (!is_int($mode) || $mode > 15 || $mode < 1) {
throw new \InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode));
}

View File

@ -44,7 +44,7 @@ class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
*
* @api
*/
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatter $formatter = null)
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
{
parent::__construct(fopen('php://stdout', 'w'), $verbosity, $decorated, $formatter);
$this->stderr = new StreamOutput(fopen('php://stderr', 'w'), $verbosity, $decorated, $formatter);

View File

@ -11,7 +11,7 @@
namespace Symfony\Component\Console\Output;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
/**
* StreamOutput writes the output to a given stream.
@ -45,7 +45,7 @@ class StreamOutput extends Output
*
* @api
*/
public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatter $formatter = null)
public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
{
if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) {
throw new \InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');

View File

@ -0,0 +1,48 @@
Console Component
=================
Console eases the creation of beautiful and testable command line interfaces.
The Application object manages the CLI application:
use Symfony\Component\Console\Application;
$console = new Application();
$console->run();
The ``run()`` method parses the arguments and options passed on the command
line and executes the right command.
Registering a new command can easily be done via the ``register()`` method,
which returns a ``Command`` instance:
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
$console
->register('ls')
->setDefinition(array(
new InputArgument('dir', InputArgument::REQUIRED, 'Directory name'),
))
->setDescription('Displays the files in the given directory')
->setCode(function (InputInterface $input, OutputInterface $output) {
$dir = $input->getArgument('dir');
$output->writeln(sprintf('Dir listing for <info>%s</info>', $dir));
})
;
You can also register new commands via classes.
The component provides a lot of features like output coloring, input and
output abstractions (so that you can easily unit-test your commands),
validation, automatic help messages, ...
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Console

View File

@ -1,4 +0,0 @@
This component is a port of the Python lxml library,
which is copyright Infrae and distributed under the BSD license.
Current code is a port of http://codespeak.net/svn/lxml/trunk/src/lxml/cssselect.py@71545

View File

@ -0,0 +1,23 @@
CssSelector Component
=====================
CssSelector converts CSS selectors to XPath expressions.
The component only goal is to convert CSS selectors to their XPath
equivalents:
use Symfony\Component\CssSelector\CssSelector;
print CssSelector::toXPath('div.item > h4 > a');
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/CssSelector
This component is a port of the Python lxml library, which is copyright Infrae
and distributed under the BSD license.
Current code is a port of http://codespeak.net/svn/lxml/trunk/src/lxml/cssselect.py@71545

View File

@ -92,7 +92,7 @@ class AnalyzeServiceReferencesPass implements RepeatablePassInterface
foreach ($arguments as $argument) {
if (is_array($argument)) {
$this->processArguments($argument);
} else if ($argument instanceof Reference) {
} elseif ($argument instanceof Reference) {
$this->graph->connect(
$this->currentId,
$this->currentDefinition,
@ -100,7 +100,7 @@ class AnalyzeServiceReferencesPass implements RepeatablePassInterface
$this->getDefinition((string) $argument),
$argument
);
} else if ($argument instanceof Definition) {
} elseif ($argument instanceof Definition) {
$this->processArguments($argument->getArguments());
$this->processArguments($argument->getMethodCalls());
$this->processArguments($argument->getProperties());

View File

@ -50,9 +50,9 @@ class CheckExceptionOnInvalidReferenceBehaviorPass implements CompilerPassInterf
foreach ($arguments as $argument) {
if (is_array($argument)) {
$this->processReferences($argument);
} else if ($argument instanceof Definition) {
} elseif ($argument instanceof Definition) {
$this->processDefinition($argument);
} else if ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) {
} elseif ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) {
$destId = (string) $argument;
if (!$this->container->has($destId)) {

View File

@ -71,7 +71,7 @@ class CheckReferenceValidityPass implements CompilerPassInterface
if (ContainerInterface::SCOPE_CONTAINER === $scope) {
$this->currentScopeChildren = array_keys($scopes);
$this->currentScopeAncestors = array();
} else if (ContainerInterface::SCOPE_PROTOTYPE !== $scope) {
} elseif (ContainerInterface::SCOPE_PROTOTYPE !== $scope) {
$this->currentScopeChildren = $children[$scope];
$this->currentScopeAncestors = $ancestors[$scope];
}

View File

@ -76,7 +76,7 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
foreach ($arguments as $k => $argument) {
if (is_array($argument)) {
$arguments[$k] = $this->inlineArguments($container, $argument);
} else if ($argument instanceof Reference) {
} elseif ($argument instanceof Reference) {
if (!$container->hasDefinition($id = (string) $argument)) {
continue;
}
@ -90,7 +90,7 @@ class InlineServiceDefinitionsPass implements RepeatablePassInterface
$arguments[$k] = clone $definition;
}
}
} else if ($argument instanceof Definition) {
} elseif ($argument instanceof Definition) {
$argument->setArguments($this->inlineArguments($container, $argument->getArguments()));
$argument->setMethodCalls($this->inlineArguments($container, $argument->getMethodCalls()));
$argument->setProperties($this->inlineArguments($container, $argument->getProperties()));

View File

@ -70,7 +70,7 @@ class RemoveUnusedDefinitionsPass implements RepeatablePassInterface
$definition->setPublic(true);
$container->removeDefinition($id);
$compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases)));
} else if (0 === count($referencingAliases) && false === $isReferenced) {
} elseif (0 === count($referencingAliases) && false === $isReferenced) {
$container->removeDefinition($id);
$compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused'));
$hasChanged = true;

View File

@ -103,7 +103,7 @@ class ReplaceAliasByActualDefinitionPass implements CompilerPassInterface
foreach ($arguments as $k => $argument) {
if (is_array($argument)) {
$arguments[$k] = $this->updateArgumentReferences($argument, $currentId, $newId);
} else if ($argument instanceof Reference) {
} elseif ($argument instanceof Reference) {
if ($currentId === (string) $argument) {
$arguments[$k] = new Reference($newId, $argument->getInvalidBehavior());
$this->compiler->addLogMessage($this->formatter->formatUpdateReference($this, $this->sourceId, $currentId, $newId));

View File

@ -77,7 +77,7 @@ class ResolveInvalidReferencesPass implements CompilerPassInterface
foreach ($arguments as $k => $argument) {
if (is_array($argument)) {
$arguments[$k] = $this->processArguments($argument, $inMethodCall);
} else if ($argument instanceof Reference) {
} elseif ($argument instanceof Reference) {
$id = (string) $argument;
$invalidBehavior = $argument->getInvalidBehavior();
@ -86,9 +86,9 @@ class ResolveInvalidReferencesPass implements CompilerPassInterface
// resolve invalid behavior
if ($exists && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
$arguments[$k] = new Reference($id);
} else if (!$exists && ContainerInterface::NULL_ON_INVALID_REFERENCE === $invalidBehavior) {
} elseif (!$exists && ContainerInterface::NULL_ON_INVALID_REFERENCE === $invalidBehavior) {
$arguments[$k] = null;
} else if (!$exists && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $invalidBehavior) {
} elseif (!$exists && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $invalidBehavior) {
if ($inMethodCall) {
throw new RuntimeException('Method shouldn\'t be called.');
}

View File

@ -504,7 +504,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
if (is_string($id)) {
$id = new Alias($id);
} else if (!$id instanceof Alias) {
} elseif (!$id instanceof Alias) {
throw new InvalidArgumentException('$id must be a string, or an Alias object.');
}

View File

@ -304,7 +304,7 @@ class PhpDumper extends Dumper
$instantiation = '';
if (ContainerInterface::SCOPE_CONTAINER === $definition->getScope()) {
$instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance');
} else if (ContainerInterface::SCOPE_PROTOTYPE !== $scope = $definition->getScope()) {
} elseif (ContainerInterface::SCOPE_PROTOTYPE !== $scope = $definition->getScope()) {
$instantiation = "\$this->services['$id'] = \$this->scopedServices['$scope']['$id'] = ".($simple ? '' : '$instance');
} elseif (!$simple) {
$instantiation = '$instance';
@ -878,7 +878,7 @@ EOF;
foreach ($arguments as $argument) {
if (is_array($argument)) {
$this->getServiceCallsFromArguments($argument, $calls, $behavior);
} else if ($argument instanceof Reference) {
} elseif ($argument instanceof Reference) {
$id = (string) $argument;
if (!isset($calls[$id])) {
@ -886,7 +886,7 @@ EOF;
}
if (!isset($behavior[$id])) {
$behavior[$id] = $argument->getInvalidBehavior();
} else if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) {
} elseif (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) {
$behavior[$id] = $argument->getInvalidBehavior();
}
@ -932,7 +932,7 @@ EOF;
foreach ($arguments as $argument) {
if (is_array($argument)) {
$definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument));
} else if ($argument instanceof Definition) {
} elseif ($argument instanceof Definition) {
$definitions = array_merge(
$definitions,
$this->getInlinedDefinitions($argument),
@ -959,7 +959,7 @@ EOF;
if ($this->hasReference($id, $argument)) {
return true;
}
} else if ($argument instanceof Reference) {
} elseif ($argument instanceof Reference) {
if ($id === (string) $argument) {
return true;
}

View File

@ -230,16 +230,16 @@ class XmlDumper extends Dumper
if (is_array($value)) {
$element->setAttribute('type', 'collection');
$this->convertParameters($value, $type, $element, 'key');
} else if (is_object($value) && $value instanceof Reference) {
} elseif (is_object($value) && $value instanceof Reference) {
$element->setAttribute('type', 'service');
$element->setAttribute('id', (string) $value);
$behaviour = $value->getInvalidBehavior();
if ($behaviour == ContainerInterface::NULL_ON_INVALID_REFERENCE) {
$element->setAttribute('on-invalid', 'null');
} else if ($behaviour == ContainerInterface::IGNORE_ON_INVALID_REFERENCE) {
} elseif ($behaviour == ContainerInterface::IGNORE_ON_INVALID_REFERENCE) {
$element->setAttribute('on-invalid', 'ignore');
}
} else if (is_object($value) && $value instanceof Definition) {
} elseif (is_object($value) && $value instanceof Definition) {
$element->setAttribute('type', 'service');
$this->addService($value, null, $element);
} else {

View File

@ -126,7 +126,7 @@ class YamlFileLoader extends FileLoader
$this->container->setAlias($id, substr($service, 1));
return;
} else if (isset($service['alias'])) {
} elseif (isset($service['alias'])) {
$public = !array_key_exists('public', $service) || (Boolean) $service['public'];
$this->container->setAlias($id, new Alias($service['alias'], $public));
@ -280,7 +280,7 @@ class YamlFileLoader extends FileLoader
{
if (is_array($value)) {
$value = array_map(array($this, 'resolveServices'), $value);
} else if (is_string($value) && 0 === strpos($value, '@')) {
} elseif (is_string($value) && 0 === strpos($value, '@')) {
if (0 === strpos($value, '@?')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;

View File

@ -0,0 +1,26 @@
DependencyInjection Component
=============================
DependencyInjection manages your services via a robust and flexible Dependency
Injection Container.
Here is a simple example that shows how to register services and parameters:
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
$sc = new ContainerBuilder();
$sc
->register('foo', '%foo.class%')
->addArgument(new Reference('bar'))
;
$sc->setParameter('foo.class', 'Foo');
$sc->get('foo');
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/DependencyInjection

View File

@ -0,0 +1,30 @@
DomCrawler Component
====================
DomCrawler eases DOM navigation for HTML and XML documents.
If you are familiar with jQuery, DomCrawler is a PHP equivalent:
use Symfony\Component\DomCrawler\Crawler;
$crawler = new Crawler();
$crawler->addContent('<html><body><p>Hello World!</p></body></html>');
print $crawler->filterXPath('descendant-or-self::body/p')->text();
If you are also using the CssSelector component, you can use CSS Selectors
instead of XPath expressions:
use Symfony\Component\DomCrawler\Crawler;
$crawler = new Crawler();
$crawler->addContent('<html><body><p>Hello World!</p></body></html>');
print $crawler->filter('body > p')->text();
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/DomCrawler

View File

@ -0,0 +1,23 @@
EventDispatcher Component
=========================
EventDispatcher implements a lightweight version of the Observer design
pattern.
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
$dispatcher = new EventDispatcher();
$dispatcher->addListener('event_name', function (Event $event) {
// ...
});
$dispatcher->dispatch('event_name');
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/EventDispatcher

View File

@ -0,0 +1,38 @@
Finder Component
================
Finder finds files and directories via an intuitive fluent interface.
use Symfony\Component\Finder\Finder;
$finder = new Finder();
$iterator = $finder
->files()
->name('*.php')
->depth(0)
->size('>= 1K')
->in(__DIR__);
foreach ($iterator as $file) {
print $file->getRealpath()."\n";
}
But you can also use it to find files stored remotely like in this example where
we are looking for files on Amazon S3:
$s3 = new \Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");
$finder = new Finder();
$finder->name('photos*')->size('< 100K')->date('since 1 hour ago');
foreach ($finder->in('s3://bucket-name') as $file) {
print $file->getFilename()."\n";
}
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Finder

View File

@ -47,7 +47,7 @@ class TimezoneChoiceList implements ChoiceListInterface
if (count($parts) > 2) {
$region = $parts[0];
$name = $parts[1].' - '.$parts[2];
} else if (count($parts) > 1) {
} elseif (count($parts) > 1) {
$region = $parts[0];
$name = $parts[1];
} else {

View File

@ -109,11 +109,11 @@ class DateTimeType extends AbstractType
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], $format)
));
} else if ($options['input'] === 'timestamp') {
} elseif ($options['input'] === 'timestamp') {
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])
));
} else if ($options['input'] === 'array') {
} elseif ($options['input'] === 'array') {
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], $parts)
));

View File

@ -114,11 +114,11 @@ class DateType extends AbstractType
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], 'Y-m-d')
));
} else if ($options['input'] === 'timestamp') {
} elseif ($options['input'] === 'timestamp') {
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])
));
} else if ($options['input'] === 'array') {
} elseif ($options['input'] === 'array') {
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], array('year', 'month', 'day'))
));

View File

@ -104,7 +104,7 @@ class MoneyType extends AbstractType
if (!empty($matches[1])) {
self::$patterns[\Locale::getDefault()] = $matches[1].' {{ widget }}';
} else if (!empty($matches[2])) {
} elseif (!empty($matches[2])) {
self::$patterns[\Locale::getDefault()] = '{{ widget }} '.$matches[2];
} else {
self::$patterns[\Locale::getDefault()] = '{{ widget }}';

View File

@ -95,11 +95,11 @@ class TimeType extends AbstractType
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], $format)
));
} else if ($options['input'] === 'timestamp') {
} elseif ($options['input'] === 'timestamp') {
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])
));
} else if ($options['input'] === 'array') {
} elseif ($options['input'] === 'array') {
$builder->appendNormTransformer(new ReversedTransformer(
new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], $parts)
));

View File

@ -0,0 +1,21 @@
Form Component
==============
Form provides tools for defining forms, rendering and binding request data to
related models. Furthermore it provides integration with the Validation
component.
Resources
---------
Silex integration:
https://github.com/fabpot/Silex/blob/master/src/Silex/Provider/FormServiceProvider.php
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Form
Documentation:
http://symfony.com/doc/2.0/book/forms.html

View File

@ -192,7 +192,7 @@ class PropertyPath implements \IteratorAggregate
$value = $this->readProperty($objectOrArray, $i);
// arrays need to be treated separately (due to PHP bug?)
// http://bugs.php.net/bug.php?id=52133
} else if (is_array($objectOrArray)) {
} elseif (is_array($objectOrArray)) {
$property = $this->elements[$i];
if (!array_key_exists($property, $objectOrArray)) {
$objectOrArray[$property] = $i + 1 < $this->length ? array() : null;
@ -242,7 +242,7 @@ class PropertyPath implements \IteratorAggregate
$nestedObject = $this->readProperty($objectOrArray, $i);
// arrays need to be treated separately (due to PHP bug?)
// http://bugs.php.net/bug.php?id=52133
} else if (is_array($objectOrArray)) {
} elseif (is_array($objectOrArray)) {
$property = $this->elements[$i];
if (!array_key_exists($property, $objectOrArray)) {
$objectOrArray[$property] = array();
@ -294,22 +294,22 @@ class PropertyPath implements \IteratorAggregate
}
return $object->$getter();
} else if ($reflClass->hasMethod($isser)) {
} elseif ($reflClass->hasMethod($isser)) {
if (!$reflClass->getMethod($isser)->isPublic()) {
throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $isser, $reflClass->getName()));
}
return $object->$isser();
} else if ($reflClass->hasMethod('__get')) {
} elseif ($reflClass->hasMethod('__get')) {
// needed to support magic method __get
return $object->$property;
} else if ($reflClass->hasProperty($property)) {
} elseif ($reflClass->hasProperty($property)) {
if (!$reflClass->getProperty($property)->isPublic()) {
throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "%s()" or "%s()"?', $property, $reflClass->getName(), $getter, $isser));
}
return $object->$property;
} else if (property_exists($object, $property)) {
} elseif (property_exists($object, $property)) {
// needed to support \stdClass instances
return $object->$property;
} else {
@ -335,7 +335,7 @@ class PropertyPath implements \IteratorAggregate
}
$objectOrArray[$property] = $value;
} else if (is_object($objectOrArray)) {
} elseif (is_object($objectOrArray)) {
$reflClass = new \ReflectionClass($objectOrArray);
$setter = 'set'.$this->camelize($property);
@ -345,16 +345,16 @@ class PropertyPath implements \IteratorAggregate
}
$objectOrArray->$setter($value);
} else if ($reflClass->hasMethod('__set')) {
} elseif ($reflClass->hasMethod('__set')) {
// needed to support magic method __set
$objectOrArray->$property = $value;
} else if ($reflClass->hasProperty($property)) {
} elseif ($reflClass->hasProperty($property)) {
if (!$reflClass->getProperty($property)->isPublic()) {
throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "%s()"?', $property, $reflClass->getName(), $setter));
}
$objectOrArray->$property = $value;
} else if (property_exists($objectOrArray, $property)) {
} elseif (property_exists($objectOrArray, $property)) {
// needed to support \stdClass instances
$objectOrArray->$property = $value;
} else {

View File

@ -118,7 +118,7 @@ class ParameterBag
}
$currentKey = '';
} else if (']' === $char) {
} elseif (']' === $char) {
if (null === $currentKey) {
throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i));
}

View File

@ -0,0 +1,36 @@
HttpFoundation Component
========================
HttpFoundation defines an object-oriented layer for the HTTP specification.
It provides an abstraction for requests, responses, uploaded files, cookies,
sessions, ...
In this example, we get a Request object from the current PHP global
variables:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$request = Request::createFromGlobals();
echo $request->getPathInfo();
You can also create a Request directly -- that's interesting for unit testing:
$request = Request::create('/?foo=bar', 'GET');
echo $request->getPathInfo();
And here is how to create and send a Response:
$response = new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
$response->send();
The Request and the Response classes have many other methods that implement
the HTTP specification.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/HttpFoundation

View File

@ -176,7 +176,7 @@ EOF;
foreach ($response->headers->getCookies() as $cookie) {
$cookies[] = new DomCookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
}
$headers['Set-Cookie'] = implode(', ', $cookies);
$headers['Set-Cookie'] = $cookies;
}
return new DomResponse($response->getContent(), $response->getStatusCode(), $headers);

View File

@ -0,0 +1,87 @@
HttpKernel Component
====================
HttpKernel provides the building blocks to create flexible and fast HTTP-based
frameworks.
``HttpKernelInterface`` is the core interface of the Symfony2 full-stack
framework:
interface HttpKernelInterface
{
/**
* Handles a Request to convert it to a Response.
*
* @param Request $request A Request instance
*
* @return Response A Response instance
*/
function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true);
}
It takes a ``Request`` as an input and should return a ``Response`` as an
output. Using this interface makes your code compatible with all frameworks
using the Symfony2 components. And this will gives you many cool features for
free.
Creating a framework based on the Symfony2 components is really easy. Here is
a very simple, but fully-featured framework based on the Symfony2 components:
$routes = new RouteCollection();
$routes->add('hello', new Route('/hello', array('_controller' =>
function (Request $request) {
return new Response(sprintf("Hello %s", $request->get('name')));
}
)));
$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new RouterListener($matcher));
$resolver = new ControllerResolver();
$kernel = new HttpKernel($dispatcher, $resolver);
$kernel->handle($request)->send();
This is all you need to create a flexible framework with the Symfony2
components.
Want to add an HTTP reverse proxy and benefit from HTTP caching and Edge Side
Includes?
$kernel = new HttpKernel($dispatcher, $resolver);
$kernel = new HttpCache($kernel, new Store(__DIR__.'/cache'));
Want to functional test this small framework?
$client = new Client($kernel);
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertEquals('Fabien', $crawler->filter('p > span')->text());
Want nice error pages instead of ugly PHP exceptions?
$dispatcher->addSubscriber(new ExceptionListener(function (Request $request) {
$msg = 'Something went wrong! ('.$request->get('exception')->getMessage().')';
return new Response($msg, 500);
}));
And that's why the simple looking ``HttpKernelInterface`` is so powerful. It
gives you access to a lot of cool features, ready to be used out of the box,
with no efforts.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/HttpKernel

View File

@ -232,9 +232,9 @@ class Filesystem
if (is_link($file)) {
$this->symlink($file, $target);
} else if (is_dir($file)) {
} elseif (is_dir($file)) {
$this->mkdir($target);
} else if (is_file($file) || ($copyOnWindows && is_link($file))) {
} elseif (is_file($file) || ($copyOnWindows && is_link($file))) {
$this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
} else {
throw new \RuntimeException(sprintf('Unable to guess "%s" file type.', $file));

View File

@ -0,0 +1,22 @@
Locale Component
================
Locale provides fallback code to handle cases when the ``intl`` extension is
missing.
Loading the fallback classes for example using the ClassLoader component only
requires adding the following lines to your autoloader:
// intl
if (!function_exists('intl_get_error_code')) {
require __DIR__.'/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->registerPrefixFallbacks(array(__DIR__.'/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs'));
}
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Locale

View File

@ -31,13 +31,7 @@ class DayTransformer extends Transformer
*/
public function getReverseMatchingRegExp($length)
{
if (1 == $length) {
$regExp = '\d{1,2}';
} else {
$regExp = '\d{'.$length.'}';
}
return $regExp;
return 1 === $length ? '\d{1,2}' : '\d{'.$length.'}';
}
/**

View File

@ -116,11 +116,11 @@ class FullTransformer
$transformer = $this->transformers[$dateChars[0]];
return $transformer->format($dateTime, $length);
} else {
// handle unimplemented characters
if (false !== strpos($this->notImplementedChars, $dateChars[0])) {
throw new NotImplementedException(sprintf("Unimplemented date character '%s' in format '%s'", $dateChars[0], $this->pattern));
}
}
// handle unimplemented characters
if (false !== strpos($this->notImplementedChars, $dateChars[0])) {
throw new NotImplementedException(sprintf("Unimplemented date character '%s' in format '%s'", $dateChars[0], $this->pattern));
}
}
@ -181,7 +181,6 @@ class FullTransformer
}
$transformers = $that->getTransformers();
if (isset($transformers[$transformerIndex])) {
$transformer = $transformers[$transformerIndex];
$captureName = str_repeat($transformerIndex, $length);

View File

@ -24,7 +24,7 @@ class Hour1200Transformer extends HourTransformer
public function format(\DateTime $dateTime, $length)
{
$hourOfDay = $dateTime->format('g');
$hourOfDay = ('12' == $hourOfDay) ? '0' : $hourOfDay;
$hourOfDay = '12' == $hourOfDay ? '0' : $hourOfDay;
return $this->padLeft($hourOfDay, $length);
}

View File

@ -35,7 +35,7 @@ class Hour1201Transformer extends HourTransformer
$hour = 0;
} elseif ('PM' === $marker && 12 !== $hour) {
// If PM and hour is not 12 (1-12), sum 12 hour
$hour = $hour + 12;
$hour += 12;
}
return $hour;

View File

@ -33,7 +33,7 @@ class Hour2400Transformer extends HourTransformer
{
if ('AM' == $marker) {
$hour = 0;
} else if ('PM' == $marker) {
} elseif ('PM' == $marker) {
$hour = 12;
}

View File

@ -34,11 +34,9 @@ class Hour2401Transformer extends HourTransformer
*/
public function normalizeHour($hour, $marker = null)
{
if (null === $marker && 24 === $hour) {
if ((null === $marker && 24 === $hour) || 'AM' == $marker) {
$hour = 0;
} else if ('AM' == $marker) {
$hour = 0;
} else if ('PM' == $marker) {
} elseif ('PM' == $marker) {
$hour = 12;
}

View File

@ -33,13 +33,7 @@ class MinuteTransformer extends Transformer
*/
public function getReverseMatchingRegExp($length)
{
if (1 == $length) {
$regExp = '\d{1,2}';
} else {
$regExp = '\d{'.$length.'}';
}
return $regExp;
return 1 === $length ? '\d{1,2}' : '\d{'.$length.'}';
}
/**

View File

@ -60,7 +60,7 @@ class MonthTransformer extends Transformer
*/
public function __construct()
{
if (0 == count(self::$shortMonths)) {
if (0 === count(self::$shortMonths)) {
self::$shortMonths = array_map(function($month) {
return substr($month, 0, 3);
}, self::$months);
@ -76,19 +76,21 @@ class MonthTransformer extends Transformer
public function format(\DateTime $dateTime, $length)
{
$matchLengthMap = array(
1 => 'n',
2 => 'm',
3 => 'M',
4 => 'F',
1 => 'n',
2 => 'm',
3 => 'M',
4 => 'F',
);
if (isset($matchLengthMap[$length])) {
return $dateTime->format($matchLengthMap[$length]);
} else if (5 == $length) {
return substr($dateTime->format('M'), 0, 1);
} else {
return $this->padLeft($dateTime->format('m'), $length);
return $dateTime->format($matchLengthMap[$length]);
}
if (5 === $length) {
return substr($dateTime->format('M'), 0, 1);
}
return $this->padLeft($dateTime->format('m'), $length);
}
/**
@ -123,13 +125,11 @@ class MonthTransformer extends Transformer
public function extractDateOptions($matched, $length)
{
if (!is_numeric($matched)) {
if (3 == $length) {
if (3 === $length) {
$matched = self::$flippedShortMonths[$matched] + 1;
}
elseif (4 == $length) {
} elseif (4 === $length) {
$matched = self::$flippedMonths[$matched] + 1;
}
elseif (5 == $length) {
} elseif (5 === $length) {
// IntlDateFormatter::parse() always returns false for MMMMM or LLLLL
$matched = false;
}

View File

@ -33,13 +33,7 @@ class SecondTransformer extends Transformer
*/
public function getReverseMatchingRegExp($length)
{
if (1 == $length) {
$regExp = '\d{1,2}';
} else {
$regExp = '\d{'.$length.'}';
}
return $regExp;
return 1 === $length ? '\d{1,2}' : '\d{'.$length.'}';
}
/**

View File

@ -23,11 +23,11 @@ class YearTransformer extends Transformer
*/
public function format(\DateTime $dateTime, $length)
{
if (2 == $length) {
if (2 === $length) {
return $dateTime->format('y');
} else {
return $this->padLeft($dateTime->format('Y'), $length);
}
return $this->padLeft($dateTime->format('Y'), $length);
}
/**
@ -35,13 +35,7 @@ class YearTransformer extends Transformer
*/
public function getReverseMatchingRegExp($length)
{
if (2 == $length) {
$regExp = '\d{2}';
} else {
$regExp = '\d{4}';
}
return $regExp;
return 2 === $length ? '\d{2}' : '\d{4}';
}
/**

View File

@ -77,7 +77,7 @@ abstract class StubIntl
*/
static public function isFailure($errorCode)
{
return in_array($errorCode, static::$errorCodes, true)
return in_array($errorCode, self::$errorCodes, true)
&& $errorCode !== self::U_ZERO_ERROR;
}
@ -90,7 +90,7 @@ abstract class StubIntl
*/
static public function getErrorCode()
{
return static::$errorCode;
return self::$errorCode;
}
/**
@ -102,7 +102,7 @@ abstract class StubIntl
*/
static public function getErrorMessage()
{
return static::$errorMessages[static::$errorCode];
return self::$errorMessages[self::$errorCode];
}
/**
@ -114,10 +114,10 @@ abstract class StubIntl
*/
static public function setErrorCode($code)
{
if (!isset(static::$errorMessages[$code])) {
if (!isset(self::$errorMessages[$code])) {
throw new \InvalidArgumentException(sprintf('No such error code: "%s"', $code));
}
static::$errorCode = $code;
self::$errorCode = $code;
}
}

View File

@ -481,8 +481,7 @@ class StubLocale
static private function getStubData($locale, $cacheVariable, $stubDataDir)
{
if ('en' != $locale) {
$message = 'Only the \'en\' locale is supported. '.NotImplementedException::INTL_INSTALL_MESSAGE;
throw new \InvalidArgumentException($message);
throw new \InvalidArgumentException(sprintf('Only the \'en\' locale is supported. %s', NotImplementedException::INTL_INSTALL_MESSAGE));
}
if (empty(self::${$cacheVariable})) {

View File

@ -0,0 +1,45 @@
Process Component
=================
Process executes commands in sub-processes.
In this example, we run a simple directory listing and get the result back:
use Symfony\Component\Process\Process;
$process = new Process('ls -lsa');
$process->setTimeout(3600);
$process->run();
if (!$process->isSuccessful()) {
throw new RuntimeException($process->getErrorOutput());
}
print $process->getOutput();
You can think that this is easy to achieve with plain PHP but it's not especially
if you want to take care of the subtle differences between the different platforms.
And if you want to be able to get some feedback in real-time, just pass an
anonymous function to the ``run()`` method and you will get the output buffer
as it becomes available:
use Symfony\Component\Process\Process;
$process = new Process('ls -lsa');
$process->run(function ($type, $buffer) {
if ('err' === $type) {
echo 'ERR > '.$buffer;
} else {
echo 'OUT > '.$buffer;
}
});
That's great if you want to execute a long running command (like rsync-ing files to a
remote server) and give feedback to the user in real-time.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Process

View File

@ -0,0 +1,32 @@
Routing Component
=================
Routing associates a request with the code that will convert it to a response.
The example below demonstrates how you can set up a fully working routing
system:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$routes = new RouteCollection();
$routes->add('hello', new Route('/hello', array('controller' => 'foo')));
$context = new RequestContext();
// this is optional and can be done without a Request instance
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match('/hello');
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Routing

View File

@ -494,7 +494,7 @@ QUERY;
$acl = $acls[$aclId];
// has the ACL been hydrated during any previous cycle, or was possibly loaded
// from cache?
} else if (isset($loadedAcls[$classType][$objectIdentifier])) {
} elseif (isset($loadedAcls[$classType][$objectIdentifier])) {
$acl = $loadedAcls[$classType][$objectIdentifier];
// keep reference in local array (saves us some hash calculations)

View File

@ -511,7 +511,7 @@ QUERY;
if ($sid instanceof UserSecurityIdentity) {
$identifier = $sid->getClass().'-'.$sid->getUsername();
$username = true;
} else if ($sid instanceof RoleSecurityIdentity) {
} elseif ($sid instanceof RoleSecurityIdentity) {
$identifier = $sid->getRole();
$username = false;
} else {
@ -579,7 +579,7 @@ QUERY;
if ($sid instanceof UserSecurityIdentity) {
$identifier = $sid->getClass().'-'.$sid->getUsername();
$username = true;
} else if ($sid instanceof RoleSecurityIdentity) {
} elseif ($sid instanceof RoleSecurityIdentity) {
$identifier = $sid->getRole();
$username = false;
} else {

View File

@ -36,7 +36,7 @@ abstract class AuditLogger implements AuditLoggerInterface
if ($granted && $ace->isAuditSuccess()) {
$this->doLog($granted, $ace);
} else if (!$granted && $ace->isAuditFailure()) {
} elseif (!$granted && $ace->isAuditFailure()) {
$this->doLog($granted, $ace);
}
}

View File

@ -60,7 +60,7 @@ final class ObjectIdentity implements ObjectIdentityInterface
try {
if ($domainObject instanceof DomainObjectInterface) {
return new self($domainObject->getObjectIdentifier(), get_class($domainObject));
} else if (method_exists($domainObject, 'getId')) {
} elseif (method_exists($domainObject, 'getId')) {
return new self($domainObject->getId(), get_class($domainObject));
}
} catch (\InvalidArgumentException $invalid) {

View File

@ -196,9 +196,9 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface
$strategy = $ace->getStrategy();
if (self::ALL === $strategy) {
return $requiredMask === ($ace->getMask() & $requiredMask);
} else if (self::ANY === $strategy) {
} elseif (self::ANY === $strategy) {
return 0 !== ($ace->getMask() & $requiredMask);
} else if (self::EQUAL === $strategy) {
} elseif (self::EQUAL === $strategy) {
return $requiredMask === $ace->getMask();
}

View File

@ -67,10 +67,10 @@ class SecurityIdentityRetrievalStrategy implements SecurityIdentityRetrievalStra
$sids[] = new RoleSecurityIdentity(AuthenticatedVoter::IS_AUTHENTICATED_FULLY);
$sids[] = new RoleSecurityIdentity(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED);
$sids[] = new RoleSecurityIdentity(AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY);
} else if ($this->authenticationTrustResolver->isRememberMe($token)) {
} elseif ($this->authenticationTrustResolver->isRememberMe($token)) {
$sids[] = new RoleSecurityIdentity(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED);
$sids[] = new RoleSecurityIdentity(AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY);
} else if ($this->authenticationTrustResolver->isAnonymous($token)) {
} elseif ($this->authenticationTrustResolver->isAnonymous($token)) {
$sids[] = new RoleSecurityIdentity(AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY);
}

View File

@ -93,7 +93,7 @@ class MaskBuilder
{
if (is_string($mask) && defined($name = 'static::MASK_'.strtoupper($mask))) {
$mask = constant($name);
} else if (!is_int($mask)) {
} elseif (!is_int($mask)) {
throw new \InvalidArgumentException('$mask must be an integer.');
}
@ -146,7 +146,7 @@ class MaskBuilder
{
if (is_string($mask) && defined($name = 'static::MASK_'.strtoupper($mask))) {
$mask = constant($name);
} else if (!is_int($mask)) {
} elseif (!is_int($mask)) {
throw new \InvalidArgumentException('$mask must be an integer.');
}

View File

@ -64,7 +64,7 @@ class AclVoter implements VoterInterface
}
return $this->allowIfObjectIdentityUnavailable ? self::ACCESS_GRANTED : self::ACCESS_ABSTAIN;
} else if ($object instanceof FieldVote) {
} elseif ($object instanceof FieldVote) {
$field = $object->getField();
$object = $object->getDomainObject();
} else {
@ -73,7 +73,7 @@ class AclVoter implements VoterInterface
if ($object instanceof ObjectIdentityInterface) {
$oid = $object;
} else if (null === $oid = $this->objectIdentityRetrievalStrategy->getObjectIdentity($object)) {
} elseif (null === $oid = $this->objectIdentityRetrievalStrategy->getObjectIdentity($object)) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Object identity unavailable. Voting to %s', $this->allowIfObjectIdentityUnavailable? 'grant access' : 'abstain'));
}
@ -96,7 +96,7 @@ class AclVoter implements VoterInterface
}
return self::ACCESS_GRANTED;
} else if (null !== $field && $acl->isFieldGranted($field, $masks, $sids, false)) {
} elseif (null !== $field && $acl->isFieldGranted($field, $masks, $sids, false)) {
if (null !== $this->logger) {
$this->logger->debug('ACL found, permission granted. Voting to grant access');
}

View File

@ -42,7 +42,7 @@ abstract class AbstractToken implements TokenInterface
foreach ($roles as $role) {
if (is_string($role)) {
$role = new Role($role);
} else if (!$role instanceof RoleInterface) {
} elseif (!$role instanceof RoleInterface) {
throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, or RoleInterface instances, but got %s.', gettype($role)));
}
@ -83,13 +83,13 @@ abstract class AbstractToken implements TokenInterface
if (null === $this->user) {
$changed = false;
} else if ($this->user instanceof UserInterface) {
} elseif ($this->user instanceof UserInterface) {
if (!$user instanceof UserInterface) {
$changed = true;
} else {
$changed = !$this->user->equals($user);
}
} else if ($user instanceof UserInterface) {
} elseif ($user instanceof UserInterface) {
$changed = true;
} else {
$changed = (string) $this->user !== (string) $user;

View File

@ -144,7 +144,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
$this->sessionStrategy->onAuthentication($request, $returnValue);
$response = $this->onSuccess($event, $request, $returnValue);
} else if ($returnValue instanceof Response) {
} elseif ($returnValue instanceof Response) {
$response = $returnValue;
} else {
throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');

View File

@ -0,0 +1,18 @@
Security Component
==================
Security provides an infrastructure for sophisticated authorization systems,
which makes it possible to easily separate the actual authorization logic from
so called user providers that hold the users credentials. It is inspired by
the Java Spring framework.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Security
Documentation:
http://symfony.com/doc/2.0/book/security.html

View File

@ -79,7 +79,7 @@ class GetSetMethodNormalizer extends SerializerAwareNormalizer implements Normal
$params[] = $data[$paramName];
// don't run set for a parameter passed to the constructor
unset($data[$paramName]);
} else if (!$constructorParameter->isOptional()) {
} elseif (!$constructorParameter->isOptional()) {
throw new RuntimeException(
'Cannot create an instance of '.$class.
' from serialized data because its constructor requires '.

View File

@ -0,0 +1,13 @@
Serializer Component
====================
With the Serializer component its possible to handle serializing data structures,
including object graphs, into array structures or other formats like XML and JSON.
It can also handle deserializing XML and JSON back to object graphs.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Serializer

View File

@ -0,0 +1,16 @@
Templating Component
====================
Templating provides all the tools needed to build any kind of template system.
It provides an infrastructure to load template files and optionally monitor
them for changes. It also provides a concrete template engine implementation
using PHP with additional tools for escaping and separating templates into
blocks and layouts.
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Templating

View File

@ -0,0 +1,33 @@
Translation Component
=====================
Translation provides tools for loading translation files and generating
translated strings from these including support for pluralization.
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\ArrayLoader;
$translator = new Translator('fr_FR', new MessageSelector());
$translator->setFallbackLocale('fr');
$translator->addLoader('array', return new ArrayLoader());
$translator->addResource('array', array(
'Hello World!' => 'Bonjour',
), 'fr');
$translator->trans('Hello World!');
Resources
---------
Silex integration:
https://github.com/fabpot/Silex/blob/master/src/Silex/Provider/TranslationServiceProvider.php
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Translation
Documentation:
http://symfony.com/doc/2.0/book/translation.html

View File

@ -100,7 +100,7 @@ abstract class Constraint
$invalidOptions[] = $option;
}
}
} else if (null !== $options && ! (is_array($options) && count($options) === 0)) {
} elseif (null !== $options && ! (is_array($options) && count($options) === 0)) {
$option = $this->getDefaultOption();
if (null === $option) {

View File

@ -54,7 +54,7 @@ class ChoiceValidator extends ConstraintValidator
if ($constraint->callback) {
if (is_callable(array($this->context->getCurrentClass(), $constraint->callback))) {
$choices = call_user_func(array($this->context->getCurrentClass(), $constraint->callback));
} else if (is_callable($constraint->callback)) {
} elseif (is_callable($constraint->callback)) {
$choices = call_user_func($constraint->callback);
} else {
throw new ConstraintDefinitionException('The Choice constraint expects a valid callback');

View File

@ -81,11 +81,11 @@ class FileValidator extends ConstraintValidator
$size = filesize($path);
$limit = $constraint->maxSize;
$suffix = ' bytes';
} else if (preg_match('/^(\d+)k$/', $constraint->maxSize, $matches)) {
} elseif (preg_match('/^(\d+)k$/', $constraint->maxSize, $matches)) {
$size = round(filesize($path) / 1000, 2);
$limit = $matches[1];
$suffix = ' kB';
} else if (preg_match('/^(\d+)M$/', $constraint->maxSize, $matches)) {
} elseif (preg_match('/^(\d+)M$/', $constraint->maxSize, $matches)) {
$size = round(filesize($path) / 1000000, 2);
$limit = $matches[1];
$suffix = ' MB';

View File

@ -186,7 +186,7 @@ class ClassMetadata extends ElementMetadata
if ($member instanceof PropertyMetadata && !isset($this->properties[$property])) {
$this->properties[$property] = $member;
} else if ($member instanceof GetterMetadata && !isset($this->getters[$property])) {
} elseif ($member instanceof GetterMetadata && !isset($this->getters[$property])) {
$this->getters[$property] = $member;
}
}

View File

@ -28,7 +28,7 @@ class GetterMetadata extends MemberMetadata
if (method_exists($class, $getMethod)) {
$method = $getMethod;
} else if (method_exists($class, $isMethod)) {
} elseif (method_exists($class, $isMethod)) {
$method = $isMethod;
} else {
throw new ValidatorException(sprintf('Neither method %s nor %s exists in class %s', $getMethod, $isMethod, $class));

View File

@ -58,7 +58,7 @@ abstract class FileLoader implements LoaderInterface
{
if (strpos($name, '\\') !== false && class_exists($name)) {
$className = (string) $name;
} else if (strpos($name, ':') !== false) {
} elseif (strpos($name, ':') !== false) {
list($prefix, $className) = explode(':', $name, 2);
if (!isset($this->namespaces[$prefix])) {

View File

@ -80,14 +80,14 @@ class XmlFileLoader extends FileLoader
if (count($node) > 0) {
if (count($node->value) > 0) {
$options = $this->parseValues($node->value);
} else if (count($node->constraint) > 0) {
} elseif (count($node->constraint) > 0) {
$options = $this->parseConstraints($node->constraint);
} else if (count($node->option) > 0) {
} elseif (count($node->option) > 0) {
$options = $this->parseOptions($node->option);
} else {
$options = array();
}
} else if (strlen((string) $node) > 0) {
} elseif (strlen((string) $node) > 0) {
$options = trim($node);
} else {
$options = null;
@ -114,7 +114,7 @@ class XmlFileLoader extends FileLoader
if (count($node) > 0) {
if (count($node->value) > 0) {
$value = $this->parseValues($node->value);
} else if (count($node->constraint) > 0) {
} elseif (count($node->constraint) > 0) {
$value = $this->parseConstraints($node->constraint);
} else {
$value = array();
@ -148,7 +148,7 @@ class XmlFileLoader extends FileLoader
if (count($node) > 0) {
if (count($node->value) > 0) {
$value = $this->parseValues($node->value);
} else if (count($node->constraint) > 0) {
} elseif (count($node->constraint) > 0) {
$value = $this->parseConstraints($node->constraint);
} else {
$value = array();

View File

@ -0,0 +1,49 @@
Validator Component
===================
This component is based on the JSR-303 Bean Validation specification and
enables specifying validation rules for classes using XML, YAML or
annotations, which can then be checked against instances of these classes.
use Symfony\Component\Validator\Validator;
use Symfony\Component\Validator\Mapping\ClassMetadataFactory;
use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Component\Validator\ConstraintValidatorFactory;
$validator = new Validator(
new ClassMetadataFactory(new StaticMethodLoader()),
new ConstraintValidatorFactory()
);
$constraint = new Assert\Collection(array(
'name' => new Assert\Collection(array(
'first_name' => new Assert\MinLength(101),
'last_name' => new Assert\MinLength(1),
)),
'email' => new Assert\Email(),
'simple' => new Assert\MinLength(102),
'gender' => new Assert\Choice(array(3, 4)),
'file' => new Assert\File(),
'password' => new Assert\MinLength(60),
));
$violations = $validator->validateValue($input, $constraint);
Resources
---------
Silex integration:
https://github.com/fabpot/Silex/blob/master/src/Silex/Provider/ValidatorServiceProvider.php
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Validator
Documentation:
http://symfony.com/doc/2.0/book/validation.html
JSR-303 Specification:
http://jcp.org/en/jsr/detail?id=303

View File

@ -110,7 +110,7 @@ class ValidatorFactory implements ValidatorContextInterface
if ($extension === 'xml') {
$xmlMappingFiles[] = $file;
} else if ($extension === 'yaml' || $extension === 'yml') {
} elseif ($extension === 'yaml' || $extension === 'yml') {
$yamlMappingFiles[] = $file;
} else {
throw new MappingException('The only supported mapping file formats are XML and YAML');
@ -135,7 +135,7 @@ class ValidatorFactory implements ValidatorContextInterface
if (count($loaders) > 1) {
$loader = new LoaderChain($loaders);
} else if (count($loaders) === 1) {
} elseif (count($loaders) === 1) {
$loader = $loaders[0];
} else {
throw new MappingException('No mapping loader was found for the given parameters');

View File

@ -171,7 +171,7 @@ class Inline
if (false !== $strpos = strpos($output, ' #')) {
$output = rtrim(substr($output, 0, $strpos));
}
} else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
} elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
$output = $match[1];
$i += strlen($output);
} else {

View File

@ -103,7 +103,7 @@ class Parser
$data[] = $this->parseValue($values['value']);
}
}
} else if (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) {
} elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) {
try {
$key = Inline::parseScalar($values['key']);
} catch (ParseException $e) {
@ -133,7 +133,7 @@ class Parser
$merged = array();
if (!is_array($parsed)) {
throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
} else if (isset($parsed[0])) {
} elseif (isset($parsed[0])) {
// Numeric array, merge individual elements
foreach (array_reverse($parsed) as $parsedItem) {
if (!is_array($parsedItem)) {
@ -148,7 +148,7 @@ class Parser
$isProcessed = $merged;
}
} else if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
} elseif (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
$isRef = $matches['ref'];
$values['value'] = $matches['value'];
}
@ -157,7 +157,7 @@ class Parser
// Merge keys
$data = $isProcessed;
// hash
} else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
} elseif (!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()) {
$data[$key] = null;
@ -298,9 +298,9 @@ class Parser
if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match)) {
// empty line
$data[] = $match['text'];
} else if ($indent >= $newIndent) {
} elseif ($indent >= $newIndent) {
$data[] = substr($this->currentLine, $newIndent);
} else if (0 == $indent) {
} elseif (0 == $indent) {
$this->moveToPreviousLine();
break;
@ -423,7 +423,7 @@ class Parser
$previousIndent = $matches['indent'];
$text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
} else if (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches)) {
} elseif (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches)) {
$text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
} else {
$this->moveToPreviousLine();

View File

@ -0,0 +1,17 @@
Yaml Component
==============
YAML implements most of the YAML 1.2 specification.
use Symfony\Component\Yaml\Yaml;
$array = Yaml::parse($file);
print Yaml::dump($array);
Resources
---------
Unit tests:
https://github.com/symfony/symfony/tree/master/tests/Symfony/Tests/Component/Yaml

View File

@ -66,16 +66,22 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$m = $r->getMethod('filterResponse');
$m->setAccessible(true);
$expected = array(
'foo=bar; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly',
'foo1=bar1; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly'
);
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
$this->assertEquals('foo=bar; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly', $domResponse->getHeader('Set-Cookie'));
$this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));
$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$response->headers->setCookie(new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
$domResponse = $m->invoke($client, $response);
$this->assertEquals('foo=bar; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly, foo1=bar1; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly', $domResponse->getHeader('Set-Cookie'));
$this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));
$this->assertEquals($expected, $domResponse->getHeader('Set-Cookie', false));
}
public function testUploadedFile()

View File

@ -165,7 +165,7 @@ class HttpCacheTestCase extends \PHPUnit_Framework_TestCase
{
if (is_link($directory.'/'.$file)) {
unlink($directory.'/'.$file);
} else if (is_dir($directory.'/'.$file)) {
} elseif (is_dir($directory.'/'.$file)) {
self::clearDirectory($directory.'/'.$file);
rmdir($directory.'/'.$file);
} else {

View File

@ -195,7 +195,7 @@ class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
$strategy = rand(0, 2);
if ($strategy === 0) {
$strategy = PermissionGrantingStrategy::ALL;
} else if ($strategy === 1) {
} elseif ($strategy === 1) {
$strategy = PermissionGrantingStrategy::ANY;
} else {
$strategy = PermissionGrantingStrategy::EQUAL;

View File

@ -148,7 +148,7 @@ class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
->expects($this->never())
->method('isRememberMe')
;
} else if ('rememberMe' === $authenticationStatus) {
} elseif ('rememberMe' === $authenticationStatus) {
$trustResolver
->expects($this->once())
->method('isFullFledged')

View File

@ -70,7 +70,7 @@ class AuthenticatedVoterTest extends \PHPUnit_Framework_TestCase
{
if ('fully' === $authenticated) {
return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
} else if ('remembered' === $authenticated) {
} elseif ('remembered' === $authenticated) {
return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('setPersistent'), array(), '', false);
} else {
return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken', null, array('', ''));

View File

@ -50,7 +50,7 @@ class DumperTest extends \PHPUnit_Framework_TestCase
$test = $this->parser->parse($yaml);
if (isset($test['dump_skip']) && $test['dump_skip']) {
continue;
} else if (isset($test['todo']) && $test['todo']) {
} elseif (isset($test['todo']) && $test['todo']) {
// TODO
} else {
$expected = eval('return '.trim($test['php']).';');