Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK!c/7/7Component/Form/CHANGELOG.mdnu[CHANGELOG ========= 2.4.0 ----- * moved CSRF implementation to the new Security CSRF sub-component * deprecated CsrfProviderInterface and its implementations * deprecated options "csrf_provider" and "intention" in favor of the new options "csrf_token_generator" and "csrf_token_id" 2.3.0 ----- * deprecated FormPerformanceTestCase and FormIntegrationTestCase in the Symfony\Component\Form\Tests namespace and moved them to the Symfony\Component\Form\Test namespace * deprecated TypeTestCase in the Symfony\Component\Form\Tests\Extension\Core\Type namespace and moved it to the Symfony\Component\Form\Test namespace * changed FormRenderer::humanize() to humanize also camel cased field name * added RequestHandlerInterface and FormInterface::handleRequest() * deprecated passing a Request instance to FormInterface::bind() * added options "method" and "action" to FormType * deprecated option "virtual" in favor "inherit_data" * deprecated VirtualFormAwareIterator in favor of InheritDataAwareIterator * [BC BREAK] removed the "array" type hint from DataMapperInterface * improved forms inheriting their parent data to actually return that data from getData(), getNormData() and getViewData() * added component-level exceptions for various SPL exceptions changed all uses of the deprecated Exception class to use more specialized exceptions instead removed NotInitializedException, NotValidException, TypeDefinitionException, TypeLoaderException, CreationException * added events PRE_SUBMIT, SUBMIT and POST_SUBMIT * deprecated events PRE_BIND, BIND and POST_BIND * [BC BREAK] renamed bind() and isBound() in FormInterface to submit() and isSubmitted() * added methods submit() and isSubmitted() to Form * deprecated bind() and isBound() in Form * deprecated AlreadyBoundException in favor of AlreadySubmittedException * added support for PATCH requests * [BC BREAK] added initialize() to FormInterface * [BC BREAK] added getAutoInitialize() to FormConfigInterface * [BC BREAK] added setAutoInitialize() to FormConfigBuilderInterface * [BC BREAK] initialization for Form instances added to a form tree must be manually disabled * PRE_SET_DATA is now guaranteed to be called after children were added by the form builder, unless FormInterface::setData() is called manually * fixed CSRF error message to be translated * custom CSRF error messages can now be set through the "csrf_message" option * fixed: expanded single-choice fields now show a radio button for the empty value 2.2.0 ----- * TrimListener now removes unicode whitespaces * deprecated getParent(), setParent() and hasParent() in FormBuilderInterface * FormInterface::add() now accepts a FormInterface instance OR a field's name, type and options * removed special characters between the choice or text fields of DateType unless the option "format" is set to a custom value * deprecated FormException and introduced ExceptionInterface instead * [BC BREAK] FormException is now an interface * protected FormBuilder methods from being called when it is turned into a FormConfigInterface with getFormConfig() * [BC BREAK] inserted argument `$message` in the constructor of `FormError` * the PropertyPath class and related classes were moved to a dedicated PropertyAccess component. During the move, InvalidPropertyException was renamed to NoSuchPropertyException. FormUtil was split: FormUtil::singularify() can now be found in Symfony\Component\PropertyAccess\StringUtil. The methods getValue() and setValue() from PropertyPath were extracted into a new class PropertyAccessor. * added an optional PropertyAccessorInterface parameter to FormType, ObjectChoiceList and PropertyPathMapper * [BC BREAK] PropertyPathMapper and FormType now have a constructor * [BC BREAK] setting the option "validation_groups" to ``false`` now disables validation instead of assuming group "Default" 2.1.0 ----- * [BC BREAK] ``read_only`` field attribute now renders as ``readonly="readonly"``, use ``disabled`` instead * [BC BREAK] child forms now aren't validated anymore by default * made validation of form children configurable (new option: cascade_validation) * added support for validation groups as callbacks * made the translation catalogue configurable via the "translation_domain" option * added Form::getErrorsAsString() to help debugging forms * allowed setting different options for RepeatedType fields (like the label) * added support for empty form name at root level, this enables rendering forms without form name prefix in field names * [BC BREAK] form and field names must start with a letter, digit or underscore and only contain letters, digits, underscores, hyphens and colons * [BC BREAK] changed default name of the prototype in the "collection" type from "$$name$$" to "\__name\__". No dollars are appended/prepended to custom names anymore. * [BC BREAK] improved ChoiceListInterface * [BC BREAK] added SimpleChoiceList and LazyChoiceList as replacement of ArrayChoiceList * added ChoiceList and ObjectChoiceList to use objects as choices * [BC BREAK] removed EntitiesToArrayTransformer and EntityToIdTransformer. The former has been replaced by CollectionToArrayTransformer in combination with EntityChoiceList, the latter is not required in the core anymore. * [BC BREAK] renamed * ArrayToBooleanChoicesTransformer to ChoicesToBooleanArrayTransformer * ScalarToBooleanChoicesTransformer to ChoiceToBooleanArrayTransformer * ArrayToChoicesTransformer to ChoicesToValuesTransformer * ScalarToChoiceTransformer to ChoiceToValueTransformer to be consistent with the naming in ChoiceListInterface. They were merged into ChoiceList and have no public equivalent anymore. * choice fields now throw a FormException if neither the "choices" nor the "choice_list" option is set * the radio type is now a child of the checkbox type * the collection, choice (with multiple selection) and entity (with multiple selection) types now make use of addXxx() and removeXxx() methods in your model if you set "by_reference" to false. For a custom, non-recognized singular form, set the "property_path" option like this: "plural|singular" * forms now don't create an empty object anymore if they are completely empty and not required. The empty value for such forms is null. * added constant Guess::VERY_HIGH_CONFIDENCE * [BC BREAK] The methods `add`, `remove`, `setParent`, `bind` and `setData` in class Form now throw an exception if the form is already bound * fields of constrained classes without a NotBlank or NotNull constraint are set to not required now, as stated in the docs * fixed TimeType and DateTimeType to not display seconds when "widget" is "single_text" unless "with_seconds" is set to true * checkboxes of in an expanded multiple-choice field don't include the choice in their name anymore. Their names terminate with "[]" now. * deprecated FormValidatorInterface and substituted its implementations by event subscribers * simplified CSRF protection and removed the csrf type * deprecated FieldType and merged it into FormType * added new option "compound" that lets you switch between field and form behavior * [BC BREAK] renamed theme blocks * "field_*" to "form_*" * "field_widget" to "form_widget_simple" * "widget_choice_options" to "choice_widget_options" * "generic_label" to "form_label" * added theme blocks "form_widget_compound", "choice_widget_expanded" and "choice_widget_collapsed" to make theming more modular * ValidatorTypeGuesser now guesses "collection" for array type constraint * added method `guessPattern` to FormTypeGuesserInterface to guess which pattern to use in the HTML5 attribute "pattern" * deprecated method `guessMinLength` in favor of `guessPattern` * labels don't display field attributes anymore. Label attributes can be passed in the "label_attr" option/variable * added option "mapped" which should be used instead of setting "property_path" to false * [BC BREAK] "data_class" now *must* be set if a form maps to an object and should be left empty otherwise * improved error mapping on forms * dot (".") rules are now allowed to map errors assigned to a form to one of its children * errors are not mapped to unsynchronized forms anymore * [BC BREAK] changed Form constructor to accept a single `FormConfigInterface` object * [BC BREAK] changed argument order in the FormBuilder constructor * added Form method `getViewData` * deprecated Form methods * `getTypes` * `getErrorBubbling` * `getNormTransformers` * `getClientTransformers` * `getAttribute` * `hasAttribute` * `getClientData` * added FormBuilder methods * `getTypes` * `addViewTransformer` * `getViewTransformers` * `resetViewTransformers` * `addModelTransformer` * `getModelTransformers` * `resetModelTransformers` * deprecated FormBuilder methods * `prependClientTransformer` * `appendClientTransformer` * `getClientTransformers` * `resetClientTransformers` * `prependNormTransformer` * `appendNormTransformer` * `getNormTransformers` * `resetNormTransformers` * deprecated the option "validation_constraint" in favor of the new option "constraints" * removed superfluous methods from DataMapperInterface * `mapFormToData` * `mapDataToForm` * added `setDefaultOptions` to FormTypeInterface and FormTypeExtensionInterface which accepts an OptionsResolverInterface instance * deprecated the methods `getDefaultOptions` and `getAllowedOptionValues` in FormTypeInterface and FormTypeExtensionInterface * options passed during construction can now be accessed from FormConfigInterface * added FormBuilderInterface and FormConfigEditorInterface * [BC BREAK] the method `buildForm` in FormTypeInterface and FormTypeExtensionInterface now receives a FormBuilderInterface instead of a FormBuilder instance * [BC BREAK] the method `buildViewBottomUp` was renamed to `finishView` in FormTypeInterface and FormTypeExtensionInterface * [BC BREAK] the options array is now passed as last argument of the methods * `buildView` * `finishView` in FormTypeInterface and FormTypeExtensionInterface * [BC BREAK] no options are passed to `getParent` of FormTypeInterface anymore * deprecated DataEvent and FilterDataEvent in favor of the new FormEvent which is now passed to all events thrown by the component * FormEvents::BIND now replaces FormEvents::BIND_NORM_DATA * FormEvents::PRE_SET_DATA now replaces FormEvents::SET_DATA * FormEvents::PRE_BIND now replaces FormEvents::BIND_CLIENT_DATA * deprecated FormEvents::SET_DATA, FormEvents::BIND_CLIENT_DATA and FormEvents::BIND_NORM_DATA * [BC BREAK] reversed the order of the first two arguments to `createNamed` and `createNamedBuilder` in `FormFactoryInterface` * deprecated `getChildren` in Form and FormBuilder in favor of `all` * deprecated `hasChildren` in Form and FormBuilder in favor of `count` * FormBuilder now implements \IteratorAggregate * [BC BREAK] compound forms now always need a data mapper * FormBuilder now maintains the order when explicitly adding form builders as children * ChoiceType now doesn't add the empty value anymore if the choices already contain an empty element * DateType, TimeType and DateTimeType now show empty values again if not required * [BC BREAK] fixed rendering of errors for DateType, BirthdayType and similar ones * [BC BREAK] fixed: form constraints are only validated if they belong to the validated group * deprecated `bindRequest` in `Form` and replaced it by a listener to FormEvents::PRE_BIND * fixed: the "data" option supersedes default values from the model * changed DateType to refer to the "format" option for calculating the year and day choices instead of padding them automatically * [BC BREAK] DateType defaults to the format "yyyy-MM-dd" now if the widget is "single_text", in order to support the HTML 5 date field out of the box * added the option "format" to DateTimeType * [BC BREAK] DateTimeType now outputs RFC 3339 dates by default, as generated and consumed by HTML5 browsers, if the widget is "single_text" * deprecated the options "data_timezone" and "user_timezone" in DateType, DateTimeType and TimeType and renamed them to "model_timezone" and "view_timezone" * fixed: TransformationFailedExceptions thrown in the model transformer are now caught by the form * added FormRegistryInterface, ResolvedFormTypeInterface and ResolvedFormTypeFactoryInterface * deprecated FormFactory methods * `addType` * `hasType` * `getType` * [BC BREAK] FormFactory now expects a FormRegistryInterface and a ResolvedFormTypeFactoryInterface as constructor argument * [BC BREAK] The method `createBuilder` in FormTypeInterface is not supported anymore for performance reasons * [BC BREAK] Removed `setTypes` from FormBuilder * deprecated AbstractType methods * `getExtensions` * `setExtensions` * ChoiceType now caches its created choice lists to improve performance * [BC BREAK] Rows of a collection field cannot be themed individually anymore. All rows in the collection field now have the same block names, which contains "entry" where it previously contained the row index. * [BC BREAK] When registering a type through the DI extension, the tag alias has to match the actual type name. * added FormRendererInterface, FormRendererEngineInterface and implementations of these interfaces * [BC BREAK] removed the following methods from FormUtil: * `toArrayKey` * `toArrayKeys` * `isChoiceGroup` * `isChoiceSelected` * [BC BREAK] renamed method `renderBlock` in FormHelper to `block` and changed its signature * made FormView properties public and deprecated their accessor methods * made the normalized data of a form accessible in the template through the variable "form.vars.data" * made the original data of a choice accessible in the template through the property "choice.data" * added convenience class Forms and FormFactoryBuilderInterface PK!J!!Component/Form/composer.jsonnu[{ "name": "symfony/form", "type": "library", "description": "Symfony Form Component", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3", "symfony/event-dispatcher": "~2.1", "symfony/intl": "~2.3", "symfony/options-resolver": "~2.1", "symfony/property-access": "~2.3" }, "require-dev": { "symfony/validator": "~2.2", "symfony/http-foundation": "~2.2", "symfony/security-csrf": "~2.4" }, "suggest": { "symfony/validator": "For form validation.", "symfony/security-csrf": "For protecting forms against CSRF attacks.", "symfony/twig-bridge": "For templating with Twig.", "symfony/framework-bundle": "For templating with PHP." }, "autoload": { "psr-0": { "Symfony\\Component\\Form\\": "" } }, "target-dir": "Symfony/Component/Form", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!Component/Form/README.mdnu[Form Component ============== Form provides tools for defining forms, rendering and mapping 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 Documentation: http://symfony.com/doc/2.4/book/forms.html Resources --------- You can run the unit tests with the following command: $ cd path/to/Symfony/Component/Form/ $ composer.phar install $ phpunit PK!E))Component/Form/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!]Q 9Component/ClassLoader/Tests/ClassCollectionLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ClassLoader\Tests; use Symfony\Component\ClassLoader\ClassCollectionLoader; require_once __DIR__.'/Fixtures/ClassesWithParents/GInterface.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/CInterface.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/B.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/A.php'; class ClassCollectionLoaderTest extends \PHPUnit_Framework_TestCase { public function testTraitDependencies() { if (version_compare(phpversion(), '5.4', '<')) { $this->markTestSkipped('Requires PHP > 5.4'); return; } require_once __DIR__.'/Fixtures/deps/traits.php'; $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); $m = $r->getMethod('getOrderedClasses'); $m->setAccessible(true); $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', array('CTFoo')); $this->assertEquals( array('TD', 'TC', 'TB', 'TA', 'TZ', 'CTFoo'), array_map(function ($class) { return $class->getName(); }, $ordered) ); $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', array('CTBar')); $this->assertEquals( array('TD', 'TZ', 'TC', 'TB', 'TA', 'CTBar'), array_map(function ($class) { return $class->getName(); }, $ordered) ); } /** * @dataProvider getDifferentOrders */ public function testClassReordering(array $classes) { $expected = array( 'ClassesWithParents\\GInterface', 'ClassesWithParents\\CInterface', 'ClassesWithParents\\B', 'ClassesWithParents\\A', ); $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); $m = $r->getMethod('getOrderedClasses'); $m->setAccessible(true); $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', $classes); $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered)); } public function getDifferentOrders() { return array( array(array( 'ClassesWithParents\\A', 'ClassesWithParents\\CInterface', 'ClassesWithParents\\GInterface', 'ClassesWithParents\\B', )), array(array( 'ClassesWithParents\\B', 'ClassesWithParents\\A', 'ClassesWithParents\\CInterface', )), array(array( 'ClassesWithParents\\CInterface', 'ClassesWithParents\\B', 'ClassesWithParents\\A', )), array(array( 'ClassesWithParents\\A', )), ); } /** * @dataProvider getDifferentOrdersForTraits */ public function testClassWithTraitsReordering(array $classes) { if (version_compare(phpversion(), '5.4', '<')) { $this->markTestSkipped('Requires PHP > 5.4'); return; } require_once __DIR__.'/Fixtures/ClassesWithParents/ATrait.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/BTrait.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/CTrait.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/D.php'; require_once __DIR__.'/Fixtures/ClassesWithParents/E.php'; $expected = array( 'ClassesWithParents\\GInterface', 'ClassesWithParents\\CInterface', 'ClassesWithParents\\ATrait', 'ClassesWithParents\\BTrait', 'ClassesWithParents\\CTrait', 'ClassesWithParents\\B', 'ClassesWithParents\\A', 'ClassesWithParents\\D', 'ClassesWithParents\\E', ); $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); $m = $r->getMethod('getOrderedClasses'); $m->setAccessible(true); $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', $classes); $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered)); } public function getDifferentOrdersForTraits() { return array( array(array( 'ClassesWithParents\\E', 'ClassesWithParents\\ATrait', )), array(array( 'ClassesWithParents\\E', )), ); } /** * @dataProvider getFixNamespaceDeclarationsData */ public function testFixNamespaceDeclarations($source, $expected) { $this->assertEquals('assertEquals('assertEquals(<< * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ClassMap; abstract class SomeParent { } PK!֡Z  ?Component/ClassLoader/Tests/Fixtures/classmap/SomeInterface.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ClassMap; interface SomeInterface { } PK!KG9Ո<Component/ClassLoader/Tests/Fixtures/classmap/multipleNs.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Foo\Bar; class A {} class B {} PK!.~oDD;Component/ClassLoader/Tests/Fixtures/classmap/SomeClass.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ClassMap; class SomeClass extends SomeParent implements SomeInterface { } PK!R;Component/ClassLoader/Tests/Fixtures/classmap/notPhpFile.mdnu[This file should be skipped. PK!i;Component/ClassLoader/Tests/Fixtures/classmap/notAClass.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NamespaceCollision\A\B; class Bar { public static $loaded = true; } PK!AAHComponent/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/A/B/Foo.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NamespaceCollision\A\B; class Foo { public static $loaded = true; } PK!@OO8Component/ClassLoader/Tests/Fixtures/Namespaced2/Bar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Namespaced; class Bar { public static $loaded = true; } PK!ᒟ557Component/ClassLoader/Tests/Fixtures/Namespaced/Baz.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Namespaced; class Baz { public static $loaded = true; } PK!R557Component/ClassLoader/Tests/Fixtures/Namespaced/Foo.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Namespaced; class Foo { public static $loaded = true; } PK!UX@Component/ClassLoader/Tests/Fixtures/Namespaced/WithComments.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Namespaced; class WithComments { /** @Boolean */ public static $loaded = true; } $string = 'string shoult not be modified {$string}'; $heredoc = (<<Component/ClassLoader/Tests/Fixtures/Pearlike/WithComments.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Pearlike_WithComments { /** @Boolean */ public static $loaded = true; } PK!>X4Component/ClassLoader/Tests/Fixtures/deps/traits.phpnu[XXGComponent/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/C/Bar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NamespaceCollision\A; class Bar { public static $loaded = true; } PK!i??GComponent/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/A/Foo.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NamespaceCollision\A; class Foo { public static $loaded = true; } PK!nDDBComponent/ClassLoader/Tests/Fixtures/fallback/Pearlike2/FooBar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Namespaced; class FooBar { public static $loaded = true; } PK!xwCCAComponent/ClassLoader/Tests/Fixtures/fallback/Pearlike/FooBar.phpnu[\oNNPComponent/ClassLoader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Bar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\NamespaceCollision\A\B; class Bar { public static $loaded = true; } PK!][EEPComponent/ClassLoader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Foo.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\NamespaceCollision\A\B; class Foo { public static $loaded = true; } PK!/5<<>Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/FooBar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\Namespaced; class FooBar { public static $loaded = true; } PK!ے99;Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Bar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\Namespaced; class Bar { public static $loaded = true; } PK!$y99;Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Baz.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\Namespaced; class Baz { public static $loaded = true; } PK!0- +99;Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Foo.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\Namespaced; class Foo { public static $loaded = true; } PK!yQUmDD9Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Bar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\NamespaceCollision\A; class Bar { public static $loaded = true; } PK!qoCCOComponent/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Foo.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\NamespaceCollision\A; class Foo { public static $loaded = true; } PK!/5<<GComponent/ClassLoader/Tests/Fixtures/Apc/fallback/Namespaced/FooBar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Apc\Namespaced; class FooBar { public static $loaded = true; } PK!GGIComponent/ClassLoader/Tests/Fixtures/Apc/fallback/Apc/Pearlike/FooBar.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ClassLoader\Tests; use Symfony\Component\ClassLoader\ClassLoader; class ClassLoaderTest extends \PHPUnit_Framework_TestCase { public function testGetPrefixes() { $loader = new ClassLoader(); $loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('Bar', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('Bas', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $prefixes = $loader->getPrefixes(); $this->assertArrayHasKey('Foo', $prefixes); $this->assertArrayNotHasKey('Foo1', $prefixes); $this->assertArrayHasKey('Bar', $prefixes); $this->assertArrayHasKey('Bas', $prefixes); } public function testGetFallbackDirs() { $loader = new ClassLoader(); $loader->addPrefix(null, __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix(null, __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $fallback_dirs = $loader->getFallbackDirs(); $this->assertCount(2, $fallback_dirs); } /** * @dataProvider getLoadClassTests */ public function testLoadClass($className, $testClassName, $message) { $loader = new ClassLoader(); $loader->addPrefix('Namespaced2\\', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('Pearlike2_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->loadClass($testClassName); $this->assertTrue(class_exists($className), $message); } public function getLoadClassTests() { return array( array('\\Namespaced2\\Foo', 'Namespaced2\\Foo', '->loadClass() loads Namespaced2\Foo class'), array('\\Pearlike2_Foo', 'Pearlike2_Foo', '->loadClass() loads Pearlike2_Foo class'), ); } /** * @dataProvider getLoadNonexistentClassTests */ public function testLoadNonexistentClass($className, $testClassName, $message) { $loader = new ClassLoader(); $loader->addPrefix('Namespaced2\\', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('Pearlike2_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->loadClass($testClassName); $this->assertFalse(class_exists($className), $message); } public function getLoadNonexistentClassTests() { return array( array('\\Pearlike3_Bar', '\\Pearlike3_Bar', '->loadClass() loads non existing Pearlike3_Bar class with a leading slash'), ); } public function testAddPrefix() { $loader = new ClassLoader(); $loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $prefixes = $loader->getPrefixes(); $this->assertArrayHasKey('Foo', $prefixes); $this->assertCount(2, $prefixes['Foo']); } public function testUseIncludePath() { $loader = new ClassLoader(); $this->assertFalse($loader->getUseIncludePath()); $this->assertNull($loader->findFile('Foo')); $includePath = get_include_path(); $loader->setUseIncludePath(true); $this->assertTrue($loader->getUseIncludePath()); set_include_path(__DIR__.'/Fixtures/includepath'.PATH_SEPARATOR.$includePath); $this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'includepath'.DIRECTORY_SEPARATOR.'Foo.php', $loader->findFile('Foo')); set_include_path($includePath); } /** * @dataProvider getLoadClassFromFallbackTests */ public function testLoadClassFromFallback($className, $testClassName, $message) { $loader = new ClassLoader(); $loader->addPrefix('Namespaced2\\', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('Pearlike2_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->addPrefix('', array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback')); $loader->loadClass($testClassName); $this->assertTrue(class_exists($className), $message); } public function getLoadClassFromFallbackTests() { return array( array('\\Namespaced2\\Baz', 'Namespaced2\\Baz', '->loadClass() loads Namespaced2\Baz class'), array('\\Pearlike2_Baz', 'Pearlike2_Baz', '->loadClass() loads Pearlike2_Baz class'), array('\\Namespaced2\\FooBar', 'Namespaced2\\FooBar', '->loadClass() loads Namespaced2\Baz class from fallback dir'), array('\\Pearlike2_FooBar', 'Pearlike2_FooBar', '->loadClass() loads Pearlike2_Baz class from fallback dir'), ); } /** * @dataProvider getLoadClassNamespaceCollisionTests */ public function testLoadClassNamespaceCollision($namespaces, $className, $message) { $loader = new ClassLoader(); $loader->addPrefixes($namespaces); $loader->loadClass($className); $this->assertTrue(class_exists($className), $message); } public function getLoadClassNamespaceCollisionTests() { return array( array( array( 'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'NamespaceCollision\C\Foo', '->loadClass() loads NamespaceCollision\C\Foo from alpha.', ), array( array( 'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'NamespaceCollision\C\Bar', '->loadClass() loads NamespaceCollision\C\Bar from alpha.', ), array( array( 'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'NamespaceCollision\C\B\Foo', '->loadClass() loads NamespaceCollision\C\B\Foo from beta.', ), array( array( 'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'NamespaceCollision\C\B\Bar', '->loadClass() loads NamespaceCollision\C\B\Bar from beta.', ), array( array( 'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'PrefixCollision_C_Foo', '->loadClass() loads PrefixCollision_C_Foo from alpha.', ), array( array( 'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'PrefixCollision_C_Bar', '->loadClass() loads PrefixCollision_C_Bar from alpha.', ), array( array( 'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'PrefixCollision_C_B_Foo', '->loadClass() loads PrefixCollision_C_B_Foo from beta.', ), array( array( 'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'PrefixCollision_C_B_Bar', '->loadClass() loads PrefixCollision_C_B_Bar from beta.', ), ); } } PK!e:{a;Component/ClassLoader/Tests/ApcUniversalClassLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ClassLoader\Tests; use Symfony\Component\ClassLoader\ApcUniversalClassLoader; class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase { protected function setUp() { if (!extension_loaded('apc')) { $this->markTestSkipped('The apc extension is not available.'); } if (!(ini_get('apc.enabled') && ini_get('apc.enable_cli'))) { $this->markTestSkipped('The apc extension is available, but not enabled.'); } else { apc_clear_cache('user'); } } protected function tearDown() { if (ini_get('apc.enabled') && ini_get('apc.enable_cli')) { apc_clear_cache('user'); } } public function testConstructor() { $loader = new ApcUniversalClassLoader('test.prefix.'); $loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $this->assertEquals($loader->findFile('\Apc\Namespaced\FooBar'), apc_fetch('test.prefix.\Apc\Namespaced\FooBar'), '__construct() takes a prefix as its first argument'); } /** * @dataProvider getLoadClassTests */ public function testLoadClass($className, $testClassName, $message) { $loader = new ApcUniversalClassLoader('test.prefix.'); $loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerPrefix('Apc_Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->loadClass($testClassName); $this->assertTrue(class_exists($className), $message); } public function getLoadClassTests() { return array( array('\\Apc\\Namespaced\\Foo', '\\Apc\\Namespaced\\Foo', '->loadClass() loads Apc\Namespaced\Foo class'), array('Apc_Pearlike_Foo', 'Apc_Pearlike_Foo', '->loadClass() loads Apc_Pearlike_Foo class'), array('\\Apc\\Namespaced\\Bar', '\\Apc\\Namespaced\\Bar', '->loadClass() loads Apc\Namespaced\Bar class with a leading slash'), array('Apc_Pearlike_Bar', '\\Apc_Pearlike_Bar', '->loadClass() loads Apc_Pearlike_Bar class with a leading slash'), ); } /** * @dataProvider getLoadClassFromFallbackTests */ public function testLoadClassFromFallback($className, $testClassName, $message) { $loader = new ApcUniversalClassLoader('test.prefix.fallback'); $loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerPrefix('Apc_Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerNamespaceFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback')); $loader->registerPrefixFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback')); $loader->loadClass($testClassName); $this->assertTrue(class_exists($className), $message); } public function getLoadClassFromFallbackTests() { return array( array('\\Apc\\Namespaced\\Baz', '\\Apc\\Namespaced\\Baz', '->loadClass() loads Apc\Namespaced\Baz class'), array('Apc_Pearlike_Baz', 'Apc_Pearlike_Baz', '->loadClass() loads Apc_Pearlike_Baz class'), array('\\Apc\\Namespaced\\FooBar', '\\Apc\\Namespaced\\FooBar', '->loadClass() loads Apc\Namespaced\Baz class from fallback dir'), array('Apc_Pearlike_FooBar', 'Apc_Pearlike_FooBar', '->loadClass() loads Apc_Pearlike_Baz class from fallback dir'), ); } /** * @dataProvider getLoadClassNamespaceCollisionTests */ public function testLoadClassNamespaceCollision($namespaces, $className, $message) { $loader = new ApcUniversalClassLoader('test.prefix.collision.'); $loader->registerNamespaces($namespaces); $loader->loadClass($className); $this->assertTrue(class_exists($className), $message); } public function getLoadClassNamespaceCollisionTests() { return array( array( array( 'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', 'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', ), '\Apc\NamespaceCollision\A\Foo', '->loadClass() loads NamespaceCollision\A\Foo from alpha.', ), array( array( 'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', 'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', ), '\Apc\NamespaceCollision\A\Bar', '->loadClass() loads NamespaceCollision\A\Bar from alpha.', ), array( array( 'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', 'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', ), '\Apc\NamespaceCollision\A\B\Foo', '->loadClass() loads NamespaceCollision\A\B\Foo from beta.', ), array( array( 'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', 'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', ), '\Apc\NamespaceCollision\A\B\Bar', '->loadClass() loads NamespaceCollision\A\B\Bar from beta.', ), ); } /** * @dataProvider getLoadClassPrefixCollisionTests */ public function testLoadClassPrefixCollision($prefixes, $className, $message) { $loader = new ApcUniversalClassLoader('test.prefix.collision.'); $loader->registerPrefixes($prefixes); $loader->loadClass($className); $this->assertTrue(class_exists($className), $message); } public function getLoadClassPrefixCollisionTests() { return array( array( array( 'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', 'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', ), 'ApcPrefixCollision_A_Foo', '->loadClass() loads ApcPrefixCollision_A_Foo from alpha.', ), array( array( 'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', 'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', ), 'ApcPrefixCollision_A_Bar', '->loadClass() loads ApcPrefixCollision_A_Bar from alpha.', ), array( array( 'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', 'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', ), 'ApcPrefixCollision_A_B_Foo', '->loadClass() loads ApcPrefixCollision_A_B_Foo from beta.', ), array( array( 'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', 'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', ), 'ApcPrefixCollision_A_B_Bar', '->loadClass() loads ApcPrefixCollision_A_B_Bar from beta.', ), ); } } PK!8`##8Component/ClassLoader/Tests/UniversalClassLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ClassLoader\Tests; use Symfony\Component\ClassLoader\UniversalClassLoader; class UniversalClassLoaderTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getLoadClassTests */ public function testLoadClass($className, $testClassName, $message) { $loader = new UniversalClassLoader(); $loader->registerNamespace('Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerPrefix('Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $this->assertTrue($loader->loadClass($testClassName)); $this->assertTrue(class_exists($className), $message); } public function getLoadClassTests() { return array( array('\\Namespaced\\Foo', 'Namespaced\\Foo', '->loadClass() loads Namespaced\Foo class'), array('\\Pearlike_Foo', 'Pearlike_Foo', '->loadClass() loads Pearlike_Foo class'), ); } public function testUseIncludePath() { $loader = new UniversalClassLoader(); $this->assertFalse($loader->getUseIncludePath()); $this->assertNull($loader->findFile('Foo')); $includePath = get_include_path(); $loader->useIncludePath(true); $this->assertTrue($loader->getUseIncludePath()); set_include_path(__DIR__.'/Fixtures/includepath'.PATH_SEPARATOR.$includePath); $this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'includepath'.DIRECTORY_SEPARATOR.'Foo.php', $loader->findFile('Foo')); set_include_path($includePath); } public function testGetNamespaces() { $loader = new UniversalClassLoader(); $loader->registerNamespace('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerNamespace('Bar', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerNamespace('Bas', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $namespaces = $loader->getNamespaces(); $this->assertArrayHasKey('Foo', $namespaces); $this->assertArrayNotHasKey('Foo1', $namespaces); $this->assertArrayHasKey('Bar', $namespaces); $this->assertArrayHasKey('Bas', $namespaces); } public function testGetPrefixes() { $loader = new UniversalClassLoader(); $loader->registerPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerPrefix('Bar', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerPrefix('Bas', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $prefixes = $loader->getPrefixes(); $this->assertArrayHasKey('Foo', $prefixes); $this->assertArrayNotHasKey('Foo1', $prefixes); $this->assertArrayHasKey('Bar', $prefixes); $this->assertArrayHasKey('Bas', $prefixes); } /** * @dataProvider getLoadClassFromFallbackTests */ public function testLoadClassFromFallback($className, $testClassName, $message) { $loader = new UniversalClassLoader(); $loader->registerNamespace('Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerPrefix('Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures'); $loader->registerNamespaceFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback')); $loader->registerPrefixFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback')); $this->assertTrue($loader->loadClass($testClassName)); $this->assertTrue(class_exists($className), $message); } public function getLoadClassFromFallbackTests() { return array( array('\\Namespaced\\Baz', 'Namespaced\\Baz', '->loadClass() loads Namespaced\Baz class'), array('\\Pearlike_Baz', 'Pearlike_Baz', '->loadClass() loads Pearlike_Baz class'), array('\\Namespaced\\FooBar', 'Namespaced\\FooBar', '->loadClass() loads Namespaced\Baz class from fallback dir'), array('\\Pearlike_FooBar', 'Pearlike_FooBar', '->loadClass() loads Pearlike_Baz class from fallback dir'), ); } public function testRegisterPrefixFallback() { $loader = new UniversalClassLoader(); $loader->registerPrefixFallback(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback'); $this->assertEquals(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback'), $loader->getPrefixFallbacks()); } public function testRegisterNamespaceFallback() { $loader = new UniversalClassLoader(); $loader->registerNamespaceFallback(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Namespaced/fallback'); $this->assertEquals(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Namespaced/fallback'), $loader->getNamespaceFallbacks()); } /** * @dataProvider getLoadClassNamespaceCollisionTests */ public function testLoadClassNamespaceCollision($namespaces, $className, $message) { $loader = new UniversalClassLoader(); $loader->registerNamespaces($namespaces); $this->assertTrue($loader->loadClass($className)); $this->assertTrue(class_exists($className), $message); } public function getLoadClassNamespaceCollisionTests() { return array( array( array( 'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'NamespaceCollision\A\Foo', '->loadClass() loads NamespaceCollision\A\Foo from alpha.', ), array( array( 'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'NamespaceCollision\A\Bar', '->loadClass() loads NamespaceCollision\A\Bar from alpha.', ), array( array( 'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'NamespaceCollision\A\B\Foo', '->loadClass() loads NamespaceCollision\A\B\Foo from beta.', ), array( array( 'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'NamespaceCollision\A\B\Bar', '->loadClass() loads NamespaceCollision\A\B\Bar from beta.', ), ); } /** * @dataProvider getLoadClassPrefixCollisionTests */ public function testLoadClassPrefixCollision($prefixes, $className, $message) { $loader = new UniversalClassLoader(); $loader->registerPrefixes($prefixes); $this->assertTrue($loader->loadClass($className)); $this->assertTrue(class_exists($className), $message); } public function getLoadClassPrefixCollisionTests() { return array( array( array( 'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'PrefixCollision_A_Foo', '->loadClass() loads PrefixCollision_A_Foo from alpha.', ), array( array( 'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'PrefixCollision_A_Bar', '->loadClass() loads PrefixCollision_A_Bar from alpha.', ), array( array( 'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', 'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', ), 'PrefixCollision_A_B_Foo', '->loadClass() loads PrefixCollision_A_B_Foo from beta.', ), array( array( 'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta', 'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha', ), 'PrefixCollision_A_B_Bar', '->loadClass() loads PrefixCollision_A_B_Bar from beta.', ), ); } } PK!\|5Component/ClassLoader/Tests/ClassMapGeneratorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ClassLoader\Tests; use Symfony\Component\ClassLoader\ClassMapGenerator; class ClassMapGeneratorTest extends \PHPUnit_Framework_TestCase { /** * @var string $workspace */ private $workspace = null; public function prepare_workspace() { $this->workspace = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.time().rand(0, 1000); mkdir($this->workspace, 0777, true); $this->workspace = realpath($this->workspace); } /** * @param string $file */ private function clean($file) { if (is_dir($file) && !is_link($file)) { $dir = new \FilesystemIterator($file); foreach ($dir as $childFile) { $this->clean($childFile); } rmdir($file); } else { unlink($file); } } /** * @dataProvider getTestCreateMapTests */ public function testDump($directory, $expected) { $this->prepare_workspace(); $file = $this->workspace.'/file'; $generator = new ClassMapGenerator(); $generator->dump($directory, $file); $this->assertFileExists($file); $this->clean($this->workspace); } /** * @dataProvider getTestCreateMapTests */ public function testCreateMap($directory, $expected) { $this->assertEqualsNormalized($expected, ClassMapGenerator::createMap($directory)); } public function getTestCreateMapTests() { $data = array( array(__DIR__.'/Fixtures/Namespaced', array( 'Namespaced\\Bar' => realpath(__DIR__).'/Fixtures/Namespaced/Bar.php', 'Namespaced\\Foo' => realpath(__DIR__).'/Fixtures/Namespaced/Foo.php', 'Namespaced\\Baz' => realpath(__DIR__).'/Fixtures/Namespaced/Baz.php', 'Namespaced\\WithComments' => realpath(__DIR__).'/Fixtures/Namespaced/WithComments.php', ) ), array(__DIR__.'/Fixtures/beta/NamespaceCollision', array( 'NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Bar.php', 'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Foo.php', 'NamespaceCollision\\C\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Bar.php', 'NamespaceCollision\\C\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Foo.php', )), array(__DIR__.'/Fixtures/Pearlike', array( 'Pearlike_Foo' => realpath(__DIR__).'/Fixtures/Pearlike/Foo.php', 'Pearlike_Bar' => realpath(__DIR__).'/Fixtures/Pearlike/Bar.php', 'Pearlike_Baz' => realpath(__DIR__).'/Fixtures/Pearlike/Baz.php', 'Pearlike_WithComments' => realpath(__DIR__).'/Fixtures/Pearlike/WithComments.php', )), array(__DIR__.'/Fixtures/classmap', array( 'Foo\\Bar\\A' => realpath(__DIR__).'/Fixtures/classmap/sameNsMultipleClasses.php', 'Foo\\Bar\\B' => realpath(__DIR__).'/Fixtures/classmap/sameNsMultipleClasses.php', 'A' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', 'Alpha\\A' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', 'Alpha\\B' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', 'Beta\\A' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', 'Beta\\B' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', 'ClassMap\\SomeInterface' => realpath(__DIR__).'/Fixtures/classmap/SomeInterface.php', 'ClassMap\\SomeParent' => realpath(__DIR__).'/Fixtures/classmap/SomeParent.php', 'ClassMap\\SomeClass' => realpath(__DIR__).'/Fixtures/classmap/SomeClass.php', )), ); if (version_compare(PHP_VERSION, '5.4', '>=')) { $data[] = array(__DIR__.'/Fixtures/php5.4', array( 'TFoo' => __DIR__.'/Fixtures/php5.4/traits.php', 'CFoo' => __DIR__.'/Fixtures/php5.4/traits.php', 'Foo\\TBar' => __DIR__.'/Fixtures/php5.4/traits.php', 'Foo\\IBar' => __DIR__.'/Fixtures/php5.4/traits.php', 'Foo\\TFooBar' => __DIR__.'/Fixtures/php5.4/traits.php', 'Foo\\CBar' => __DIR__.'/Fixtures/php5.4/traits.php', )); } return $data; } public function testCreateMapFinderSupport() { $finder = new \Symfony\Component\Finder\Finder(); $finder->files()->in(__DIR__.'/Fixtures/beta/NamespaceCollision'); $this->assertEqualsNormalized(array( 'NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Bar.php', 'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Foo.php', 'NamespaceCollision\\C\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Bar.php', 'NamespaceCollision\\C\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Foo.php', ), ClassMapGenerator::createMap($finder)); } protected function assertEqualsNormalized($expected, $actual, $message = null) { foreach ($expected as $ns => $path) { $expected[$ns] = strtr($path, '\\', '/'); } foreach ($actual as $ns => $path) { $actual[$ns] = strtr($path, '\\', '/'); } $this->assertEquals($expected, $actual, $message); } } PK!)mm&Component/ClassLoader/phpunit.xml.distnu[ ./Tests/ ./ ./Resources ./Tests ./vendor PK!ާ Component/Validator/CHANGELOG.mdnu[CHANGELOG ========= 2.4.0 ----- * added a constraint the uses the expression language * added `minRatio`, `maxRatio`, `allowSquare`, `allowLandscape`, and `allowPortrait` to Image validator 2.3.0 ----- * added the ISBN, ISSN, and IBAN validators * copied the constraints `Optional` and `Required` to the `Symfony\Component\Validator\Constraints\` namespace and deprecated the original classes. * added comparison validators (EqualTo, NotEqualTo, LessThan, LessThanOrEqualTo, GreaterThan, GreaterThanOrEqualTo, IdenticalTo, NotIdenticalTo) 2.2.0 ----- * added a CardScheme validator * added a Luhn validator * moved @api-tags from `Validator` to `ValidatorInterface` * moved @api-tags from `ConstraintViolation` to the new `ConstraintViolationInterface` * moved @api-tags from `ConstraintViolationList` to the new `ConstraintViolationListInterface` * moved @api-tags from `ExecutionContext` to the new `ExecutionContextInterface` * [BC BREAK] `ConstraintValidatorInterface::initialize` is now type hinted against `ExecutionContextInterface` instead of `ExecutionContext` * [BC BREAK] changed the visibility of the properties in `Validator` from protected to private * deprecated `ClassMetadataFactoryInterface` in favor of the new `MetadataFactoryInterface` * deprecated `ClassMetadataFactory::getClassMetadata` in favor of `getMetadataFor` * created `MetadataInterface`, `PropertyMetadataInterface`, `ClassBasedInterface` and `PropertyMetadataContainerInterface` * deprecated `GraphWalker` in favor of the new `ValidationVisitorInterface` * deprecated `ExecutionContext::addViolationAtPath` * deprecated `ExecutionContext::addViolationAtSubPath` in favor of `ExecutionContextInterface::addViolationAt` * deprecated `ExecutionContext::getCurrentClass` in favor of `ExecutionContextInterface::getClassName` * deprecated `ExecutionContext::getCurrentProperty` in favor of `ExecutionContextInterface::getPropertyName` * deprecated `ExecutionContext::getCurrentValue` in favor of `ExecutionContextInterface::getValue` * deprecated `ExecutionContext::getGraphWalker` in favor of `ExecutionContextInterface::validate` and `ExecutionContextInterface::validateValue` * improved `ValidatorInterface::validateValue` to accept arrays of constraints * changed `ValidatorInterface::getMetadataFactory` to return a `MetadataFactoryInterface` instead of a `ClassMetadataFactoryInterface` * removed `ClassMetadataFactoryInterface` type hint from `ValidatorBuilderInterface::setMetadataFactory`. As of Symfony 2.3, this method will be typed against `MetadataFactoryInterface` instead. * [BC BREAK] the switches `traverse` and `deep` in the `Valid` constraint and in `GraphWalker::walkReference` are ignored for arrays now. Arrays are always traversed recursively. * added dependency to Translation component * violation messages are now translated with a TranslatorInterface implementation * [BC BREAK] inserted argument `$message` in the constructor of `ConstraintViolation` * [BC BREAK] inserted arguments `$translator` and `$translationDomain` in the constructor of `ExecutionContext` * [BC BREAK] inserted arguments `$translator` and `$translationDomain` in the constructor of `GraphWalker` * [BC BREAK] inserted arguments `$translator` and `$translationDomain` in the constructor of `ValidationVisitor` * [BC BREAK] inserted arguments `$translator` and `$translationDomain` in the constructor of `Validator` * [BC BREAK] added `setTranslator()` and `setTranslationDomain()` to `ValidatorBuilderInterface` * improved the Validator to support pluralized messages by default * [BC BREAK] changed the source of all pluralized messages in the translation files to the pluralized version * added ExceptionInterface, BadMethodCallException and InvalidArgumentException 2.1.0 ----- * added support for `ctype_*` assertions in `TypeValidator` * improved the ImageValidator with min width, max width, min height, and max height constraints * added support for MIME with wildcard in FileValidator * changed Collection validator to add "missing" and "extra" errors to individual fields * changed default value for `extraFieldsMessage` and `missingFieldsMessage` in Collection constraint * made ExecutionContext immutable * deprecated Constraint methods `setMessage`, `getMessageTemplate` and `getMessageParameters` * added support for dynamic group sequences with the GroupSequenceProvider pattern * [BC BREAK] ConstraintValidatorInterface method `isValid` has been renamed to `validate`, its return value was dropped. ConstraintValidator still contains `isValid` for BC * [BC BREAK] collections in fields annotated with `Valid` are not traversed recursively anymore by default. `Valid` contains a new property `deep` which enables the BC behavior. * added Count constraint * added Length constraint * added Range constraint * deprecated the Min and Max constraints * deprecated the MinLength and MaxLength constraints * added Validation and ValidatorBuilderInterface * deprecated ValidatorContext, ValidatorContextInterface and ValidatorFactory PK!_ss!Component/Validator/composer.jsonnu[{ "name": "symfony/validator", "type": "library", "description": "Symfony Validator Component", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3", "symfony/translation": "~2.0", "symfony/property-access": "~2.2" }, "require-dev": { "symfony/http-foundation": "~2.1", "symfony/intl": "~2.3", "symfony/yaml": "~2.0", "symfony/config": "~2.2", "doctrine/annotations": "~1.0", "doctrine/cache": "~1.0" }, "suggest": { "doctrine/annotations": "For using the annotation mapping. You will also need doctrine/cache.", "doctrine/cache": "For using the default cached annotation reader", "symfony/http-foundation": "", "symfony/intl": "", "symfony/yaml": "", "symfony/config": "" }, "autoload": { "psr-0": { "Symfony\\Component\\Validator\\": "" } }, "target-dir": "Symfony/Component/Validator", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!bComponent/Validator/README.mdnu[Validator Component =================== This component is based on the JSR-303 Bean Validation specification and enables specifying validation rules for classes using XML, YAML, PHP or annotations, which can then be checked against instances of these classes. Usage ----- The component provides "validation constraints", which are simple objects containing the rules for the validation. Let's validate a simple string as an example: use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Constraints\Length; $validator = Validation::createValidator(); $violations = $validator->validateValue('Bernhard', new Length(array('min' => 10))); This validation will fail because the given string is shorter than ten characters. The precise errors, here called "constraint violations", are returned by the validator. You can analyze these or return them to the user. If the violation list is empty, validation succeeded. Validation of arrays is possible using the `Collection` constraint: use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Constraints as Assert; $validator = Validation::createValidator(); $constraint = new Assert\Collection(array( 'name' => new Assert\Collection(array( 'first_name' => new Assert\Length(array('min' => 101)), 'last_name' => new Assert\Length(array('min' => 1)), )), 'email' => new Assert\Email(), 'simple' => new Assert\Length(array('min' => 102)), 'gender' => new Assert\Choice(array(3, 4)), 'file' => new Assert\File(), 'password' => new Assert\Length(array('min' => 60)), )); $violations = $validator->validateValue($input, $constraint); Again, the validator returns the list of violations. Validation of objects is possible using "constraint mapping". With such a mapping you can put constraints onto properties and objects of classes. Whenever an object of this class is validated, its properties and method results are matched against the constraints. use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Constraints as Assert; class User { /** * @Assert\Length(min = 3) * @Assert\NotBlank */ private $name; /** * @Assert\Email * @Assert\NotBlank */ private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } /** * @Assert\True(message = "The user should have a Google Mail account") */ public function isGmailUser() { return false !== strpos($this->email, '@gmail.com'); } } $validator = Validation::createValidatorBuilder() ->enableAnnotationMapping() ->getValidator(); $user = new User('John Doe', 'john@example.com'); $violations = $validator->validate($user); This example uses the annotation support of Doctrine Common to map constraints to properties and methods. You can also map constraints using XML, YAML or plain PHP, if you dislike annotations or don't want to include Doctrine. Check the documentation for more information about these drivers. Resources --------- Silex integration: https://github.com/fabpot/Silex/blob/master/src/Silex/Provider/ValidatorServiceProvider.php Documentation: http://symfony.com/doc/2.4/book/validation.html JSR-303 Specification: http://jcp.org/en/jsr/detail?id=303 You can run the unit tests with the following command: $ cd path/to/Symfony/Component/Validator/ $ composer.phar install $ phpunit PK!E))Component/Validator/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!yMV<Component/DependencyInjection/Tests/ContainerBuilderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; require_once __DIR__.'/Fixtures/includes/classes.php'; require_once __DIR__.'/Fixtures/includes/ProjectExtension.php'; use Symfony\Component\Config\Resource\ResourceInterface; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\InactiveScopeException; use Symfony\Component\DependencyInjection\Loader\ClosureLoader; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\ExpressionLanguage\Expression; class ContainerBuilderTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setDefinitions * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getDefinitions * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setDefinition * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getDefinition */ public function testDefinitions() { $builder = new ContainerBuilder(); $definitions = array( 'foo' => new Definition('FooClass'), 'bar' => new Definition('BarClass'), ); $builder->setDefinitions($definitions); $this->assertEquals($definitions, $builder->getDefinitions(), '->setDefinitions() sets the service definitions'); $this->assertTrue($builder->hasDefinition('foo'), '->hasDefinition() returns true if a service definition exists'); $this->assertFalse($builder->hasDefinition('foobar'), '->hasDefinition() returns false if a service definition does not exist'); $builder->setDefinition('foobar', $foo = new Definition('FooBarClass')); $this->assertEquals($foo, $builder->getDefinition('foobar'), '->getDefinition() returns a service definition if defined'); $this->assertTrue($builder->setDefinition('foobar', $foo = new Definition('FooBarClass')) === $foo, '->setDefinition() implements a fluid interface by returning the service reference'); $builder->addDefinitions($defs = array('foobar' => new Definition('FooBarClass'))); $this->assertEquals(array_merge($definitions, $defs), $builder->getDefinitions(), '->addDefinitions() adds the service definitions'); try { $builder->getDefinition('baz'); $this->fail('->getDefinition() throws an InvalidArgumentException if the service definition does not exist'); } catch (\InvalidArgumentException $e) { $this->assertEquals('The service definition "baz" does not exist.', $e->getMessage(), '->getDefinition() throws an InvalidArgumentException if the service definition does not exist'); } } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::register */ public function testRegister() { $builder = new ContainerBuilder(); $builder->register('foo', 'FooClass'); $this->assertTrue($builder->hasDefinition('foo'), '->register() registers a new service definition'); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $builder->getDefinition('foo'), '->register() returns the newly created Definition instance'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::has */ public function testHas() { $builder = new ContainerBuilder(); $this->assertFalse($builder->has('foo'), '->has() returns false if the service does not exist'); $builder->register('foo', 'FooClass'); $this->assertTrue($builder->has('foo'), '->has() returns true if a service definition exists'); $builder->set('bar', new \stdClass()); $this->assertTrue($builder->has('bar'), '->has() returns true if a service exists'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::get */ public function testGet() { $builder = new ContainerBuilder(); try { $builder->get('foo'); $this->fail('->get() throws an InvalidArgumentException if the service does not exist'); } catch (\InvalidArgumentException $e) { $this->assertEquals('The service definition "foo" does not exist.', $e->getMessage(), '->get() throws an InvalidArgumentException if the service does not exist'); } $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service does not exist and NULL_ON_INVALID_REFERENCE is passed as a second argument'); $builder->register('foo', 'stdClass'); $this->assertInternalType('object', $builder->get('foo'), '->get() returns the service definition associated with the id'); $builder->set('bar', $bar = new \stdClass()); $this->assertEquals($bar, $builder->get('bar'), '->get() returns the service associated with the id'); $builder->register('bar', 'stdClass'); $this->assertEquals($bar, $builder->get('bar'), '->get() returns the service associated with the id even if a definition has been defined'); $builder->register('baz', 'stdClass')->setArguments(array(new Reference('baz'))); try { @$builder->get('baz'); $this->fail('->get() throws a ServiceCircularReferenceException if the service has a circular reference to itself'); } catch (\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException $e) { $this->assertEquals('Circular reference detected for service "baz", path: "baz".', $e->getMessage(), '->get() throws a LogicException if the service has a circular reference to itself'); } $builder->register('foobar', 'stdClass')->setScope('container'); $this->assertTrue($builder->get('bar') === $builder->get('bar'), '->get() always returns the same instance if the service is shared'); } /** * @covers \Symfony\Component\DependencyInjection\ContainerBuilder::get * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException * @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service. */ public function testGetUnsetLoadingServiceWhenCreateServiceThrowsAnException() { $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass')->setSynthetic(true); // we expect a RuntimeException here as foo is synthetic try { $builder->get('foo'); } catch (RuntimeException $e) { } // we must also have the same RuntimeException here $builder->get('foo'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::get */ public function testGetReturnsNullOnInactiveScope() { $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass')->setScope('request'); $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::get */ public function testGetReturnsNullOnInactiveScopeWhenServiceIsCreatedByAMethod() { $builder = new ProjectContainer(); $this->assertNull($builder->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getServiceIds */ public function testGetServiceIds() { $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass'); $builder->bar = $bar = new \stdClass(); $builder->register('bar', 'stdClass'); $this->assertEquals(array('foo', 'bar', 'service_container'), $builder->getServiceIds(), '->getServiceIds() returns all defined service ids'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setAlias * @covers Symfony\Component\DependencyInjection\ContainerBuilder::hasAlias * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getAlias */ public function testAliases() { $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass'); $builder->setAlias('bar', 'foo'); $this->assertTrue($builder->hasAlias('bar'), '->hasAlias() returns true if the alias exists'); $this->assertFalse($builder->hasAlias('foobar'), '->hasAlias() returns false if the alias does not exist'); $this->assertEquals('foo', (string) $builder->getAlias('bar'), '->getAlias() returns the aliased service'); $this->assertTrue($builder->has('bar'), '->setAlias() defines a new service'); $this->assertTrue($builder->get('bar') === $builder->get('foo'), '->setAlias() creates a service that is an alias to another one'); try { $builder->getAlias('foobar'); $this->fail('->getAlias() throws an InvalidArgumentException if the alias does not exist'); } catch (\InvalidArgumentException $e) { $this->assertEquals('The service alias "foobar" does not exist.', $e->getMessage(), '->getAlias() throws an InvalidArgumentException if the alias does not exist'); } } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getAliases */ public function testGetAliases() { $builder = new ContainerBuilder(); $builder->setAlias('bar', 'foo'); $builder->setAlias('foobar', 'foo'); $builder->setAlias('moo', new Alias('foo', false)); $aliases = $builder->getAliases(); $this->assertEquals('foo', (string) $aliases['bar']); $this->assertTrue($aliases['bar']->isPublic()); $this->assertEquals('foo', (string) $aliases['foobar']); $this->assertEquals('foo', (string) $aliases['moo']); $this->assertFalse($aliases['moo']->isPublic()); $builder->register('bar', 'stdClass'); $this->assertFalse($builder->hasAlias('bar')); $builder->set('foobar', 'stdClass'); $builder->set('moo', 'stdClass'); $this->assertCount(0, $builder->getAliases(), '->getAliases() does not return aliased services that have been overridden'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setAliases */ public function testSetAliases() { $builder = new ContainerBuilder(); $builder->setAliases(array('bar' => 'foo', 'foobar' => 'foo')); $aliases = $builder->getAliases(); $this->assertTrue(isset($aliases['bar'])); $this->assertTrue(isset($aliases['foobar'])); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addAliases */ public function testAddAliases() { $builder = new ContainerBuilder(); $builder->setAliases(array('bar' => 'foo')); $builder->addAliases(array('foobar' => 'foo')); $aliases = $builder->getAliases(); $this->assertTrue(isset($aliases['bar'])); $this->assertTrue(isset($aliases['foobar'])); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addCompilerPass * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getCompilerPassConfig */ public function testAddGetCompilerPass() { $builder = new ContainerBuilder(); $builder->setResourceTracking(false); $builderCompilerPasses = $builder->getCompiler()->getPassConfig()->getPasses(); $builder->addCompilerPass($this->getMock('Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface')); $this->assertEquals(sizeof($builderCompilerPasses) + 1, sizeof($builder->getCompiler()->getPassConfig()->getPasses())); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateService() { $builder = new ContainerBuilder(); $builder->register('foo1', 'FooClass')->setFile(__DIR__.'/Fixtures/includes/foo.php'); $this->assertInstanceOf('\FooClass', $builder->get('foo1'), '->createService() requires the file defined by the service definition'); $builder->register('foo2', 'FooClass')->setFile(__DIR__.'/Fixtures/includes/%file%.php'); $builder->setParameter('file', 'foo'); $this->assertInstanceOf('\FooClass', $builder->get('foo2'), '->createService() replaces parameters in the file provided by the service definition'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateProxyWithRealServiceInstantiator() { $builder = new ContainerBuilder(); $builder->register('foo1', 'FooClass')->setFile(__DIR__.'/Fixtures/includes/foo.php'); $builder->getDefinition('foo1')->setLazy(true); $foo1 = $builder->get('foo1'); $this->assertSame($foo1, $builder->get('foo1'), 'The same proxy is retrieved on multiple subsequent calls'); $this->assertSame('FooClass', get_class($foo1)); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateServiceClass() { $builder = new ContainerBuilder(); $builder->register('foo1', '%class%'); $builder->setParameter('class', 'stdClass'); $this->assertInstanceOf('\stdClass', $builder->get('foo1'), '->createService() replaces parameters in the class provided by the service definition'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateServiceArguments() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); $builder->register('foo1', 'FooClass')->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar'), '%%unescape_it%%')); $builder->setParameter('value', 'bar'); $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar'), '%unescape_it%'), $builder->get('foo1')->arguments, '->createService() replaces parameters and service references in the arguments provided by the service definition'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateServiceFactoryMethod() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); $builder->register('foo1', 'FooClass')->setFactoryClass('FooClass')->setFactoryMethod('getInstance')->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar'))); $builder->setParameter('value', 'bar'); $this->assertTrue($builder->get('foo1')->called, '->createService() calls the factory method to create the service instance'); $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar')), $builder->get('foo1')->arguments, '->createService() passes the arguments to the factory method'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateServiceFactoryService() { $builder = new ContainerBuilder(); $builder->register('baz_service')->setFactoryService('baz_factory')->setFactoryMethod('getInstance'); $builder->register('baz_factory', 'BazClass'); $this->assertInstanceOf('BazClass', $builder->get('baz_service')); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateServiceMethodCalls() { $builder = new ContainerBuilder(); $builder->register('bar', 'stdClass'); $builder->register('foo1', 'FooClass')->addMethodCall('setBar', array(array('%value%', new Reference('bar')))); $builder->setParameter('value', 'bar'); $this->assertEquals(array('bar', $builder->get('bar')), $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService */ public function testCreateServiceConfigurator() { $builder = new ContainerBuilder(); $builder->register('foo1', 'FooClass')->setConfigurator('sc_configure'); $this->assertTrue($builder->get('foo1')->configured, '->createService() calls the configurator'); $builder->register('foo2', 'FooClass')->setConfigurator(array('%class%', 'configureStatic')); $builder->setParameter('class', 'BazClass'); $this->assertTrue($builder->get('foo2')->configured, '->createService() calls the configurator'); $builder->register('baz', 'BazClass'); $builder->register('foo3', 'FooClass')->setConfigurator(array(new Reference('baz'), 'configure')); $this->assertTrue($builder->get('foo3')->configured, '->createService() calls the configurator'); $builder->register('foo4', 'FooClass')->setConfigurator('foo'); try { $builder->get('foo4'); $this->fail('->createService() throws an InvalidArgumentException if the configure callable is not a valid callable'); } catch (\InvalidArgumentException $e) { $this->assertEquals('The configure callable for class "FooClass" is not a callable.', $e->getMessage(), '->createService() throws an InvalidArgumentException if the configure callable is not a valid callable'); } } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService * @expectedException \RuntimeException */ public function testCreateSyntheticService() { $builder = new ContainerBuilder(); $builder->register('foo', 'FooClass')->setSynthetic(true); $builder->get('foo'); } public function testCreateServiceWithExpression() { $builder = new ContainerBuilder(); $builder->setParameter('bar', 'bar'); $builder->register('bar', 'BarClass'); $builder->register('foo', 'FooClass')->addArgument(array('foo' => new Expression('service("bar").foo ~ parameter("bar")'))); $this->assertEquals('foobar', $builder->get('foo')->arguments['foo']); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::resolveServices */ public function testResolveServices() { $builder = new ContainerBuilder(); $builder->register('foo', 'FooClass'); $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Reference('foo')), '->resolveServices() resolves service references to service instances'); $this->assertEquals(array('foo' => array('foo', $builder->get('foo'))), $builder->resolveServices(array('foo' => array('foo', new Reference('foo')))), '->resolveServices() resolves service references to service instances in nested arrays'); $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::merge */ public function testMerge() { $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo'))); $container->setResourceTracking(false); $config = new ContainerBuilder(new ParameterBag(array('foo' => 'bar'))); $container->merge($config); $this->assertEquals(array('bar' => 'foo', 'foo' => 'bar'), $container->getParameterBag()->all(), '->merge() merges current parameters with the loaded ones'); $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo'))); $container->setResourceTracking(false); $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%'))); $container->merge($config); $container->compile(); $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo'))); $container->setResourceTracking(false); $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%', 'baz' => '%foo%'))); $container->merge($config); $container->compile(); $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->register('foo', 'FooClass'); $container->register('bar', 'BarClass'); $config = new ContainerBuilder(); $config->setDefinition('baz', new Definition('BazClass')); $config->setAlias('alias_for_foo', 'foo'); $container->merge($config); $this->assertEquals(array('foo', 'bar', 'baz'), array_keys($container->getDefinitions()), '->merge() merges definitions already defined ones'); $aliases = $container->getAliases(); $this->assertTrue(isset($aliases['alias_for_foo'])); $this->assertEquals('foo', (string) $aliases['alias_for_foo']); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->register('foo', 'FooClass'); $config->setDefinition('foo', new Definition('BazClass')); $container->merge($config); $this->assertEquals('BazClass', $container->getDefinition('foo')->getClass(), '->merge() overrides already defined services'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::merge * @expectedException \LogicException */ public function testMergeLogicException() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); $container->merge(new ContainerBuilder()); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::findTaggedServiceIds */ public function testfindTaggedServiceIds() { $builder = new ContainerBuilder(); $builder ->register('foo', 'FooClass') ->addTag('foo', array('foo' => 'foo')) ->addTag('bar', array('bar' => 'bar')) ->addTag('foo', array('foofoo' => 'foofoo')) ; $this->assertEquals($builder->findTaggedServiceIds('foo'), array( 'foo' => array( array('foo' => 'foo'), array('foofoo' => 'foofoo'), ) ), '->findTaggedServiceIds() returns an array of service ids and its tag attributes'); $this->assertEquals(array(), $builder->findTaggedServiceIds('foobar'), '->findTaggedServiceIds() returns an empty array if there is annotated services'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::findDefinition */ public function testFindDefinition() { $container = new ContainerBuilder(); $container->setDefinition('foo', $definition = new Definition('FooClass')); $container->setAlias('bar', 'foo'); $container->setAlias('foobar', 'bar'); $this->assertEquals($definition, $container->findDefinition('foobar'), '->findDefinition() returns a Definition'); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addObjectResource */ public function testAddObjectResource() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->addObjectResource(new \BarClass()); $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking'); $container->setResourceTracking(true); $container->addObjectResource(new \BarClass()); $resources = $container->getResources(); $this->assertCount(1, $resources, '1 resource was registered'); /* @var $resource \Symfony\Component\Config\Resource\FileResource */ $resource = end($resources); $this->assertInstanceOf('Symfony\Component\Config\Resource\FileResource', $resource); $this->assertSame(realpath(__DIR__.'/Fixtures/includes/classes.php'), realpath($resource->getResource())); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addClassResource */ public function testAddClassResource() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->addClassResource(new \ReflectionClass('BarClass')); $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking'); $container->setResourceTracking(true); $container->addClassResource(new \ReflectionClass('BarClass')); $resources = $container->getResources(); $this->assertCount(1, $resources, '1 resource was registered'); /* @var $resource \Symfony\Component\Config\Resource\FileResource */ $resource = end($resources); $this->assertInstanceOf('Symfony\Component\Config\Resource\FileResource', $resource); $this->assertSame(realpath(__DIR__.'/Fixtures/includes/classes.php'), realpath($resource->getResource())); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::compile */ public function testCompilesClassDefinitionsOfLazyServices() { $container = new ContainerBuilder(); $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking'); $container->register('foo', 'BarClass'); $container->getDefinition('foo')->setLazy(true); $container->compile(); $classesPath = realpath(__DIR__.'/Fixtures/includes/classes.php'); $matchingResources = array_filter( $container->getResources(), function (ResourceInterface $resource) use ($classesPath) { return $resource instanceof FileResource && $classesPath === realpath($resource->getResource()); } ); $this->assertNotEmpty($matchingResources); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getResources * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addResource */ public function testResources() { $container = new ContainerBuilder(); $container->addResource($a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml')); $container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml')); $resources = array(); foreach ($container->getResources() as $resource) { if (false === strpos($resource, '.php')) { $resources[] = $resource; } } $this->assertEquals(array($a, $b), $resources, '->getResources() returns an array of resources read for the current configuration'); $this->assertSame($container, $container->setResources(array())); $this->assertEquals(array(), $container->getResources()); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::registerExtension * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getExtension */ public function testExtension() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->registerExtension($extension = new \ProjectExtension()); $this->assertTrue($container->getExtension('project') === $extension, '->registerExtension() registers an extension'); $this->setExpectedException('LogicException'); $container->getExtension('no_registered'); } public function testRegisteredButNotLoadedExtension() { $extension = $this->getMock('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface'); $extension->expects($this->once())->method('getAlias')->will($this->returnValue('project')); $extension->expects($this->never())->method('load'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->registerExtension($extension); $container->compile(); } public function testRegisteredAndLoadedExtension() { $extension = $this->getMock('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface'); $extension->expects($this->exactly(2))->method('getAlias')->will($this->returnValue('project')); $extension->expects($this->once())->method('load')->with(array(array('foo' => 'bar'))); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->registerExtension($extension); $container->loadFromExtension('project', array('foo' => 'bar')); $container->compile(); } public function testPrivateServiceUser() { $fooDefinition = new Definition('BarClass'); $fooUserDefinition = new Definition('BarUserClass', array(new Reference('bar'))); $container = new ContainerBuilder(); $container->setResourceTracking(false); $fooDefinition->setPublic(false); $container->addDefinitions(array( 'bar' => $fooDefinition, 'bar_user' => $fooUserDefinition )); $container->compile(); $this->assertInstanceOf('BarClass', $container->get('bar_user')->bar); } /** * @expectedException \BadMethodCallException */ public function testThrowsExceptionWhenSetServiceOnAFrozenContainer() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->setDefinition('a', new Definition('stdClass')); $container->compile(); $container->set('a', new \stdClass()); } /** * @expectedException \BadMethodCallException */ public function testThrowsExceptionWhenAddServiceOnAFrozenContainer() { $container = new ContainerBuilder(); $container->compile(); $container->set('a', new \stdClass()); } public function testNoExceptionWhenSetSyntheticServiceOnAFrozenContainer() { $container = new ContainerBuilder(); $def = new Definition('stdClass'); $def->setSynthetic(true); $container->setDefinition('a', $def); $container->compile(); $container->set('a', $a = new \stdClass()); $this->assertEquals($a, $container->get('a')); } public function testSetOnSynchronizedService() { $container = new ContainerBuilder(); $container->register('baz', 'BazClass') ->setSynchronized(true) ; $container->register('bar', 'BarClass') ->addMethodCall('setBaz', array(new Reference('baz'))) ; $container->set('baz', $baz = new \BazClass()); $this->assertSame($baz, $container->get('bar')->getBaz()); $container->set('baz', $baz = new \BazClass()); $this->assertSame($baz, $container->get('bar')->getBaz()); } public function testSynchronizedServiceWithScopes() { $container = new ContainerBuilder(); $container->addScope(new Scope('foo')); $container->register('baz', 'BazClass') ->setSynthetic(true) ->setSynchronized(true) ->setScope('foo') ; $container->register('bar', 'BarClass') ->addMethodCall('setBaz', array(new Reference('baz', ContainerInterface::NULL_ON_INVALID_REFERENCE, false))) ; $container->compile(); $container->enterScope('foo'); $container->set('baz', $outerBaz = new \BazClass(), 'foo'); $this->assertSame($outerBaz, $container->get('bar')->getBaz()); $container->enterScope('foo'); $container->set('baz', $innerBaz = new \BazClass(), 'foo'); $this->assertSame($innerBaz, $container->get('bar')->getBaz()); $container->leaveScope('foo'); $this->assertNotSame($innerBaz, $container->get('bar')->getBaz()); $this->assertSame($outerBaz, $container->get('bar')->getBaz()); $container->leaveScope('foo'); } /** * @expectedException \BadMethodCallException */ public function testThrowsExceptionWhenSetDefinitionOnAFrozenContainer() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); $container->setDefinition('a', new Definition()); } /** * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getExtensionConfig * @covers Symfony\Component\DependencyInjection\ContainerBuilder::prependExtensionConfig */ public function testExtensionConfig() { $container = new ContainerBuilder(); $configs = $container->getExtensionConfig('foo'); $this->assertEmpty($configs); $first = array('foo' => 'bar'); $container->prependExtensionConfig('foo', $first); $configs = $container->getExtensionConfig('foo'); $this->assertEquals(array($first), $configs); $second = array('ding' => 'dong'); $container->prependExtensionConfig('foo', $second); $configs = $container->getExtensionConfig('foo'); $this->assertEquals(array($second, $first), $configs); } public function testLazyLoadedService() { $loader = new ClosureLoader($container = new ContainerBuilder()); $loader->load(function (ContainerBuilder $container) { $container->set('a', new \BazClass()); $definition = new Definition('BazClass'); $definition->setLazy(true); $container->setDefinition('a', $definition); } ); $container->setResourceTracking(true); $container->compile(); $class = new \BazClass(); $reflectionClass = new \ReflectionClass($class); $r = new \ReflectionProperty($container, 'resources'); $r->setAccessible(true); $resources = $r->getValue($container); $classInList = false; foreach ($resources as $resource) { if ($resource->getResource() === $reflectionClass->getFileName()) { $classInList = true; break; } } $this->assertTrue($classInList); } } class FooClass {} class ProjectContainer extends ContainerBuilder { public function getFoobazService() { throw new InactiveScopeException('foo', 'request'); } } PK![5Component/DependencyInjection/Tests/ParameterTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; use Symfony\Component\DependencyInjection\Parameter; class ParameterTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\Parameter::__construct */ public function testConstructor() { $ref = new Parameter('foo'); $this->assertEquals('foo', (string) $ref, '__construct() sets the id of the parameter, which is used for the __toString() method'); } } PK!~O99JComponent/DependencyInjection/Tests/LazyProxy/PhpDumper/NullDumperTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\LazyProxy\PhpDumper; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; /** * Tests for {@see \Symfony\Component\DependencyInjection\PhpDumper\NullDumper} * * @author Marco Pivetta * * @covers \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper */ class NullDumperTest extends \PHPUnit_Framework_TestCase { public function testNullDumper() { $dumper = new NullDumper(); $definition = new Definition('stdClass'); $this->assertFalse($dumper->isProxyCandidate($definition)); $this->assertSame('', $dumper->getProxyFactoryCode($definition, 'foo')); $this->assertSame('', $dumper->getProxyCode($definition)); } } PK!I8iZComponent/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\LazyProxy\Instantiator; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; /** * Tests for {@see \Symfony\Component\DependencyInjection\Instantiator\RealServiceInstantiator} * * @author Marco Pivetta * * @covers \Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator */ class RealServiceInstantiatorTest extends \PHPUnit_Framework_TestCase { public function testInstantiateProxy() { $instantiator = new RealServiceInstantiator(); $instance = new \stdClass(); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $callback = function () use ($instance) { return $instance; }; $this->assertSame($instance, $instantiator->instantiateProxy($container, new Definition(), 'foo', $callback)); } } PK!//;Component/DependencyInjection/Tests/Fixtures/php/simple.phpnu[setParameter('foo', 'foo'); PK!G3G@ ?Component/DependencyInjection/Tests/Fixtures/php/services10.phpnu[parameters = $this->getDefaultParameters(); $this->services = $this->scopedServices = $this->scopeStacks = array(); $this->set('service_container', $this); $this->scopes = array(); $this->scopeChildren = array(); $this->methodMap = array( 'test' => 'getTestService', ); $this->aliases = array(); } /** * Gets the 'test' service. * * This service is shared. * This method always returns the same instance of the service. * * @return stdClass A stdClass instance. */ protected function getTestService() { return $this->services['test'] = new \stdClass(array('only dot' => '.', 'concatenation as value' => '.\'\'.', 'concatenation from the start value' => '\'\'.', '.' => 'dot as a key', '.\'\'.' => 'concatenation as a key', '\'\'.' => 'concatenation from the start key', 'optimize concatenation' => 'string1-string2', 'optimize concatenation with empty string' => 'string1string2', 'optimize concatenation from the start' => 'start', 'optimize concatenation at the end' => 'end')); } /** * {@inheritdoc} */ public function getParameter($name) { $name = strtolower($name); if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) { throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); } return $this->parameters[$name]; } /** * {@inheritdoc} */ public function hasParameter($name) { $name = strtolower($name); return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters); } /** * {@inheritdoc} */ public function setParameter($name, $value) { throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); } /** * {@inheritDoc} */ public function getParameterBag() { if (null === $this->parameterBag) { $this->parameterBag = new FrozenParameterBag($this->parameters); } return $this->parameterBag; } /** * Gets the default parameters. * * @return array An array of the default parameters */ protected function getDefaultParameters() { return array( 'empty_value' => '', 'some_string' => '-', ); } } PK!E))@Component/DependencyInjection/Tests/Fixtures/php/services1-1.phpnu[Component/DependencyInjection/Tests/Fixtures/php/services1.phpnu[Component/DependencyInjection/Tests/Fixtures/php/services9.phpnu[getDefaultParameters())); $this->methodMap = array( 'bar' => 'getBarService', 'baz' => 'getBazService', 'depends_on_request' => 'getDependsOnRequestService', 'factory_service' => 'getFactoryServiceService', 'foo' => 'getFooService', 'foo.baz' => 'getFoo_BazService', 'foo_bar' => 'getFooBarService', 'foo_with_inline' => 'getFooWithInlineService', 'inlined' => 'getInlinedService', 'method_call1' => 'getMethodCall1Service', 'request' => 'getRequestService', ); $this->aliases = array( 'alias_for_alias' => 'foo', 'alias_for_foo' => 'foo', ); } /** * Gets the 'bar' service. * * This service is shared. * This method always returns the same instance of the service. * * @return FooClass A FooClass instance. */ protected function getBarService() { $this->services['bar'] = $instance = new \FooClass('foo', $this->get('foo.baz'), $this->getParameter('foo_bar')); $this->get('foo.baz')->configure($instance); return $instance; } /** * Gets the 'baz' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Baz A Baz instance. */ protected function getBazService() { $this->services['baz'] = $instance = new \Baz(); $instance->setFoo($this->get('foo_with_inline')); return $instance; } /** * Gets the 'depends_on_request' service. * * This service is shared. * This method always returns the same instance of the service. * * @return stdClass A stdClass instance. */ protected function getDependsOnRequestService() { $this->services['depends_on_request'] = $instance = new \stdClass(); $instance->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE)); return $instance; } /** * Gets the 'factory_service' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Bar A Bar instance. */ protected function getFactoryServiceService() { return $this->services['factory_service'] = $this->get('foo.baz')->getInstance(); } /** * Gets the 'foo' service. * * This service is shared. * This method always returns the same instance of the service. * * @return FooClass A FooClass instance. */ protected function getFooService() { $a = $this->get('foo.baz'); $this->services['foo'] = $instance = call_user_func(array('FooClass', 'getInstance'), 'foo', $a, array($this->getParameter('foo') => 'foo is '.$this->getParameter('foo').'', 'foobar' => $this->getParameter('foo')), true, $this); $instance->setBar($this->get('bar')); $instance->initialize(); $instance->foo = 'bar'; $instance->moo = $a; $instance->qux = array($this->getParameter('foo') => 'foo is '.$this->getParameter('foo').'', 'foobar' => $this->getParameter('foo')); sc_configure($instance); return $instance; } /** * Gets the 'foo.baz' service. * * This service is shared. * This method always returns the same instance of the service. * * @return object A %baz_class% instance. */ protected function getFoo_BazService() { $this->services['foo.baz'] = $instance = call_user_func(array($this->getParameter('baz_class'), 'getInstance')); call_user_func(array($this->getParameter('baz_class'), 'configureStatic1'), $instance); return $instance; } /** * Gets the 'foo_bar' service. * * @return object A %foo_class% instance. */ protected function getFooBarService() { $class = $this->getParameter('foo_class'); return new $class(); } /** * Gets the 'foo_with_inline' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Foo A Foo instance. */ protected function getFooWithInlineService() { $this->services['foo_with_inline'] = $instance = new \Foo(); $instance->setBar($this->get('inlined')); return $instance; } /** * Gets the 'method_call1' service. * * This service is shared. * This method always returns the same instance of the service. * * @return FooClass A FooClass instance. */ protected function getMethodCall1Service() { require_once '%path%foo.php'; $this->services['method_call1'] = $instance = new \FooClass(); $instance->setBar($this->get('foo')); $instance->setBar($this->get('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)); if ($this->has('foo3')) { $instance->setBar($this->get('foo3', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } if ($this->has('foobaz')) { $instance->setBar($this->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } $instance->setBar(($this->get("foo")->foo() . $this->getParameter("foo"))); return $instance; } /** * Gets the 'request' service. * * This service is shared. * This method always returns the same instance of the service. * * @throws RuntimeException always since this service is expected to be injected dynamically */ protected function getRequestService() { throw new RuntimeException('You have requested a synthetic service ("request"). The DIC does not know how to construct this service.'); } /** * Updates the 'request' service. */ protected function synchronizeRequestService() { if ($this->initialized('depends_on_request')) { $this->get('depends_on_request')->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } } /** * Gets the 'inlined' service. * * This service is shared. * This method always returns the same instance of the service. * * This service is private. * If you want to be able to request this service from the container directly, * make it public, otherwise you might end up with broken code. * * @return Bar A Bar instance. */ protected function getInlinedService() { $this->services['inlined'] = $instance = new \Bar(); $instance->setBaz($this->get('baz')); $instance->pub = 'pub'; return $instance; } /** * Gets the default parameters. * * @return array An array of the default parameters */ protected function getDefaultParameters() { return array( 'baz_class' => 'BazClass', 'foo_class' => 'FooClass', 'foo' => 'bar', ); } } PK!$oyy?Component/DependencyInjection/Tests/Fixtures/php/services11.phpnu[services = $this->scopedServices = $this->scopeStacks = array(); $this->set('service_container', $this); $this->scopes = array(); $this->scopeChildren = array(); $this->methodMap = array( 'foo' => 'getFooService', ); $this->aliases = array(); } /** * Gets the 'foo' service. * * This service is shared. * This method always returns the same instance of the service. * * @return stdClass A stdClass instance. */ protected function getFooService() { return $this->services['foo'] = new \stdClass(); } } PK!:A!!GComponent/DependencyInjection/Tests/Fixtures/php/services9_compiled.phpnu[parameters = $this->getDefaultParameters(); $this->services = $this->scopedServices = $this->scopeStacks = array(); $this->set('service_container', $this); $this->scopes = array(); $this->scopeChildren = array(); $this->methodMap = array( 'bar' => 'getBarService', 'baz' => 'getBazService', 'depends_on_request' => 'getDependsOnRequestService', 'factory_service' => 'getFactoryServiceService', 'foo' => 'getFooService', 'foo.baz' => 'getFoo_BazService', 'foo_bar' => 'getFooBarService', 'foo_with_inline' => 'getFooWithInlineService', 'method_call1' => 'getMethodCall1Service', 'request' => 'getRequestService', ); $this->aliases = array( 'alias_for_alias' => 'foo', 'alias_for_foo' => 'foo', ); } /** * Gets the 'bar' service. * * This service is shared. * This method always returns the same instance of the service. * * @return FooClass A FooClass instance. */ protected function getBarService() { $this->services['bar'] = $instance = new \FooClass('foo', $this->get('foo.baz'), $this->getParameter('foo_bar')); $this->get('foo.baz')->configure($instance); return $instance; } /** * Gets the 'baz' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Baz A Baz instance. */ protected function getBazService() { $this->services['baz'] = $instance = new \Baz(); $instance->setFoo($this->get('foo_with_inline')); return $instance; } /** * Gets the 'depends_on_request' service. * * This service is shared. * This method always returns the same instance of the service. * * @return stdClass A stdClass instance. */ protected function getDependsOnRequestService() { $this->services['depends_on_request'] = $instance = new \stdClass(); $instance->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE)); return $instance; } /** * Gets the 'factory_service' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Bar A Bar instance. */ protected function getFactoryServiceService() { return $this->services['factory_service'] = $this->get('foo.baz')->getInstance(); } /** * Gets the 'foo' service. * * This service is shared. * This method always returns the same instance of the service. * * @return FooClass A FooClass instance. */ protected function getFooService() { $a = $this->get('foo.baz'); $this->services['foo'] = $instance = call_user_func(array('FooClass', 'getInstance'), 'foo', $a, array('bar' => 'foo is bar', 'foobar' => 'bar'), true, $this); $instance->setBar($this->get('bar')); $instance->initialize(); $instance->foo = 'bar'; $instance->moo = $a; $instance->qux = array('bar' => 'foo is bar', 'foobar' => 'bar'); sc_configure($instance); return $instance; } /** * Gets the 'foo.baz' service. * * This service is shared. * This method always returns the same instance of the service. * * @return BazClass A BazClass instance. */ protected function getFoo_BazService() { $this->services['foo.baz'] = $instance = call_user_func(array('BazClass', 'getInstance')); call_user_func(array('BazClass', 'configureStatic1'), $instance); return $instance; } /** * Gets the 'foo_bar' service. * * @return FooClass A FooClass instance. */ protected function getFooBarService() { return new \FooClass(); } /** * Gets the 'foo_with_inline' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Foo A Foo instance. */ protected function getFooWithInlineService() { $a = new \Bar(); $this->services['foo_with_inline'] = $instance = new \Foo(); $a->setBaz($this->get('baz')); $a->pub = 'pub'; $instance->setBar($a); return $instance; } /** * Gets the 'method_call1' service. * * This service is shared. * This method always returns the same instance of the service. * * @return FooClass A FooClass instance. */ protected function getMethodCall1Service() { require_once '%path%foo.php'; $this->services['method_call1'] = $instance = new \FooClass(); $instance->setBar($this->get('foo')); $instance->setBar(NULL); $instance->setBar(($this->get("foo")->foo() . $this->getParameter("foo"))); return $instance; } /** * Gets the 'request' service. * * This service is shared. * This method always returns the same instance of the service. * * @throws RuntimeException always since this service is expected to be injected dynamically */ protected function getRequestService() { throw new RuntimeException('You have requested a synthetic service ("request"). The DIC does not know how to construct this service.'); } /** * Updates the 'request' service. */ protected function synchronizeRequestService() { if ($this->initialized('depends_on_request')) { $this->get('depends_on_request')->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } } /** * {@inheritdoc} */ public function getParameter($name) { $name = strtolower($name); if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) { throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); } return $this->parameters[$name]; } /** * {@inheritdoc} */ public function hasParameter($name) { $name = strtolower($name); return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters); } /** * {@inheritdoc} */ public function setParameter($name, $value) { throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); } /** * {@inheritDoc} */ public function getParameterBag() { if (null === $this->parameterBag) { $this->parameterBag = new FrozenParameterBag($this->parameters); } return $this->parameterBag; } /** * Gets the default parameters. * * @return array An array of the default parameters */ protected function getDefaultParameters() { return array( 'baz_class' => 'BazClass', 'foo_class' => 'FooClass', 'foo' => 'bar', ); } } PK!7/>Component/DependencyInjection/Tests/Fixtures/php/services8.phpnu[getDefaultParameters())); } /** * Gets the default parameters. * * @return array An array of the default parameters */ protected function getDefaultParameters() { return array( 'foo' => '%baz%', 'baz' => 'bar', 'bar' => 'foo is %%foo bar', 'escape' => '@escapeme', 'values' => array( 0 => true, 1 => false, 2 => NULL, 3 => 0, 4 => 1000.3, 5 => 'true', 6 => 'false', 7 => 'null', ), ); } } PK!(]  >Component/DependencyInjection/Tests/Fixtures/xml/services1.xmlnu[ PK!ibĤ>Component/DependencyInjection/Tests/Fixtures/xml/services5.xmlnu[ PK!![  ?Component/DependencyInjection/Tests/Fixtures/xml/services10.xmlnu[ PK!u  >Component/DependencyInjection/Tests/Fixtures/xml/services4.xmlnu[ PK!_+WW>Component/DependencyInjection/Tests/Fixtures/xml/services7.xmlnu[ PK!x' 11@Component/DependencyInjection/Tests/Fixtures/xml/withdoctype.xmlnu[ PK!wzhh>Component/DependencyInjection/Tests/Fixtures/xml/services8.xmlnu[ %baz% bar foo is %%foo bar @escapeme true false null 0 1000.3 true false null PK! true PK!pԠ>Component/DependencyInjection/Tests/Fixtures/xml/services6.xmlnu[ %path%/foo.php foo true false service("foo").foo() ~ parameter("foo") foo true false PK!˕n%%=Component/DependencyInjection/Tests/Fixtures/xml/nonvalid.xmlnu[ PK!PggIComponent/DependencyInjection/Tests/Fixtures/xml/services4_bad_import.xmlnu[ PK!\_>Component/DependencyInjection/Tests/Fixtures/xml/services3.xmlnu[ foo true false PK!]2 HComponent/DependencyInjection/Tests/Fixtures/xml/extension2/services.xmlnu[ PK! >Component/DependencyInjection/Tests/Fixtures/xml/services2.xmlnu[ a string bar 0 4 null true true false on off 1.3 1000.3 a string foo bar value PHP_EOL PK!HComponent/DependencyInjection/Tests/Fixtures/xml/extension1/services.xmlnu[ PK!BX  >Component/DependencyInjection/Tests/Fixtures/xml/services9.xmlnu[ BazClass FooClass bar foo foo is %foo% %foo% true bar foo is %foo% %foo% foo %foo_bar% %path%foo.php service("foo").foo() ~ parameter("foo") pub PK!^IComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services1.xmlnu[ BAR %project.parameter.foo% PK!ŃIComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services5.xmlnu[ PK!җ'yIComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services4.xmlnu[ PK! IComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services7.xmlnu[ PK!ixCIComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services6.xmlnu[ PK!>UIComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services3.xmlnu[ BAR PK!}IComponent/DependencyInjection/Tests/Fixtures/xml/extensions/services2.xmlnu[ BAR PK!33DComponent/DependencyInjection/Tests/Fixtures/graphviz/services10.dotnu[digraph sc { ratio="compress" node [fontsize="11" fontname="Arial" shape="record"]; edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"]; node_foo [label="foo\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"]; node_bar [label="bar\n\n", shape=record, fillcolor="#ff9999", style="filled"]; node_foo -> node_bar [label="" style="filled"]; } PK!h CComponent/DependencyInjection/Tests/Fixtures/graphviz/services9.dotnu[digraph sc { ratio="compress" node [fontsize="11" fontname="Arial" shape="record"]; edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"]; node_foo [label="foo (alias_for_foo)\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_bar [label="bar\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_foo_baz [label="foo.baz\nBazClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_foo_bar [label="foo_bar\nFooClass\n", shape=record, fillcolor="#eeeeee", style="dotted"]; node_method_call1 [label="method_call1\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_factory_service [label="factory_service\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_foo_with_inline [label="foo_with_inline\nFoo\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_inlined [label="inlined\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_baz [label="baz\nBaz\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_request [label="request\nRequest\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_depends_on_request [label="depends_on_request\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"]; node_foo2 [label="foo2\n\n", shape=record, fillcolor="#ff9999", style="filled"]; node_foo3 [label="foo3\n\n", shape=record, fillcolor="#ff9999", style="filled"]; node_foobaz [label="foobaz\n\n", shape=record, fillcolor="#ff9999", style="filled"]; node_foo -> node_foo_baz [label="" style="filled"]; node_foo -> node_service_container [label="" style="filled"]; node_foo -> node_foo_baz [label="" style="dashed"]; node_foo -> node_bar [label="setBar()" style="dashed"]; node_bar -> node_foo_baz [label="" style="filled"]; node_method_call1 -> node_foo [label="setBar()" style="dashed"]; node_method_call1 -> node_foo2 [label="setBar()" style="dashed"]; node_method_call1 -> node_foo3 [label="setBar()" style="dashed"]; node_method_call1 -> node_foobaz [label="setBar()" style="dashed"]; node_foo_with_inline -> node_inlined [label="setBar()" style="dashed"]; node_inlined -> node_baz [label="setBaz()" style="dashed"]; node_baz -> node_foo_with_inline [label="setFoo()" style="dashed"]; node_depends_on_request -> node_request [label="setRequest()" style="dashed"]; } PK!Ձ1*,,FComponent/DependencyInjection/Tests/Fixtures/graphviz/services10-1.dotnu[digraph sc { ratio="normal" node [fontsize="13" fontname="Verdana" shape="square"]; edge [fontsize="12" fontname="Verdana" color="white" arrowhead="closed" arrowsize="1"]; node_foo [label="foo\nFooClass\n", shape=square, fillcolor="grey", style="filled"]; node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=square, fillcolor="green", style="empty"]; node_bar [label="bar\n\n", shape=square, fillcolor="red", style="empty"]; node_foo -> node_bar [label="" style="filled"]; } PK!&WWCComponent/DependencyInjection/Tests/Fixtures/graphviz/services1.dotnu[digraph sc { ratio="compress" node [fontsize="11" fontname="Arial" shape="record"]; edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"]; node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"]; } PK!ŏD;;DComponent/DependencyInjection/Tests/Fixtures/graphviz/services13.dotnu[digraph sc { ratio="compress" node [fontsize="11" fontname="Arial" shape="record"]; edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"]; node_foo [label="foo\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_bar [label="bar\nBarClass\n", shape=record, fillcolor="#eeeeee", style="filled"]; node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"]; node_foo -> node_bar [label="" style="filled"]; } PK!8BBDComponent/DependencyInjection/Tests/Fixtures/graphviz/services14.dotnu[digraph sc { ratio="compress" node [fontsize="11" fontname="Arial" shape="record"]; edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"]; node_service_container [label="service_container\nContainer14\\ProjectServiceContainer\n", shape=record, fillcolor="#9999ff", style="filled"]; } PK!N{rrXComponent/DependencyInjection/Tests/Fixtures/includes/ProjectWithXsdExtensionInPhar.pharnu[ "ProjectWithXsdExtensionInPhar.phar!ProjectWithXsdExtensionInPhar.php~akM~ schema/project-1.0.xsdakMQp W]ʯ`5,,) EYGBMBPK! =Component/DependencyInjection/Tests/Fixtures/includes/foo.phpnu[arguments = $arguments; } public static function getInstance($arguments = array()) { $obj = new self($arguments); $obj->called = true; return $obj; } public function initialize() { $this->initialized = true; } public function configure() { $this->configured = true; } public function setBar($value = null) { $this->bar = $value; } } PK!]DComponent/DependencyInjection/Tests/Fixtures/includes/createphar.phpnu[addFromString('ProjectWithXsdExtensionInPhar.php',<<addFromString('schema/project-1.0.xsd', << EOT ); $phar->setStub(''); PK!.Y<ҿJComponent/DependencyInjection/Tests/Fixtures/includes/ProjectExtension.phpnu[setDefinition('project.service.bar', new Definition('FooClass')); $configuration->setParameter('project.parameter.bar', isset($config['foo']) ? $config['foo'] : 'foobar'); $configuration->setDefinition('project.service.foo', new Definition('FooClass')); $configuration->setParameter('project.parameter.foo', isset($config['foo']) ? $config['foo'] : 'foobar'); return $configuration; } public function getXsdValidationBasePath() { return false; } public function getNamespace() { return 'http://www.example.com/schema/project'; } public function getAlias() { return 'project'; } public function getConfiguration(array $config, ContainerBuilder $container) { return null; } } PK!Aov:ZZAComponent/DependencyInjection/Tests/Fixtures/includes/classes.phpnu[configure(); } class BarClass { protected $baz; public $foo = 'foo'; public function setBaz(BazClass $baz) { $this->baz = $baz; } public function getBaz() { return $this->baz; } } class BazClass { protected $foo; public function setFoo(Foo $foo) { $this->foo = $foo; } public function configure($instance) { $instance->configure(); } public static function getInstance() { return new self(); } public static function configureStatic($instance) { $instance->configure(); } public static function configureStatic1() { } } class BarUserClass { public $bar; public function __construct(BarClass $bar) { $this->bar = $bar; } } PK!RK:LComponent/DependencyInjection/Tests/Fixtures/includes/schema/project-1.0.xsdnu[ PK![[QComponent/DependencyInjection/Tests/Fixtures/includes/ProjectWithXsdExtension.phpnu[=Component/DependencyInjection/Tests/Fixtures/yaml/badtag2.ymlnu[services: foo_service: class: FooClass tags: # tag is missing the name key foo_tag: { foo: bar } PK!:Ʋ?Component/DependencyInjection/Tests/Fixtures/yaml/services2.ymlnu[parameters: FOO: bar values: - true - false - 0 - 1000.3 bar: foo escape: @@escapeme foo_bar: @foo_bar MixedCase: MixedCaseKey: value PK!W%?Component/DependencyInjection/Tests/Fixtures/yaml/nonvalid2.ymlnu[false PK!|w?Component/DependencyInjection/Tests/Fixtures/yaml/services9.ymlnu[parameters: baz_class: BazClass foo_class: FooClass foo: bar services: foo: class: FooClass tags: - { name: foo, foo: foo } - { name: foo, bar: bar } factory_class: FooClass factory_method: getInstance arguments: [foo, '@foo.baz', { '%foo%': 'foo is %foo%', foobar: '%foo%' }, true, '@service_container'] properties: { foo: bar, moo: '@foo.baz', qux: { '%foo%': 'foo is %foo%', foobar: '%foo%' } } calls: - [setBar, ['@bar']] - [initialize, { }] configurator: sc_configure bar: class: FooClass arguments: [foo, '@foo.baz', '%foo_bar%'] configurator: ['@foo.baz', configure] foo.baz: class: %baz_class% factory_class: %baz_class% factory_method: getInstance configurator: ['%baz_class%', configureStatic1] foo_bar: class: %foo_class% scope: prototype method_call1: class: FooClass file: %path%foo.php calls: - [setBar, ['@foo']] - [setBar, ['@?foo2']] - [setBar, ['@?foo3']] - [setBar, ['@?foobaz']] - [setBar, ['@=service("foo").foo() ~ parameter("foo")']] factory_service: class: Bar factory_method: getInstance factory_service: foo.baz foo_with_inline: class: Foo calls: - [setBar, ['@inlined']] inlined: class: Bar public: false properties: { pub: pub } calls: - [setBaz, ['@baz']] baz: class: Baz calls: - [setFoo, ['@foo_with_inline']] request: class: Request synthetic: true synchronized: true depends_on_request: class: stdClass calls: - [setRequest, ['@?request']] alias_for_foo: @foo alias_for_alias: @foo PK!GG@Component/DependencyInjection/Tests/Fixtures/yaml/services13.ymlnu[# used to test imports in XML parameters: imported_from_yaml: true PK!۴)++=Component/DependencyInjection/Tests/Fixtures/ini/nonvalid.ininu[{NOT AN INI FILE} {JUST A PLAIN TEXT FILE} PK!pu((@Component/DependencyInjection/Tests/Fixtures/ini/parameters2.ininu[[parameters] imported_from_ini = true PK!s4''?Component/DependencyInjection/Tests/Fixtures/ini/parameters.ininu[[parameters] foo = bar bar = %foo% PK!5l%%@Component/DependencyInjection/Tests/Fixtures/ini/parameters1.ininu[[parameters] FOO = foo baz = baz PK!FmGComponent/DependencyInjection/Tests/Fixtures/containers/interfaces2.phpnu[setDefinition('barFactory', $factoryDefinition); $definition = new Definition(); $definition->setFactoryService('barFactory'); $definition->setFactoryMethod('createBarClass'); $container->setDefinition('bar', $definition); return $container; class BarClass { public $foo; public function setBar($foo) { $this->foo = $foo; } } class BarClassFactory { public function createBarClass() { return new BarClass(); } } PK!4hFComponent/DependencyInjection/Tests/Fixtures/containers/container8.phpnu[ '%baz%', 'baz' => 'bar', 'bar' => 'foo is %%foo bar', 'escape' => '@escapeme', 'values' => array(true, false, null, 0, 1000.3, 'true', 'false', 'null'), ))); return $container; PK! Z FComponent/DependencyInjection/Tests/Fixtures/containers/container9.phpnu[ register('foo', 'FooClass')-> addTag('foo', array('foo' => 'foo'))-> addTag('foo', array('bar' => 'bar'))-> setFactoryClass('FooClass')-> setFactoryMethod('getInstance')-> setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))-> setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')))-> addMethodCall('setBar', array(new Reference('bar')))-> addMethodCall('initialize')-> setConfigurator('sc_configure') ; $container-> register('bar', 'FooClass')-> setArguments(array('foo', new Reference('foo.baz'), new Parameter('foo_bar')))-> setScope('container')-> setConfigurator(array(new Reference('foo.baz'), 'configure')) ; $container-> register('foo.baz', '%baz_class%')-> setFactoryClass('%baz_class%')-> setFactoryMethod('getInstance')-> setConfigurator(array('%baz_class%', 'configureStatic1')) ; $container-> register('foo_bar', '%foo_class%')-> setScope('prototype') ; $container->getParameterBag()->clear(); $container->getParameterBag()->add(array( 'baz_class' => 'BazClass', 'foo_class' => 'FooClass', 'foo' => 'bar', )); $container->setAlias('alias_for_foo', 'foo'); $container->setAlias('alias_for_alias', 'alias_for_foo'); $container-> register('method_call1', 'FooClass')-> setFile(realpath(__DIR__.'/../includes/foo.php'))-> addMethodCall('setBar', array(new Reference('foo')))-> addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)))-> addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))-> addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))-> addMethodCall('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")'))) ; $container-> register('factory_service', 'Bar')-> setFactoryService('foo.baz')-> setFactoryMethod('getInstance') ; $container ->register('foo_with_inline', 'Foo') ->addMethodCall('setBar', array(new Reference('inlined'))) ; $container ->register('inlined', 'Bar') ->setProperty('pub', 'pub') ->addMethodCall('setBaz', array(new Reference('baz'))) ->setPublic(false) ; $container ->register('baz', 'Baz') ->addMethodCall('setFoo', array(new Reference('foo_with_inline'))) ; $container ->register('request', 'Request') ->setSynthetic(true) ->setSynchronized(true) ; $container ->register('depends_on_request', 'stdClass') ->addMethodCall('setRequest', array(new Reference('request', ContainerInterface::NULL_ON_INVALID_REFERENCE, false))) ; return $container; PK!33GComponent/DependencyInjection/Tests/Fixtures/containers/container11.phpnu[ register('foo', 'FooClass')-> addArgument(new Definition('BarClass', array(new Definition('BazClass')))) ; return $container; PK! |GComponent/DependencyInjection/Tests/Fixtures/containers/interfaces1.phpnu[setParameter('cla', 'Fo'); $container->setParameter('ss', 'Class'); $definition = new Definition('%cla%o%ss%'); $container->setDefinition('foo', $definition); return $container; if (!class_exists('FooClass')) { class FooClass { public $bar; public function setBar($bar) { $this->bar = $bar; } } } PK!Cݲ;;GComponent/DependencyInjection/Tests/Fixtures/containers/container10.phpnu[ register('foo', 'FooClass')-> addArgument(new Reference('bar')) ; return $container; PK!BreOOGComponent/DependencyInjection/Tests/Fixtures/containers/container13.phpnu[ register('foo', 'FooClass')-> addArgument(new Reference('bar')) ; $container-> register('bar', 'BarClass') ; $container->compile(); return $container; PK!*EEGComponent/DependencyInjection/Tests/Fixtures/containers/container12.phpnu[ register('foo', 'FooClass\\Foo')-> addArgument('foo<>&bar')-> addTag('foo"bar\\bar', array('foo' => 'foo"barřž€')) ; return $container; PK!1vGComponent/DependencyInjection/Tests/Fixtures/containers/container14.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; class FrozenParameterBagTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::__construct */ public function testConstructor() { $parameters = array( 'foo' => 'foo', 'bar' => 'bar', ); $bag = new FrozenParameterBag($parameters); $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::clear * @expectedException \LogicException */ public function testClear() { $bag = new FrozenParameterBag(array()); $bag->clear(); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::set * @expectedException \LogicException */ public function testSet() { $bag = new FrozenParameterBag(array()); $bag->set('foo', 'bar'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::add * @expectedException \LogicException */ public function testAdd() { $bag = new FrozenParameterBag(array()); $bag->add(array()); } } PK!$99EComponent/DependencyInjection/Tests/ParameterBag/ParameterBagTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException; use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; class ParameterBagTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::__construct */ public function testConstructor() { $bag = new ParameterBag($parameters = array( 'foo' => 'foo', 'bar' => 'bar', )); $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::clear */ public function testClear() { $bag = new ParameterBag($parameters = array( 'foo' => 'foo', 'bar' => 'bar', )); $bag->clear(); $this->assertEquals(array(), $bag->all(), '->clear() removes all parameters'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::remove */ public function testRemove() { $bag = new ParameterBag(array( 'foo' => 'foo', 'bar' => 'bar', )); $bag->remove('foo'); $this->assertEquals(array('bar' => 'bar'), $bag->all(), '->remove() removes a parameter'); $bag->remove('BAR'); $this->assertEquals(array(), $bag->all(), '->remove() converts key to lowercase before removing'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::get * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::set */ public function testGetSet() { $bag = new ParameterBag(array('foo' => 'bar')); $bag->set('bar', 'foo'); $this->assertEquals('foo', $bag->get('bar'), '->set() sets the value of a new parameter'); $bag->set('foo', 'baz'); $this->assertEquals('baz', $bag->get('foo'), '->set() overrides previously set parameter'); $bag->set('Foo', 'baz1'); $this->assertEquals('baz1', $bag->get('foo'), '->set() converts the key to lowercase'); $this->assertEquals('baz1', $bag->get('FOO'), '->get() converts the key to lowercase'); try { $bag->get('baba'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent parameter "baba".', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); } } public function testGetThrowParameterNotFoundException() { $bag = new ParameterBag(array( 'foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz', )); try { $bag->get('foo1'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent parameter "foo1". Did you mean this: "foo"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException with some advices'); } try { $bag->get('bag'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent parameter "bag". Did you mean one of these: "bar", "baz"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException with some advices'); } try { $bag->get(''); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent parameter "".', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException with some advices'); } } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::has */ public function testHas() { $bag = new ParameterBag(array('foo' => 'bar')); $this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined'); $this->assertTrue($bag->has('Foo'), '->has() converts the key to lowercase'); $this->assertFalse($bag->has('bar'), '->has() returns false if a parameter is not defined'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolveValue */ public function testResolveValue() { $bag = new ParameterBag(array()); $this->assertEquals('foo', $bag->resolveValue('foo'), '->resolveValue() returns its argument unmodified if no placeholders are found'); $bag = new ParameterBag(array('foo' => 'bar')); $this->assertEquals('I\'m a bar', $bag->resolveValue('I\'m a %foo%'), '->resolveValue() replaces placeholders by their values'); $this->assertEquals(array('bar' => 'bar'), $bag->resolveValue(array('%foo%' => '%foo%')), '->resolveValue() replaces placeholders in keys and values of arrays'); $this->assertEquals(array('bar' => array('bar' => array('bar' => 'bar'))), $bag->resolveValue(array('%foo%' => array('%foo%' => array('%foo%' => '%foo%')))), '->resolveValue() replaces placeholders in nested arrays'); $this->assertEquals('I\'m a %%foo%%', $bag->resolveValue('I\'m a %%foo%%'), '->resolveValue() supports % escaping by doubling it'); $this->assertEquals('I\'m a bar %%foo bar', $bag->resolveValue('I\'m a %foo% %%foo %foo%'), '->resolveValue() supports % escaping by doubling it'); $this->assertEquals(array('foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar'))), $bag->resolveValue(array('foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar')))), '->resolveValue() supports % escaping by doubling it'); $bag = new ParameterBag(array('foo' => true)); $this->assertTrue($bag->resolveValue('%foo%'), '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings'); $bag = new ParameterBag(array('foo' => null)); $this->assertNull($bag->resolveValue('%foo%'), '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings'); $bag = new ParameterBag(array('foo' => 'bar', 'baz' => '%%%foo% %foo%%% %%foo%% %%%foo%%%')); $this->assertEquals('%%bar bar%% %%foo%% %%bar%%', $bag->resolveValue('%baz%'), '->resolveValue() replaces params placed besides escaped %'); $bag = new ParameterBag(array('baz' => '%%s?%%s')); $this->assertEquals('%%s?%%s', $bag->resolveValue('%baz%'), '->resolveValue() is not replacing greedily'); $bag = new ParameterBag(array()); try { $bag->resolveValue('%foobar%'); $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existent parameter'); } catch (ParameterNotFoundException $e) { $this->assertEquals('You have requested a non-existent parameter "foobar".', $e->getMessage(), '->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter'); } try { $bag->resolveValue('foo %foobar% bar'); $this->fail('->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter'); } catch (ParameterNotFoundException $e) { $this->assertEquals('You have requested a non-existent parameter "foobar".', $e->getMessage(), '->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter'); } $bag = new ParameterBag(array('foo' => 'a %bar%', 'bar' => array())); try { $bag->resolveValue('%foo%'); $this->fail('->resolveValue() throws a RuntimeException when a parameter embeds another non-string parameter'); } catch (RuntimeException $e) { $this->assertEquals('A string value must be composed of strings and/or numbers, but found parameter "bar" of type array inside string value "a %bar%".', $e->getMessage(), '->resolveValue() throws a RuntimeException when a parameter embeds another non-string parameter'); } $bag = new ParameterBag(array('foo' => '%bar%', 'bar' => '%foobar%', 'foobar' => '%foo%')); try { $bag->resolveValue('%foo%'); $this->fail('->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); } catch (ParameterCircularReferenceException $e) { $this->assertEquals('Circular reference detected for parameter "foo" ("foo" > "bar" > "foobar" > "foo").', $e->getMessage(), '->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); } $bag = new ParameterBag(array('foo' => 'a %bar%', 'bar' => 'a %foobar%', 'foobar' => 'a %foo%')); try { $bag->resolveValue('%foo%'); $this->fail('->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); } catch (ParameterCircularReferenceException $e) { $this->assertEquals('Circular reference detected for parameter "foo" ("foo" > "bar" > "foobar" > "foo").', $e->getMessage(), '->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference'); } $bag = new ParameterBag(array('host' => 'foo.bar', 'port' => 1337)); $this->assertEquals('foo.bar:1337', $bag->resolveValue('%host%:%port%')); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve */ public function testResolveIndicatesWhyAParameterIsNeeded() { $bag = new ParameterBag(array('foo' => '%bar%')); try { $bag->resolve(); } catch (ParameterNotFoundException $e) { $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage()); } $bag = new ParameterBag(array('foo' => '%bar%')); try { $bag->resolve(); } catch (ParameterNotFoundException $e) { $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage()); } } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve */ public function testResolveUnescapesValue() { $bag = new ParameterBag(array( 'foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar')), 'bar' => 'I\'m a %%foo%%', )); $bag->resolve(); $this->assertEquals('I\'m a %foo%', $bag->get('bar'), '->resolveValue() supports % escaping by doubling it'); $this->assertEquals(array('bar' => array('ding' => 'I\'m a bar %foo %bar')), $bag->get('foo'), '->resolveValue() supports % escaping by doubling it'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::escapeValue */ public function testEscapeValue() { $bag = new ParameterBag(); $bag->add(array( 'foo' => $bag->escapeValue(array('bar' => array('ding' => 'I\'m a bar %foo %bar', 'zero' => null))), 'bar' => $bag->escapeValue('I\'m a %foo%'), )); $this->assertEquals('I\'m a %%foo%%', $bag->get('bar'), '->escapeValue() escapes % by doubling it'); $this->assertEquals(array('bar' => array('ding' => 'I\'m a bar %%foo %%bar', 'zero' => null)), $bag->get('foo'), '->escapeValue() escapes % by doubling it'); } /** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve * @dataProvider stringsWithSpacesProvider */ public function testResolveStringWithSpacesReturnsString($expected, $test, $description) { $bag = new ParameterBag(array('foo' => 'bar')); try { $this->assertEquals($expected, $bag->resolveString($test), $description); } catch (ParameterNotFoundException $e) { $this->fail(sprintf('%s - "%s"', $description, $expected)); } } public function stringsWithSpacesProvider() { return array( array('bar', '%foo%', 'Parameters must be wrapped by %.'), array('% foo %', '% foo %', 'Parameters should not have spaces.'), array('{% set my_template = "foo" %}', '{% set my_template = "foo" %}', 'Twig-like strings are not parameters.'), array('50% is less than 100%', '50% is less than 100%', 'Text between % signs is allowed, if there are spaces.'), ); } } PK! 6Component/DependencyInjection/Tests/CrossCheckTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; class CrossCheckTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = __DIR__.'/Fixtures/'; require_once self::$fixturesPath.'/includes/classes.php'; require_once self::$fixturesPath.'/includes/foo.php'; } /** * @dataProvider crossCheckLoadersDumpers */ public function testCrossCheck($fixture, $type) { $loaderClass = 'Symfony\\Component\\DependencyInjection\\Loader\\'.ucfirst($type).'FileLoader'; $dumperClass = 'Symfony\\Component\\DependencyInjection\\Dumper\\'.ucfirst($type).'Dumper'; $tmp = tempnam('sf_service_container', 'sf'); file_put_contents($tmp, file_get_contents(self::$fixturesPath.'/'.$type.'/'.$fixture)); $container1 = new ContainerBuilder(); $loader1 = new $loaderClass($container1, new FileLocator()); $loader1->load($tmp); $dumper = new $dumperClass($container1); file_put_contents($tmp, $dumper->dump()); $container2 = new ContainerBuilder(); $loader2 = new $loaderClass($container2, new FileLocator()); $loader2->load($tmp); unlink($tmp); $this->assertEquals($container2->getAliases(), $container1->getAliases(), 'loading a dump from a previously loaded container returns the same container'); $this->assertEquals($container2->getDefinitions(), $container1->getDefinitions(), 'loading a dump from a previously loaded container returns the same container'); $this->assertEquals($container2->getParameterBag()->all(), $container1->getParameterBag()->all(), '->getParameterBag() returns the same value for both containers'); $this->assertEquals(serialize($container2), serialize($container1), 'loading a dump from a previously loaded container returns the same container'); $services1 = array(); foreach ($container1 as $id => $service) { $services1[$id] = serialize($service); } $services2 = array(); foreach ($container2 as $id => $service) { $services2[$id] = serialize($service); } unset($services1['service_container'], $services2['service_container']); $this->assertEquals($services2, $services1, 'Iterator on the containers returns the same services'); } public function crossCheckLoadersDumpers() { $tests = array( array('services1.xml', 'xml'), array('services2.xml', 'xml'), array('services6.xml', 'xml'), array('services8.xml', 'xml'), array('services9.xml', 'xml'), ); if (class_exists('Symfony\Component\Yaml\Yaml')) { $tests = array_merge($tests, array( array('services1.yml', 'yaml'), array('services2.yml', 'yaml'), array('services6.yml', 'yaml'), array('services8.yml', 'yaml'), array('services9.yml', 'yaml'), )); } return $tests; } } PK!2+` =Component/DependencyInjection/Tests/Dumper/YamlDumperTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Dumper; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\YamlDumper; class YamlDumperTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); } public function testDump() { $dumper = new YamlDumper($container = new ContainerBuilder()); $this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services1.yml', $dumper->dump(), '->dump() dumps an empty container as an empty YAML file'); $container = new ContainerBuilder(); $dumper = new YamlDumper($container); } public function testAddParameters() { $container = include self::$fixturesPath.'/containers/container8.php'; $dumper = new YamlDumper($container); $this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services8.yml', $dumper->dump(), '->dump() dumps parameters'); } public function testAddService() { $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new YamlDumper($container); $this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/yaml/services9.yml')), $dumper->dump(), '->dump() dumps services'); $dumper = new YamlDumper($container = new ContainerBuilder()); $container->register('foo', 'FooClass')->addArgument(new \stdClass()); try { $dumper->dump(); $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); } catch (\Exception $e) { $this->assertInstanceOf('\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); } } } PK!v  AComponent/DependencyInjection/Tests/Dumper/GraphvizDumperTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Dumper; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\GraphvizDumper; class GraphvizDumperTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = __DIR__.'/../Fixtures/'; } public function testDump() { $dumper = new GraphvizDumper($container = new ContainerBuilder()); $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services1.dot', $dumper->dump(), '->dump() dumps an empty container as an empty dot file'); $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new GraphvizDumper($container); $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services9.dot')), $dumper->dump(), '->dump() dumps services'); $container = include self::$fixturesPath.'/containers/container10.php'; $dumper = new GraphvizDumper($container); $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services10.dot')), $dumper->dump(), '->dump() dumps services'); $container = include self::$fixturesPath.'/containers/container10.php'; $dumper = new GraphvizDumper($container); $this->assertEquals($dumper->dump(array( 'graph' => array('ratio' => 'normal'), 'node' => array('fontsize' => 13, 'fontname' => 'Verdana', 'shape' => 'square'), 'edge' => array('fontsize' => 12, 'fontname' => 'Verdana', 'color' => 'white', 'arrowhead' => 'closed', 'arrowsize' => 1), 'node.instance' => array('fillcolor' => 'green', 'style' => 'empty'), 'node.definition' => array('fillcolor' => 'grey'), 'node.missing' => array('fillcolor' => 'red', 'style' => 'empty'), )), str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services10-1.dot')), '->dump() dumps services'); } public function testDumpWithFrozenContainer() { $container = include self::$fixturesPath.'/containers/container13.php'; $dumper = new GraphvizDumper($container); $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services13.dot')), $dumper->dump(), '->dump() dumps services'); } public function testDumpWithFrozenCustomClassContainer() { $container = include self::$fixturesPath.'/containers/container14.php'; $dumper = new GraphvizDumper($container); $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services14.dot')), $dumper->dump(), '->dump() dumps services'); } } PK!)<Component/DependencyInjection/Tests/Dumper/XmlDumperTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Dumper; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\XmlDumper; class XmlDumperTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); } public function testDump() { $dumper = new XmlDumper($container = new ContainerBuilder()); $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services1.xml', $dumper->dump(), '->dump() dumps an empty container as an empty XML file'); $container = new ContainerBuilder(); $dumper = new XmlDumper($container); } public function testExportParameters() { $container = include self::$fixturesPath.'//containers/container8.php'; $dumper = new XmlDumper($container); $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services8.xml', $dumper->dump(), '->dump() dumps parameters'); } public function testAddParameters() { $container = include self::$fixturesPath.'//containers/container8.php'; $dumper = new XmlDumper($container); $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services8.xml', $dumper->dump(), '->dump() dumps parameters'); } public function testAddService() { $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new XmlDumper($container); $this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/xml/services9.xml')), $dumper->dump(), '->dump() dumps services'); $dumper = new XmlDumper($container = new ContainerBuilder()); $container->register('foo', 'FooClass')->addArgument(new \stdClass()); try { $dumper->dump(); $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); } catch (\Exception $e) { $this->assertInstanceOf('\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); } } public function testDumpAnonymousServices() { include self::$fixturesPath.'/containers/container11.php'; $dumper = new XmlDumper($container); $this->assertEquals(" ", $dumper->dump()); } public function testDumpEntities() { include self::$fixturesPath.'/containers/container12.php'; $dumper = new XmlDumper($container); $this->assertEquals(" foo<>&bar ", $dumper->dump()); } } PK!"."."<Component/DependencyInjection/Tests/Dumper/PhpDumperTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Dumper; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; class PhpDumperTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); } public function testDump() { $dumper = new PhpDumper($container = new ContainerBuilder()); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class'); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(array('class' => 'Container', 'base_class' => 'AbstractContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Dump')), '->dump() takes a class and a base_class options'); $container = new ContainerBuilder(); new PhpDumper($container); } public function testDumpFrozenContainerWithNoParameter() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->register('foo', 'stdClass'); $container->compile(); $dumper = new PhpDumper($container); $dumpedString = $dumper->dump(); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services11.php', $dumpedString, '->dump() does not add getDefaultParameters() method call if container have no parameters.'); $this->assertNotRegexp("/function getDefaultParameters\(/", $dumpedString, '->dump() does not add getDefaultParameters() method definition.'); } public function testDumpOptimizationString() { $definition = new Definition(); $definition->setClass('stdClass'); $definition->addArgument(array( 'only dot' => '.', 'concatenation as value' => '.\'\'.', 'concatenation from the start value' => '\'\'.', '.' => 'dot as a key', '.\'\'.' => 'concatenation as a key', '\'\'.' =>'concatenation from the start key', 'optimize concatenation' => "string1%some_string%string2", 'optimize concatenation with empty string' => "string1%empty_value%string2", 'optimize concatenation from the start' => '%empty_value%start', 'optimize concatenation at the end' => 'end%empty_value%', )); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->setDefinition('test', $definition); $container->setParameter('empty_value', ''); $container->setParameter('some_string', '-'); $container->compile(); $dumper = new PhpDumper($container); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services10.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class'); } /** * @expectedException \InvalidArgumentException */ public function testExportParameters() { $dumper = new PhpDumper(new ContainerBuilder(new ParameterBag(array('foo' => new Reference('foo'))))); $dumper->dump(); } public function testAddParameters() { $container = include self::$fixturesPath.'/containers/container8.php'; $dumper = new PhpDumper($container); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services8.php', $dumper->dump(), '->dump() dumps parameters'); } public function testAddService() { // without compilation $container = include self::$fixturesPath.'/containers/container9.php'; $dumper = new PhpDumper($container); $this->assertEquals(str_replace('%path%', str_replace('\\','\\\\',self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services9.php')), $dumper->dump(), '->dump() dumps services'); // with compilation $container = include self::$fixturesPath.'/containers/container9.php'; $container->compile(); $dumper = new PhpDumper($container); $this->assertEquals(str_replace('%path%', str_replace('\\','\\\\',self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services9_compiled.php')), $dumper->dump(), '->dump() dumps services'); $dumper = new PhpDumper($container = new ContainerBuilder()); $container->register('foo', 'FooClass')->addArgument(new \stdClass()); try { $dumper->dump(); $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); } catch (\Exception $e) { $this->assertInstanceOf('\Symfony\Component\DependencyInjection\Exception\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources'); } } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Service id "bar$" cannot be converted to a valid PHP method name. */ public function testAddServiceInvalidServiceId() { $container = new ContainerBuilder(); $container->register('bar$', 'FooClass'); $dumper = new PhpDumper($container); $dumper->dump(); } public function testAliases() { $container = include self::$fixturesPath.'/containers/container9.php'; $container->compile(); $dumper = new PhpDumper($container); eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Aliases'))); $container = new \Symfony_DI_PhpDumper_Test_Aliases(); $container->set('foo', $foo = new \stdClass); $this->assertSame($foo, $container->get('foo')); $this->assertSame($foo, $container->get('alias_for_foo')); $this->assertSame($foo, $container->get('alias_for_alias')); } public function testFrozenContainerWithoutAliases() { $container = new ContainerBuilder(); $container->compile(); $dumper = new PhpDumper($container); eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Frozen_No_Aliases'))); $container = new \Symfony_DI_PhpDumper_Test_Frozen_No_Aliases(); $this->assertFalse($container->has('foo')); } public function testOverrideServiceWhenUsingADumpedContainer() { require_once self::$fixturesPath.'/php/services9.php'; require_once self::$fixturesPath.'/includes/foo.php'; $container = new \ProjectServiceContainer(); $container->set('bar', $bar = new \stdClass()); $container->setParameter('foo_bar', 'foo_bar'); $this->assertEquals($bar, $container->get('bar'), '->set() overrides an already defined service'); } public function testOverrideServiceWhenUsingADumpedContainerAndServiceIsUsedFromAnotherOne() { require_once self::$fixturesPath.'/php/services9.php'; require_once self::$fixturesPath.'/includes/foo.php'; require_once self::$fixturesPath.'/includes/classes.php'; $container = new \ProjectServiceContainer(); $container->set('bar', $bar = new \stdClass()); $this->assertSame($bar, $container->get('foo')->bar, '->set() overrides an already defined service'); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException */ public function testCircularReference() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->addArgument(new Reference('bar')); $container->register('bar', 'stdClass')->setPublic(false)->addMethodCall('setA', array(new Reference('baz'))); $container->register('baz', 'stdClass')->addMethodCall('setA', array(new Reference('foo'))); $container->compile(); $dumper = new PhpDumper($container); $dumper->dump(); } } PK!5Component/DependencyInjection/Tests/ReferenceTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; use Symfony\Component\DependencyInjection\Reference; class ReferenceTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\Reference::__construct */ public function testConstructor() { $ref = new Reference('foo'); $this->assertEquals('foo', (string) $ref, '__construct() sets the id of the reference, which is used for the __toString() method'); } public function testCaseInsensitive() { $ref = new Reference('FooBar'); $this->assertEquals('foobar', (string) $ref, 'the id is lowercased as the container is case insensitive'); } } PK!ł``@Component/DependencyInjection/Tests/Loader/ClosureLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\ClosureLoader; class ClosureLoaderTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\Loader\ClosureLoader::supports */ public function testSupports() { $loader = new ClosureLoader(new ContainerBuilder()); $this->assertTrue($loader->supports(function ($container) {}), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); } /** * @covers Symfony\Component\DependencyInjection\Loader\ClosureLoader::load */ public function testLoad() { $loader = new ClosureLoader($container = new ContainerBuilder()); $loader->load(function ($container) { $container->setParameter('foo', 'foo'); }); $this->assertEquals('foo', $container->getParameter('foo'), '->load() loads a \Closure resource'); } } PK!SR@Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\Config\FileLocator; class PhpFileLoaderTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\Loader\PhpFileLoader::supports */ public function testSupports() { $loader = new PhpFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('foo.php'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); } /** * @covers Symfony\Component\DependencyInjection\Loader\PhpFileLoader::load */ public function testLoad() { $loader = new PhpFileLoader($container = new ContainerBuilder(), new FileLocator()); $loader->load(__DIR__.'/../Fixtures/php/simple.php'); $this->assertEquals('foo', $container->getParameter('foo'), '->load() loads a PHP file resource'); } } PK!kV00AComponent/DependencyInjection/Tests/Loader/YamlFileLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\FileLocator; use Symfony\Component\ExpressionLanguage\Expression; class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); require_once self::$fixturesPath.'/includes/foo.php'; require_once self::$fixturesPath.'/includes/ProjectExtension.php'; } public function testLoadFile() { $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('loadFile'); $m->setAccessible(true); try { $m->invoke($loader, 'foo.yml'); $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist'); $this->assertEquals('The service file "foo.yml" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist'); } try { $m->invoke($loader, 'parameters.ini'); $this->fail('->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file'); $this->assertEquals('The service file "parameters.ini" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file'); } $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); foreach (array('nonvalid1', 'nonvalid2') as $fixture) { try { $m->invoke($loader, $fixture.'.yml'); $this->fail('->load() throws an InvalidArgumentException if the loaded file does not validate'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not validate'); $this->assertStringMatchesFormat('The service file "nonvalid%d.yml" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not validate'); } } } public function testLoadParameters() { $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services2.yml'); $this->assertEquals(array('foo' => 'bar', 'mixedcase' => array('MixedCaseKey' => 'value'), 'values' => array(true, false, 0, 1000.3), 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')), $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase'); } public function testLoadImports() { $container = new ContainerBuilder(); $resolver = new LoaderResolver(array( new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')), $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), )); $loader->setResolver($resolver); $loader->load('services4.yml'); $actual = $container->getParameterBag()->all(); $expected = array('foo' => 'bar', 'values' => array(true, false), 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'imported_from_ini' => true, 'imported_from_xml' => true); $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); // Bad import throws no exception due to ignore_errors value. $loader->load('services4_bad_import.yml'); } public function testLoadServices() { $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services6.yml'); $services = $container->getDefinitions(); $this->assertTrue(isset($services['foo']), '->load() parses service elements'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts service element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('container', $services['scope.container']->getScope()); $this->assertEquals('custom', $services['scope.custom']->getScope()); $this->assertEquals('prototype', $services['scope.prototype']->getScope()); $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory_method attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(array('setBar', array()), array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService()); $this->assertTrue($services['request']->isSynthetic(), '->load() parses the synthetic flag'); $this->assertTrue($services['request']->isSynchronized(), '->load() parses the synchronized flag'); $this->assertTrue($services['request']->isLazy(), '->load() parses the lazy flag'); $aliases = $container->getAliases(); $this->assertTrue(isset($aliases['alias_for_foo']), '->load() parses aliases'); $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases'); $this->assertTrue($aliases['alias_for_foo']->isPublic()); $this->assertTrue(isset($aliases['another_alias_for_foo'])); $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']); $this->assertFalse($aliases['another_alias_for_foo']->isPublic()); } public function testExtensions() { $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services10.yml'); $container->compile(); $services = $container->getDefinitions(); $parameters = $container->getParameterBag()->all(); $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements'); $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements'); $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements'); $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements'); try { $loader->load('services11.yml'); $this->fail('->load() throws an InvalidArgumentException if the tag is not valid'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid'); $this->assertStringStartsWith('There is no extension able to load the configuration for "foobarfoobar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid'); } } /** * @covers Symfony\Component\DependencyInjection\Loader\YamlFileLoader::supports */ public function testSupports() { $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); } public function testNonArrayTagThrowsException() { $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); try { $loader->load('badtag1.yml'); $this->fail('->load() should throw an exception when the tags key of a service is not an array'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tags key is not an array'); $this->assertStringStartsWith('Parameter "tags" must be an array for service', $e->getMessage(), '->load() throws an InvalidArgumentException if the tags key is not an array'); } } public function testTagWithoutNameThrowsException() { $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); try { $loader->load('badtag2.yml'); $this->fail('->load() should throw an exception when a tag is missing the name key'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag is missing the name key'); $this->assertStringStartsWith('A "tags" entry is missing a "name" key for service ', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag is missing the name key'); } } public function testTagWithAttributeArrayThrowsException() { $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); try { $loader->load('badtag3.yml'); $this->fail('->load() should throw an exception when a tag-attribute is not a scalar'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar'); $this->assertStringStartsWith('A "tags" attribute must be of a scalar-type for service "foo_service", tag "foo", attribute "bar"', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar'); } } } PK!Q&I8a8a@Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\FileLocator; use Symfony\Component\ExpressionLanguage\Expression; class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); require_once self::$fixturesPath.'/includes/foo.php'; require_once self::$fixturesPath.'/includes/ProjectExtension.php'; require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php'; } public function testLoad() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); try { $loader->load('foo.xml'); $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist'); $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist'); } } public function testParseFile() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('parseFile'); $m->setAccessible(true); try { $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini'); $this->fail('->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'parameters.ini'), $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertStringStartsWith('[ERROR 4] Start tag expected, \'<\' not found (in', $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml')); try { $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml'); $this->fail('->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'nonvalid.xml'), $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\SimpleXMLElement', $xml, '->parseFile() returns an SimpleXMLElement object'); } public function testLoadParameters() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services2.xml'); $actual = $container->getParameterBag()->all(); $expected = array( 'a string', 'foo' => 'bar', 'values' => array( 0, 'integer' => 4, 100 => null, 'true', true, false, 'on', 'off', 'float' => 1.3, 1000.3, 'a string', array('foo', 'bar'), ), 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'constant' => PHP_EOL, ); $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones'); } public function testLoadImports() { $container = new ContainerBuilder(); $resolver = new LoaderResolver(array( new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), )); $loader->setResolver($resolver); $loader->load('services4.xml'); $actual = $container->getParameterBag()->all(); $expected = array( 'a string', 'foo' => 'bar', 'values' => array( 0, 'integer' => 4, 100 => null, 'true', true, false, 'on', 'off', 'float' => 1.3, 1000.3, 'a string', array('foo', 'bar'), ), 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'constant' => PHP_EOL, 'bar' => '%foo%', 'imported_from_ini' => true, 'imported_from_yaml' => true ); $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); // Bad import throws no exception due to ignore_errors value. $loader->load('services4_bad_import.xml'); } public function testLoadAnonymousServices() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services5.xml'); $services = $container->getDefinitions(); $this->assertCount(4, $services, '->load() attributes unique ids to anonymous services'); // anonymous service as an argument $args = $services['foo']->getArguments(); $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services'); $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones'); $inner = $services[(string) $args[0]]; $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones'); // inner anonymous services $args = $inner->getArguments(); $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services'); $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones'); $inner = $services[(string) $args[0]]; $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones'); // anonymous service as a property $properties = $services['foo']->getProperties(); $property = $properties['p']; $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $property, '->load() converts anonymous services to references to "normal" services'); $this->assertTrue(isset($services[(string) $property]), '->load() makes a reference to the created ones'); $inner = $services[(string) $property]; $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones'); } public function testLoadServices() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services6.xml'); $services = $container->getDefinitions(); $this->assertTrue(isset($services['foo']), '->load() parses elements'); $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts element to Definition instances'); $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute'); $this->assertEquals('container', $services['scope.container']->getScope()); $this->assertEquals('custom', $services['scope.custom']->getScope()); $this->assertEquals('prototype', $services['scope.prototype']->getScope()); $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory-method attribute'); $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag'); $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags'); $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag'); $this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag'); $this->assertNull($services['factory_service']->getClass()); $this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod()); $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService()); $this->assertTrue($services['request']->isSynthetic(), '->load() parses the synthetic flag'); $this->assertTrue($services['request']->isSynchronized(), '->load() parses the synchronized flag'); $this->assertTrue($services['request']->isLazy(), '->load() parses the lazy flag'); $aliases = $container->getAliases(); $this->assertTrue(isset($aliases['alias_for_foo']), '->load() parses elements'); $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases'); $this->assertTrue($aliases['alias_for_foo']->isPublic()); $this->assertTrue(isset($aliases['another_alias_for_foo'])); $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']); $this->assertFalse($aliases['another_alias_for_foo']->isPublic()); } public function testParsesTags() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services10.xml'); $services = $container->findTaggedServiceIds('foo_tag'); $this->assertCount(1, $services); foreach ($services as $id => $tagAttributes) { foreach ($tagAttributes as $attributes) { $this->assertArrayHasKey('other_option', $attributes); $this->assertEquals('lorem', $attributes['other_option']); $this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed'); $this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing'); $this->assertEquals('cat', $attributes['some-option']); $this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found'); } } } public function testConvertDomElementToArray() { $doc = new \DOMDocument("1.0"); $doc->loadXML('bar'); $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument("1.0"); $doc->loadXML(''); $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument("1.0"); $doc->loadXML('bar'); $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument("1.0"); $doc->loadXML('barbar'); $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument("1.0"); $doc->loadXML(''); $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument("1.0"); $doc->loadXML(''); $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); $doc = new \DOMDocument("1.0"); $doc->loadXML(''); $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array'); } public function testExtensions() { $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $container->registerExtension(new \ProjectWithXsdExtension()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); // extension without an XSD $loader->load('extensions/services1.xml'); $container->compile(); $services = $container->getDefinitions(); $parameters = $container->getParameterBag()->all(); $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements'); $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements'); $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements'); $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements'); // extension with an XSD $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $container->registerExtension(new \ProjectWithXsdExtension()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('extensions/services2.xml'); $container->compile(); $services = $container->getDefinitions(); $parameters = $container->getParameterBag()->all(); $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements'); $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements'); $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements'); $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements'); $container = new ContainerBuilder(); $container->registerExtension(new \ProjectExtension()); $container->registerExtension(new \ProjectWithXsdExtension()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); // extension with an XSD (does not validate) try { $loader->load('extensions/services3.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } // non-registered extension try { $loader->load('extensions/services4.xml'); $this->fail('->load() throws an InvalidArgumentException if the tag is not valid'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid'); $this->assertStringStartsWith('There is no extension able to load the configuration for "project:bar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid'); } } public function testExtensionInPhar() { if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) { $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.'); } require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar'; // extension with an XSD in PHAR archive $container = new ContainerBuilder(); $container->registerExtension(new \ProjectWithXsdExtensionInPhar()); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('extensions/services6.xml'); // extension with an XSD in PHAR archive (does not validate) try { $loader->load('extensions/services7.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } } /** * @covers Symfony\Component\DependencyInjection\Loader\XmlFileLoader::supports */ public function testSupports() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); } public function testNoNamingConflictsForAnonymousServices() { $container = new ContainerBuilder(); $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1')); $loader1->load('services.xml'); $services = $container->getDefinitions(); $this->assertCount(2, $services, '->load() attributes unique ids to anonymous services'); $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2')); $loader2->load('services.xml'); $services = $container->getDefinitions(); $this->assertCount(4, $services, '->load() attributes unique ids to anonymous services'); $services = $container->getDefinitions(); $args1 = $services['extension1.foo']->getArguments(); $inner1 = $services[(string) $args1[0]]; $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones'); $args2 = $services['extension2.foo']->getArguments(); $inner2 = $services[(string) $args2[0]]; $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones'); } public function testDocTypeIsNotAllowed() { $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); // document types are not allowed. try { $loader->load('withdoctype.xml'); $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type'); $this->assertSame('Document types are not allowed.', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type'); } } } PK! @Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; use Symfony\Component\Config\FileLocator; class IniFileLoaderTest extends \PHPUnit_Framework_TestCase { protected static $fixturesPath; protected $container; protected $loader; public static function setUpBeforeClass() { self::$fixturesPath = realpath(__DIR__.'/../Fixtures/'); } protected function setUp() { $this->container = new ContainerBuilder(); $this->loader = new IniFileLoader($this->container, new FileLocator(self::$fixturesPath.'/ini')); } /** * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::__construct * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::load */ public function testIniFileCanBeLoaded() { $this->loader->load('parameters.ini'); $this->assertEquals(array('foo' => 'bar', 'bar' => '%foo%'), $this->container->getParameterBag()->all(), '->load() takes a single file name as its first argument'); } /** * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::__construct * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::load * * @expectedException \InvalidArgumentException * @expectedExceptionMessage The file "foo.ini" does not exist (in: */ public function testExceptionIsRaisedWhenIniFileDoesNotExist() { $this->loader->load('foo.ini'); } /** * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::__construct * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::load * * @expectedException \InvalidArgumentException * @expectedExceptionMessage The "nonvalid.ini" file is not valid. */ public function testExceptionIsRaisedWhenIniFileCannotBeParsed() { @$this->loader->load('nonvalid.ini'); } /** * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::supports */ public function testSupports() { $loader = new IniFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('foo.ini'), '->supports() returns true if the resource is loadable'); $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable'); } } PK!' QComponent/DependencyInjection/Tests/Compiler/ResolveInvalidReferencesPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\ResolveInvalidReferencesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class ResolveInvalidReferencesPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $def = $container ->register('foo') ->setArguments(array(new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE))) ->addMethodCall('foo', array(new Reference('moo', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))) ; $this->process($container); $arguments = $def->getArguments(); $this->assertNull($arguments[0]); $this->assertCount(0, $def->getMethodCalls()); } public function testProcessIgnoreNonExistentServices() { $container = new ContainerBuilder(); $def = $container ->register('foo') ->setArguments(array(new Reference('bar'))) ; $this->process($container); $arguments = $def->getArguments(); $this->assertEquals('bar', (string) $arguments[0]); } public function testProcessRemovesPropertiesOnInvalid() { $container = new ContainerBuilder(); $def = $container ->register('foo') ->setProperty('foo', new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)) ; $this->process($container); $this->assertEquals(array(), $def->getProperties()); } public function testStrictFlagIsPreserved() { $container = new ContainerBuilder(); $container->register('bar'); $def = $container ->register('foo') ->addArgument(new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE, false)) ; $this->process($container); $this->assertFalse($def->getArgument(0)->isStrict()); } protected function process(ContainerBuilder $container) { $pass = new ResolveInvalidReferencesPass(); $pass->process($container); } } PK!'{ { PComponent/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; class CheckCircularReferencesPassTest extends \PHPUnit_Framework_TestCase { /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException */ public function testProcess() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('a')); $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException */ public function testProcessWithAliases() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->setAlias('b', 'c'); $container->setAlias('c', 'a'); $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException */ public function testProcessDetectsIndirectCircularReference() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); $container->register('c')->addArgument(new Reference('a')); $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException */ public function testDeepCircularReference() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); $container->register('c')->addArgument(new Reference('b')); $this->process($container); } public function testProcessIgnoresMethodCalls() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addMethodCall('setA', array(new Reference('a'))); $this->process($container); } protected function process(ContainerBuilder $container) { $compiler = new Compiler(); $passConfig = $compiler->getPassConfig(); $passConfig->setOptimizationPasses(array( new AnalyzeServiceReferencesPass(true), new CheckCircularReferencesPass(), )); $passConfig->setRemovingPasses(array()); $compiler->compile($container); } } PK!>" OComponent/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\DependencyInjection\Compiler\CheckReferenceValidityPass; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; class CheckReferenceValidityPassTest extends \PHPUnit_Framework_TestCase { public function testProcessIgnoresScopeWideningIfNonStrictReference() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false)); $container->register('b')->setScope('prototype'); $this->process($container); } /** * @expectedException \RuntimeException */ public function testProcessDetectsScopeWidening() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->setScope('prototype'); $this->process($container); } public function testProcessIgnoresCrossScopeHierarchyReferenceIfNotStrict() { $container = new ContainerBuilder(); $container->addScope(new Scope('a')); $container->addScope(new Scope('b')); $container->register('a')->setScope('a')->addArgument(new Reference('b', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false)); $container->register('b')->setScope('b'); $this->process($container); } /** * @expectedException \RuntimeException */ public function testProcessDetectsCrossScopeHierarchyReference() { $container = new ContainerBuilder(); $container->addScope(new Scope('a')); $container->addScope(new Scope('b')); $container->register('a')->setScope('a')->addArgument(new Reference('b')); $container->register('b')->setScope('b'); $this->process($container); } /** * @expectedException \RuntimeException */ public function testProcessDetectsReferenceToAbstractDefinition() { $container = new ContainerBuilder(); $container->register('a')->setAbstract(true); $container->register('b')->addArgument(new Reference('a')); $this->process($container); } public function testProcess() { $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b'); $this->process($container); } protected function process(ContainerBuilder $container) { $pass = new CheckReferenceValidityPass(); $pass->process($container); } } PK!]SComponent/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\DefinitionDecorator; use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class ResolveDefinitionTemplatesPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $container->register('parent', 'foo')->setArguments(array('moo', 'b'))->setProperty('foo', 'moo'); $container->setDefinition('child', new DefinitionDecorator('parent')) ->replaceArgument(0, 'a') ->setProperty('foo', 'bar') ->setClass('bar') ; $this->process($container); $def = $container->getDefinition('child'); $this->assertNotInstanceOf('Symfony\Component\DependencyInjection\DefinitionDecorator', $def); $this->assertEquals('bar', $def->getClass()); $this->assertEquals(array('a', 'b'), $def->getArguments()); $this->assertEquals(array('foo' => 'bar'), $def->getProperties()); } public function testProcessAppendsMethodCallsAlways() { $container = new ContainerBuilder(); $container ->register('parent') ->addMethodCall('foo', array('bar')) ; $container ->setDefinition('child', new DefinitionDecorator('parent')) ->addMethodCall('bar', array('foo')) ; $this->process($container); $def = $container->getDefinition('child'); $this->assertEquals(array( array('foo', array('bar')), array('bar', array('foo')), ), $def->getMethodCalls()); } public function testProcessDoesNotCopyAbstract() { $container = new ContainerBuilder(); $container ->register('parent') ->setAbstract(true) ; $container ->setDefinition('child', new DefinitionDecorator('parent')) ; $this->process($container); $def = $container->getDefinition('child'); $this->assertFalse($def->isAbstract()); } public function testProcessDoesNotCopyScope() { $container = new ContainerBuilder(); $container ->register('parent') ->setScope('foo') ; $container ->setDefinition('child', new DefinitionDecorator('parent')) ; $this->process($container); $def = $container->getDefinition('child'); $this->assertEquals(ContainerInterface::SCOPE_CONTAINER, $def->getScope()); } public function testProcessDoesNotCopyTags() { $container = new ContainerBuilder(); $container ->register('parent') ->addTag('foo') ; $container ->setDefinition('child', new DefinitionDecorator('parent')) ; $this->process($container); $def = $container->getDefinition('child'); $this->assertEquals(array(), $def->getTags()); } public function testProcessHandlesMultipleInheritance() { $container = new ContainerBuilder(); $container ->register('parent', 'foo') ->setArguments(array('foo', 'bar', 'c')) ; $container ->setDefinition('child2', new DefinitionDecorator('child1')) ->replaceArgument(1, 'b') ; $container ->setDefinition('child1', new DefinitionDecorator('parent')) ->replaceArgument(0, 'a') ; $this->process($container); $def = $container->getDefinition('child2'); $this->assertEquals(array('a', 'b', 'c'), $def->getArguments()); $this->assertEquals('foo', $def->getClass()); } public function testSetLazyOnServiceHasParent() { $container = new ContainerBuilder(); $container->register('parent','stdClass'); $container->setDefinition('child1',new DefinitionDecorator('parent')) ->setLazy(true) ; $this->process($container); $this->assertTrue($container->getDefinition('child1')->isLazy()); } public function testSetLazyOnServiceIsParent() { $container = new ContainerBuilder(); $container->register('parent','stdClass') ->setLazy(true) ; $container->setDefinition('child1',new DefinitionDecorator('parent')); $this->process($container); $this->assertTrue($container->getDefinition('child1')->isLazy()); } protected function process(ContainerBuilder $container) { $pass = new ResolveDefinitionTemplatesPass(); $pass->process($container); } } PK!}1H@@WComponent/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Compiler\ReplaceAliasByActualDefinitionPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; class ReplaceAliasByActualDefinitionPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $container->register('a', '\stdClass'); $bDefinition = new Definition('\stdClass'); $bDefinition->setPublic(false); $container->setDefinition('b', $bDefinition); $container->setAlias('a_alias', 'a'); $container->setAlias('b_alias', 'b'); $this->process($container); $this->assertTrue($container->has('a'), '->process() does nothing to public definitions.'); $this->assertTrue($container->hasAlias('a_alias')); $this->assertFalse($container->has('b'), '->process() removes non-public definitions.'); $this->assertTrue( $container->has('b_alias') && !$container->hasAlias('b_alias'), '->process() replaces alias to actual.' ); } /** * @expectedException \InvalidArgumentException */ public function testProcessWithInvalidAlias() { $container = new ContainerBuilder(); $container->setAlias('a_alias', 'a'); $this->process($container); } protected function process(ContainerBuilder $container) { $pass = new ReplaceAliasByActualDefinitionPass(); $pass->process($container); } } PK!f00QComponent/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; class InlineServiceDefinitionsPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $container ->register('inlinable.service') ->setPublic(false) ; $container ->register('service') ->setArguments(array(new Reference('inlinable.service'))) ; $this->process($container); $arguments = $container->getDefinition('service')->getArguments(); $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $arguments[0]); $this->assertSame($container->getDefinition('inlinable.service'), $arguments[0]); } public function testProcessDoesNotInlineWhenAliasedServiceIsNotOfPrototypeScope() { $container = new ContainerBuilder(); $container ->register('foo') ->setPublic(false) ; $container->setAlias('moo', 'foo'); $container ->register('service') ->setArguments(array($ref = new Reference('foo'))) ; $this->process($container); $arguments = $container->getDefinition('service')->getArguments(); $this->assertSame($ref, $arguments[0]); } public function testProcessDoesInlineServiceOfPrototypeScope() { $container = new ContainerBuilder(); $container ->register('foo') ->setScope('prototype') ; $container ->register('bar') ->setPublic(false) ->setScope('prototype') ; $container->setAlias('moo', 'bar'); $container ->register('service') ->setArguments(array(new Reference('foo'), $ref = new Reference('moo'), new Reference('bar'))) ; $this->process($container); $arguments = $container->getDefinition('service')->getArguments(); $this->assertEquals($container->getDefinition('foo'), $arguments[0]); $this->assertNotSame($container->getDefinition('foo'), $arguments[0]); $this->assertSame($ref, $arguments[1]); $this->assertEquals($container->getDefinition('bar'), $arguments[2]); $this->assertNotSame($container->getDefinition('bar'), $arguments[2]); } public function testProcessInlinesIfMultipleReferencesButAllFromTheSameDefinition() { $container = new ContainerBuilder(); $a = $container->register('a')->setPublic(false); $b = $container ->register('b') ->addArgument(new Reference('a')) ->addArgument(new Definition(null, array(new Reference('a')))) ; $this->process($container); $arguments = $b->getArguments(); $this->assertSame($a, $arguments[0]); $inlinedArguments = $arguments[1]->getArguments(); $this->assertSame($a, $inlinedArguments[0]); } public function testProcessInlinesOnlyIfSameScope() { $container = new ContainerBuilder(); $container->addScope(new Scope('foo')); $a = $container->register('a')->setPublic(false)->setScope('foo'); $b = $container->register('b')->addArgument(new Reference('a')); $this->process($container); $arguments = $b->getArguments(); $this->assertEquals(new Reference('a'), $arguments[0]); $this->assertTrue($container->hasDefinition('a')); } public function testProcessDoesNotInlineWhenServiceIsPrivateButLazy() { $container = new ContainerBuilder(); $container ->register('foo') ->setPublic(false) ->setLazy(true) ; $container ->register('service') ->setArguments(array($ref = new Reference('foo'))) ; $this->process($container); $arguments = $container->getDefinition('service')->getArguments(); $this->assertSame($ref, $arguments[0]); } public function testProcessDoesNotInlineWhenServiceReferencesItself() { $container = new ContainerBuilder(); $container ->register('foo') ->setPublic(false) ->addMethodCall('foo', array($ref = new Reference('foo'))) ; $this->process($container); $calls = $container->getDefinition('foo')->getMethodCalls(); $this->assertSame($ref, $calls[0][1][0]); } protected function process(ContainerBuilder $container) { $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass())); $repeatedPass->process($container); } } PK!O @Component/DependencyInjection/Tests/Compiler/IntegrationTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * This class tests the integration of the different compiler passes */ class IntegrationTest extends \PHPUnit_Framework_TestCase { /** * This tests that the following dependencies are correctly processed: * * A is public, B/C are private * A -> C * B -> C */ public function testProcessRemovesAndInlinesRecursively() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $a = $container ->register('a', '\stdClass') ->addArgument(new Reference('c')) ; $b = $container ->register('b', '\stdClass') ->addArgument(new Reference('c')) ->setPublic(false) ; $c = $container ->register('c', '\stdClass') ->setPublic(false) ; $container->compile(); $this->assertTrue($container->hasDefinition('a')); $arguments = $a->getArguments(); $this->assertSame($c, $arguments[0]); $this->assertFalse($container->hasDefinition('b')); $this->assertFalse($container->hasDefinition('c')); } public function testProcessInlinesReferencesToAliases() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $a = $container ->register('a', '\stdClass') ->addArgument(new Reference('b')) ; $container->setAlias('b', new Alias('c', false)); $c = $container ->register('c', '\stdClass') ->setPublic(false) ; $container->compile(); $this->assertTrue($container->hasDefinition('a')); $arguments = $a->getArguments(); $this->assertSame($c, $arguments[0]); $this->assertFalse($container->hasAlias('b')); $this->assertFalse($container->hasDefinition('c')); } public function testProcessInlinesWhenThereAreMultipleReferencesButFromTheSameDefinition() { $container = new ContainerBuilder(); $container->setResourceTracking(false); $container ->register('a', '\stdClass') ->addArgument(new Reference('b')) ->addMethodCall('setC', array(new Reference('c'))) ; $container ->register('b', '\stdClass') ->addArgument(new Reference('c')) ->setPublic(false) ; $container ->register('c', '\stdClass') ->setPublic(false) ; $container->compile(); $this->assertTrue($container->hasDefinition('a')); $this->assertFalse($container->hasDefinition('b')); $this->assertFalse($container->hasDefinition('c'), 'Service C was not inlined.'); } } PK!@|޵aComponent/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Compiler\CheckExceptionOnInvalidReferenceBehaviorPass; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; class CheckExceptionOnInvalidReferenceBehaviorPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $container ->register('a', '\stdClass') ->addArgument(new Reference('b')) ; $container->register('b', '\stdClass'); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException */ public function testProcessThrowsExceptionOnInvalidReference() { $container = new ContainerBuilder(); $container ->register('a', '\stdClass') ->addArgument(new Reference('b')) ; $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException */ public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition() { $container = new ContainerBuilder(); $def = new Definition(); $def->addArgument(new Reference('b')); $container ->register('a', '\stdClass') ->addArgument($def) ; $this->process($container); } private function process(ContainerBuilder $container) { $pass = new CheckExceptionOnInvalidReferenceBehaviorPass(); $pass->process($container); } } PK!@w PComponent/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Compiler\CheckDefinitionValidityPass; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase { /** * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException */ public function testProcessDetectsSyntheticNonPublicDefinitions() { $container = new ContainerBuilder(); $container->register('a')->setSynthetic(true)->setPublic(false); $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException */ public function testProcessDetectsSyntheticPrototypeDefinitions() { $container = new ContainerBuilder(); $container->register('a')->setSynthetic(true)->setScope(ContainerInterface::SCOPE_PROTOTYPE); $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException */ public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass() { $container = new ContainerBuilder(); $container->register('a')->setSynthetic(false)->setAbstract(false); $this->process($container); } public function testProcess() { $container = new ContainerBuilder(); $container->register('a', 'class'); $container->register('b', 'class')->setSynthetic(true)->setPublic(true); $container->register('c', 'class')->setAbstract(true); $container->register('d', 'class')->setSynthetic(true); $this->process($container); } public function testValidTags() { $container = new ContainerBuilder(); $container->register('a', 'class')->addTag('foo', array('bar' => 'baz')); $container->register('b', 'class')->addTag('foo', array('bar' => null)); $container->register('c', 'class')->addTag('foo', array('bar' => 1)); $container->register('d', 'class')->addTag('foo', array('bar' => 1.1)); $this->process($container); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException */ public function testInvalidTags() { $container = new ContainerBuilder(); $container->register('a', 'class')->addTag('foo', array('bar' => array('baz' => 'baz'))); $this->process($container); } protected function process(ContainerBuilder $container) { $pass = new CheckDefinitionValidityPass(); $pass->process($container); } } PK!~ ` ` QComponent/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Compiler\Compiler; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; class AnalyzeServiceReferencesPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $a = $container ->register('a') ->addArgument($ref1 = new Reference('b')) ; $b = $container ->register('b') ->addMethodCall('setA', array($ref2 = new Reference('a'))) ; $c = $container ->register('c') ->addArgument($ref3 = new Reference('a')) ->addArgument($ref4 = new Reference('b')) ; $d = $container ->register('d') ->setProperty('foo', $ref5 = new Reference('b')) ; $e = $container ->register('e') ->setConfigurator(array($ref6 = new Reference('b'), 'methodName')) ; $graph = $this->process($container); $this->assertCount(4, $edges = $graph->getNode('b')->getInEdges()); $this->assertSame($ref1, $edges[0]->getValue()); $this->assertSame($ref4, $edges[1]->getValue()); $this->assertSame($ref5, $edges[2]->getValue()); $this->assertSame($ref6, $edges[3]->getValue()); } public function testProcessDetectsReferencesFromInlinedDefinitions() { $container = new ContainerBuilder(); $container ->register('a') ; $container ->register('b') ->addArgument(new Definition(null, array($ref = new Reference('a')))) ; $graph = $this->process($container); $this->assertCount(1, $refs = $graph->getNode('a')->getInEdges()); $this->assertSame($ref, $refs[0]->getValue()); } public function testProcessDoesNotSaveDuplicateReferences() { $container = new ContainerBuilder(); $container ->register('a') ; $container ->register('b') ->addArgument(new Definition(null, array($ref1 = new Reference('a')))) ->addArgument(new Definition(null, array($ref2 = new Reference('a')))) ; $graph = $this->process($container); $this->assertCount(2, $graph->getNode('a')->getInEdges()); } protected function process(ContainerBuilder $container) { $pass = new RepeatedPass(array(new AnalyzeServiceReferencesPass())); $pass->process($container); return $container->getCompiler()->getServiceReferenceGraph(); } } PK!I PComponent/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; use Symfony\Component\DependencyInjection\Compiler\Compiler; use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; use Symfony\Component\DependencyInjection\Compiler\RemoveUnusedDefinitionsPass; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; class RemoveUnusedDefinitionsPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $container ->register('foo') ->setPublic(false) ; $container ->register('bar') ->setPublic(false) ; $container ->register('moo') ->setArguments(array(new Reference('bar'))) ; $this->process($container); $this->assertFalse($container->hasDefinition('foo')); $this->assertTrue($container->hasDefinition('bar')); $this->assertTrue($container->hasDefinition('moo')); } public function testProcessRemovesUnusedDefinitionsRecursively() { $container = new ContainerBuilder(); $container ->register('foo') ->setPublic(false) ; $container ->register('bar') ->setArguments(array(new Reference('foo'))) ->setPublic(false) ; $this->process($container); $this->assertFalse($container->hasDefinition('foo')); $this->assertFalse($container->hasDefinition('bar')); } public function testProcessWorksWithInlinedDefinitions() { $container = new ContainerBuilder(); $container ->register('foo') ->setPublic(false) ; $container ->register('bar') ->setArguments(array(new Definition(null, array(new Reference('foo'))))) ; $this->process($container); $this->assertTrue($container->hasDefinition('foo')); $this->assertTrue($container->hasDefinition('bar')); } protected function process(ContainerBuilder $container) { $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new RemoveUnusedDefinitionsPass())); $repeatedPass->process($container); } } PK! T^??SComponent/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Compiler\ResolveReferencesToAliasesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; class ResolveReferencesToAliasesPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { $container = new ContainerBuilder(); $container->setAlias('bar', 'foo'); $def = $container ->register('moo') ->setArguments(array(new Reference('bar'))) ; $this->process($container); $arguments = $def->getArguments(); $this->assertEquals('foo', (string) $arguments[0]); } public function testProcessRecursively() { $container = new ContainerBuilder(); $container->setAlias('bar', 'foo'); $container->setAlias('moo', 'bar'); $def = $container ->register('foobar') ->setArguments(array(new Reference('moo'))) ; $this->process($container); $arguments = $def->getArguments(); $this->assertEquals('foo', (string) $arguments[0]); } protected function process(ContainerBuilder $container) { $pass = new ResolveReferencesToAliasesPass(); $pass->process($container); } } PK!e556Component/DependencyInjection/Tests/DefinitionTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; use Symfony\Component\DependencyInjection\Definition; class DefinitionTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\Definition::__construct */ public function testConstructor() { $def = new Definition('stdClass'); $this->assertEquals('stdClass', $def->getClass(), '__construct() takes the class name as its first argument'); $def = new Definition('stdClass', array('foo')); $this->assertEquals(array('foo'), $def->getArguments(), '__construct() takes an optional array of arguments as its second argument'); } public function testSetGetFactoryClass() { $def = new Definition('stdClass'); $this->assertNull($def->getFactoryClass()); $this->assertSame($def, $def->setFactoryClass('stdClass2'), "->setFactoryClass() implements a fluent interface."); $this->assertEquals('stdClass2', $def->getFactoryClass(), "->getFactoryClass() returns current class to construct this service."); } public function testSetGetFactoryMethod() { $def = new Definition('stdClass'); $this->assertNull($def->getFactoryMethod()); $this->assertSame($def, $def->setFactoryMethod('foo'), '->setFactoryMethod() implements a fluent interface'); $this->assertEquals('foo', $def->getFactoryMethod(), '->getFactoryMethod() returns the factory method name'); } public function testSetGetFactoryService() { $def = new Definition('stdClass'); $this->assertNull($def->getFactoryService()); $this->assertSame($def, $def->setFactoryService('foo.bar'), "->setFactoryService() implements a fluent interface."); $this->assertEquals('foo.bar', $def->getFactoryService(), "->getFactoryService() returns current service to construct this service."); } /** * @covers Symfony\Component\DependencyInjection\Definition::setClass * @covers Symfony\Component\DependencyInjection\Definition::getClass */ public function testSetGetClass() { $def = new Definition('stdClass'); $this->assertSame($def, $def->setClass('foo'), '->setClass() implements a fluent interface'); $this->assertEquals('foo', $def->getClass(), '->getClass() returns the class name'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setArguments * @covers Symfony\Component\DependencyInjection\Definition::getArguments * @covers Symfony\Component\DependencyInjection\Definition::addArgument */ public function testArguments() { $def = new Definition('stdClass'); $this->assertSame($def, $def->setArguments(array('foo')), '->setArguments() implements a fluent interface'); $this->assertEquals(array('foo'), $def->getArguments(), '->getArguments() returns the arguments'); $this->assertSame($def, $def->addArgument('bar'), '->addArgument() implements a fluent interface'); $this->assertEquals(array('foo', 'bar'), $def->getArguments(), '->addArgument() adds an argument'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setMethodCalls * @covers Symfony\Component\DependencyInjection\Definition::addMethodCall * @covers Symfony\Component\DependencyInjection\Definition::hasMethodCall * @covers Symfony\Component\DependencyInjection\Definition::removeMethodCall */ public function testMethodCalls() { $def = new Definition('stdClass'); $this->assertSame($def, $def->setMethodCalls(array(array('foo', array('foo')))), '->setMethodCalls() implements a fluent interface'); $this->assertEquals(array(array('foo', array('foo'))), $def->getMethodCalls(), '->getMethodCalls() returns the methods to call'); $this->assertSame($def, $def->addMethodCall('bar', array('bar')), '->addMethodCall() implements a fluent interface'); $this->assertEquals(array(array('foo', array('foo')), array('bar', array('bar'))), $def->getMethodCalls(), '->addMethodCall() adds a method to call'); $this->assertTrue($def->hasMethodCall('bar'), '->hasMethodCall() returns true if first argument is a method to call registered'); $this->assertFalse($def->hasMethodCall('no_registered'), '->hasMethodCall() returns false if first argument is not a method to call registered'); $this->assertSame($def, $def->removeMethodCall('bar'), '->removeMethodCall() implements a fluent interface'); $this->assertEquals(array(array('foo', array('foo'))), $def->getMethodCalls(), '->removeMethodCall() removes a method to call'); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @expectedExceptionMessage Method name cannot be empty. */ public function testExceptionOnEmptyMethodCall() { $def = new Definition('stdClass'); $def->addMethodCall(''); } /** * @covers Symfony\Component\DependencyInjection\Definition::setFile * @covers Symfony\Component\DependencyInjection\Definition::getFile */ public function testSetGetFile() { $def = new Definition('stdClass'); $this->assertSame($def, $def->setFile('foo'), '->setFile() implements a fluent interface'); $this->assertEquals('foo', $def->getFile(), '->getFile() returns the file to include'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setScope * @covers Symfony\Component\DependencyInjection\Definition::getScope */ public function testSetGetScope() { $def = new Definition('stdClass'); $this->assertEquals('container', $def->getScope()); $this->assertSame($def, $def->setScope('foo')); $this->assertEquals('foo', $def->getScope()); } /** * @covers Symfony\Component\DependencyInjection\Definition::setPublic * @covers Symfony\Component\DependencyInjection\Definition::isPublic */ public function testSetIsPublic() { $def = new Definition('stdClass'); $this->assertTrue($def->isPublic(), '->isPublic() returns true by default'); $this->assertSame($def, $def->setPublic(false), '->setPublic() implements a fluent interface'); $this->assertFalse($def->isPublic(), '->isPublic() returns false if the instance must not be public.'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setSynthetic * @covers Symfony\Component\DependencyInjection\Definition::isSynthetic */ public function testSetIsSynthetic() { $def = new Definition('stdClass'); $this->assertFalse($def->isSynthetic(), '->isSynthetic() returns false by default'); $this->assertSame($def, $def->setSynthetic(true), '->setSynthetic() implements a fluent interface'); $this->assertTrue($def->isSynthetic(), '->isSynthetic() returns true if the service is synthetic.'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setSynchronized * @covers Symfony\Component\DependencyInjection\Definition::isSynchronized */ public function testSetIsSynchronized() { $def = new Definition('stdClass'); $this->assertFalse($def->isSynchronized(), '->isSynchronized() returns false by default'); $this->assertSame($def, $def->setSynchronized(true), '->setSynchronized() implements a fluent interface'); $this->assertTrue($def->isSynchronized(), '->isSynchronized() returns true if the service is synchronized.'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setLazy * @covers Symfony\Component\DependencyInjection\Definition::isLazy */ public function testSetIsLazy() { $def = new Definition('stdClass'); $this->assertFalse($def->isLazy(), '->isLazy() returns false by default'); $this->assertSame($def, $def->setLazy(true), '->setLazy() implements a fluent interface'); $this->assertTrue($def->isLazy(), '->isLazy() returns true if the service is lazy.'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setAbstract * @covers Symfony\Component\DependencyInjection\Definition::isAbstract */ public function testSetIsAbstract() { $def = new Definition('stdClass'); $this->assertFalse($def->isAbstract(), '->isAbstract() returns false by default'); $this->assertSame($def, $def->setAbstract(true), '->setAbstract() implements a fluent interface'); $this->assertTrue($def->isAbstract(), '->isAbstract() returns true if the instance must not be public.'); } /** * @covers Symfony\Component\DependencyInjection\Definition::setConfigurator * @covers Symfony\Component\DependencyInjection\Definition::getConfigurator */ public function testSetGetConfigurator() { $def = new Definition('stdClass'); $this->assertSame($def, $def->setConfigurator('foo'), '->setConfigurator() implements a fluent interface'); $this->assertEquals('foo', $def->getConfigurator(), '->getConfigurator() returns the configurator'); } /** * @covers Symfony\Component\DependencyInjection\Definition::clearTags */ public function testClearTags() { $def = new Definition('stdClass'); $this->assertSame($def, $def->clearTags(), '->clearTags() implements a fluent interface'); $def->addTag('foo', array('foo' => 'bar')); $def->clearTags(); $this->assertEquals(array(), $def->getTags(), '->clearTags() removes all current tags'); } /** * @covers Symfony\Component\DependencyInjection\Definition::clearTags */ public function testClearTag() { $def = new Definition('stdClass'); $this->assertSame($def, $def->clearTags(), '->clearTags() implements a fluent interface'); $def->addTag('1foo1', array('foo1' => 'bar1')); $def->addTag('2foo2', array('foo2' => 'bar2')); $def->addTag('3foo3', array('foo3' => 'bar3')); $def->clearTag('2foo2'); $this->assertTrue($def->hasTag('1foo1')); $this->assertFalse($def->hasTag('2foo2')); $this->assertTrue($def->hasTag('3foo3')); $def->clearTag('1foo1'); $this->assertFalse($def->hasTag('1foo1')); $this->assertTrue($def->hasTag('3foo3')); } /** * @covers Symfony\Component\DependencyInjection\Definition::addTag * @covers Symfony\Component\DependencyInjection\Definition::getTag * @covers Symfony\Component\DependencyInjection\Definition::getTags * @covers Symfony\Component\DependencyInjection\Definition::hasTag */ public function testTags() { $def = new Definition('stdClass'); $this->assertEquals(array(), $def->getTag('foo'), '->getTag() returns an empty array if the tag is not defined'); $this->assertFalse($def->hasTag('foo')); $this->assertSame($def, $def->addTag('foo'), '->addTag() implements a fluent interface'); $this->assertTrue($def->hasTag('foo')); $this->assertEquals(array(array()), $def->getTag('foo'), '->getTag() returns attributes for a tag name'); $def->addTag('foo', array('foo' => 'bar')); $this->assertEquals(array(array(), array('foo' => 'bar')), $def->getTag('foo'), '->addTag() can adds the same tag several times'); $def->addTag('bar', array('bar' => 'bar')); $this->assertEquals($def->getTags(), array( 'foo' => array(array(), array('foo' => 'bar')), 'bar' => array(array('bar' => 'bar')), ), '->getTags() returns all tags'); } /** * @covers Symfony\Component\DependencyInjection\Definition::replaceArgument */ public function testSetArgument() { $def = new Definition('stdClass'); $def->addArgument('foo'); $this->assertSame(array('foo'), $def->getArguments()); $this->assertSame($def, $def->replaceArgument(0, 'moo')); $this->assertSame(array('moo'), $def->getArguments()); $def->addArgument('moo'); $def ->replaceArgument(0, 'foo') ->replaceArgument(1, 'bar') ; $this->assertSame(array('foo', 'bar'), $def->getArguments()); } /** * @expectedException \OutOfBoundsException */ public function testGetArgumentShouldCheckBounds() { $def = new Definition('stdClass'); $def->addArgument('foo'); $def->getArgument(1); } /** * @expectedException \OutOfBoundsException */ public function testReplaceArgumentShouldCheckBounds() { $def = new Definition('stdClass'); $def->addArgument('foo'); $def->replaceArgument(1, 'bar'); } public function testSetGetProperties() { $def = new Definition('stdClass'); $this->assertEquals(array(), $def->getProperties()); $this->assertSame($def, $def->setProperties(array('foo' => 'bar'))); $this->assertEquals(array('foo' => 'bar'), $def->getProperties()); } public function testSetProperty() { $def = new Definition('stdClass'); $this->assertEquals(array(), $def->getProperties()); $this->assertSame($def, $def->setProperty('foo', 'bar')); $this->assertEquals(array('foo' => 'bar'), $def->getProperties()); } } PK!+E ?Component/DependencyInjection/Tests/DefinitionDecoratorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; use Symfony\Component\DependencyInjection\DefinitionDecorator; class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase { public function testConstructor() { $def = new DefinitionDecorator('foo'); $this->assertEquals('foo', $def->getParent()); $this->assertEquals(array(), $def->getChanges()); } /** * @dataProvider getPropertyTests */ public function testSetProperty($property, $changeKey) { $def = new DefinitionDecorator('foo'); $getter = 'get'.ucfirst($property); $setter = 'set'.ucfirst($property); $this->assertNull($def->$getter()); $this->assertSame($def, $def->$setter('foo')); $this->assertEquals('foo', $def->$getter()); $this->assertEquals(array($changeKey => true), $def->getChanges()); } public function getPropertyTests() { return array( array('class', 'class'), array('factoryClass', 'factory_class'), array('factoryMethod', 'factory_method'), array('factoryService', 'factory_service'), array('configurator', 'configurator'), array('file', 'file'), ); } public function testSetPublic() { $def = new DefinitionDecorator('foo'); $this->assertTrue($def->isPublic()); $this->assertSame($def, $def->setPublic(false)); $this->assertFalse($def->isPublic()); $this->assertEquals(array('public' => true), $def->getChanges()); } public function testSetLazy() { $def = new DefinitionDecorator('foo'); $this->assertFalse($def->isLazy()); $this->assertSame($def, $def->setLazy(false)); $this->assertFalse($def->isLazy()); $this->assertEquals(array('lazy' => true), $def->getChanges()); } public function testSetArgument() { $def = new DefinitionDecorator('foo'); $this->assertEquals(array(), $def->getArguments()); $this->assertSame($def, $def->replaceArgument(0, 'foo')); $this->assertEquals(array('index_0' => 'foo'), $def->getArguments()); } /** * @expectedException \InvalidArgumentException */ public function testReplaceArgumentShouldRequireIntegerIndex() { $def = new DefinitionDecorator('foo'); $def->replaceArgument('0', 'foo'); } public function testReplaceArgument() { $def = new DefinitionDecorator('foo'); $def->setArguments(array(0 => 'foo', 1 => 'bar')); $this->assertEquals('foo', $def->getArgument(0)); $this->assertEquals('bar', $def->getArgument(1)); $this->assertSame($def, $def->replaceArgument(1, 'baz')); $this->assertEquals('foo', $def->getArgument(0)); $this->assertEquals('baz', $def->getArgument(1)); $this->assertEquals(array(0 => 'foo', 1 => 'bar', 'index_1' => 'baz'), $def->getArguments()); } /** * @expectedException \OutOfBoundsException */ public function testGetArgumentShouldCheckBounds() { $def = new DefinitionDecorator('foo'); $def->setArguments(array(0 => 'foo')); $def->replaceArgument(0, 'foo'); $def->getArgument(1); } } PK!K5WW5Component/DependencyInjection/Tests/ContainerTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests; use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Exception\InactiveScopeException; class ContainerTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\DependencyInjection\Container::__construct */ public function testConstructor() { $sc = new Container(); $this->assertSame($sc, $sc->get('service_container'), '__construct() automatically registers itself as a service'); $sc = new Container(new ParameterBag(array('foo' => 'bar'))); $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '__construct() takes an array of parameters as its first argument'); } /** * @dataProvider dataForTestCamelize */ public function testCamelize($id, $expected) { $this->assertEquals($expected, Container::camelize($id), sprintf('Container::camelize("%s")', $id)); } public function dataForTestCamelize() { return array( array('foo_bar', 'FooBar'), array('foo.bar', 'Foo_Bar'), array('foo.bar_baz', 'Foo_BarBaz'), array('foo._bar', 'Foo_Bar'), array('foo_.bar', 'Foo_Bar'), array('_foo', 'Foo'), array('.foo', '_Foo'), array('foo_', 'Foo'), array('foo.', 'Foo_'), array('foo\bar', 'Foo_Bar'), ); } /** * @covers Symfony\Component\DependencyInjection\Container::compile */ public function testCompile() { $sc = new Container(new ParameterBag(array('foo' => 'bar'))); $sc->compile(); $this->assertInstanceOf('Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag', $sc->getParameterBag(), '->compile() changes the parameter bag to a FrozenParameterBag instance'); $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '->compile() copies the current parameters to the new parameter bag'); } /** * @covers Symfony\Component\DependencyInjection\Container::isFrozen */ public function testIsFrozen() { $sc = new Container(new ParameterBag(array('foo' => 'bar'))); $this->assertFalse($sc->isFrozen(), '->isFrozen() returns false if the parameters are not frozen'); $sc->compile(); $this->assertTrue($sc->isFrozen(), '->isFrozen() returns true if the parameters are frozen'); } /** * @covers Symfony\Component\DependencyInjection\Container::getParameterBag */ public function testGetParameterBag() { $sc = new Container(); $this->assertEquals(array(), $sc->getParameterBag()->all(), '->getParameterBag() returns an empty array if no parameter has been defined'); } /** * @covers Symfony\Component\DependencyInjection\Container::setParameter * @covers Symfony\Component\DependencyInjection\Container::getParameter */ public function testGetSetParameter() { $sc = new Container(new ParameterBag(array('foo' => 'bar'))); $sc->setParameter('bar', 'foo'); $this->assertEquals('foo', $sc->getParameter('bar'), '->setParameter() sets the value of a new parameter'); $sc->setParameter('foo', 'baz'); $this->assertEquals('baz', $sc->getParameter('foo'), '->setParameter() overrides previously set parameter'); $sc->setParameter('Foo', 'baz1'); $this->assertEquals('baz1', $sc->getParameter('foo'), '->setParameter() converts the key to lowercase'); $this->assertEquals('baz1', $sc->getParameter('FOO'), '->getParameter() converts the key to lowercase'); try { $sc->getParameter('baba'); $this->fail('->getParameter() thrown an \InvalidArgumentException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->getParameter() thrown an \InvalidArgumentException if the key does not exist'); $this->assertEquals('You have requested a non-existent parameter "baba".', $e->getMessage(), '->getParameter() thrown an \InvalidArgumentException if the key does not exist'); } } /** * @covers Symfony\Component\DependencyInjection\Container::getServiceIds */ public function testGetServiceIds() { $sc = new Container(); $sc->set('foo', $obj = new \stdClass()); $sc->set('bar', $obj = new \stdClass()); $this->assertEquals(array('service_container', 'foo', 'bar'), $sc->getServiceIds(), '->getServiceIds() returns all defined service ids'); $sc = new ProjectServiceContainer(); $this->assertEquals(array('scoped', 'scoped_foo', 'inactive', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'service_container'), $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods'); } /** * @covers Symfony\Component\DependencyInjection\Container::set */ public function testSet() { $sc = new Container(); $sc->set('foo', $foo = new \stdClass()); $this->assertEquals($foo, $sc->get('foo'), '->set() sets a service'); } /** * @covers Symfony\Component\DependencyInjection\Container::set */ public function testSetWithNullResetTheService() { $sc = new Container(); $sc->set('foo', null); $this->assertFalse($sc->has('foo')); } /** * @expectedException \InvalidArgumentException */ public function testSetDoesNotAllowPrototypeScope() { $c = new Container(); $c->set('foo', new \stdClass(), 'prototype'); } /** * @expectedException \RuntimeException */ public function testSetDoesNotAllowInactiveScope() { $c = new Container(); $c->addScope(new Scope('foo')); $c->set('foo', new \stdClass(), 'foo'); } public function testSetAlsoSetsScopedService() { $c = new Container(); $c->addScope(new Scope('foo')); $c->enterScope('foo'); $c->set('foo', $foo = new \stdClass(), 'foo'); $services = $this->getField($c, 'scopedServices'); $this->assertTrue(isset($services['foo']['foo'])); $this->assertSame($foo, $services['foo']['foo']); } /** * @covers Symfony\Component\DependencyInjection\Container::get */ public function testGet() { $sc = new ProjectServiceContainer(); $sc->set('foo', $foo = new \stdClass()); $this->assertEquals($foo, $sc->get('foo'), '->get() returns the service for the given id'); $this->assertEquals($sc->__bar, $sc->get('bar'), '->get() returns the service for the given id'); $this->assertEquals($sc->__foo_bar, $sc->get('foo_bar'), '->get() returns the service if a get*Method() is defined'); $this->assertEquals($sc->__foo_baz, $sc->get('foo.baz'), '->get() returns the service if a get*Method() is defined'); $this->assertEquals($sc->__foo_baz, $sc->get('foo\\baz'), '->get() returns the service if a get*Method() is defined'); $sc->set('bar', $bar = new \stdClass()); $this->assertEquals($bar, $sc->get('bar'), '->get() prefers to return a service defined with set() than one defined with a getXXXMethod()'); try { $sc->get(''); $this->fail('->get() throws a \InvalidArgumentException exception if the service is empty'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws a ServiceNotFoundException exception if the service is empty'); } $this->assertNull($sc->get('', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } public function testGetThrowServiceNotFoundException() { $sc = new ProjectServiceContainer(); $sc->set('foo', $foo = new \stdClass()); $sc->set('bar', $foo = new \stdClass()); $sc->set('baz', $foo = new \stdClass()); try { $sc->get('foo1'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent service "foo1". Did you mean this: "foo"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices'); } try { $sc->get('bag'); $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist'); $this->assertEquals('You have requested a non-existent service "bag". Did you mean one of these: "bar", "baz"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices'); } } public function testGetCircularReference() { $sc = new ProjectServiceContainer(); try { $sc->get('circular'); $this->fail('->get() throws a ServiceCircularReferenceException if it contains circular reference'); } catch (\Exception $e) { $this->assertInstanceOf('\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException', $e, '->get() throws a ServiceCircularReferenceException if it contains circular reference'); $this->assertStringStartsWith('Circular reference detected for service "circular"', $e->getMessage(), '->get() throws a \LogicException if it contains circular reference'); } } /** * @covers Symfony\Component\DependencyInjection\Container::get */ public function testGetReturnsNullOnInactiveScope() { $sc = new ProjectServiceContainer(); $this->assertNull($sc->get('inactive', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } /** * @covers Symfony\Component\DependencyInjection\Container::has */ public function testHas() { $sc = new ProjectServiceContainer(); $sc->set('foo', new \stdClass()); $this->assertFalse($sc->has('foo1'), '->has() returns false if the service does not exist'); $this->assertTrue($sc->has('foo'), '->has() returns true if the service exists'); $this->assertTrue($sc->has('bar'), '->has() returns true if a get*Method() is defined'); $this->assertTrue($sc->has('foo_bar'), '->has() returns true if a get*Method() is defined'); $this->assertTrue($sc->has('foo.baz'), '->has() returns true if a get*Method() is defined'); $this->assertTrue($sc->has('foo\\baz'), '->has() returns true if a get*Method() is defined'); } /** * @covers Symfony\Component\DependencyInjection\Container::initialized */ public function testInitialized() { $sc = new ProjectServiceContainer(); $sc->set('foo', new \stdClass()); $this->assertTrue($sc->initialized('foo'), '->initialized() returns true if service is loaded'); $this->assertFalse($sc->initialized('foo1'), '->initialized() returns false if service is not loaded'); $this->assertFalse($sc->initialized('bar'), '->initialized() returns false if a service is defined, but not currently loaded'); } public function testEnterLeaveCurrentScope() { $container = new ProjectServiceContainer(); $container->addScope(new Scope('foo')); $container->enterScope('foo'); $scoped1 = $container->get('scoped'); $scopedFoo1 = $container->get('scoped_foo'); $container->enterScope('foo'); $scoped2 = $container->get('scoped'); $scoped3 = $container->get('scoped'); $scopedFoo2 = $container->get('scoped_foo'); $container->leaveScope('foo'); $scoped4 = $container->get('scoped'); $scopedFoo3 = $container->get('scoped_foo'); $this->assertNotSame($scoped1, $scoped2); $this->assertSame($scoped2, $scoped3); $this->assertSame($scoped1, $scoped4); $this->assertNotSame($scopedFoo1, $scopedFoo2); $this->assertSame($scopedFoo1, $scopedFoo3); } public function testEnterLeaveScopeWithChildScopes() { $container = new Container(); $container->addScope(new Scope('foo')); $container->addScope(new Scope('bar', 'foo')); $this->assertFalse($container->isScopeActive('foo')); $container->enterScope('foo'); $container->enterScope('bar'); $this->assertTrue($container->isScopeActive('foo')); $this->assertFalse($container->has('a')); $a = new \stdClass(); $container->set('a', $a, 'bar'); $services = $this->getField($container, 'scopedServices'); $this->assertTrue(isset($services['bar']['a'])); $this->assertSame($a, $services['bar']['a']); $this->assertTrue($container->has('a')); $container->leaveScope('foo'); $services = $this->getField($container, 'scopedServices'); $this->assertFalse(isset($services['bar'])); $this->assertFalse($container->isScopeActive('foo')); $this->assertFalse($container->has('a')); } public function testEnterScopeRecursivelyWithInactiveChildScopes() { $container = new Container(); $container->addScope(new Scope('foo')); $container->addScope(new Scope('bar', 'foo')); $this->assertFalse($container->isScopeActive('foo')); $container->enterScope('foo'); $this->assertTrue($container->isScopeActive('foo')); $this->assertFalse($container->isScopeActive('bar')); $this->assertFalse($container->has('a')); $a = new \stdClass(); $container->set('a', $a, 'foo'); $services = $this->getField($container, 'scopedServices'); $this->assertTrue(isset($services['foo']['a'])); $this->assertSame($a, $services['foo']['a']); $this->assertTrue($container->has('a')); $container->enterScope('foo'); $services = $this->getField($container, 'scopedServices'); $this->assertFalse(isset($services['a'])); $this->assertTrue($container->isScopeActive('foo')); $this->assertFalse($container->isScopeActive('bar')); $this->assertFalse($container->has('a')); } public function testLeaveScopeNotActive() { $container = new Container(); $container->addScope(new Scope('foo')); try { $container->leaveScope('foo'); $this->fail('->leaveScope() throws a \LogicException if the scope is not active yet'); } catch (\Exception $e) { $this->assertInstanceOf('\LogicException', $e, '->leaveScope() throws a \LogicException if the scope is not active yet'); $this->assertEquals('The scope "foo" is not active.', $e->getMessage(), '->leaveScope() throws a \LogicException if the scope is not active yet'); } try { $container->leaveScope('bar'); $this->fail('->leaveScope() throws a \LogicException if the scope does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('\LogicException', $e, '->leaveScope() throws a \LogicException if the scope does not exist'); $this->assertEquals('The scope "bar" is not active.', $e->getMessage(), '->leaveScope() throws a \LogicException if the scope does not exist'); } } /** * @expectedException \InvalidArgumentException * @dataProvider getBuiltInScopes */ public function testAddScopeDoesNotAllowBuiltInScopes($scope) { $container = new Container(); $container->addScope(new Scope($scope)); } /** * @expectedException \InvalidArgumentException */ public function testAddScopeDoesNotAllowExistingScope() { $container = new Container(); $container->addScope(new Scope('foo')); $container->addScope(new Scope('foo')); } /** * @expectedException \InvalidArgumentException * @dataProvider getInvalidParentScopes */ public function testAddScopeDoesNotAllowInvalidParentScope($scope) { $c = new Container(); $c->addScope(new Scope('foo', $scope)); } public function testAddScope() { $c = new Container(); $c->addScope(new Scope('foo')); $c->addScope(new Scope('bar', 'foo')); $this->assertSame(array('foo' => 'container', 'bar' => 'foo'), $this->getField($c, 'scopes')); $this->assertSame(array('foo' => array('bar'), 'bar' => array()), $this->getField($c, 'scopeChildren')); } public function testHasScope() { $c = new Container(); $this->assertFalse($c->hasScope('foo')); $c->addScope(new Scope('foo')); $this->assertTrue($c->hasScope('foo')); } public function testIsScopeActive() { $c = new Container(); $this->assertFalse($c->isScopeActive('foo')); $c->addScope(new Scope('foo')); $this->assertFalse($c->isScopeActive('foo')); $c->enterScope('foo'); $this->assertTrue($c->isScopeActive('foo')); $c->leaveScope('foo'); $this->assertFalse($c->isScopeActive('foo')); } public function testGetThrowsException() { $c = new ProjectServiceContainer(); try { $c->get('throw_exception'); $this->fail(); } catch (\Exception $e) { $this->assertEquals('Something went terribly wrong!', $e->getMessage()); } try { $c->get('throw_exception'); $this->fail(); } catch (\Exception $e) { $this->assertEquals('Something went terribly wrong!', $e->getMessage()); } } public function testGetThrowsExceptionOnServiceConfiguration() { $c = new ProjectServiceContainer(); try { $c->get('throws_exception_on_service_configuration'); $this->fail('The container can not contain invalid service!'); } catch (\Exception $e) { $this->assertEquals('Something was terribly wrong while trying to configure the service!', $e->getMessage()); } $this->assertFalse($c->initialized('throws_exception_on_service_configuration')); try { $c->get('throws_exception_on_service_configuration'); $this->fail('The container can not contain invalid service!'); } catch (\Exception $e) { $this->assertEquals('Something was terribly wrong while trying to configure the service!', $e->getMessage()); } $this->assertFalse($c->initialized('throws_exception_on_service_configuration')); } public function getInvalidParentScopes() { return array( array(ContainerInterface::SCOPE_PROTOTYPE), array('bar'), ); } public function getBuiltInScopes() { return array( array(ContainerInterface::SCOPE_CONTAINER), array(ContainerInterface::SCOPE_PROTOTYPE), ); } protected function getField($obj, $field) { $reflection = new \ReflectionProperty($obj, $field); $reflection->setAccessible(true); return $reflection->getValue($obj); } public function testAlias() { $c = new ProjectServiceContainer(); $this->assertTrue($c->has('alias')); $this->assertSame($c->get('alias'), $c->get('bar')); } } class ProjectServiceContainer extends Container { public $__bar, $__foo_bar, $__foo_baz; public function __construct() { parent::__construct(); $this->__bar = new \stdClass(); $this->__foo_bar = new \stdClass(); $this->__foo_baz = new \stdClass(); $this->aliases = array('alias' => 'bar'); } protected function getScopedService() { if (!isset($this->scopedServices['foo'])) { throw new \RuntimeException('Invalid call'); } return $this->services['scoped'] = $this->scopedServices['foo']['scoped'] = new \stdClass(); } protected function getScopedFooService() { if (!isset($this->scopedServices['foo'])) { throw new \RuntimeException('invalid call'); } return $this->services['scoped_foo'] = $this->scopedServices['foo']['scoped_foo'] = new \stdClass(); } protected function getInactiveService() { throw new InactiveScopeException('request', 'request'); } protected function getBarService() { return $this->__bar; } protected function getFooBarService() { return $this->__foo_bar; } protected function getFoo_BazService() { return $this->__foo_baz; } protected function getCircularService() { return $this->get('circular'); } protected function getThrowExceptionService() { throw new \Exception('Something went terribly wrong!'); } protected function getThrowsExceptionOnServiceConfigurationService() { $this->services['throws_exception_on_service_configuration'] = $instance = new \stdClass(); throw new \Exception('Something was terribly wrong while trying to configure the service!'); } } PK!`= ?Component/DependencyInjection/Tests/Extension/ExtensionTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Extension; class ExtensionTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getResolvedEnabledFixtures */ public function testIsConfigEnabledReturnsTheResolvedValue($enabled) { $pb = $this->getMockBuilder('Symfony\Component\DependencyInjection\ParameterBag\ParameterBag') ->setMethods(array('resolveValue')) ->getMock() ; $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder') ->setMethods(array('getParameterBag')) ->getMock() ; $pb->expects($this->once()) ->method('resolveValue') ->with($this->equalTo($enabled)) ->will($this->returnValue($enabled)) ; $container->expects($this->once()) ->method('getParameterBag') ->will($this->returnValue($pb)) ; $extension = $this->getMockBuilder('Symfony\Component\DependencyInjection\Extension\Extension') ->setMethods(array()) ->getMockForAbstractClass() ; $r = new \ReflectionMethod('Symfony\Component\DependencyInjection\Extension\Extension', 'isConfigEnabled'); $r->setAccessible(true); $r->invoke($extension, $container, array('enabled' => $enabled)); } public function getResolvedEnabledFixtures() { return array( array(true), array(false) ); } /** * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @expectedExceptionMessage The config array has no 'enabled' key. */ public function testIsConfigEnabledOnNonEnableableConfig() { $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder') ->getMock() ; $extension = $this->getMockBuilder('Symfony\Component\DependencyInjection\Extension\Extension') ->setMethods(array()) ->getMockForAbstractClass() ; $r = new \ReflectionMethod('Symfony\Component\DependencyInjection\Extension\Extension', 'isConfigEnabled'); $r->setAccessible(true); $r->invoke($extension, $container, array()); } } PK!uu.Component/DependencyInjection/phpunit.xml.distnu[ ./Tests/ ./ ./Resources ./Tests ./vendor PK!J='',Component/BrowserKit/Tests/CookieJarTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\BrowserKit\Tests; use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\BrowserKit\Cookie; use Symfony\Component\BrowserKit\Response; class CookieJarTest extends \PHPUnit_Framework_TestCase { public function testSetGet() { $cookieJar = new CookieJar(); $cookieJar->set($cookie = new Cookie('foo', 'bar')); $this->assertEquals($cookie, $cookieJar->get('foo'), '->set() sets a cookie'); $this->assertNull($cookieJar->get('foobar'), '->get() returns null if the cookie does not exist'); $cookieJar->set($cookie = new Cookie('foo', 'bar', time() - 86400)); $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired'); } public function testExpire() { $cookieJar = new CookieJar(); $cookieJar->set($cookie = new Cookie('foo', 'bar')); $cookieJar->expire('foo'); $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired'); } public function testAll() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar')); $cookieJar->set($cookie2 = new Cookie('bar', 'foo')); $this->assertEquals(array($cookie1, $cookie2), $cookieJar->all(), '->all() returns all cookies in the jar'); } public function testClear() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar')); $cookieJar->set($cookie2 = new Cookie('bar', 'foo')); $cookieJar->clear(); $this->assertEquals(array(), $cookieJar->all(), '->clear() expires all cookies'); } public function testUpdateFromResponse() { $response = new Response('', 200, array('Set-Cookie' => 'foo=foo')); $cookieJar = new CookieJar(); $cookieJar->updateFromResponse($response); $this->assertEquals('foo', $cookieJar->get('foo')->getValue(), '->updateFromResponse() updates cookies from a Response objects'); } public function testUpdateFromSetCookie() { $setCookies = array('foo=foo'); $cookieJar = new CookieJar(); $cookieJar->set(new Cookie('bar', 'bar')); $cookieJar->updateFromSetCookie($setCookies); $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $cookieJar->get('foo')); $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $cookieJar->get('bar')); $this->assertEquals('foo', $cookieJar->get('foo')->getValue(), '->updateFromSetCookie() updates cookies from a Set-Cookie header'); $this->assertEquals('bar', $cookieJar->get('bar')->getValue(), '->updateFromSetCookie() keeps existing cookies'); } public function testUpdateFromEmptySetCookie() { $cookieJar = new CookieJar(); $cookieJar->updateFromSetCookie(array('')); $this->assertEquals(array(), $cookieJar->all()); } public function testUpdateFromSetCookieWithMultipleCookies() { $timestamp = time() + 3600; $date = gmdate('D, d M Y H:i:s \G\M\T', $timestamp); $setCookies = array(sprintf('foo=foo; expires=%s; domain=.symfony.com; path=/, bar=bar; domain=.blog.symfony.com, PHPSESSID=id; expires=%s', $date, $date)); $cookieJar = new CookieJar(); $cookieJar->updateFromSetCookie($setCookies); $fooCookie = $cookieJar->get('foo', '/', '.symfony.com'); $barCookie = $cookieJar->get('bar', '/', '.blog.symfony.com'); $phpCookie = $cookieJar->get('PHPSESSID'); $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $fooCookie); $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $barCookie); $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $phpCookie); $this->assertEquals('foo', $fooCookie->getValue()); $this->assertEquals('bar', $barCookie->getValue()); $this->assertEquals('id', $phpCookie->getValue()); $this->assertEquals($timestamp, $fooCookie->getExpiresTime()); $this->assertNull($barCookie->getExpiresTime()); $this->assertEquals($timestamp, $phpCookie->getExpiresTime()); } /** * @dataProvider provideAllValuesValues */ public function testAllValues($uri, $values) { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo_nothing', 'foo')); $cookieJar->set($cookie2 = new Cookie('foo_expired', 'foo', time() - 86400)); $cookieJar->set($cookie3 = new Cookie('foo_path', 'foo', null, '/foo')); $cookieJar->set($cookie4 = new Cookie('foo_domain', 'foo', null, '/', '.example.com')); $cookieJar->set($cookie4 = new Cookie('foo_strict_domain', 'foo', null, '/', '.www4.example.com')); $cookieJar->set($cookie5 = new Cookie('foo_secure', 'foo', null, '/', '', true)); $this->assertEquals($values, array_keys($cookieJar->allValues($uri)), '->allValues() returns the cookie for a given URI'); } public function provideAllValuesValues() { return array( array('http://www.example.com', array('foo_nothing', 'foo_domain')), array('http://www.example.com/', array('foo_nothing', 'foo_domain')), array('http://foo.example.com/', array('foo_nothing', 'foo_domain')), array('http://foo.example1.com/', array('foo_nothing')), array('https://foo.example.com/', array('foo_nothing', 'foo_secure', 'foo_domain')), array('http://www.example.com/foo/bar', array('foo_nothing', 'foo_path', 'foo_domain')), array('http://www4.example.com/', array('foo_nothing', 'foo_domain', 'foo_strict_domain')), ); } public function testEncodedValues() { $cookieJar = new CookieJar(); $cookieJar->set($cookie = new Cookie('foo', 'bar%3Dbaz', null, '/', '', false, true, true)); $this->assertEquals(array('foo' => 'bar=baz'), $cookieJar->allValues('/')); $this->assertEquals(array('foo' => 'bar%3Dbaz'), $cookieJar->allRawValues('/')); } public function testCookieExpireWithSameNameButDifferentPaths() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/foo')); $cookieJar->set($cookie2 = new Cookie('foo', 'bar2', null, '/bar')); $cookieJar->expire('foo', '/foo'); $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired'); $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/'))); $this->assertEquals(array(), $cookieJar->allValues('http://example.com/foo')); $this->assertEquals(array('foo' => 'bar2'), $cookieJar->allValues('http://example.com/bar')); } public function testCookieExpireWithNullPaths() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/')); $cookieJar->expire('foo', null); $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired'); $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/'))); } public function testCookieWithSameNameButDifferentPaths() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/foo')); $cookieJar->set($cookie2 = new Cookie('foo', 'bar2', null, '/bar')); $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/'))); $this->assertEquals(array('foo' => 'bar1'), $cookieJar->allValues('http://example.com/foo')); $this->assertEquals(array('foo' => 'bar2'), $cookieJar->allValues('http://example.com/bar')); } public function testCookieWithSameNameButDifferentDomains() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/', 'foo.example.com')); $cookieJar->set($cookie2 = new Cookie('foo', 'bar2', null, '/', 'bar.example.com')); $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/'))); $this->assertEquals(array('foo' => 'bar1'), $cookieJar->allValues('http://foo.example.com/')); $this->assertEquals(array('foo' => 'bar2'), $cookieJar->allValues('http://bar.example.com/')); } public function testCookieGetWithSubdomain() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar', null, '/', '.example.com')); $cookieJar->set($cookie2 = new Cookie('foo1', 'bar', null, '/', 'test.example.com')); $this->assertEquals($cookie1, $cookieJar->get('foo','/','foo.example.com')); $this->assertEquals($cookie1, $cookieJar->get('foo','/','example.com')); $this->assertEquals($cookie2, $cookieJar->get('foo1','/','test.example.com')); } public function testCookieGetWithSubdirectory() { $cookieJar = new CookieJar(); $cookieJar->set($cookie1 = new Cookie('foo', 'bar', null, '/test', '.example.com')); $cookieJar->set($cookie2 = new Cookie('foo1', 'bar1', null, '/', '.example.com')); $this->assertNull($cookieJar->get('foo','/','.example.com')); $this->assertNull($cookieJar->get('foo','/bar','.example.com')); $this->assertEquals($cookie1, $cookieJar->get('foo','/test','example.com')); $this->assertEquals($cookie2, $cookieJar->get('foo1','/','example.com')); $this->assertEquals($cookie2, $cookieJar->get('foo1','/bar','example.com')); } public function testCookieWithWildcardDomain() { $cookieJar = new CookieJar(); $cookieJar->set(new Cookie('foo', 'bar', null, '/', '.example.com')); $this->assertEquals(array('foo' => 'bar'), $cookieJar->allValues('http://www.example.com')); $this->assertEmpty($cookieJar->allValues('http://wwwexample.com')); } } PK!N4Zcc)Component/BrowserKit/Tests/ClientTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\BrowserKit\Tests; use Symfony\Component\BrowserKit\Client; use Symfony\Component\BrowserKit\History; use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\BrowserKit\Request; use Symfony\Component\BrowserKit\Response; class SpecialResponse extends Response { } class TestClient extends Client { protected $nextResponse = null; protected $nextScript = null; public function setNextResponse(Response $response) { $this->nextResponse = $response; } public function setNextScript($script) { $this->nextScript = $script; } protected function doRequest($request) { if (null === $this->nextResponse) { return new Response(); } $response = $this->nextResponse; $this->nextResponse = null; return $response; } protected function filterResponse($response) { if ($response instanceof SpecialResponse) { return new Response($response->getContent(), $response->getStatus(), $response->getHeaders()); } return $response; } protected function getScript($request) { $r = new \ReflectionClass('Symfony\Component\BrowserKit\Response'); $path = $r->getFileName(); return <<nextScript); EOF; } } class ClientTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\BrowserKit\Client::getHistory */ public function testGetHistory() { $client = new TestClient(array(), $history = new History()); $this->assertSame($history, $client->getHistory(), '->getHistory() returns the History'); } /** * @covers Symfony\Component\BrowserKit\Client::getCookieJar */ public function testGetCookieJar() { $client = new TestClient(array(), null, $cookieJar = new CookieJar()); $this->assertSame($cookieJar, $client->getCookieJar(), '->getCookieJar() returns the CookieJar'); } /** * @covers Symfony\Component\BrowserKit\Client::getRequest */ public function testGetRequest() { $client = new TestClient(); $client->request('GET', 'http://example.com/'); $this->assertEquals('http://example.com/', $client->getRequest()->getUri(), '->getCrawler() returns the Request of the last request'); } public function testGetResponse() { $client = new TestClient(); $client->setNextResponse(new Response('foo')); $client->request('GET', 'http://example.com/'); $this->assertEquals('foo', $client->getResponse()->getContent(), '->getCrawler() returns the Response of the last request'); $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getResponse(), '->getCrawler() returns the Response of the last request'); } public function testGetInternalResponse() { $client = new TestClient(); $client->setNextResponse(new SpecialResponse('foo')); $client->request('GET', 'http://example.com/'); $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getInternalResponse()); $this->assertNotInstanceOf('Symfony\Component\BrowserKit\Tests\SpecialResponse', $client->getInternalResponse()); $this->assertInstanceOf('Symfony\Component\BrowserKit\Tests\SpecialResponse', $client->getResponse()); } public function testGetContent() { $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}'; $client = new TestClient(); $client->request('POST', 'http://example.com/jsonrpc', array(), array(), array(), $json); $this->assertEquals($json, $client->getRequest()->getContent()); } /** * @covers Symfony\Component\BrowserKit\Client::getCrawler */ public function testGetCrawler() { $client = new TestClient(); $client->setNextResponse(new Response('foo')); $crawler = $client->request('GET', 'http://example.com/'); $this->assertSame($crawler, $client->getCrawler(), '->getCrawler() returns the Crawler of the last request'); } public function testRequestHttpHeaders() { $client = new TestClient(); $client->request('GET', '/'); $headers = $client->getRequest()->getServer(); $this->assertEquals('localhost', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header'); $client = new TestClient(); $client->request('GET', 'http://www.example.com'); $headers = $client->getRequest()->getServer(); $this->assertEquals('www.example.com', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header'); $client->request('GET', 'https://www.example.com'); $headers = $client->getRequest()->getServer(); $this->assertTrue($headers['HTTPS'], '->request() sets the HTTPS header'); $client = new TestClient(); $client->request('GET', 'http://www.example.com:8080'); $headers = $client->getRequest()->getServer(); $this->assertEquals('www.example.com:8080', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header with port'); } public function testRequestURIConversion() { $client = new TestClient(); $client->request('GET', '/foo'); $this->assertEquals('http://localhost/foo', $client->getRequest()->getUri(), '->request() converts the URI to an absolute one'); $client = new TestClient(); $client->request('GET', 'http://www.example.com'); $this->assertEquals('http://www.example.com', $client->getRequest()->getUri(), '->request() does not change absolute URIs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/'); $client->request('GET', '/foo'); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo'); $client->request('GET', '#'); $this->assertEquals('http://www.example.com/foo#', $client->getRequest()->getUri(), '->request() uses the previous request for #'); $client->request('GET', '#'); $this->assertEquals('http://www.example.com/foo#', $client->getRequest()->getUri(), '->request() uses the previous request for #'); $client->request('GET', '#foo'); $this->assertEquals('http://www.example.com/foo#foo', $client->getRequest()->getUri(), '->request() uses the previous request for #'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/'); $client->request('GET', 'bar'); $this->assertEquals('http://www.example.com/foo/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'bar'); $this->assertEquals('http://www.example.com/foo/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); } public function testRequestReferer() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'bar'); $server = $client->getRequest()->getServer(); $this->assertEquals('http://www.example.com/foo/foobar', $server['HTTP_REFERER'], '->request() sets the referer'); } public function testRequestHistory() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'bar'); $this->assertEquals('http://www.example.com/foo/bar', $client->getHistory()->current()->getUri(), '->request() updates the History'); $this->assertEquals('http://www.example.com/foo/foobar', $client->getHistory()->back()->getUri(), '->request() updates the History'); } public function testRequestCookies() { $client = new TestClient(); $client->setNextResponse(new Response('foo', 200, array('Set-Cookie' => 'foo=bar'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals(array('foo' => 'bar'), $client->getCookieJar()->allValues('http://www.example.com/foo/foobar'), '->request() updates the CookieJar'); $client->request('GET', 'bar'); $this->assertEquals(array('foo' => 'bar'), $client->getCookieJar()->allValues('http://www.example.com/foo/foobar'), '->request() updates the CookieJar'); } public function testRequestSecureCookies() { $client = new TestClient(); $client->setNextResponse(new Response('foo', 200, array('Set-Cookie' => 'foo=bar; path=/; secure'))); $client->request('GET', 'https://www.example.com/foo/foobar'); $this->assertTrue($client->getCookieJar()->get('foo', '/', 'www.example.com')->isSecure()); } public function testClick() { $client = new TestClient(); $client->setNextResponse(new Response('foo')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $client->click($crawler->filter('a')->link()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->click() clicks on links'); } public function testClickForm() { $client = new TestClient(); $client->setNextResponse(new Response('
')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $client->click($crawler->filter('input')->form()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->click() Form submit forms'); } public function testSubmit() { $client = new TestClient(); $client->setNextResponse(new Response('
')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $client->submit($crawler->filter('input')->form()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submit() submit forms'); } public function testSubmitPreserveAuth() { $client = new TestClient(array('PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'bar')); $client->setNextResponse(new Response('
')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $server = $client->getRequest()->getServer(); $this->assertArrayHasKey('PHP_AUTH_USER', $server); $this->assertEquals('foo', $server['PHP_AUTH_USER']); $this->assertArrayHasKey('PHP_AUTH_PW', $server); $this->assertEquals('bar', $server['PHP_AUTH_PW']); $client->submit($crawler->filter('input')->form()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submit() submit forms'); $server = $client->getRequest()->getServer(); $this->assertArrayHasKey('PHP_AUTH_USER', $server); $this->assertEquals('foo', $server['PHP_AUTH_USER']); $this->assertArrayHasKey('PHP_AUTH_PW', $server); $this->assertEquals('bar', $server['PHP_AUTH_PW']); } public function testFollowRedirect() { $client = new TestClient(); $client->followRedirects(false); $client->request('GET', 'http://www.example.com/foo/foobar'); try { $client->followRedirect(); $this->fail('->followRedirect() throws a \LogicException if the request was not redirected'); } catch (\Exception $e) { $this->assertInstanceof('LogicException', $e, '->followRedirect() throws a \LogicException if the request was not redirected'); } $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->followRedirect(); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() automatically follows redirects if followRedirects is true'); $client = new TestClient(); $client->setNextResponse(new Response('', 201, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->followRedirect() does not follow redirect if HTTP Code is not 30x'); $client = new TestClient(); $client->setNextResponse(new Response('', 201, array('Location' => 'http://www.example.com/redirected'))); $client->followRedirects(false); $client->request('GET', 'http://www.example.com/foo/foobar'); try { $client->followRedirect(); $this->fail('->followRedirect() throws a \LogicException if the request did not respond with 30x HTTP Code'); } catch (\Exception $e) { $this->assertInstanceof('LogicException', $e, '->followRedirect() throws a \LogicException if the request did not respond with 30x HTTP Code'); } } public function testFollowRedirectWithMaxRedirects() { $client = new TestClient(); $client->setMaxRedirects(1); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected2'))); try { $client->followRedirect(); $this->fail('->followRedirect() throws a \LogicException if the request was redirected and limit of redirections was reached'); } catch (\Exception $e) { $this->assertInstanceof('LogicException', $e, '->followRedirect() throws a \LogicException if the request was redirected and limit of redirections was reached'); } $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client->setNextResponse(new Response('', 302, array('Location' => '/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows relative URLs'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => '//www.example.org/'))); $client->request('GET', 'https://www.example.com/'); $this->assertEquals('https://www.example.org/', $client->getRequest()->getUri(), '->followRedirect() follows protocol-relative URLs'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('POST', 'http://www.example.com/foo/foobar', array('name' => 'bar')); $this->assertEquals('get', $client->getRequest()->getMethod(), '->followRedirect() uses a get for 302'); $this->assertEquals(array(), $client->getRequest()->getParameters(), '->followRedirect() does not submit parameters when changing the method'); } public function testFollowRedirectWithCookies() { $client = new TestClient(); $client->followRedirects(false); $client->setNextResponse(new Response('', 302, array( 'Location' => 'http://www.example.com/redirected', 'Set-Cookie' => 'foo=bar', ))); $client->request('GET', 'http://www.example.com/'); $this->assertEquals(array(), $client->getRequest()->getCookies()); $client->followRedirect(); $this->assertEquals(array('foo' => 'bar'), $client->getRequest()->getCookies()); } public function testFollowRedirectWithHeaders() { $headers = array( 'HTTP_HOST' => 'www.example.com', 'HTTP_USER_AGENT' => 'Symfony2 BrowserKit', 'CONTENT_TYPE' => 'application/vnd.custom+xml', 'HTTPS' => false, ); $client = new TestClient(); $client->followRedirects(false); $client->setNextResponse(new Response('', 302, array( 'Location' => 'http://www.example.com/redirected', ))); $client->request('GET', 'http://www.example.com/', array(), array(), array( 'CONTENT_TYPE' => 'application/vnd.custom+xml', )); $this->assertEquals($headers, $client->getRequest()->getServer()); $client->followRedirect(); $headers['HTTP_REFERER'] = 'http://www.example.com/'; $this->assertEquals($headers, $client->getRequest()->getServer()); } public function testFollowRedirectWithPort() { $headers = array( 'HTTP_HOST' => 'www.example.com:8080', 'HTTP_USER_AGENT' => 'Symfony2 BrowserKit', 'HTTPS' => false ); $client = new TestClient(); $client->followRedirects(false); $client->setNextResponse(new Response('', 302, array( 'Location' => 'http://www.example.com:8080/redirected', ))); $client->request('GET', 'http://www.example.com:8080/'); $this->assertEquals($headers, $client->getRequest()->getServer()); } public function testBack() { $client = new TestClient(); $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client->request('GET', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content); $client->request('GET', 'http://www.example.com/foo'); $client->back(); $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->back() goes back in the history'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->back() keeps parameters'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->back() keeps files'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->back() keeps $_SERVER'); $this->assertEquals($content, $client->getRequest()->getContent(), '->back() keeps content'); } public function testForward() { $client = new TestClient(); $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'http://www.example.com/foo', $parameters, $files, $server, $content); $client->back(); $client->forward(); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->forward() goes forward in the history'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->forward() keeps parameters'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->forward() keeps files'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->forward() keeps $_SERVER'); $this->assertEquals($content, $client->getRequest()->getContent(), '->forward() keeps content'); } public function testReload() { $client = new TestClient(); $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client->request('GET', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content); $client->reload(); $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->reload() reloads the current page'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->reload() keeps parameters'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->reload() keeps files'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->reload() keeps $_SERVER'); $this->assertEquals($content, $client->getRequest()->getContent(), '->reload() keeps content'); } public function testRestart() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->restart(); $this->assertTrue($client->getHistory()->isEmpty(), '->restart() clears the history'); $this->assertEquals(array(), $client->getCookieJar()->all(), '->restart() clears the cookies'); } public function testInsulatedRequests() { $client = new TestClient(); $client->insulate(); $client->setNextScript("new Symfony\Component\BrowserKit\Response('foobar')"); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('foobar', $client->getResponse()->getContent(), '->insulate() process the request in a forked process'); $client->setNextScript("new Symfony\Component\BrowserKit\Response('foobar)"); try { $client->request('GET', 'http://www.example.com/foo/foobar'); $this->fail('->request() throws a \RuntimeException if the script has an error'); } catch (\Exception $e) { $this->assertInstanceof('RuntimeException', $e, '->request() throws a \RuntimeException if the script has an error'); } } public function testGetServerParameter() { $client = new TestClient(); $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $this->assertEquals('testvalue', $client->getServerParameter('testkey', 'testvalue')); } public function testSetServerParameter() { $client = new TestClient(); $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $client->setServerParameter('HTTP_HOST', 'testhost'); $this->assertEquals('testhost', $client->getServerParameter('HTTP_HOST')); $client->setServerParameter('HTTP_USER_AGENT', 'testua'); $this->assertEquals('testua', $client->getServerParameter('HTTP_USER_AGENT')); } public function testSetServerParameterInRequest() { $client = new TestClient(); $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $client->request('GET', 'https://www.example.com/https/www.example.com', array(), array(), array( 'HTTP_HOST' => 'testhost', 'HTTP_USER_AGENT' => 'testua', 'HTTPS' => false, 'NEW_SERVER_KEY' => 'new-server-key-value' )); $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $this->assertEquals('http://testhost/https/www.example.com', $client->getRequest()->getUri()); $server = $client->getRequest()->getServer(); $this->assertArrayHasKey('HTTP_USER_AGENT', $server); $this->assertEquals('testua', $server['HTTP_USER_AGENT']); $this->assertArrayHasKey('HTTP_HOST', $server); $this->assertEquals('testhost', $server['HTTP_HOST']); $this->assertArrayHasKey('NEW_SERVER_KEY', $server); $this->assertEquals('new-server-key-value', $server['NEW_SERVER_KEY']); $this->assertArrayHasKey('HTTPS', $server); $this->assertFalse($server['HTTPS']); } } PK!ɹ(RR)Component/BrowserKit/Tests/CookieTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\BrowserKit\Tests; use Symfony\Component\BrowserKit\Cookie; class CookieTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getTestsForToFromString */ public function testToFromString($cookie, $url = null) { $this->assertEquals($cookie, (string) Cookie::fromString($cookie, $url)); } public function getTestsForToFromString() { return array( array('foo=bar; path=/'), array('foo=bar; path=/foo'), array('foo=bar; domain=google.com; path=/'), array('foo=bar; domain=example.com; path=/; secure', 'https://example.com/'), array('foo=bar; path=/; httponly'), array('foo=bar; domain=google.com; path=/foo; secure; httponly', 'https://google.com/'), array('foo=bar=baz; path=/'), array('foo=bar%3Dbaz; path=/'), ); } public function testFromStringIgnoreSecureFlag() { $this->assertFalse(Cookie::fromString('foo=bar; secure')->isSecure()); $this->assertFalse(Cookie::fromString('foo=bar; secure', 'http://example.com/')->isSecure()); } /** * @dataProvider getExpireCookieStrings */ public function testFromStringAcceptsSeveralExpiresDateFormats($cookie) { $this->assertEquals(1596185377, Cookie::fromString($cookie)->getExpiresTime()); } public function getExpireCookieStrings() { return array( array('foo=bar; expires=Fri, 31-Jul-2020 08:49:37 GMT'), array('foo=bar; expires=Fri, 31 Jul 2020 08:49:37 GMT'), array('foo=bar; expires=Fri, 31-07-2020 08:49:37 GMT'), array('foo=bar; expires=Fri, 31-07-20 08:49:37 GMT'), array('foo=bar; expires=Friday, 31-Jul-20 08:49:37 GMT'), array('foo=bar; expires=Fri Jul 31 08:49:37 2020'), array('foo=bar; expires=\'Fri Jul 31 08:49:37 2020\''), array('foo=bar; expires=Friday July 31st 2020, 08:49:37 GMT'), ); } public function testFromStringWithCapitalization() { $this->assertEquals('Foo=Bar; path=/', (string) Cookie::fromString('Foo=Bar')); $this->assertEquals('foo=bar; expires=Fri, 31 Dec 2010 23:59:59 GMT; path=/', (string) Cookie::fromString('foo=bar; Expires=Fri, 31 Dec 2010 23:59:59 GMT')); $this->assertEquals('foo=bar; domain=www.example.org; path=/; httponly', (string) Cookie::fromString('foo=bar; DOMAIN=www.example.org; HttpOnly')); } public function testFromStringWithUrl() { $this->assertEquals('foo=bar; domain=www.example.com; path=/', (string) Cookie::FromString('foo=bar', 'http://www.example.com/')); $this->assertEquals('foo=bar; domain=www.example.com; path=/foo', (string) Cookie::FromString('foo=bar', 'http://www.example.com/foo/bar')); $this->assertEquals('foo=bar; domain=www.example.com; path=/', (string) Cookie::FromString('foo=bar; path=/', 'http://www.example.com/foo/bar')); $this->assertEquals('foo=bar; domain=www.myotherexample.com; path=/', (string) Cookie::FromString('foo=bar; domain=www.myotherexample.com', 'http://www.example.com/')); } public function testFromStringThrowsAnExceptionIfCookieIsNotValid() { $this->setExpectedException('InvalidArgumentException'); Cookie::FromString('foo'); } public function testFromStringThrowsAnExceptionIfCookieDateIsNotValid() { $this->setExpectedException('InvalidArgumentException'); Cookie::FromString('foo=bar; expires=Flursday July 31st 2020, 08:49:37 GMT'); } public function testFromStringThrowsAnExceptionIfUrlIsNotValid() { $this->setExpectedException('InvalidArgumentException'); Cookie::FromString('foo=bar', 'foobar'); } public function testGetName() { $cookie = new Cookie('foo', 'bar'); $this->assertEquals('foo', $cookie->getName(), '->getName() returns the cookie name'); } public function testGetValue() { $cookie = new Cookie('foo', 'bar'); $this->assertEquals('bar', $cookie->getValue(), '->getValue() returns the cookie value'); $cookie = new Cookie('foo', 'bar%3Dbaz', null, '/', '', false, true, true); // raw value $this->assertEquals('bar=baz', $cookie->getValue(), '->getValue() returns the urldecoded cookie value'); } public function testGetRawValue() { $cookie = new Cookie('foo', 'bar=baz'); // decoded value $this->assertEquals('bar%3Dbaz', $cookie->getRawValue(), '->getRawValue() returns the urlencoded cookie value'); $cookie = new Cookie('foo', 'bar%3Dbaz', null, '/', '', false, true, true); // raw value $this->assertEquals('bar%3Dbaz', $cookie->getRawValue(), '->getRawValue() returns the non-urldecoded cookie value'); } public function testGetPath() { $cookie = new Cookie('foo', 'bar', 0); $this->assertEquals('/', $cookie->getPath(), '->getPath() returns / is no path is defined'); $cookie = new Cookie('foo', 'bar', 0, '/foo'); $this->assertEquals('/foo', $cookie->getPath(), '->getPath() returns the cookie path'); } public function testGetDomain() { $cookie = new Cookie('foo', 'bar', 0, '/', 'foo.com'); $this->assertEquals('foo.com', $cookie->getDomain(), '->getDomain() returns the cookie domain'); } public function testIsSecure() { $cookie = new Cookie('foo', 'bar'); $this->assertFalse($cookie->isSecure(), '->isSecure() returns false if not defined'); $cookie = new Cookie('foo', 'bar', 0, '/', 'foo.com', true); $this->assertTrue($cookie->isSecure(), '->isSecure() returns the cookie secure flag'); } public function testIsHttponly() { $cookie = new Cookie('foo', 'bar'); $this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns false if not defined'); $cookie = new Cookie('foo', 'bar', 0, '/', 'foo.com', false, true); $this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns the cookie httponly flag'); } public function testGetExpiresTime() { $cookie = new Cookie('foo', 'bar'); $this->assertNull($cookie->getExpiresTime(), '->getExpiresTime() returns the expires time'); $cookie = new Cookie('foo', 'bar', $time = time() - 86400); $this->assertEquals($time, $cookie->getExpiresTime(), '->getExpiresTime() returns the expires time'); } public function testIsExpired() { $cookie = new Cookie('foo', 'bar'); $this->assertFalse($cookie->isExpired(), '->isExpired() returns false when the cookie never expires (null as expires time)'); $cookie = new Cookie('foo', 'bar', time() - 86400); $this->assertTrue($cookie->isExpired(), '->isExpired() returns true when the cookie is expired'); $cookie = new Cookie('foo', 'bar', 0); $this->assertFalse($cookie->isExpired()); } } PK!K*Component/BrowserKit/Tests/HistoryTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\BrowserKit\Tests; use Symfony\Component\BrowserKit\History; use Symfony\Component\BrowserKit\Request; class HistoryTest extends \PHPUnit_Framework_TestCase { public function testAdd() { $history = new History(); $history->add(new Request('http://www.example1.com/', 'get')); $this->assertSame('http://www.example1.com/', $history->current()->getUri(), '->add() adds a request to the history'); $history->add(new Request('http://www.example2.com/', 'get')); $this->assertSame('http://www.example2.com/', $history->current()->getUri(), '->add() adds a request to the history'); $history->add(new Request('http://www.example3.com/', 'get')); $history->back(); $history->add(new Request('http://www.example4.com/', 'get')); $this->assertSame('http://www.example4.com/', $history->current()->getUri(), '->add() adds a request to the history'); $history->back(); $this->assertSame('http://www.example2.com/', $history->current()->getUri(), '->add() adds a request to the history'); } public function testClearIsEmpty() { $history = new History(); $history->add(new Request('http://www.example.com/', 'get')); $this->assertFalse($history->isEmpty(), '->isEmpty() returns false if the history is not empty'); $history->clear(); $this->assertTrue($history->isEmpty(), '->isEmpty() true if the history is empty'); } public function testCurrent() { $history = new History(); try { $history->current(); $this->fail('->current() throws a \LogicException if the history is empty'); } catch (\Exception $e) { $this->assertInstanceof('LogicException', $e, '->current() throws a \LogicException if the history is empty'); } $history->add(new Request('http://www.example.com/', 'get')); $this->assertSame('http://www.example.com/', $history->current()->getUri(), '->current() returns the current request in the history'); } public function testBack() { $history = new History(); $history->add(new Request('http://www.example.com/', 'get')); try { $history->back(); $this->fail('->back() throws a \LogicException if the history is already on the first page'); } catch (\Exception $e) { $this->assertInstanceof('LogicException', $e, '->current() throws a \LogicException if the history is already on the first page'); } $history->add(new Request('http://www.example1.com/', 'get')); $history->back(); $this->assertSame('http://www.example.com/', $history->current()->getUri(), '->back() returns the previous request in the history'); } public function testForward() { $history = new History(); $history->add(new Request('http://www.example.com/', 'get')); $history->add(new Request('http://www.example1.com/', 'get')); try { $history->forward(); $this->fail('->forward() throws a \LogicException if the history is already on the last page'); } catch (\Exception $e) { $this->assertInstanceof('LogicException', $e, '->forward() throws a \LogicException if the history is already on the last page'); } $history->back(); $history->forward(); $this->assertSame('http://www.example1.com/', $history->current()->getUri(), '->forward() returns the next request in the history'); } } PK!{2w  +Component/BrowserKit/Tests/ResponseTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\BrowserKit\Tests; use Symfony\Component\BrowserKit\Response; class ResponseTest extends \PHPUnit_Framework_TestCase { public function testGetUri() { $response = new Response('foo'); $this->assertEquals('foo', $response->getContent(), '->getContent() returns the content of the response'); } public function testGetStatus() { $response = new Response('foo', 304); $this->assertEquals('304', $response->getStatus(), '->getStatus() returns the status of the response'); } public function testGetHeaders() { $response = new Response('foo', 200, array('foo' => 'bar')); $this->assertEquals(array('foo' => 'bar'), $response->getHeaders(), '->getHeaders() returns the headers of the response'); } public function testGetHeader() { $response = new Response('foo', 200, array( 'Content-Type' => 'text/html', 'Set-Cookie' => array('foo=bar', 'bar=foo'), )); $this->assertEquals('text/html', $response->getHeader('Content-Type'), '->getHeader() returns a header of the response'); $this->assertEquals('text/html', $response->getHeader('content-type'), '->getHeader() returns a header of the response'); $this->assertEquals('text/html', $response->getHeader('content_type'), '->getHeader() returns a header of the response'); $this->assertEquals('foo=bar', $response->getHeader('Set-Cookie'), '->getHeader() returns the first header value'); $this->assertEquals(array('foo=bar', 'bar=foo'), $response->getHeader('Set-Cookie', false), '->getHeader() returns all header values if first is false'); $this->assertNull($response->getHeader('foo'), '->getHeader() returns null if the header is not defined'); $this->assertEquals(array(), $response->getHeader('foo', false), '->getHeader() returns an empty array if the header is not defined and first is set to false'); } public function testMagicToString() { $response = new Response('foo', 304, array('foo' => 'bar')); $this->assertEquals("foo: bar\n\nfoo", $response->__toString(), '->__toString() returns the headers and the content as a string'); } public function testMagicToStringWithMultipleSetCookieHeader() { $headers = array( 'content-type' => 'text/html; charset=utf-8', 'set-cookie' => array('foo=bar', 'bar=foo') ); $expected = 'content-type: text/html; charset=utf-8'."\n"; $expected.= 'set-cookie: foo=bar'."\n"; $expected.= 'set-cookie: bar=foo'."\n\n"; $expected.= 'foo'; $response = new Response('foo', 304, $headers); $this->assertEquals($expected, $response->__toString(), '->__toString() returns the headers and the content as a string'); } } PK!|*Component/BrowserKit/Tests/RequestTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\BrowserKit\Tests; use Symfony\Component\BrowserKit\Request; class RequestTest extends \PHPUnit_Framework_TestCase { public function testGetUri() { $request = new Request('http://www.example.com/', 'get'); $this->assertEquals('http://www.example.com/', $request->getUri(), '->getUri() returns the URI of the request'); } public function testGetMethod() { $request = new Request('http://www.example.com/', 'get'); $this->assertEquals('get', $request->getMethod(), '->getMethod() returns the method of the request'); } public function testGetParameters() { $request = new Request('http://www.example.com/', 'get', array('foo' => 'bar')); $this->assertEquals(array('foo' => 'bar'), $request->getParameters(), '->getParameters() returns the parameters of the request'); } public function testGetFiles() { $request = new Request('http://www.example.com/', 'get', array(), array('foo' => 'bar')); $this->assertEquals(array('foo' => 'bar'), $request->getFiles(), '->getFiles() returns the uploaded files of the request'); } public function testGetCookies() { $request = new Request('http://www.example.com/', 'get', array(), array(), array('foo' => 'bar')); $this->assertEquals(array('foo' => 'bar'), $request->getCookies(), '->getCookies() returns the cookies of the request'); } public function testGetServer() { $request = new Request('http://www.example.com/', 'get', array(), array(), array(), array('foo' => 'bar')); $this->assertEquals(array('foo' => 'bar'), $request->getServer(), '->getServer() returns the server parameters of the request'); } } PK!p6ll%Component/BrowserKit/phpunit.xml.distnu[ ./Tests/ ./ ./Resources ./Tests ./vendor PK![b1Bridge/Twig/CHANGELOG.mdnu[CHANGELOG ========= 2.4.0 ----- * added stopwatch tag to time templates with the WebProfilerBundle 2.3.0 ----- * added helpers form(), form_start() and form_end() * deprecated form_enctype() in favor of form_start() 2.2.0 ----- * added a `controller` function to help generating controller references * added a `render_esi` and a `render_hinclude` function * [BC BREAK] restricted the `render` tag to only accept URIs or ControllerReference instances (the signature changed) * added a `render` function to render a request * The `app` global variable is now injected even when using the twig service directly. * Added an optional parameter to the `path` and `url` function which allows to generate relative paths (e.g. "../parent-file") and scheme-relative URLs (e.g. "//example.com/dir/file"). 2.1.0 ----- * added global variables access in a form theme * added TwigEngine * added TwigExtractor * added a csrf_token function * added a way to specify a default domain for a Twig template (via the 'trans_default_domain' tag) PK!VBridge/Twig/composer.jsonnu[{ "name": "symfony/twig-bridge", "type": "symfony-bridge", "description": "Symfony Twig Bridge", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3", "symfony/security-csrf": "~2.4", "twig/twig": "~1.12" }, "require-dev": { "symfony/form": "~2.2", "symfony/http-kernel": "~2.2", "symfony/routing": "~2.2", "symfony/templating": "~2.1", "symfony/translation": "~2.2", "symfony/yaml": "~2.0", "symfony/security": "~2.4", "symfony/stopwatch": "~2.2", "symfony/expression-language": "~2.4" }, "suggest": { "symfony/form": "For using the FormExtension", "symfony/http-kernel": "For using the HttpKernelExtension", "symfony/routing": "For using the RoutingExtension", "symfony/templating": "For using the TwigEngine", "symfony/translation": "For using the TranslationExtension", "symfony/yaml": "For using the YamlExtension", "symfony/security": "For using the SecurityExtension", "symfony/stopwatch": "For using the StopwatchExtension", "symfony/expression-language": "For using the ExpressionExtension" }, "autoload": { "psr-0": { "Symfony\\Bridge\\Twig\\": "" } }, "target-dir": "Symfony/Bridge/Twig", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!b33Bridge/Twig/README.mdnu[Twig Bridge =========== Provides integration for [Twig](http://twig.sensiolabs.org/) with various Symfony2 components. Resources --------- If you want to run the unit tests, install dev dependencies before running PHPUnit: $ cd path/to/Symfony/Bridge/Twig/ $ composer.phar install $ phpunit PK!E))Bridge/Twig/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!g/Component/Process/CHANGELOG.mdnu[CHANGELOG ========= 2.4.0 ----- * added the ability to define an idle timeout 2.3.0 ----- * added ProcessUtils::escapeArgument() to fix the bug in escapeshellarg() function on Windows * added Process::signal() * added Process::getPid() * added support for a TTY mode 2.2.0 ----- * added ProcessBuilder::setArguments() to reset the arguments on a builder * added a way to retrieve the standard and error output incrementally * added Process:restart() 2.1.0 ----- * added support for non-blocking processes (start(), wait(), isRunning(), stop()) * enhanced Windows compatibility * added Process::getExitCodeText() that returns a string representation for the exit code returned by the process * added ProcessBuilder PK!dBComponent/Process/composer.jsonnu[{ "name": "symfony/process", "type": "library", "description": "Symfony Process Component", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3" }, "autoload": { "psr-0": { "Symfony\\Component\\Process\\": "" } }, "target-dir": "Symfony/Component/Process", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!oSJJComponent/Process/README.mdnu[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 --------- You can run the unit tests with the following command: $ cd path/to/Symfony/Component/XXX/ $ composer.phar install $ phpunit PK!E))Component/Process/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!O9 !Component/HttpKernel/CHANGELOG.mdnu[CHANGELOG ========= 2.4.0 ----- * added event listeners for the session * added the KernelEvents::FINISH_REQUEST event 2.3.0 ----- * [BC BREAK] renamed `Symfony\Component\HttpKernel\EventListener\DeprecationLoggerListener` to `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener` and changed its constructor * deprecated `Symfony\Component\HttpKernel\Debug\ErrorHandler`, `Symfony\Component\HttpKernel\Debug\ExceptionHandler`, `Symfony\Component\HttpKernel\Exception\FatalErrorException`, and `Symfony\Component\HttpKernel\Exception\FlattenException` * deprecated `Symfony\Component\HttpKernel\Kernel::init()`` * added the possibility to specify an id an extra attributes to hinclude tags * added the collect of data if a controller is a Closure in the Request collector * pass exceptions from the ExceptionListener to the logger using the logging context to allow for more detailed messages 2.2.0 ----- * [BC BREAK] the path info for sub-request is now always _fragment (or whatever you configured instead of the default) * added Symfony\Component\HttpKernel\EventListener\FragmentListener * added Symfony\Component\HttpKernel\UriSigner * added Symfony\Component\HttpKernel\FragmentRenderer and rendering strategies (in Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface) * added Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel * added ControllerReference to create reference of Controllers (used in the FragmentRenderer class) * [BC BREAK] renamed TimeDataCollector::getTotalTime() to TimeDataCollector::getDuration() * updated the MemoryDataCollector to include the memory used in the kernel.terminate event listeners * moved the Stopwatch classes to a new component * added TraceableControllerResolver * added TraceableEventDispatcher (removed ContainerAwareTraceableEventDispatcher) * added support for WinCache opcode cache in ConfigDataCollector 2.1.0 ----- * [BC BREAK] the charset is now configured via the Kernel::getCharset() method * [BC BREAK] the current locale for the user is not stored anymore in the session * added the HTTP method to the profiler storage * updated all listeners to implement EventSubscriberInterface * added TimeDataCollector * added ContainerAwareTraceableEventDispatcher * moved TraceableEventDispatcherInterface to the EventDispatcher component * added RouterListener, LocaleListener, and StreamedResponseListener * added CacheClearerInterface (and ChainCacheClearer) * added a kernel.terminate event (via TerminableInterface and PostResponseEvent) * added a Stopwatch class * added WarmableInterface * improved extensibility between bundles * added profiler storages for Memcache(d), File-based, MongoDB, Redis * moved Filesystem class to its own component PK!7k"Component/HttpKernel/composer.jsonnu[{ "name": "symfony/http-kernel", "type": "library", "description": "Symfony HttpKernel Component", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3", "symfony/event-dispatcher": "~2.1", "symfony/http-foundation": "~2.4", "symfony/debug": "~2.3", "psr/log": "~1.0" }, "require-dev": { "symfony/browser-kit": "~2.2", "symfony/class-loader": "~2.1", "symfony/config": "~2.0", "symfony/console": "~2.2", "symfony/dependency-injection": "~2.0", "symfony/finder": "~2.0", "symfony/process": "~2.0", "symfony/routing": "~2.2", "symfony/stopwatch": "~2.2", "symfony/templating": "~2.2" }, "suggest": { "symfony/browser-kit": "", "symfony/class-loader": "", "symfony/config": "", "symfony/console": "", "symfony/dependency-injection": "", "symfony/finder": "" }, "autoload": { "psr-0": { "Symfony\\Component\\HttpKernel\\": "" } }, "target-dir": "Symfony/Component/HttpKernel", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!Xͫ Component/HttpKernel/README.mdnu[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 give 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 --------- You can run the unit tests with the following command: $ cd path/to/Symfony/Component/HttpKernel/ $ composer.phar install $ phpunit PK!E))Component/HttpKernel/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!@"SComponent/Finder/CHANGELOG.mdnu[CHANGELOG ========= 2.3.0 ----- * added a way to ignore unreadable directories (via Finder::ignoreUnreadableDirs()) * unified the way subfolders that are not executable are handled by always throwing an AccessDeniedException exception 2.2.0 ----- * added Finder::path() and Finder::notPath() methods * added finder adapters to improve performance on specific platforms * added support for wildcard characters (glob patterns) in the paths passed to Finder::in() 2.1.0 ----- * added Finder::sortByAccessedTime(), Finder::sortByChangedTime(), and Finder::sortByModifiedTime() * added Countable to Finder * added support for an array of directories as an argument to Finder::exclude() * added searching based on the file content via Finder::contains() and Finder::notContains() * added support for the != operator in the Comparator * [BC BREAK] filter expressions (used for file name and content) are no more considered as regexps but glob patterns when they are enclosed in '*' or '?' PK!V:Component/Finder/composer.jsonnu[{ "name": "symfony/finder", "type": "library", "description": "Symfony Finder Component", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3" }, "autoload": { "psr-0": { "Symfony\\Component\\Finder\\": "" } }, "target-dir": "Symfony/Component/Finder", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!c9@Component/Finder/README.mdnu[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 --------- You can run the unit tests with the following command: $ cd path/to/Symfony/Component/Finder/ $ composer.phar install $ phpunit PK!E))Component/Finder/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!+\MM3Component/Process/Tests/PhpExecutableFinderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\PhpExecutableFinder; /** * @author Robert Schönthal */ class PhpExecutableFinderTest extends \PHPUnit_Framework_TestCase { /** * tests find() with the env var PHP_PATH */ public function testFindWithPhpPath() { if (defined('PHP_BINARY')) { $this->markTestSkipped('The PHP binary is easily available as of PHP 5.4'); } $f = new PhpExecutableFinder(); $current = $f->find(); //not executable PHP_PATH putenv('PHP_PATH=/not/executable/php'); $this->assertFalse($f->find(), '::find() returns false for not executable PHP'); //executable PHP_PATH putenv('PHP_PATH='.$current); $this->assertEquals($f->find(), $current, '::find() returns the executable PHP'); } /** * tests find() with default executable */ public function testFindWithSuffix() { if (defined('PHP_BINARY')) { $this->markTestSkipped('The PHP binary is easily available as of PHP 5.4'); } putenv('PHP_PATH='); putenv('PHP_PEAR_PHP_BIN='); $f = new PhpExecutableFinder(); $current = $f->find(); //TODO maybe php executable is custom or even Windows if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertTrue(is_executable($current)); $this->assertTrue((bool) preg_match('/'.addSlashes(DIRECTORY_SEPARATOR).'php\.(exe|bat|cmd|com)$/i', $current), '::find() returns the executable PHP with suffixes'); } } } PK!#?Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.phpnu[ 0) { $written = fwrite(STDOUT, (binary) $out, 32768); if (false === $written) { die(ERR_WRITE_FAILED); } $out = (binary) substr($out, $written); } if (null === $read && strlen($out) < 1) { $write = array_diff($write, array(STDOUT)); } if (in_array(STDERR, $w) && strlen($err) > 0) { $written = fwrite(STDERR, (binary) $err, 32768); if (false === $written) { die(ERR_WRITE_FAILED); } $err = (binary) substr($err, $written); } if (null === $read && strlen($err) < 1) { $write = array_diff($write, array(STDERR)); } if ($r) { $str = fread(STDIN, 32768); if (false !== $str) { $out .= $str; $err .= $str; } if (false === $str || feof(STDIN)) { $read = null; if (!feof(STDIN)) { die(ERR_READ_FAILED); } } } } PK!WKo 6Component/Process/Tests/ProcessFailedExceptionTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\Exception\ProcessFailedException; /** * @author Sebastian Marek */ class ProcessFailedExceptionTest extends \PHPUnit_Framework_TestCase { /** * tests ProcessFailedException throws exception if the process was successful */ public function testProcessFailedExceptionThrowsException() { $process = $this->getMock( 'Symfony\Component\Process\Process', array('isSuccessful'), array('php') ); $process->expects($this->once()) ->method('isSuccessful') ->will($this->returnValue(true)); $this->setExpectedException( '\InvalidArgumentException', 'Expected a failed process, but the given process was successful.' ); new ProcessFailedException($process); } /** * tests ProcessFailedException uses information from process output * to generate exception message */ public function testProcessFailedExceptionPopulatesInformationFromProcessOutput() { $cmd = 'php'; $exitCode = 1; $exitText = 'General error'; $output = "Command output"; $errorOutput = "FATAL: Unexpected error"; $process = $this->getMock( 'Symfony\Component\Process\Process', array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText'), array($cmd) ); $process->expects($this->once()) ->method('isSuccessful') ->will($this->returnValue(false)); $process->expects($this->once()) ->method('getOutput') ->will($this->returnValue($output)); $process->expects($this->once()) ->method('getErrorOutput') ->will($this->returnValue($errorOutput)); $process->expects($this->once()) ->method('getExitCode') ->will($this->returnValue($exitCode)); $process->expects($this->once()) ->method('getExitCodeText') ->will($this->returnValue($exitText)); $exception = new ProcessFailedException($process); $this->assertEquals( "The command \"$cmd\" failed.\nExit Code: $exitCode($exitText)\n\nOutput:\n================\n{$output}\n\nError Output:\n================\n{$errorOutput}", $exception->getMessage() ); } } PK!Cu^UU,Component/Process/Tests/ProcessUtilsTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\ProcessUtils; class ProcessUtilsTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider dataArguments */ public function testEscapeArgument($result, $argument) { $this->assertSame($result, ProcessUtils::escapeArgument($argument)); } public function dataArguments() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { return array( array('"\"php\" \"-v\""', '"php" "-v"'), array('"foo bar"', 'foo bar'), array('^%"path"^%', '%path%'), array('"<|>\\" \\"\'f"', '<|>" "\'f'), array('""', ''), array('"with\trailingbs\\\\"', 'with\trailingbs\\'), ); } return array( array("'\"php\" \"-v\"'", '"php" "-v"'), array("'foo bar'", 'foo bar'), array("'%path%'", '%path%'), array("'<|>\" \"'\\''f'", '<|>" "\'f'), array("''", ''), array("'with\\trailingbs\\'", 'with\trailingbs\\'), ); } } PK![VAChCh/Component/Process/Tests/AbstractProcessTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\Exception\ProcessTimedOutException; use Symfony\Component\Process\Process; use Symfony\Component\Process\Exception\RuntimeException; use Symfony\Component\Process\ProcessPipes; /** * @author Robert Schönthal */ abstract class AbstractProcessTest extends \PHPUnit_Framework_TestCase { public function testThatProcessDoesNotThrowWarningDuringRun() { @trigger_error('Test Error', E_USER_NOTICE); $process = $this->getProcess("php -r 'sleep(3)'"); $process->run(); $actualError = error_get_last(); $this->assertEquals('Test Error', $actualError['message']); $this->assertEquals(E_USER_NOTICE, $actualError['type']); } /** * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException */ public function testNegativeTimeoutFromConstructor() { $this->getProcess('', null, null, null, -1); } /** * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException */ public function testNegativeTimeoutFromSetter() { $p = $this->getProcess(''); $p->setTimeout(-1); } public function testFloatAndNullTimeout() { $p = $this->getProcess(''); $p->setTimeout(10); $this->assertSame(10.0, $p->getTimeout()); $p->setTimeout(null); $this->assertNull($p->getTimeout()); $p->setTimeout(0.0); $this->assertNull($p->getTimeout()); } public function testStopWithTimeoutIsActuallyWorking() { $this->verifyPosixIsEnabled(); // exec is mandatory here since we send a signal to the process // see https://github.com/symfony/symfony/issues/5030 about prepending // command with exec $p = $this->getProcess('exec php '.__DIR__.'/NonStopableProcess.php 3'); $p->start(); usleep(100000); $start = microtime(true); $p->stop(1.1, SIGKILL); while ($p->isRunning()) { usleep(1000); } $duration = microtime(true) - $start; $this->assertLessThan(1.8, $duration); } public function testAllOutputIsActuallyReadOnTermination() { // this code will result in a maximum of 2 reads of 8192 bytes by calling // start() and isRunning(). by the time getOutput() is called the process // has terminated so the internal pipes array is already empty. normally // the call to start() will not read any data as the process will not have // generated output, but this is non-deterministic so we must count it as // a possibility. therefore we need 2 * ProcessPipes::CHUNK_SIZE plus // another byte which will never be read. $expectedOutputSize = ProcessPipes::CHUNK_SIZE * 2 + 2; $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize); $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code))); $p->start(); // Let's wait enough time for process to finish... // Here we don't call Process::run or Process::wait to avoid any read of pipes usleep(500000); if ($p->isRunning()) { $this->markTestSkipped('Process execution did not complete in the required time frame'); } $o = $p->getOutput(); $this->assertEquals($expectedOutputSize, strlen($o)); } public function testCallbacksAreExecutedWithStart() { $data = ''; $process = $this->getProcess('echo foo && php -r "sleep(1);" && echo foo'); $process->start(function ($type, $buffer) use (&$data) { $data .= $buffer; }); while ($process->isRunning()) { usleep(10000); } $this->assertEquals(2, preg_match_all('/foo/', $data, $matches)); } /** * tests results from sub processes * * @dataProvider responsesCodeProvider */ public function testProcessResponses($expected, $getter, $code) { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code))); $p->run(); $this->assertSame($expected, $p->$getter()); } /** * tests results from sub processes * * @dataProvider pipesCodeProvider */ public function testProcessPipes($code, $size) { $expected = str_repeat(str_repeat('*', 1024), $size) . '!'; $expectedLength = (1024 * $size) + 1; $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code))); $p->setStdin($expected); $p->run(); $this->assertEquals($expectedLength, strlen($p->getOutput())); $this->assertEquals($expectedLength, strlen($p->getErrorOutput())); } public function chainedCommandsOutputProvider() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { return array( array("2 \r\n2\r\n", '&&', '2') ); } return array( array("1\n1\n", ';', '1'), array("2\n2\n", '&&', '2'), ); } /** * * @dataProvider chainedCommandsOutputProvider */ public function testChainedCommandsOutput($expected, $operator, $input) { $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input)); $process->run(); $this->assertEquals($expected, $process->getOutput()); } public function testCallbackIsExecutedForOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('echo \'foo\';'))); $called = false; $p->run(function ($type, $buffer) use (&$called) { $called = $buffer === 'foo'; }); $this->assertTrue($called, 'The callback should be executed with the output'); } public function testGetErrorOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }'))); $p->run(); $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches)); } public function testGetIncrementalErrorOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { usleep(100000); file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }'))); $p->start(); while ($p->isRunning()) { $this->assertLessThanOrEqual(1, preg_match_all('/ERROR/', $p->getIncrementalErrorOutput(), $matches)); usleep(20000); } } public function testFlushErrorOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }'))); $p->run(); $p->clearErrorOutput(); $this->assertEmpty($p->getErrorOutput()); } public function testGetOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++; usleep(500); }'))); $p->run(); $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches)); } public function testGetIncrementalOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) { echo \' foo \'; usleep(50000); $n++; }'))); $p->start(); while ($p->isRunning()) { $this->assertLessThanOrEqual(1, preg_match_all('/foo/', $p->getIncrementalOutput(), $matches)); usleep(20000); } } public function testFlushOutput() { $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}'))); $p->run(); $p->clearOutput(); $this->assertEmpty($p->getOutput()); } public function testExitCodeCommandFailed() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX exit code'); } // such command run in bash return an exitcode 127 $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis'); $process->run(); $this->assertGreaterThan(0, $process->getExitCode()); } public function testTTYCommand() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does have /dev/tty support'); } $process = $this->getProcess('echo "foo" >> /dev/null && php -r "usleep(100000);"'); $process->setTTY(true); $process->start(); $this->assertTrue($process->isRunning()); $process->wait(); $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus()); } public function testTTYCommandExitCode() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does have /dev/tty support'); } $process = $this->getProcess('echo "foo" >> /dev/null'); $process->setTTY(true); $process->run(); $this->assertTrue($process->isSuccessful()); } public function testExitCodeTextIsNullWhenExitCodeIsNull() { $process = $this->getProcess(''); $this->assertNull($process->getExitCodeText()); } public function testExitCodeText() { $process = $this->getProcess(''); $r = new \ReflectionObject($process); $p = $r->getProperty('exitcode'); $p->setAccessible(true); $p->setValue($process, 2); $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText()); } public function testStartIsNonBlocking() { $process = $this->getProcess('php -r "usleep(500000);"'); $start = microtime(true); $process->start(); $end = microtime(true); $this->assertLessThan(0.2, $end-$start); $process->wait(); } public function testUpdateStatus() { $process = $this->getProcess('php -h'); $process->run(); $this->assertTrue(strlen($process->getOutput()) > 0); } public function testGetExitCodeIsNullOnStart() { $process = $this->getProcess('php -r "usleep(200000);"'); $this->assertNull($process->getExitCode()); $process->start(); $this->assertNull($process->getExitCode()); $process->wait(); $this->assertEquals(0, $process->getExitCode()); } public function testGetExitCodeIsNullOnWhenStartingAgain() { $process = $this->getProcess('php -r "usleep(200000);"'); $process->run(); $this->assertEquals(0, $process->getExitCode()); $process->start(); $this->assertNull($process->getExitCode()); $process->wait(); $this->assertEquals(0, $process->getExitCode()); } public function testGetExitCode() { $process = $this->getProcess('php -m'); $process->run(); $this->assertSame(0, $process->getExitCode()); } public function testStatus() { $process = $this->getProcess('php -r "usleep(500000);"'); $this->assertFalse($process->isRunning()); $this->assertFalse($process->isStarted()); $this->assertFalse($process->isTerminated()); $this->assertSame(Process::STATUS_READY, $process->getStatus()); $process->start(); $this->assertTrue($process->isRunning()); $this->assertTrue($process->isStarted()); $this->assertFalse($process->isTerminated()); $this->assertSame(Process::STATUS_STARTED, $process->getStatus()); $process->wait(); $this->assertFalse($process->isRunning()); $this->assertTrue($process->isStarted()); $this->assertTrue($process->isTerminated()); $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus()); } public function testStop() { $process = $this->getProcess('php -r "sleep(4);"'); $process->start(); $this->assertTrue($process->isRunning()); $process->stop(); $this->assertFalse($process->isRunning()); } public function testIsSuccessful() { $process = $this->getProcess('php -m'); $process->run(); $this->assertTrue($process->isSuccessful()); } public function testIsSuccessfulOnlyAfterTerminated() { $process = $this->getProcess('php -r "sleep(1);"'); $process->start(); while ($process->isRunning()) { $this->assertFalse($process->isSuccessful()); usleep(300000); } $this->assertTrue($process->isSuccessful()); } public function testIsNotSuccessful() { $process = $this->getProcess('php -r "usleep(500000);throw new \Exception(\'BOUM\');"'); $process->start(); $this->assertTrue($process->isRunning()); $process->wait(); $this->assertFalse($process->isSuccessful()); } public function testProcessIsNotSignaled() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX signals'); } $process = $this->getProcess('php -m'); $process->run(); $this->assertFalse($process->hasBeenSignaled()); } public function testProcessWithoutTermSignalIsNotSignaled() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX signals'); } $process = $this->getProcess('php -m'); $process->run(); $this->assertFalse($process->hasBeenSignaled()); } public function testProcessWithoutTermSignal() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX signals'); } $process = $this->getProcess('php -m'); $process->run(); $this->assertEquals(0, $process->getTermSignal()); } public function testProcessIsSignaledIfStopped() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX signals'); } $process = $this->getProcess('php -r "sleep(4);"'); $process->start(); $process->stop(); $this->assertTrue($process->hasBeenSignaled()); } public function testProcessWithTermSignal() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX signals'); } // SIGTERM is only defined if pcntl extension is present $termSignal = defined('SIGTERM') ? SIGTERM : 15; $process = $this->getProcess('php -r "sleep(4);"'); $process->start(); $process->stop(); $this->assertEquals($termSignal, $process->getTermSignal()); } public function testProcessThrowsExceptionWhenExternallySignaled() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Windows does not support POSIX signals'); } if (!function_exists('posix_kill')) { $this->markTestSkipped('posix_kill is required for this test'); } $termSignal = defined('SIGKILL') ? SIGKILL : 9; $process = $this->getProcess('exec php -r "while (true) {}"'); $process->start(); posix_kill($process->getPid(), $termSignal); $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'The process has been signaled with signal "9".'); $process->wait(); } public function testRestart() { $process1 = $this->getProcess('php -r "echo getmypid();"'); $process1->run(); $process2 = $process1->restart(); $process2->wait(); // wait for output // Ensure that both processed finished and the output is numeric $this->assertFalse($process1->isRunning()); $this->assertFalse($process2->isRunning()); $this->assertTrue(is_numeric($process1->getOutput())); $this->assertTrue(is_numeric($process2->getOutput())); // Ensure that restart returned a new process by check that the output is different $this->assertNotEquals($process1->getOutput(), $process2->getOutput()); } public function testPhpDeadlock() { $this->markTestSkipped('Can course PHP to hang'); // Sleep doesn't work as it will allow the process to handle signals and close // file handles from the other end. $process = $this->getProcess('php -r "while (true) {}"'); $process->start(); // PHP will deadlock when it tries to cleanup $process } public function testRunProcessWithTimeout() { $timeout = 0.5; $process = $this->getProcess('php -r "usleep(600000);"'); $process->setTimeout($timeout); $start = microtime(true); try { $process->run(); $this->fail('A RuntimeException should have been raised'); } catch (RuntimeException $e) { } $duration = microtime(true) - $start; $this->assertLessThan($timeout + Process::TIMEOUT_PRECISION, $duration); } public function testCheckTimeoutOnNonStartedProcess() { $process = $this->getProcess('php -r "sleep(3);"'); $process->checkTimeout(); } public function testCheckTimeoutOnTerminatedProcess() { $process = $this->getProcess('php -v'); $process->run(); $process->checkTimeout(); } public function testCheckTimeoutOnStartedProcess() { $timeout = 0.5; $precision = 100000; $process = $this->getProcess('php -r "sleep(3);"'); $process->setTimeout($timeout); $start = microtime(true); $process->start(); try { while ($process->isRunning()) { $process->checkTimeout(); usleep($precision); } $this->fail('A RuntimeException should have been raised'); } catch (RuntimeException $e) { } $duration = microtime(true) - $start; $this->assertLessThan($timeout + $precision, $duration); $this->assertFalse($process->isSuccessful()); } /** * @group idle-timeout */ public function testIdleTimeout() { $process = $this->getProcess('sleep 3'); $process->setTimeout(10); $process->setIdleTimeout(1); try { $process->run(); $this->fail('A timeout exception was expected.'); } catch (ProcessTimedOutException $ex) { $this->assertTrue($ex->isIdleTimeout()); $this->assertFalse($ex->isGeneralTimeout()); $this->assertEquals(1.0, $ex->getExceededTimeout()); } } /** * @group idle-timeout */ public function testIdleTimeoutNotExceededWhenOutputIsSent() { $process = $this->getProcess('echo "foo" && sleep 1 && echo "foo" && sleep 1 && echo "foo" && sleep 1 && echo "foo" && sleep 5'); $process->setTimeout(5); $process->setIdleTimeout(3); try { $process->run(); $this->fail('A timeout exception was expected.'); } catch (ProcessTimedOutException $ex) { $this->assertTrue($ex->isGeneralTimeout()); $this->assertFalse($ex->isIdleTimeout()); $this->assertEquals(5.0, $ex->getExceededTimeout()); } } public function testStartAfterATimeout() { $process = $this->getProcess('php -r "$n = 1000; while ($n--) {echo \'\'; usleep(1000); }"'); $process->setTimeout(0.1); try { $process->run(); $this->fail('An exception should have been raised.'); } catch (\Exception $e) { } $process->start(); usleep(10000); $process->stop(); } public function testGetPid() { $process = $this->getProcess('php -r "usleep(500000);"'); $process->start(); $this->assertGreaterThan(0, $process->getPid()); $process->wait(); } public function testGetPidIsNullBeforeStart() { $process = $this->getProcess('php -r "sleep(1);"'); $this->assertNull($process->getPid()); } public function testGetPidIsNullAfterRun() { $process = $this->getProcess('php -m'); $process->run(); $this->assertNull($process->getPid()); } public function testSignal() { $this->verifyPosixIsEnabled(); $process = $this->getProcess('exec php -f ' . __DIR__ . '/SignalListener.php'); $process->start(); usleep(500000); $process->signal(SIGUSR1); while ($process->isRunning() && false === strpos($process->getoutput(), 'Caught SIGUSR1')) { usleep(10000); } $this->assertEquals('Caught SIGUSR1', $process->getOutput()); } public function testExitCodeIsAvailableAfterSignal() { $this->verifyPosixIsEnabled(); $process = $this->getProcess('sleep 4'); $process->start(); $process->signal(SIGKILL); while ($process->isRunning()) { usleep(10000); } $this->assertFalse($process->isRunning()); $this->assertTrue($process->hasBeenSignaled()); $this->assertFalse($process->isSuccessful()); $this->assertEquals(137, $process->getExitCode()); } /** * @expectedException \Symfony\Component\Process\Exception\LogicException */ public function testSignalProcessNotRunning() { $this->verifyPosixIsEnabled(); $process = $this->getProcess('php -m'); $process->signal(SIGHUP); } /** * @dataProvider provideMethodsThatNeedARunningProcess */ public function testMethodsThatNeedARunningProcess($method) { $process = $this->getProcess('php -m'); $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method)); call_user_func(array($process, $method)); } public function provideMethodsThatNeedARunningProcess() { return array( array('getOutput'), array('getIncrementalOutput'), array('getErrorOutput'), array('getIncrementalErrorOutput'), array('wait'), ); } /** * @dataProvider provideMethodsThatNeedATerminatedProcess */ public function testMethodsThatNeedATerminatedProcess($method) { $process = $this->getProcess('php -r "sleep(1);"'); $process->start(); try { call_user_func(array($process, $method)); $process->stop(0); $this->fail('A LogicException must have been thrown'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\Process\Exception\LogicException', $e); $this->assertEquals(sprintf('Process must be terminated before calling %s.', $method), $e->getMessage()); } $process->stop(0); } public function provideMethodsThatNeedATerminatedProcess() { return array( array('hasBeenSignaled'), array('getTermSignal'), array('hasBeenStopped'), array('getStopSignal'), ); } private function verifyPosixIsEnabled() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('POSIX signals do not work on Windows'); } if (!defined('SIGUSR1')) { $this->markTestSkipped('The pcntl extension is not enabled'); } } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException */ public function testSignalWithWrongIntSignal() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('POSIX signals do not work on Windows'); } $process = $this->getProcess('php -r "sleep(3);"'); $process->start(); $process->signal(-4); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException */ public function testSignalWithWrongNonIntSignal() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('POSIX signals do not work on Windows'); } $process = $this->getProcess('php -r "sleep(3);"'); $process->start(); $process->signal('Céphalopodes'); } public function responsesCodeProvider() { return array( //expected output / getter / code to execute //array(1,'getExitCode','exit(1);'), //array(true,'isSuccessful','exit();'), array('output', 'getOutput', 'echo \'output\';'), ); } public function pipesCodeProvider() { $variations = array( 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);', 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';', ); if (defined('PHP_WINDOWS_VERSION_BUILD')) { // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650 $sizes = array(1, 2, 4, 8); } else { $sizes = array(1, 16, 64, 1024, 4096); } $codes = array(); foreach ($sizes as $size) { foreach ($variations as $code) { $codes[] = array($code, $size); } } return $codes; } /** * provides default method names for simple getter/setter */ public function methodProvider() { $defaults = array( array('CommandLine'), array('Timeout'), array('WorkingDirectory'), array('Env'), array('Stdin'), array('Options') ); return $defaults; } /** * @param string $commandline * @param null $cwd * @param array $env * @param null $stdin * @param integer $timeout * @param array $options * * @return Process */ abstract protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array()); } PK!=,j*Component/Process/Tests/SignalListener.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\Process; class SimpleProcessTest extends AbstractProcessTest { private $enabledSigchild = false; public function setUp() { ob_start(); phpinfo(INFO_GENERAL); $this->enabledSigchild = false !== strpos(ob_get_clean(), '--enable-sigchild'); } public function testGetExitCode() { $this->skipIfPHPSigchild(); // This test use exitcode that is not available in this case parent::testGetExitCode(); } public function testExitCodeCommandFailed() { $this->skipIfPHPSigchild(); // This test use exitcode that is not available in this case parent::testExitCodeCommandFailed(); } public function testProcessIsSignaledIfStopped() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved'); parent::testProcessIsSignaledIfStopped(); } public function testProcessWithTermSignal() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved'); parent::testProcessWithTermSignal(); } public function testProcessIsNotSignaled() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved'); parent::testProcessIsNotSignaled(); } public function testProcessWithoutTermSignal() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved'); parent::testProcessWithoutTermSignal(); } public function testExitCodeText() { $this->skipIfPHPSigchild(); // This test use exitcode that is not available in this case parent::testExitCodeText(); } public function testIsSuccessful() { $this->skipIfPHPSigchild(); // This test use PID that is not available in this case parent::testIsSuccessful(); } public function testIsNotSuccessful() { $this->skipIfPHPSigchild(); // This test use PID that is not available in this case parent::testIsNotSuccessful(); } public function testGetPid() { $this->skipIfPHPSigchild(); // This test use PID that is not available in this case parent::testGetPid(); } public function testGetPidIsNullBeforeStart() { $this->skipIfPHPSigchild(); // This test use PID that is not available in this case parent::testGetPidIsNullBeforeStart(); } public function testGetPidIsNullAfterRun() { $this->skipIfPHPSigchild(); // This test use PID that is not available in this case parent::testGetPidIsNullAfterRun(); } public function testSignal() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.'); parent::testSignal(); } public function testProcessWithoutTermSignalIsNotSignaled() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved'); parent::testProcessWithoutTermSignalIsNotSignaled(); } public function testProcessThrowsExceptionWhenExternallySignaled() { $this->skipIfPHPSigchild(); // This test use PID that is not available in this case parent::testProcessThrowsExceptionWhenExternallySignaled(); } public function testExitCodeIsAvailableAfterSignal() { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.'); parent::testExitCodeIsAvailableAfterSignal(); } public function testSignalProcessNotRunning() { $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', 'Can not send signal on a non running process.'); parent::testSignalProcessNotRunning(); } public function testSignalWithWrongIntSignal() { if ($this->enabledSigchild) { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.'); } else { $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'Error while sending signal `-4`.'); } parent::testSignalWithWrongIntSignal(); } public function testSignalWithWrongNonIntSignal() { if ($this->enabledSigchild) { $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.'); } else { $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'Error while sending signal `Céphalopodes`.'); } parent::testSignalWithWrongNonIntSignal(); } /** * {@inheritdoc} */ protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array()) { return new Process($commandline, $cwd, $env, $stdin, $timeout, $options); } private function skipIfPHPSigchild() { if ($this->enabledSigchild) { $this->markTestSkipped('Your PHP has been compiled with --enable-sigchild, this test can not be executed'); } } private function expectExceptionIfPHPSigchild($classname, $message) { if ($this->enabledSigchild) { $this->setExpectedException($classname, $message); } } } PK!+v,,.Component/Process/Tests/NonStopableProcess.phpnu[ (microtime(true) - $start)) { usleep(1000); } PK!m8Component/Process/Tests/ProcessInSigchildEnvironment.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\Process; class ProcessInSigchildEnvironment extends Process { protected function isSigchildEnabled() { return true; } } PK!7Component/Process/Tests/SigchildDisabledProcessTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; class SigchildDisabledProcessTest extends AbstractProcessTest { /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testGetExitCode() { parent::testGetExitCode(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testGetExitCodeIsNullOnStart() { parent::testGetExitCodeIsNullOnStart(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testGetExitCodeIsNullOnWhenStartingAgain() { parent::testGetExitCodeIsNullOnWhenStartingAgain(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testExitCodeCommandFailed() { parent::testExitCodeCommandFailed(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessIsSignaledIfStopped() { parent::testProcessIsSignaledIfStopped(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessWithTermSignal() { parent::testProcessWithTermSignal(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessIsNotSignaled() { parent::testProcessIsNotSignaled(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessWithoutTermSignal() { parent::testProcessWithoutTermSignal(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testCheckTimeoutOnStartedProcess() { parent::testCheckTimeoutOnStartedProcess(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved. */ public function testGetPid() { parent::testGetPid(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved. */ public function testGetPidIsNullBeforeStart() { parent::testGetPidIsNullBeforeStart(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved. */ public function testGetPidIsNullAfterRun() { parent::testGetPidIsNullAfterRun(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testExitCodeText() { $process = $this->getProcess('qdfsmfkqsdfmqmsd'); $process->run(); $process->getExitCodeText(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testExitCodeTextIsNullWhenExitCodeIsNull() { parent::testExitCodeTextIsNullWhenExitCodeIsNull(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testIsSuccessful() { parent::testIsSuccessful(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testIsSuccessfulOnlyAfterTerminated() { parent::testIsSuccessfulOnlyAfterTerminated(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testIsNotSuccessful() { parent::testIsNotSuccessful(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method. */ public function testTTYCommandExitCode() { parent::testTTYCommandExitCode(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process can not be signaled. */ public function testSignal() { parent::testSignal(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessWithoutTermSignalIsNotSignaled() { parent::testProcessWithoutTermSignalIsNotSignaled(); } public function testStopWithTimeoutIsActuallyWorking() { $this->markTestSkipped('Stopping with signal is not supported in sigchild environment'); } public function testProcessThrowsExceptionWhenExternallySignaled() { $this->markTestSkipped('Retrieving Pid is not supported in sigchild environment'); } public function testExitCodeIsAvailableAfterSignal() { $this->markTestSkipped('Signal is not supported in sigchild environment'); } /** * {@inheritdoc} */ protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array()) { $process = new ProcessInSigchildEnvironment($commandline, $cwd, $env, $stdin, $timeout, $options); $process->setEnhanceSigchildCompatibility(false); return $process; } } PK!Hspp.Component/Process/Tests/ProcessBuilderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\ProcessBuilder; class ProcessBuilderTest extends \PHPUnit_Framework_TestCase { public function testInheritEnvironmentVars() { $_ENV['MY_VAR_1'] = 'foo'; $proc = ProcessBuilder::create() ->add('foo') ->getProcess(); unset($_ENV['MY_VAR_1']); $env = $proc->getEnv(); $this->assertArrayHasKey('MY_VAR_1', $env); $this->assertEquals('foo', $env['MY_VAR_1']); } public function testAddEnvironmentVariables() { $pb = new ProcessBuilder(); $env = array( 'foo' => 'bar', 'foo2' => 'bar2', ); $proc = $pb ->add('command') ->setEnv('foo', 'bar2') ->addEnvironmentVariables($env) ->inheritEnvironmentVariables(false) ->getProcess() ; $this->assertSame($env, $proc->getEnv()); } public function testProcessShouldInheritAndOverrideEnvironmentVars() { $_ENV['MY_VAR_1'] = 'foo'; $proc = ProcessBuilder::create() ->setEnv('MY_VAR_1', 'bar') ->add('foo') ->getProcess(); unset($_ENV['MY_VAR_1']); $env = $proc->getEnv(); $this->assertArrayHasKey('MY_VAR_1', $env); $this->assertEquals('bar', $env['MY_VAR_1']); } /** * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException */ public function testNegativeTimeoutFromSetter() { $pb = new ProcessBuilder(); $pb->setTimeout(-1); } public function testNullTimeout() { $pb = new ProcessBuilder(); $pb->setTimeout(10); $pb->setTimeout(null); $r = new \ReflectionObject($pb); $p = $r->getProperty('timeout'); $p->setAccessible(true); $this->assertNull($p->getValue($pb)); } public function testShouldSetArguments() { $pb = new ProcessBuilder(array('initial')); $pb->setArguments(array('second')); $proc = $pb->getProcess(); $this->assertContains("second", $proc->getCommandLine()); } public function testPrefixIsPrependedToAllGeneratedProcess() { $pb = new ProcessBuilder(); $pb->setPrefix('/usr/bin/php'); $proc = $pb->setArguments(array('-v'))->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertEquals('"/usr/bin/php" "-v"', $proc->getCommandLine()); } else { $this->assertEquals("'/usr/bin/php' '-v'", $proc->getCommandLine()); } $proc = $pb->setArguments(array('-i'))->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertEquals('"/usr/bin/php" "-i"', $proc->getCommandLine()); } else { $this->assertEquals("'/usr/bin/php' '-i'", $proc->getCommandLine()); } } public function testArrayPrefixesArePrependedToAllGeneratedProcess() { $pb = new ProcessBuilder(); $pb->setPrefix(array('/usr/bin/php', 'composer.phar')); $proc = $pb->setArguments(array('-v'))->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertEquals('"/usr/bin/php" "composer.phar" "-v"', $proc->getCommandLine()); } else { $this->assertEquals("'/usr/bin/php' 'composer.phar' '-v'", $proc->getCommandLine()); } $proc = $pb->setArguments(array('-i'))->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertEquals('"/usr/bin/php" "composer.phar" "-i"', $proc->getCommandLine()); } else { $this->assertEquals("'/usr/bin/php' 'composer.phar' '-i'", $proc->getCommandLine()); } } public function testShouldEscapeArguments() { $pb = new ProcessBuilder(array('%path%', 'foo " bar', '%baz%baz')); $proc = $pb->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertSame('^%"path"^% "foo \\" bar" "%baz%baz"', $proc->getCommandLine()); } else { $this->assertSame("'%path%' 'foo \" bar' '%baz%baz'", $proc->getCommandLine()); } } public function testShouldEscapeArgumentsAndPrefix() { $pb = new ProcessBuilder(array('arg')); $pb->setPrefix('%prefix%'); $proc = $pb->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertSame('^%"prefix"^% "arg"', $proc->getCommandLine()); } else { $this->assertSame("'%prefix%' 'arg'", $proc->getCommandLine()); } } /** * @expectedException \Symfony\Component\Process\Exception\LogicException */ public function testShouldThrowALogicExceptionIfNoPrefixAndNoArgument() { ProcessBuilder::create()->getProcess(); } public function testShouldNotThrowALogicExceptionIfNoArgument() { $process = ProcessBuilder::create() ->setPrefix('/usr/bin/php') ->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertEquals('"/usr/bin/php"', $process->getCommandLine()); } else { $this->assertEquals("'/usr/bin/php'", $process->getCommandLine()); } } public function testShouldNotThrowALogicExceptionIfNoPrefix() { $process = ProcessBuilder::create(array('/usr/bin/php')) ->getProcess(); if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->assertEquals('"/usr/bin/php"', $process->getCommandLine()); } else { $this->assertEquals("'/usr/bin/php'", $process->getCommandLine()); } } } PK!x[*Component/Process/Tests/PhpProcessTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; use Symfony\Component\Process\PhpProcess; class PhpProcessTest extends \PHPUnit_Framework_TestCase { public function testNonBlockingWorks() { $expected = 'hello world!'; $process = new PhpProcess(<<start(); $process->wait(); $this->assertEquals($expected, $process->getOutput()); } } PK!钊\\6Component/Process/Tests/SigchildEnabledProcessTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process\Tests; class SigchildEnabledProcessTest extends AbstractProcessTest { /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessIsSignaledIfStopped() { parent::testProcessIsSignaledIfStopped(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessWithTermSignal() { parent::testProcessWithTermSignal(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessIsNotSignaled() { parent::testProcessIsNotSignaled(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessWithoutTermSignal() { parent::testProcessWithoutTermSignal(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved. */ public function testGetPid() { parent::testGetPid(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved. */ public function testGetPidIsNullBeforeStart() { parent::testGetPidIsNullBeforeStart(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved. */ public function testGetPidIsNullAfterRun() { parent::testGetPidIsNullAfterRun(); } public function testExitCodeText() { $process = $this->getProcess('qdfsmfkqsdfmqmsd'); $process->run(); $this->assertInternalType('string', $process->getExitCodeText()); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process can not be signaled. */ public function testSignal() { parent::testSignal(); } /** * @expectedException \Symfony\Component\Process\Exception\RuntimeException * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved. */ public function testProcessWithoutTermSignalIsNotSignaled() { parent::testProcessWithoutTermSignalIsNotSignaled(); } public function testProcessThrowsExceptionWhenExternallySignaled() { $this->markTestSkipped('Retrieving Pid is not supported in sigchild environment'); } public function testExitCodeIsAvailableAfterSignal() { $this->markTestSkipped('Signal is not supported in sigchild environment'); } public function testStartAfterATimeout() { if (defined('PHP_WINDOWS_VERSION_BUILD')) { $this->markTestSkipped('Restarting a timed-out process on Windows is not supported in sigchild environment'); } parent::testStartAfterATimeout(); } /** * {@inheritdoc} */ protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array()) { $process = new ProcessInSigchildEnvironment($commandline, $cwd, $env, $stdin, $timeout, $options); $process->setEnhanceSigchildCompatibility(true); return $process; } } PK!p\H"Component/Process/phpunit.xml.distnu[ ./Tests/ ./ ./Tests PK!KKComponent/Config/CHANGELOG.mdnu[CHANGELOG ========= 2.2.0 ----- * added ArrayNodeDefinition::canBeEnabled() and ArrayNodeDefinition::canBeDisabled() to ease configuration when some sections are respectively disabled / enabled by default. * added a `normalizeKeys()` method for array nodes (to avoid key normalization) * added numerical type handling for config definitions * added convenience methods for optional configuration sections to ArrayNodeDefinition * added a utils class for XML manipulations 2.1.0 ----- * added a way to add documentation on configuration * implemented `Serializable` on resources * LoaderResolverInterface is now used instead of LoaderResolver for type hinting PK!˴Component/Config/composer.jsonnu[{ "name": "symfony/config", "type": "library", "description": "Symfony Config Component", "keywords": [], "homepage": "http://symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "http://symfony.com/contributors" } ], "require": { "php": ">=5.3.3", "symfony/filesystem": "~2.3" }, "autoload": { "psr-0": { "Symfony\\Component\\Config\\": "" } }, "target-dir": "Symfony/Component/Config", "minimum-stability": "dev", "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } PK!!rComponent/Config/README.mdnu[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 --------- You can run the unit tests with the following command: $ cd path/to/Symfony/Component/Config/ $ composer.phar install $ phpunit PK!E))Component/Config/LICENSEnu[Copyright (c) 2004-2014 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!w۴5Component/DomCrawler/Tests/Fixtures/windows-1250.htmlnu[

PK!x0Component/DomCrawler/Tests/Fixtures/no-extensionnu[Test PK!l#8*Component/DomCrawler/Tests/CrawlerTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DomCrawler\Tests; use Symfony\Component\CssSelector\CssSelector; use Symfony\Component\DomCrawler\Crawler; class CrawlerTest extends \PHPUnit_Framework_TestCase { public function testConstructor() { $crawler = new Crawler(); $this->assertCount(0, $crawler, '__construct() returns an empty crawler'); $crawler = new Crawler(new \DOMNode()); $this->assertCount(1, $crawler, '__construct() takes a node as a first argument'); } /** * @covers Symfony\Component\DomCrawler\Crawler::add */ public function testAdd() { $crawler = new Crawler(); $crawler->add($this->createDomDocument()); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMDocument'); $crawler = new Crawler(); $crawler->add($this->createNodeList()); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMNodeList'); foreach ($this->createNodeList() as $node) { $list[] = $node; } $crawler = new Crawler(); $crawler->add($list); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from an array of nodes'); $crawler = new Crawler(); $crawler->add($this->createNodeList()->item(0)); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from an \DOMNode'); $crawler = new Crawler(); $crawler->add('Foo'); $this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string'); } /** * @expectedException \InvalidArgumentException */ public function testAddInvalidNode() { $crawler = new Crawler(); $crawler->add(1); } /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */ public function testAddHtmlContent() { $crawler = new Crawler(); $crawler->addHtmlContent('
', 'UTF-8'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addHtmlContent() adds nodes from an HTML string'); $crawler->addHtmlContent('', 'UTF-8'); $this->assertEquals('http://symfony.com', $crawler->filterXPath('//base')->attr('href'), '->addHtmlContent() adds nodes from an HTML string'); $this->assertEquals('http://symfony.com/contact', $crawler->filterXPath('//a')->link()->getUri(), '->addHtmlContent() adds nodes from an HTML string'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */ public function testAddHtmlContentCharset() { $crawler = new Crawler(); $crawler->addHtmlContent('
Tiếng Việt', 'UTF-8'); $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text()); } /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */ public function testAddHtmlContentInvalidBaseTag() { $crawler = new Crawler(null, 'http://symfony.com'); $crawler->addHtmlContent('', 'UTF-8'); $this->assertEquals('http://symfony.com/contact', current($crawler->filterXPath('//a')->links())->getUri(), '->addHtmlContent() correctly handles a non-existent base tag href attribute'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */ public function testAddHtmlContentUnsupportedCharset() { $crawler = new Crawler(); $crawler->addHtmlContent(file_get_contents(__DIR__.'/Fixtures/windows-1250.html'), 'Windows-1250'); $this->assertEquals('Žťčýů', $crawler->filterXPath('//p')->text()); } /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */ public function testAddHtmlContentCharsetGbk() { $crawler = new Crawler(); //gbk encode of

中文

$crawler->addHtmlContent(base64_decode('PGh0bWw+PHA+1tDOxDwvcD48L2h0bWw+'), 'gbk'); $this->assertEquals('中文', $crawler->filterXPath('//p')->text()); } /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */ public function testAddHtmlContentWithErrors() { $internalErrors = libxml_use_internal_errors(true); $crawler = new Crawler(); $crawler->addHtmlContent(<< EOF , 'UTF-8'); $errors = libxml_get_errors(); $this->assertCount(1, $errors); $this->assertEquals("Tag nav invalid\n", $errors[0]->message); libxml_clear_errors(); libxml_use_internal_errors($internalErrors); } /** * @covers Symfony\Component\DomCrawler\Crawler::addXmlContent */ public function testAddXmlContent() { $crawler = new Crawler(); $crawler->addXmlContent('
', 'UTF-8'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addXmlContent() adds nodes from an XML string'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addXmlContent */ public function testAddXmlContentCharset() { $crawler = new Crawler(); $crawler->addXmlContent('
Tiếng Việt
', 'UTF-8'); $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text()); } /** * @covers Symfony\Component\DomCrawler\Crawler::addXmlContent */ public function testAddXmlContentWithErrors() { $internalErrors = libxml_use_internal_errors(true); $crawler = new Crawler(); $crawler->addXmlContent(<<
EOF , 'UTF-8'); $this->assertTrue(count(libxml_get_errors()) > 1); libxml_clear_errors(); libxml_use_internal_errors($internalErrors); } /** * @covers Symfony\Component\DomCrawler\Crawler::addContent */ public function testAddContent() { $crawler = new Crawler(); $crawler->addContent('
', 'text/html; charset=UTF-8'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string'); $crawler = new Crawler(); $crawler->addContent('
', 'text/html; charset=UTF-8; dir=RTL'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string with extended content type'); $crawler = new Crawler(); $crawler->addContent('
'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() uses text/html as the default type'); $crawler = new Crawler(); $crawler->addContent('
', 'text/xml; charset=UTF-8'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string'); $crawler = new Crawler(); $crawler->addContent('
', 'text/xml'); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string'); $crawler = new Crawler(); $crawler->addContent('foo bar', 'text/plain'); $this->assertCount(0, $crawler, '->addContent() does nothing if the type is not (x|ht)ml'); $crawler = new Crawler(); $crawler->addContent('中文'); $this->assertEquals('中文', $crawler->filterXPath('//span')->text(), '->addContent() guess wrong charset'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addDocument */ public function testAddDocument() { $crawler = new Crawler(); $crawler->addDocument($this->createDomDocument()); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addDocument() adds nodes from a \DOMDocument'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addNodeList */ public function testAddNodeList() { $crawler = new Crawler(); $crawler->addNodeList($this->createNodeList()); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodeList() adds nodes from a \DOMNodeList'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addNodes */ public function testAddNodes() { foreach ($this->createNodeList() as $node) { $list[] = $node; } $crawler = new Crawler(); $crawler->addNodes($list); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodes() adds nodes from an array of nodes'); } /** * @covers Symfony\Component\DomCrawler\Crawler::addNode */ public function testAddNode() { $crawler = new Crawler(); $crawler->addNode($this->createNodeList()->item(0)); $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNode() adds nodes from an \DOMNode'); } public function testClear() { $crawler = new Crawler(new \DOMNode()); $crawler->clear(); $this->assertCount(0, $crawler, '->clear() removes all the nodes from the crawler'); } public function testEq() { $crawler = $this->createTestCrawler()->filterXPath('//li'); $this->assertNotSame($crawler, $crawler->eq(0), '->eq() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->eq() returns a new instance of a crawler'); $this->assertEquals('Two', $crawler->eq(1)->text(), '->eq() returns the nth node of the list'); $this->assertCount(0, $crawler->eq(100), '->eq() returns an empty crawler if the nth node does not exist'); } public function testEach() { $data = $this->createTestCrawler()->filterXPath('//ul[1]/li')->each(function ($node, $i) { return $i.'-'.$node->text(); }); $this->assertEquals(array('0-One', '1-Two', '2-Three'), $data, '->each() executes an anonymous function on each node of the list'); } public function testReduce() { $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li'); $nodes = $crawler->reduce(function ($node, $i) { return $i == 1 ? false : true; }); $this->assertNotSame($nodes, $crawler, '->reduce() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $nodes, '->reduce() returns a new instance of a crawler'); $this->assertCount(2, $nodes, '->reduce() filters the nodes in the list'); } public function testAttr() { $this->assertEquals('first', $this->createTestCrawler()->filterXPath('//li')->attr('class'), '->attr() returns the attribute of the first element of the node list'); try { $this->createTestCrawler()->filterXPath('//ol')->attr('class'); $this->fail('->attr() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->attr() throws an \InvalidArgumentException if the node list is empty'); } } public function testMissingAttrValueIsNull() { $crawler = new Crawler(); $crawler->addContent('
', 'text/html; charset=UTF-8'); $div = $crawler->filterXPath('//div'); $this->assertEquals('sample value', $div->attr('non-empty-attr'), '->attr() reads non-empty attributes correctly'); $this->assertEquals('', $div->attr('empty-attr'), '->attr() reads empty attributes correctly'); $this->assertNull($div->attr('missing-attr'), '->attr() reads missing attributes correctly'); } public function testText() { $this->assertEquals('One', $this->createTestCrawler()->filterXPath('//li')->text(), '->text() returns the node value of the first element of the node list'); try { $this->createTestCrawler()->filterXPath('//ol')->text(); $this->fail('->text() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->text() throws an \InvalidArgumentException if the node list is empty'); } } public function testHtml() { $this->assertEquals('Bar', $this->createTestCrawler()->filterXPath('//a[5]')->html()); $this->assertEquals('' , trim($this->createTestCrawler()->filterXPath('//form[@id="FooFormId"]')->html())); try { $this->createTestCrawler()->filterXPath('//ol')->html(); $this->fail('->html() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->html() throws an \InvalidArgumentException if the node list is empty'); } } public function testExtract() { $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li'); $this->assertEquals(array('One', 'Two', 'Three'), $crawler->extract('_text'), '->extract() returns an array of extracted data from the node list'); $this->assertEquals(array(array('One', 'first'), array('Two', ''), array('Three', '')), $crawler->extract(array('_text', 'class')), '->extract() returns an array of extracted data from the node list'); $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->extract('_text'), '->extract() returns an empty array if the node list is empty'); } /** * @covers Symfony\Component\DomCrawler\Crawler::filterXPath */ public function testFilterXPath() { $crawler = $this->createTestCrawler(); $this->assertNotSame($crawler, $crawler->filterXPath('//li'), '->filterXPath() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filterXPath() returns a new instance of a crawler'); $crawler = $this->createTestCrawler()->filterXPath('//ul'); $this->assertCount(6, $crawler->filterXPath('//li'), '->filterXPath() filters the node list with the XPath expression'); } public function testFilterXPathWithDefaultNamespace() { $crawler = $this->createTestXmlCrawler()->filterXPath('//default:entry/default:id'); $this->assertCount(1, $crawler, '->filterXPath() automatically registers a namespace'); $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text()); } public function testFilterXPathWithCustomDefaultNamespace() { $crawler = $this->createTestXmlCrawler(); $crawler->setDefaultNamespacePrefix('x'); $crawler = $crawler->filterXPath('//x:entry/x:id'); $this->assertCount(1, $crawler, '->filterXPath() lets to override the default namespace prefix'); $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text()); } public function testFilterXPathWithNamespace() { $crawler = $this->createTestXmlCrawler()->filterXPath('//yt:accessControl'); $this->assertCount(2, $crawler, '->filterXPath() automatically registers a namespace'); } public function testFilterXPathWithMultipleNamespaces() { $crawler = $this->createTestXmlCrawler()->filterXPath('//media:group/yt:aspectRatio'); $this->assertCount(1, $crawler, '->filterXPath() automatically registers multiple namespaces'); $this->assertSame('widescreen', $crawler->text()); } public function testFilterXPathWithManuallyRegisteredNamespace() { $crawler = $this->createTestXmlCrawler(); $crawler->registerNamespace('m', 'http://search.yahoo.com/mrss/'); $crawler = $crawler->filterXPath('//m:group/yt:aspectRatio'); $this->assertCount(1, $crawler, '->filterXPath() uses manually registered namespace'); $this->assertSame('widescreen', $crawler->text()); } public function testFilterXPathWithAnUrl() { $crawler = $this->createTestXmlCrawler(); $crawler = $crawler->filterXPath('//media:category[@scheme="http://gdata.youtube.com/schemas/2007/categories.cat"]'); $this->assertCount(1, $crawler); $this->assertSame('Music', $crawler->text()); } /** * @covers Symfony\Component\DomCrawler\Crawler::filter */ public function testFilter() { $crawler = $this->createTestCrawler(); $this->assertNotSame($crawler, $crawler->filter('li'), '->filter() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filter() returns a new instance of a crawler'); $crawler = $this->createTestCrawler()->filter('ul'); $this->assertCount(6, $crawler->filter('li'), '->filter() filters the node list with the CSS selector'); } public function testFilterWithDefaultNamespace() { $crawler = $this->createTestXmlCrawler()->filter('default|entry default|id'); $this->assertCount(1, $crawler, '->filter() automatically registers namespaces'); $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text()); } public function testFilterWithNamespace() { CssSelector::disableHtmlExtension(); $crawler = $this->createTestXmlCrawler()->filter('yt|accessControl'); $this->assertCount(2, $crawler, '->filter() automatically registers namespaces'); } public function testFilterWithMultipleNamespaces() { CssSelector::disableHtmlExtension(); $crawler = $this->createTestXmlCrawler()->filter('media|group yt|aspectRatio'); $this->assertCount(1, $crawler, '->filter() automatically registers namespaces'); $this->assertSame('widescreen', $crawler->text()); } public function testFilterWithDefaultNamespaceOnly() { $crawler = new Crawler(' http://localhost/foo weekly 0.5 2012-11-16 http://localhost/bar weekly 0.5 2012-11-16 '); $this->assertEquals(2, $crawler->filter('url')->count()); } public function testSelectLink() { $crawler = $this->createTestCrawler(); $this->assertNotSame($crawler, $crawler->selectLink('Foo'), '->selectLink() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectLink() returns a new instance of a crawler'); $this->assertCount(1, $crawler->selectLink('Fabien\'s Foo'), '->selectLink() selects links by the node values'); $this->assertCount(1, $crawler->selectLink('Fabien\'s Bar'), '->selectLink() selects links by the alt attribute of a clickable image'); $this->assertCount(2, $crawler->selectLink('Fabien"s Foo'), '->selectLink() selects links by the node values'); $this->assertCount(2, $crawler->selectLink('Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image'); $this->assertCount(1, $crawler->selectLink('\' Fabien"s Foo'), '->selectLink() selects links by the node values'); $this->assertCount(1, $crawler->selectLink('\' Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image'); $this->assertCount(4, $crawler->selectLink('Foo'), '->selectLink() selects links by the node values'); $this->assertCount(4, $crawler->selectLink('Bar'), '->selectLink() selects links by the node values'); } public function testSelectButton() { $crawler = $this->createTestCrawler(); $this->assertNotSame($crawler, $crawler->selectButton('FooValue'), '->selectButton() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectButton() returns a new instance of a crawler'); $this->assertEquals(1, $crawler->selectButton('FooValue')->count(), '->selectButton() selects buttons'); $this->assertEquals(1, $crawler->selectButton('FooName')->count(), '->selectButton() selects buttons'); $this->assertEquals(1, $crawler->selectButton('FooId')->count(), '->selectButton() selects buttons'); $this->assertEquals(1, $crawler->selectButton('BarValue')->count(), '->selectButton() selects buttons'); $this->assertEquals(1, $crawler->selectButton('BarName')->count(), '->selectButton() selects buttons'); $this->assertEquals(1, $crawler->selectButton('BarId')->count(), '->selectButton() selects buttons'); $this->assertEquals(1, $crawler->selectButton('FooBarValue')->count(), '->selectButton() selects buttons with form attribute too'); $this->assertEquals(1, $crawler->selectButton('FooBarName')->count(), '->selectButton() selects buttons with form attribute too'); } public function testLink() { $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $crawler->link(), '->link() returns a Link instance'); $this->assertEquals('POST', $crawler->link('post')->getMethod(), '->link() takes a method as its argument'); $crawler = $this->createTestCrawler('http://example.com/bar')->selectLink('GetLink'); $this->assertEquals('http://example.com/bar?get=param', $crawler->link()->getUri(), '->link() returns a Link instance'); try { $this->createTestCrawler()->filterXPath('//ol')->link(); $this->fail('->link() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->link() throws an \InvalidArgumentException if the node list is empty'); } } public function testLinks() { $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo'); $this->assertInternalType('array', $crawler->links(), '->links() returns an array'); $this->assertCount(4, $crawler->links(), '->links() returns an array'); $links = $crawler->links(); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $links[0], '->links() returns an array of Link instances'); $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->links(), '->links() returns an empty array if the node selection is empty'); } public function testForm() { $testCrawler = $this->createTestCrawler('http://example.com/bar/'); $crawler = $testCrawler->selectButton('FooValue'); $crawler2 = $testCrawler->selectButton('FooBarValue'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler->form(), '->form() returns a Form instance'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler2->form(), '->form() returns a Form instance'); $this->assertEquals($crawler->form()->getFormNode()->getAttribute('id'), $crawler2->form()->getFormNode()->getAttribute('id'), '->form() works on elements with form attribute'); $this->assertEquals(array('FooName' => 'FooBar', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler->form(array('FooName' => 'FooBar'))->getValues(), '->form() takes an array of values to submit as its first argument'); $this->assertEquals(array('FooName' => 'FooValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler->form()->getValues(), '->getValues() returns correct form values'); $this->assertEquals(array('FooBarName' => 'FooBarValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler2->form()->getValues(), '->getValues() returns correct form values'); try { $this->createTestCrawler()->filterXPath('//ol')->form(); $this->fail('->form() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->form() throws an \InvalidArgumentException if the node list is empty'); } } public function testLast() { $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li'); $this->assertNotSame($crawler, $crawler->last(), '->last() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->last() returns a new instance of a crawler'); $this->assertEquals('Three', $crawler->last()->text()); } public function testFirst() { $crawler = $this->createTestCrawler()->filterXPath('//li'); $this->assertNotSame($crawler, $crawler->first(), '->first() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->first() returns a new instance of a crawler'); $this->assertEquals('One', $crawler->first()->text()); } public function testSiblings() { $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1); $this->assertNotSame($crawler, $crawler->siblings(), '->siblings() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->siblings() returns a new instance of a crawler'); $nodes = $crawler->siblings(); $this->assertEquals(2, $nodes->count()); $this->assertEquals('One', $nodes->eq(0)->text()); $this->assertEquals('Three', $nodes->eq(1)->text()); $nodes = $this->createTestCrawler()->filterXPath('//li')->eq(0)->siblings(); $this->assertEquals(2, $nodes->count()); $this->assertEquals('Two', $nodes->eq(0)->text()); $this->assertEquals('Three', $nodes->eq(1)->text()); try { $this->createTestCrawler()->filterXPath('//ol')->siblings(); $this->fail('->siblings() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->siblings() throws an \InvalidArgumentException if the node list is empty'); } } public function testNextAll() { $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1); $this->assertNotSame($crawler, $crawler->nextAll(), '->nextAll() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->nextAll() returns a new instance of a crawler'); $nodes = $crawler->nextAll(); $this->assertEquals(1, $nodes->count()); $this->assertEquals('Three', $nodes->eq(0)->text()); try { $this->createTestCrawler()->filterXPath('//ol')->nextAll(); $this->fail('->nextAll() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->nextAll() throws an \InvalidArgumentException if the node list is empty'); } } public function testPreviousAll() { $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(2); $this->assertNotSame($crawler, $crawler->previousAll(), '->previousAll() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->previousAll() returns a new instance of a crawler'); $nodes = $crawler->previousAll(); $this->assertEquals(2, $nodes->count()); $this->assertEquals('Two', $nodes->eq(0)->text()); try { $this->createTestCrawler()->filterXPath('//ol')->previousAll(); $this->fail('->previousAll() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->previousAll() throws an \InvalidArgumentException if the node list is empty'); } } public function testChildren() { $crawler = $this->createTestCrawler()->filterXPath('//ul'); $this->assertNotSame($crawler, $crawler->children(), '->children() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->children() returns a new instance of a crawler'); $nodes = $crawler->children(); $this->assertEquals(3, $nodes->count()); $this->assertEquals('One', $nodes->eq(0)->text()); $this->assertEquals('Two', $nodes->eq(1)->text()); $this->assertEquals('Three', $nodes->eq(2)->text()); try { $this->createTestCrawler()->filterXPath('//ol')->children(); $this->fail('->children() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->children() throws an \InvalidArgumentException if the node list is empty'); } try { $crawler = new Crawler('

'); $crawler->filter('p')->children(); $this->assertTrue(true, '->children() does not trigger a notice if the node has no children'); } catch (\PHPUnit_Framework_Error_Notice $e) { $this->fail('->children() does not trigger a notice if the node has no children'); } } public function testParents() { $crawler = $this->createTestCrawler()->filterXPath('//li[1]'); $this->assertNotSame($crawler, $crawler->parents(), '->parents() returns a new instance of a crawler'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->parents() returns a new instance of a crawler'); $nodes = $crawler->parents(); $this->assertEquals(3, $nodes->count()); $nodes = $this->createTestCrawler()->filterXPath('//html')->parents(); $this->assertEquals(0, $nodes->count()); try { $this->createTestCrawler()->filterXPath('//ol')->parents(); $this->fail('->parents() throws an \InvalidArgumentException if the node list is empty'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->parents() throws an \InvalidArgumentException if the node list is empty'); } } public function testBaseTag() { $crawler = new Crawler('
'); $this->assertEquals('http://base.com/link', $crawler->filterXPath('//a')->link()->getUri()); $crawler = new Crawler('', 'https://domain.com'); $this->assertEquals('https://base.com/link', $crawler->filterXPath('//a')->link()->getUri(), ' tag can use a schema-less URL'); $crawler = new Crawler('', 'https://domain.com'); $this->assertEquals('https://domain.com/path/link', $crawler->filterXPath('//a')->link()->getUri(), ' tag can set a path'); } public function createTestCrawler($uri = null) { $dom = new \DOMDocument(); $dom->loadHTML(' Foo Fabien\'s Foo Fabien"s Foo \' Fabien"s Foo Bar    Fabien\'s Bar   Fabien"s Bar \' Fabien"s Bar GetLink
', array('bar' => array('InputFormField', 'bar')), ), array( 'appends the submitted button value but not other submit buttons', ' ', array('foobar' => array('InputFormField', 'foobar')), ), array( 'turns an image input into x and y fields', '', array('bar.x' => array('InputFormField', '0'), 'bar.y' => array('InputFormField', '0')), ), array( 'returns textareas', ' ', array('foo' => array('TextareaFormField', 'foo')), ), array( 'returns inputs', ' ', array('foo' => array('InputFormField', 'foo')), ), array( 'returns checkboxes', ' ', array('foo' => array('ChoiceFormField', 'foo')), ), array( 'returns not-checked checkboxes', ' ', array('foo' => array('ChoiceFormField', false)), ), array( 'returns radio buttons', ' ', array('foo' => array('ChoiceFormField', 'bar')), ), array( 'returns file inputs', ' ', array('foo' => array('FileFormField', array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), ), ); } public function testGetFormNode() { $dom = new \DOMDocument(); $dom->loadHTML('
'); $form = new Form($dom->getElementsByTagName('input')->item(0), 'http://example.com'); $this->assertSame($dom->getElementsByTagName('form')->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form'); } public function testGetFormNodeFromNamedForm() { $dom = new \DOMDocument(); $dom->loadHTML('
'); $form = new Form($dom->getElementsByTagName('form')->item(0), 'http://example.com'); $this->assertSame($dom->getElementsByTagName('form')->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form'); } public function testGetMethod() { $form = $this->createForm('
'); $this->assertEquals('GET', $form->getMethod(), '->getMethod() returns get if no method is defined'); $form = $this->createForm('
'); $this->assertEquals('POST', $form->getMethod(), '->getMethod() returns the method attribute value of the form'); $form = $this->createForm('
', 'put'); $this->assertEquals('PUT', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided'); $form = $this->createForm('
', 'delete'); $this->assertEquals('DELETE', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided'); $form = $this->createForm('
', 'patch'); $this->assertEquals('PATCH', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided'); } public function testGetSetValue() { $form = $this->createForm('
'); $this->assertEquals('foo', $form['foo']->getValue(), '->offsetGet() returns the value of a form field'); $form['foo'] = 'bar'; $this->assertEquals('bar', $form['foo']->getValue(), '->offsetSet() changes the value of a form field'); try { $form['foobar'] = 'bar'; $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the field does not exist'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the field does not exist'); } try { $form['foobar']; $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the field does not exist'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the field does not exist'); } } public function testSetValueOnMultiValuedFieldsWithMalformedName() { $form = $this->createForm('
'); try { $form['foo[bar'] = 'bar'; $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the name is malformed.'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the name is malformed.'); } } public function testDisableValidation() { $form = $this->createForm('
'); $form->disableValidation(); $form['foo[bar]']->select('foo'); $form['foo[baz]']->select('bar'); $this->assertEquals('foo', $form['foo[bar]']->getValue(), '->disableValidation() disables validation of all ChoiceFormField.'); $this->assertEquals('bar', $form['foo[baz]']->getValue(), '->disableValidation() disables validation of all ChoiceFormField.'); } public function testOffsetUnset() { $form = $this->createForm('
'); unset($form['foo']); $this->assertFalse(isset($form['foo']), '->offsetUnset() removes a field'); } public function testOffsetExists() { $form = $this->createForm('
'); $this->assertTrue(isset($form['foo']), '->offsetExists() return true if the field exists'); $this->assertFalse(isset($form['bar']), '->offsetExists() return false if the field does not exist'); } public function testGetValues() { $form = $this->createForm('
'); $this->assertEquals(array('foo[bar]' => 'foo', 'bar' => 'bar'), $form->getValues(), '->getValues() returns all form field values'); $form = $this->createForm('
'); $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include not-checked checkboxes'); $form = $this->createForm('
'); $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include file input fields'); $form = $this->createForm('
'); $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include disabled fields'); } public function testSetValues() { $form = $this->createForm('
'); $form->setValues(array('foo' => false, 'bar' => 'foo')); $this->assertEquals(array('bar' => 'foo'), $form->getValues(), '->setValues() sets the values of fields'); } public function testMultiselectSetValues() { $form = $this->createForm('
'); $form->setValues(array('multi' => array("foo", "bar"))); $this->assertEquals(array('multi' => array('foo', 'bar')), $form->getValues(), '->setValue() sets the values of select'); } public function testGetPhpValues() { $form = $this->createForm('
'); $this->assertEquals(array('foo' => array('bar' => 'foo'), 'bar' => 'bar'), $form->getPhpValues(), '->getPhpValues() converts keys with [] to arrays'); $form = $this->createForm('
'); $this->assertEquals(array('fo.o' => array('ba.r' => 'foo'), 'ba r' => 'bar'), $form->getPhpValues(), '->getPhpValues() preserves periods and spaces in names'); $form = $this->createForm('
'); $this->assertEquals(array('fo.o' => array('ba.r' => array('foo', 'ba.z' => 'bar'))), $form->getPhpValues(), '->getPhpValues() preserves periods and spaces in names recursively'); } public function testGetFiles() { $form = $this->createForm('
'); $this->assertEquals(array(), $form->getFiles(), '->getFiles() returns an empty array if method is get'); $form = $this->createForm('
'); $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for POST'); $form = $this->createForm('
', 'put'); $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for PUT'); $form = $this->createForm('
', 'delete'); $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for DELETE'); $form = $this->createForm('
', 'patch'); $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for PATCH'); $form = $this->createForm('
'); $this->assertEquals(array(), $form->getFiles(), '->getFiles() does not include disabled file fields'); } public function testGetPhpFiles() { $form = $this->createForm('
'); $this->assertEquals(array('foo' => array('bar' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), $form->getPhpFiles(), '->getPhpFiles() converts keys with [] to arrays'); $form = $this->createForm('
'); $this->assertEquals(array('f.o o' => array('bar' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), $form->getPhpFiles(), '->getPhpFiles() preserves periods and spaces in names'); $form = $this->createForm('
'); $this->assertEquals(array('f.o o' => array('bar' => array('ba.z' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0), array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)))), $form->getPhpFiles(), '->getPhpFiles() preserves periods and spaces in names recursively'); } /** * @dataProvider provideGetUriValues */ public function testGetUri($message, $form, $values, $uri, $method = null) { $form = $this->createForm($form, $method); $form->setValues($values); $this->assertEquals('http://example.com'.$uri, $form->getUri(), '->getUri() '.$message); } public function testGetBaseUri() { $dom = new \DOMDocument(); $dom->loadHTML('
'); $nodes = $dom->getElementsByTagName('input'); $form = new Form($nodes->item($nodes->length - 1), 'http://www.foo.com/'); $this->assertEquals('http://www.foo.com/foo.php', $form->getUri()); } public function testGetUriWithAnchor() { $form = $this->createForm('
', null, 'http://example.com/id/123'); $this->assertEquals('http://example.com/id/123#foo', $form->getUri()); } public function testGetUriActionAbsolute() { $formHtml='
'; $form = $this->createForm($formHtml); $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form'); $form = $this->createForm($formHtml, null, 'https://login.foo.com'); $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form'); $form = $this->createForm($formHtml, null, 'https://login.foo.com/bar/'); $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form'); // The action URI haven't the same domain Host have an another domain as Host $form = $this->createForm($formHtml, null, 'https://www.foo.com'); $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form'); $form = $this->createForm($formHtml, null, 'https://www.foo.com/bar/'); $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form'); } public function testGetUriAbsolute() { $form = $this->createForm('
', null, 'http://localhost/foo/'); $this->assertEquals('http://localhost/foo/foo', $form->getUri(), '->getUri() returns absolute URIs'); $form = $this->createForm('
', null, 'http://localhost/foo/'); $this->assertEquals('http://localhost/foo', $form->getUri(), '->getUri() returns absolute URIs'); } public function testGetUriWithOnlyQueryString() { $form = $this->createForm('
', null, 'http://localhost/foo/bar'); $this->assertEquals('http://localhost/foo/bar?get=param', $form->getUri(), '->getUri() returns absolute URIs only if the host has been defined in the constructor'); } public function testGetUriWithoutAction() { $form = $this->createForm('
', null, 'http://localhost/foo/bar'); $this->assertEquals('http://localhost/foo/bar', $form->getUri(), '->getUri() returns path if no action defined'); } public function provideGetUriValues() { return array( array( 'returns the URI of the form', '
', array(), '/foo' ), array( 'appends the form values if the method is get', '
', array(), '/foo?foo=foo' ), array( 'appends the form values and merges the submitted values', '
', array('foo' => 'bar'), '/foo?foo=bar' ), array( 'does not append values if the method is post', '
', array(), '/foo' ), array( 'does not append values if the method is patch', '
', array(), '/foo', 'PUT' ), array( 'does not append values if the method is delete', '
', array(), '/foo', 'DELETE' ), array( 'does not append values if the method is put', '
', array(), '/foo', 'PATCH' ), array( 'appends the form values to an existing query string', '
', array(), '/foo?bar=bar&foo=foo' ), array( 'returns an empty URI if the action is empty', '
', array(), '/', ), array( 'appends the form values even if the action is empty', '
', array(), '/?foo=foo', ), array( 'chooses the path if the action attribute value is a sharp (#)', '
', array(), '/#', ), ); } public function testHas() { $form = $this->createForm('
'); $this->assertFalse($form->has('foo'), '->has() returns false if a field is not in the form'); $this->assertTrue($form->has('bar'), '->has() returns true if a field is in the form'); } public function testRemove() { $form = $this->createForm('
'); $form->remove('bar'); $this->assertFalse($form->has('bar'), '->remove() removes a field'); } public function testGet() { $form = $this->createForm('
'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Field\\InputFormField', $form->get('bar'), '->get() returns the field object associated with the given name'); try { $form->get('foo'); $this->fail('->get() throws an \InvalidArgumentException if the field does not exist'); } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->get() throws an \InvalidArgumentException if the field does not exist'); } } public function testAll() { $form = $this->createForm('
'); $fields = $form->all(); $this->assertCount(1, $fields, '->all() return an array of form field objects'); $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Field\\InputFormField', $fields['bar'], '->all() return an array of form field objects'); } public function testSubmitWithoutAFormButton() { $dom = new \DOMDocument(); $dom->loadHTML('
'); $nodes = $dom->getElementsByTagName('form'); $form = new Form($nodes->item(0), 'http://example.com'); $this->assertSame($nodes->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form'); } /** * @expectedException \InvalidArgumentException */ public function testFormFieldRegistryAddThrowAnExceptionWhenTheNameIsMalformed() { $registry = new FormFieldRegistry(); $registry->add($this->getFormFieldMock('[foo]')); } /** * @expectedException \InvalidArgumentException */ public function testFormFieldRegistryRemoveThrowAnExceptionWhenTheNameIsMalformed() { $registry = new FormFieldRegistry(); $registry->remove('[foo]'); } /** * @expectedException \InvalidArgumentException */ public function testFormFieldRegistryGetThrowAnExceptionWhenTheNameIsMalformed() { $registry = new FormFieldRegistry(); $registry->get('[foo]'); } /** * @expectedException \InvalidArgumentException */ public function testFormFieldRegistryGetThrowAnExceptionWhenTheFieldDoesNotExist() { $registry = new FormFieldRegistry(); $registry->get('foo'); } /** * @expectedException \InvalidArgumentException */ public function testFormFieldRegistrySetThrowAnExceptionWhenTheNameIsMalformed() { $registry = new FormFieldRegistry(); $registry->set('[foo]', null); } /** * @expectedException \InvalidArgumentException */ public function testFormFieldRegistrySetThrowAnExceptionWhenTheFieldDoesNotExist() { $registry = new FormFieldRegistry(); $registry->set('foo', null); } public function testFormFieldRegistryHasReturnsTrueWhenTheFQNExists() { $registry = new FormFieldRegistry(); $registry->add($this->getFormFieldMock('foo[bar]')); $this->assertTrue($registry->has('foo')); $this->assertTrue($registry->has('foo[bar]')); $this->assertFalse($registry->has('bar')); $this->assertFalse($registry->has('foo[foo]')); } public function testFormRegistryFieldsCanBeRemoved() { $registry = new FormFieldRegistry(); $registry->add($this->getFormFieldMock('foo')); $registry->remove('foo'); $this->assertFalse($registry->has('foo')); } public function testFormRegistrySupportsMultivaluedFields() { $registry = new FormFieldRegistry(); $registry->add($this->getFormFieldMock('foo[]')); $registry->add($this->getFormFieldMock('foo[]')); $registry->add($this->getFormFieldMock('bar[5]')); $registry->add($this->getFormFieldMock('bar[]')); $registry->add($this->getFormFieldMock('bar[baz]')); $this->assertEquals( array('foo[0]', 'foo[1]', 'bar[5]', 'bar[6]', 'bar[baz]'), array_keys($registry->all()) ); } public function testFormRegistrySetValues() { $registry = new FormFieldRegistry(); $registry->add($f2 = $this->getFormFieldMock('foo[2]')); $registry->add($f3 = $this->getFormFieldMock('foo[3]')); $registry->add($fbb = $this->getFormFieldMock('foo[bar][baz]')); $f2 ->expects($this->exactly(2)) ->method('setValue') ->with(2) ; $f3 ->expects($this->exactly(2)) ->method('setValue') ->with(3) ; $fbb ->expects($this->exactly(2)) ->method('setValue') ->with('fbb') ; $registry->set('foo[2]', 2); $registry->set('foo[3]', 3); $registry->set('foo[bar][baz]', 'fbb'); $registry->set('foo', array( 2 => 2, 3 => 3, 'bar' => array( 'baz' => 'fbb' ) )); } protected function getFormFieldMock($name, $value = null) { $field = $this ->getMockBuilder('Symfony\\Component\\DomCrawler\\Field\\FormField') ->setMethods(array('getName', 'getValue', 'setValue', 'initialize')) ->disableOriginalConstructor() ->getMock() ; $field ->expects($this->any()) ->method('getName') ->will($this->returnValue($name)) ; $field ->expects($this->any()) ->method('getValue') ->will($this->returnValue($value)) ; return $field; } protected function createForm($form, $method = null, $currentUri = null) { $dom = new \DOMDocument(); $dom->loadHTML(''.$form.''); $nodes = $dom->getElementsByTagName('input'); $xPath = new \DOMXPath($dom); $nodes = $xPath->query('//input | //button'); if (null === $currentUri) { $currentUri = 'http://example.com/'; } return new Form($nodes->item($nodes->length - 1), $currentUri, $method); } protected function createTestHtml5Form() { $dom = new \DOMDocument(); $dom->loadHTML('

Hello form