From bcd4b6d14095661402dacbb118930f4d5e00d4c1 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Thu, 24 Jun 2010 11:24:08 +0200 Subject: [PATCH] Adapted Form, Validator, File and I18N component to new coding standards --- .../File/Exception/AccessDeniedException.php | 18 +- .../File/Exception/FileNotFoundException.php | 18 +- src/Symfony/Components/File/File.php | 1095 ++++++------- .../MimeType/ContentTypeMimeTypeGuesser.php | 70 +- .../MimeType/FileBinaryMimeTypeGuesser.php | 68 +- .../File/MimeType/FileinfoMimeTypeGuesser.php | 79 +- .../File/MimeType/MimeTypeGuesser.php | 157 +- .../MimeType/MimeTypeGuesserInterface.php | 18 +- src/Symfony/Components/File/UploadedFile.php | 174 +- src/Symfony/Components/Form/BirthdayField.php | 18 +- src/Symfony/Components/Form/CheckboxField.php | 18 +- src/Symfony/Components/Form/ChoiceField.php | 485 +++--- .../Components/Form/CollectionField.php | 118 +- src/Symfony/Components/Form/Configurable.php | 205 ++- .../Configurator/ConfiguratorInterface.php | 8 +- .../Configurator/ValidatorConfigurator.php | 42 +- src/Symfony/Components/Form/DateField.php | 416 +++-- src/Symfony/Components/Form/DateTimeField.php | 197 ++- .../Exception/InvalidOptionsException.php | 20 +- .../Exception/MissingOptionsException.php | 20 +- src/Symfony/Components/Form/Field.php | 1214 +++++++------- src/Symfony/Components/Form/FieldGroup.php | 1100 ++++++------- .../Components/Form/FieldInterface.php | 436 ++--- src/Symfony/Components/Form/Form.php | 965 ++++++----- src/Symfony/Components/Form/HiddenField.php | 32 +- src/Symfony/Components/Form/HtmlGenerator.php | 218 ++- .../Form/HtmlGeneratorInterface.php | 94 +- src/Symfony/Components/Form/HybridField.php | 129 +- src/Symfony/Components/Form/InputField.php | 24 +- src/Symfony/Components/Form/IntegerField.php | 30 +- ...ecursiveFieldsWithPropertyPathIterator.php | 24 +- src/Symfony/Components/Form/Localizable.php | 12 +- src/Symfony/Components/Form/MoneyField.php | 150 +- src/Symfony/Components/Form/NumberField.php | 44 +- src/Symfony/Components/Form/PasswordField.php | 36 +- src/Symfony/Components/Form/PercentField.php | 42 +- src/Symfony/Components/Form/PropertyPath.php | 261 ++- src/Symfony/Components/Form/RadioField.php | 20 +- .../Components/Form/Renderer/Renderer.php | 134 +- .../Form/Renderer/RendererInterface.php | 52 +- .../Form/Renderer/TableRenderer.php | 54 +- src/Symfony/Components/Form/RepeatedField.php | 127 +- src/Symfony/Components/Form/TextField.php | 36 +- src/Symfony/Components/Form/TextareaField.php | 26 +- src/Symfony/Components/Form/TimeField.php | 245 ++- src/Symfony/Components/Form/TimezoneField.php | 127 +- src/Symfony/Components/Form/ToggleField.php | 62 +- src/Symfony/Components/Form/Translatable.php | 12 +- .../BaseDateTimeTransformer.php | 65 +- .../ValueTransformer/BaseValueTransformer.php | 50 +- .../BooleanToStringTransformer.php | 50 +- .../DateTimeToArrayTransformer.php | 154 +- .../DateTimeToLocalizedStringTransformer.php | 168 +- .../MoneyToLocalizedStringTransformer.php | 67 +- .../NumberToLocalizedStringTransformer.php | 125 +- .../PercentToLocalizedStringTransformer.php | 161 +- .../ValueTransformer/ReversedTransformer.php | 70 +- .../StringToDateTimeTransformer.php | 99 +- .../TimestampToDateTimeTransformer.php | 95 +- .../ValueTransformerChain.php | 117 +- .../ValueTransformerInterface.php | 46 +- .../Components/I18N/TranslatorInterface.php | 20 +- .../Components/Validator/Constraint.php | 259 ++- .../Validator/ConstraintValidator.php | 44 +- .../Validator/ConstraintValidatorFactory.php | 19 +- .../ConstraintValidatorFactoryInterface.php | 2 +- .../ConstraintValidatorInterface.php | 8 +- .../Validator/ConstraintViolation.php | 54 +- .../Validator/ConstraintViolationList.php | 60 +- .../Components/Validator/Constraints/All.php | 18 +- .../Validator/Constraints/AllValidator.php | 52 +- .../Validator/Constraints/AssertFalse.php | 2 +- .../Constraints/AssertFalseValidator.php | 26 +- .../Validator/Constraints/AssertTrue.php | 2 +- .../Constraints/AssertTrueValidator.php | 26 +- .../Validator/Constraints/AssertType.php | 32 +- .../Constraints/AssertTypeValidator.php | 44 +- .../Validator/Constraints/Blank.php | 2 +- .../Validator/Constraints/BlankValidator.php | 15 +- .../Validator/Constraints/Choice.php | 30 +- .../Validator/Constraints/ChoiceValidator.php | 114 +- .../Validator/Constraints/Collection.php | 18 +- .../Constraints/CollectionValidator.php | 112 +- .../Components/Validator/Constraints/Date.php | 2 +- .../Validator/Constraints/DateTime.php | 2 +- .../Constraints/DateTimeValidator.php | 41 +- .../Validator/Constraints/DateValidator.php | 41 +- .../Validator/Constraints/Email.php | 4 +- .../Validator/Constraints/EmailValidator.php | 130 +- .../Components/Validator/Constraints/File.php | 12 +- .../Validator/Constraints/FileValidator.php | 152 +- .../Components/Validator/Constraints/Max.php | 32 +- .../Validator/Constraints/MaxLength.php | 34 +- .../Constraints/MaxLengthValidator.php | 49 +- .../Validator/Constraints/MaxValidator.php | 41 +- .../Components/Validator/Constraints/Min.php | 32 +- .../Validator/Constraints/MinLength.php | 34 +- .../Constraints/MinLengthValidator.php | 49 +- .../Validator/Constraints/MinValidator.php | 41 +- .../Validator/Constraints/NotBlank.php | 2 +- .../Constraints/NotBlankValidator.php | 15 +- .../Validator/Constraints/NotNull.php | 2 +- .../Constraints/NotNullValidator.php | 15 +- .../Components/Validator/Constraints/Null.php | 2 +- .../Validator/Constraints/NullValidator.php | 15 +- .../Validator/Constraints/Regex.php | 34 +- .../Validator/Constraints/RegexValidator.php | 48 +- .../Components/Validator/Constraints/Time.php | 2 +- .../Validator/Constraints/TimeValidator.php | 41 +- .../Components/Validator/Constraints/Url.php | 4 +- .../Validator/Constraints/UrlValidator.php | 63 +- .../Validator/Constraints/Valid.php | 4 +- .../Validator/Constraints/ValidValidator.php | 55 +- .../Validator/Constraints/Validation.php | 10 +- .../DependencyInjectionValidatorFactory.php | 81 +- .../Exception/InvalidOptionsException.php | 20 +- .../Exception/MissingOptionsException.php | 20 +- .../Exception/UnexpectedTypeException.php | 8 +- .../DependencyInjectionValidatorFactory.php | 86 +- .../Components/Validator/GraphWalker.php | 119 +- .../Components/Validator/GroupChain.php | 42 +- .../Validator/Mapping/ClassMetadata.php | 384 +++-- .../Mapping/ClassMetadataFactory.php | 59 +- .../Mapping/ClassMetadataFactoryInterface.php | 2 +- .../Validator/Mapping/ElementMetadata.php | 127 +- .../Validator/Mapping/GetterMetadata.php | 71 +- .../Mapping/Loader/AnnotationLoader.php | 88 +- .../Validator/Mapping/Loader/FileLoader.php | 22 +- .../Validator/Mapping/Loader/FilesLoader.php | 54 +- .../Validator/Mapping/Loader/LoaderChain.php | 57 +- .../Mapping/Loader/LoaderInterface.php | 10 +- .../Mapping/Loader/StaticMethodLoader.php | 50 +- .../Mapping/Loader/XmlFileLoader.php | 355 ++-- .../Mapping/Loader/XmlFilesLoader.php | 14 +- .../Mapping/Loader/YamlFileLoader.php | 156 +- .../Mapping/Loader/YamlFilesLoader.php | 14 +- .../Validator/Mapping/MemberMetadata.php | 205 ++- .../Validator/Mapping/PropertyMetadata.php | 57 +- .../MessageInterpolatorInterface.php | 16 +- .../XliffMessageInterpolator.php | 155 +- .../Validator/ValidationContext.php | 166 +- .../Components/Validator/Validator.php | 231 ++- .../Validator/ValidatorInterface.php | 8 +- .../Tests/Components/File/FileTest.php | 94 +- .../Components/File/UploadedFileTest.php | 50 +- .../Components/Form/CheckboxFieldTest.php | 18 +- .../Tests/Components/Form/ChoiceFieldTest.php | 434 ++--- .../Components/Form/CollectionFieldTest.php | 146 +- .../Tests/Components/Form/DateFieldTest.php | 256 +-- .../Components/Form/DateTimeFieldTest.php | 280 ++-- .../Components/Form/DateTimeTestCase.php | 8 +- .../Tests/Components/Form/FieldGroupTest.php | 1452 ++++++++--------- .../Tests/Components/Form/FieldTest.php | 1204 +++++++------- .../Tests/Components/Form/Fixtures/Author.php | 70 +- .../Components/Form/Fixtures/InvalidField.php | 14 +- .../Form/Fixtures/RequiredOptionsField.php | 16 +- .../Components/Form/Fixtures/TestField.php | 6 +- .../Tests/Components/Form/FormTest.php | 686 ++++---- .../Tests/Components/Form/HiddenFieldTest.php | 34 +- .../Components/Form/HtmlGeneratorTest.php | 138 +- .../Tests/Components/Form/InputFieldTest.php | 32 +- .../Components/Form/IntegerFieldTest.php | 14 +- .../Tests/Components/Form/MoneyFieldTest.php | 48 +- .../Tests/Components/Form/NumberFieldTest.php | 48 +- .../Components/Form/PasswordFieldTest.php | 58 +- .../Components/Form/PercentFieldTest.php | 48 +- .../Components/Form/PropertyPathTest.php | 108 +- .../Tests/Components/Form/RadioFieldTest.php | 36 +- .../Form/Renderer/RendererTestCase.php | 28 +- .../Components/Form/RepeatedFieldTest.php | 62 +- .../Tests/Components/Form/TextFieldTest.php | 28 +- .../Components/Form/TextareaFieldTest.php | 28 +- .../Tests/Components/Form/TimeFieldTest.php | 326 ++-- .../Tests/Components/Form/ToggleFieldTest.php | 82 +- .../BooleanToStringTransformerTest.php | 52 +- .../DateTimeToArrayTransformerTest.php | 270 +-- ...teTimeToLocalizedStringTransformerTest.php | 501 +++--- ...NumberToLocalizedStringTransformerTest.php | 118 +- ...ercentToLocalizedStringTransformerTest.php | 136 +- .../StringToDateTimeTransformerTest.php | 112 +- .../TimestampToDateTimeTransformerTest.php | 132 +- .../ValueTransformerChainTest.php | 86 +- .../Components/Validator/ConstraintTest.php | 106 +- .../Constraints/AllValidatorTest.php | 142 +- .../Constraints/AssertFalseValidatorTest.php | 44 +- .../Constraints/AssertTrueValidatorTest.php | 44 +- .../Constraints/AssertTypeValidatorTest.php | 216 ++- .../Constraints/BlankValidatorTest.php | 80 +- .../Constraints/ChoiceValidatorTest.php | 254 +-- .../Constraints/CollectionValidatorTest.php | 302 ++-- .../Constraints/DateTimeValidatorTest.php | 124 +- .../Constraints/DateValidatorTest.php | 112 +- .../Constraints/EmailValidatorTest.php | 112 +- .../Constraints/FileValidatorTest.php | 250 +-- .../Constraints/MaxLengthValidatorTest.php | 134 +- .../Constraints/MaxValidatorTest.php | 118 +- .../Constraints/MinLengthValidatorTest.php | 134 +- .../Constraints/MinValidatorTest.php | 118 +- .../Constraints/NotBlankValidatorTest.php | 76 +- .../Constraints/NotNullValidatorTest.php | 60 +- .../Constraints/NullValidatorTest.php | 72 +- .../Constraints/RegexValidatorTest.php | 116 +- .../Constraints/TimeValidatorTest.php | 114 +- .../Constraints/UrlValidatorTest.php | 120 +- .../Constraints/ValidValidatorTest.php | 140 +- ...ependencyInjectionValidatorFactoryTest.php | 72 +- ...ependencyInjectionValidatorFactoryTest.php | 72 +- .../Validator/Fixtures/ConstraintA.php | 12 +- .../Fixtures/ConstraintAValidator.php | 15 +- .../Validator/Fixtures/ConstraintC.php | 10 +- .../Components/Validator/Fixtures/Entity.php | 50 +- .../Validator/Fixtures/EntityParent.php | 4 +- .../Validator/Fixtures/FilesLoader.php | 32 +- .../Components/Validator/GraphWalkerTest.php | 116 +- .../Mapping/ClassMetadataFactoryTest.php | 74 +- .../Validator/Mapping/ClassMetadataTest.php | 170 +- .../Validator/Mapping/ElementMetadataTest.php | 54 +- .../Validator/Mapping/GetterMetadataTest.php | 28 +- .../Mapping/Loader/AnnotationLoaderTest.php | 72 +- .../Mapping/Loader/FilesLoaderTest.php | 52 +- .../Mapping/Loader/LoaderChainTest.php | 102 +- .../Mapping/Loader/StaticMethodLoaderTest.php | 48 +- .../Mapping/Loader/XmlFileLoaderTest.php | 68 +- .../Mapping/Loader/YamlFileLoaderTest.php | 68 +- .../Mapping/PropertyMetadataTest.php | 24 +- .../XliffMessageInterpolatorTest.php | 46 +- .../Components/Validator/ValidatorTest.php | 98 +- 227 files changed, 12877 insertions(+), 13518 deletions(-) diff --git a/src/Symfony/Components/File/Exception/AccessDeniedException.php b/src/Symfony/Components/File/Exception/AccessDeniedException.php index eb8a3a4d7b..d60a28cf68 100644 --- a/src/Symfony/Components/File/Exception/AccessDeniedException.php +++ b/src/Symfony/Components/File/Exception/AccessDeniedException.php @@ -17,13 +17,13 @@ namespace Symfony\Components\File\Exception; */ class AccessDeniedException extends FileException { - /** - * Constructor. - * - * @param string $path The path to the accessed file - */ - public function __construct($path) - { - parent::__construct(sprintf('The file %s could not be accessed', $path)); - } + /** + * Constructor. + * + * @param string $path The path to the accessed file + */ + public function __construct($path) + { + parent::__construct(sprintf('The file %s could not be accessed', $path)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/File/Exception/FileNotFoundException.php b/src/Symfony/Components/File/Exception/FileNotFoundException.php index b5cfd1c92c..4118eacf41 100644 --- a/src/Symfony/Components/File/Exception/FileNotFoundException.php +++ b/src/Symfony/Components/File/Exception/FileNotFoundException.php @@ -17,13 +17,13 @@ namespace Symfony\Components\File\Exception; */ class FileNotFoundException extends FileException { - /** - * Constructor. - * - * @param string $path The path to the file that was not found - */ - public function __construct($path) - { - parent::__construct(sprintf('The file %s does not exist', $path)); - } + /** + * Constructor. + * + * @param string $path The path to the file that was not found + */ + public function __construct($path) + { + parent::__construct(sprintf('The file %s does not exist', $path)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/File/File.php b/src/Symfony/Components/File/File.php index 719c33966e..3b10b76e25 100644 --- a/src/Symfony/Components/File/File.php +++ b/src/Symfony/Components/File/File.php @@ -21,566 +21,557 @@ use Symfony\Components\File\MimeType\MimeTypeGuesser; */ class File { - /** - * Assignment of mime types to their default extensions - * @var array - */ - static protected $defaultExtensions = array( - 'application/andrew-inset' => 'ez', - 'application/appledouble' => 'base64', - 'application/applefile' => 'base64', - 'application/commonground' => 'dp', - 'application/cprplayer' => 'pqi', - 'application/dsptype' => 'tsp', - 'application/excel' => 'xls', - 'application/font-tdpfr' => 'pfr', - 'application/futuresplash' => 'spl', - 'application/hstu' => 'stk', - 'application/hyperstudio' => 'stk', - 'application/javascript' => 'js', - 'application/mac-binhex40' => 'hqx', - 'application/mac-compactpro' => 'cpt', - 'application/mbed' => 'mbd', - 'application/mirage' => 'mfp', - 'application/msword' => 'doc', - 'application/ocsp-request' => 'orq', - 'application/ocsp-response' => 'ors', - 'application/octet-stream' => 'bin', - 'application/oda' => 'oda', - 'application/ogg' => 'ogg', - 'application/pdf' => 'pdf', - 'application/x-pdf' => 'pdf', - 'application/pgp-encrypted' => '7bit', - 'application/pgp-keys' => '7bit', - 'application/pgp-signature' => 'sig', - 'application/pkcs10' => 'p10', - 'application/pkcs7-mime' => 'p7m', - 'application/pkcs7-signature' => 'p7s', - 'application/pkix-cert' => 'cer', - 'application/pkix-crl' => 'crl', - 'application/pkix-pkipath' => 'pkipath', - 'application/pkixcmp' => 'pki', - 'application/postscript' => 'ps', - 'application/presentations' => 'shw', - 'application/prs.cww' => 'cw', - 'application/prs.nprend' => 'rnd', - 'application/quest' => 'qrt', - 'application/rtf' => 'rtf', - 'application/sgml-open-catalog' => 'soc', - 'application/sieve' => 'siv', - 'application/smil' => 'smi', - 'application/toolbook' => 'tbk', - 'application/vnd.3gpp.pic-bw-large' => 'plb', - 'application/vnd.3gpp.pic-bw-small' => 'psb', - 'application/vnd.3gpp.pic-bw-var' => 'pvb', - 'application/vnd.3gpp.sms' => 'sms', - 'application/vnd.acucorp' => 'atc', - 'application/vnd.adobe.xfdf' => 'xfdf', - 'application/vnd.amiga.amu' => 'ami', - 'application/vnd.blueice.multipass' => 'mpm', - 'application/vnd.cinderella' => 'cdy', - 'application/vnd.cosmocaller' => 'cmc', - 'application/vnd.criticaltools.wbs+xml' => 'wbs', - 'application/vnd.curl' => 'curl', - 'application/vnd.data-vision.rdz' => 'rdz', - 'application/vnd.dreamfactory' => 'dfac', - 'application/vnd.fsc.weblauch' => 'fsc', - 'application/vnd.genomatix.tuxedo' => 'txd', - 'application/vnd.hbci' => 'hbci', - 'application/vnd.hhe.lesson-player' => 'les', - 'application/vnd.hp-hpgl' => 'plt', - 'application/vnd.ibm.electronic-media' => 'emm', - 'application/vnd.ibm.rights-management' => 'irm', - 'application/vnd.ibm.secure-container' => 'sc', - 'application/vnd.ipunplugged.rcprofile' => 'rcprofile', - 'application/vnd.irepository.package+xml' => 'irp', - 'application/vnd.jisp' => 'jisp', - 'application/vnd.kde.karbon' => 'karbon', - 'application/vnd.kde.kchart' => 'chrt', - 'application/vnd.kde.kformula' => 'kfo', - 'application/vnd.kde.kivio' => 'flw', - 'application/vnd.kde.kontour' => 'kon', - 'application/vnd.kde.kpresenter' => 'kpr', - 'application/vnd.kde.kspread' => 'ksp', - 'application/vnd.kde.kword' => 'kwd', - 'application/vnd.kenameapp' => 'htke', - 'application/vnd.kidspiration' => 'kia', - 'application/vnd.kinar' => 'kne', - 'application/vnd.llamagraphics.life-balance.desktop' => 'lbd', - 'application/vnd.llamagraphics.life-balance.exchange+xml' => 'lbe', - 'application/vnd.lotus-1-2-3' => 'wks', - 'application/vnd.mcd' => 'mcd', - 'application/vnd.mfmp' => 'mfm', - 'application/vnd.micrografx.flo' => 'flo', - 'application/vnd.micrografx.igx' => 'igx', - 'application/vnd.mif' => 'mif', - 'application/vnd.mophun.application' => 'mpn', - 'application/vnd.mophun.certificate' => 'mpc', - 'application/vnd.mozilla.xul+xml' => 'xul', - 'application/vnd.ms-artgalry' => 'cil', - 'application/vnd.ms-asf' => 'asf', - 'application/vnd.ms-excel' => 'xls', - 'application/vnd.ms-excel.sheet.macroenabled.12' => 'xlsm', - 'application/vnd.ms-lrm' => 'lrm', - 'application/vnd.ms-powerpoint' => 'ppt', - 'application/vnd.ms-project' => 'mpp', - 'application/vnd.ms-tnef' => 'base64', - 'application/vnd.ms-works' => 'base64', - 'application/vnd.ms-wpl' => 'wpl', - 'application/vnd.mseq' => 'mseq', - 'application/vnd.nervana' => 'ent', - 'application/vnd.nokia.radio-preset' => 'rpst', - 'application/vnd.nokia.radio-presets' => 'rpss', - 'application/vnd.oasis.opendocument.text' => 'odt', - 'application/vnd.oasis.opendocument.text-template' => 'ott', - 'application/vnd.oasis.opendocument.text-web' => 'oth', - 'application/vnd.oasis.opendocument.text-master' => 'odm', - 'application/vnd.oasis.opendocument.graphics' => 'odg', - 'application/vnd.oasis.opendocument.graphics-template' => 'otg', - 'application/vnd.oasis.opendocument.presentation' => 'odp', - 'application/vnd.oasis.opendocument.presentation-template' => 'otp', - 'application/vnd.oasis.opendocument.spreadsheet' => 'ods', - 'application/vnd.oasis.opendocument.spreadsheet-template' => 'ots', - 'application/vnd.oasis.opendocument.chart' => 'odc', - 'application/vnd.oasis.opendocument.formula' => 'odf', - 'application/vnd.oasis.opendocument.database' => 'odb', - 'application/vnd.oasis.opendocument.image' => 'odi', - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx', - 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => 'dotx', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx', - 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx', - 'application/vnd.palm' => 'prc', - 'application/vnd.picsel' => 'efif', - 'application/vnd.pvi.ptid1' => 'pti', - 'application/vnd.quark.quarkxpress' => 'qxd', - 'application/vnd.sealed.doc' => 'sdoc', - 'application/vnd.sealed.eml' => 'seml', - 'application/vnd.sealed.mht' => 'smht', - 'application/vnd.sealed.ppt' => 'sppt', - 'application/vnd.sealed.xls' => 'sxls', - 'application/vnd.sealedmedia.softseal.html' => 'stml', - 'application/vnd.sealedmedia.softseal.pdf' => 'spdf', - 'application/vnd.seemail' => 'see', - 'application/vnd.smaf' => 'mmf', - 'application/vnd.sun.xml.calc' => 'sxc', - 'application/vnd.sun.xml.calc.template' => 'stc', - 'application/vnd.sun.xml.draw' => 'sxd', - 'application/vnd.sun.xml.draw.template' => 'std', - 'application/vnd.sun.xml.impress' => 'sxi', - 'application/vnd.sun.xml.impress.template' => 'sti', - 'application/vnd.sun.xml.math' => 'sxm', - 'application/vnd.sun.xml.writer' => 'sxw', - 'application/vnd.sun.xml.writer.global' => 'sxg', - 'application/vnd.sun.xml.writer.template' => 'stw', - 'application/vnd.sus-calendar' => 'sus', - 'application/vnd.vidsoft.vidconference' => 'vsc', - 'application/vnd.visio' => 'vsd', - 'application/vnd.visionary' => 'vis', - 'application/vnd.wap.sic' => 'sic', - 'application/vnd.wap.slc' => 'slc', - 'application/vnd.wap.wbxml' => 'wbxml', - 'application/vnd.wap.wmlc' => 'wmlc', - 'application/vnd.wap.wmlscriptc' => 'wmlsc', - 'application/vnd.webturbo' => 'wtb', - 'application/vnd.wordperfect' => 'wpd', - 'application/vnd.wqd' => 'wqd', - 'application/vnd.wv.csp+wbxml' => 'wv', - 'application/vnd.wv.csp+xml' => '8bit', - 'application/vnd.wv.ssp+xml' => '8bit', - 'application/vnd.yamaha.hv-dic' => 'hvd', - 'application/vnd.yamaha.hv-script' => 'hvs', - 'application/vnd.yamaha.hv-voice' => 'hvp', - 'application/vnd.yamaha.smaf-audio' => 'saf', - 'application/vnd.yamaha.smaf-phrase' => 'spf', - 'application/vocaltec-media-desc' => 'vmd', - 'application/vocaltec-media-file' => 'vmf', - 'application/vocaltec-talker' => 'vtk', - 'application/watcherinfo+xml' => 'wif', - 'application/wordperfect5.1' => 'wp5', - 'application/x-123' => 'wk', - 'application/x-7th_level_event' => '7ls', - 'application/x-authorware-bin' => 'aab', - 'application/x-authorware-map' => 'aam', - 'application/x-authorware-seg' => 'aas', - 'application/x-bcpio' => 'bcpio', - 'application/x-bleeper' => 'bleep', - 'application/x-bzip2' => 'bz2', - 'application/x-cdlink' => 'vcd', - 'application/x-chat' => 'chat', - 'application/x-chess-pgn' => 'pgn', - 'application/x-compress' => 'z', - 'application/x-cpio' => 'cpio', - 'application/x-cprplayer' => 'pqf', - 'application/x-csh' => 'csh', - 'application/x-cu-seeme' => 'csm', - 'application/x-cult3d-object' => 'co', - 'application/x-debian-package' => 'deb', - 'application/x-director' => 'dcr', - 'application/x-dvi' => 'dvi', - 'application/x-envoy' => 'evy', - 'application/x-futuresplash' => 'spl', - 'application/x-gtar' => 'gtar', - 'application/x-gzip' => 'gz', - 'application/x-hdf' => 'hdf', - 'application/x-hep' => 'hep', - 'application/x-html+ruby' => 'rhtml', - 'application/x-httpd-miva' => 'mv', - 'application/x-httpd-php' => 'phtml', - 'application/x-ica' => 'ica', - 'application/x-imagemap' => 'imagemap', - 'application/x-ipix' => 'ipx', - 'application/x-ipscript' => 'ips', - 'application/x-java-archive' => 'jar', - 'application/x-java-jnlp-file' => 'jnlp', - 'application/x-java-serialized-object' => 'ser', - 'application/x-java-vm' => 'class', - 'application/x-javascript' => 'js', - 'application/x-koan' => 'skp', - 'application/x-latex' => 'latex', - 'application/x-mac-compactpro' => 'cpt', - 'application/x-maker' => 'frm', - 'application/x-mathcad' => 'mcd', - 'application/x-midi' => 'mid', - 'application/x-mif' => 'mif', - 'application/x-msaccess' => 'mda', - 'application/x-msdos-program' => 'com', - 'application/x-msdownload' => 'base64', - 'application/x-msexcel' => 'xls', - 'application/x-msword' => 'doc', - 'application/x-netcdf' => 'nc', - 'application/x-ns-proxy-autoconfig' => 'pac', - 'application/x-pagemaker' => 'pm5', - 'application/x-perl' => 'pl', - 'application/x-pn-realmedia' => 'rp', - 'application/x-python' => 'py', - 'application/x-quicktimeplayer' => 'qtl', - 'application/x-rar-compressed' => 'rar', - 'application/x-ruby' => 'rb', - 'application/x-sh' => 'sh', - 'application/x-shar' => 'shar', - 'application/x-shockwave-flash' => 'swf', - 'application/x-sprite' => 'spr', - 'application/x-spss' => 'sav', - 'application/x-spt' => 'spt', - 'application/x-stuffit' => 'sit', - 'application/x-sv4cpio' => 'sv4cpio', - 'application/x-sv4crc' => 'sv4crc', - 'application/x-tar' => 'tar', - 'application/x-tcl' => 'tcl', - 'application/x-tex' => 'tex', - 'application/x-texinfo' => 'texinfo', - 'application/x-troff' => 't', - 'application/x-troff-man' => 'man', - 'application/x-troff-me' => 'me', - 'application/x-troff-ms' => 'ms', - 'application/x-twinvq' => 'vqf', - 'application/x-twinvq-plugin' => 'vqe', - 'application/x-ustar' => 'ustar', - 'application/x-vmsbackup' => 'bck', - 'application/x-wais-source' => 'src', - 'application/x-wingz' => 'wz', - 'application/x-word' => 'base64', - 'application/x-wordperfect6.1' => 'wp6', - 'application/x-x509-ca-cert' => 'crt', - 'application/x-zip-compressed' => 'zip', - 'application/xhtml+xml' => 'xhtml', - 'application/zip' => 'zip', - 'audio/3gpp' => '3gpp', - 'audio/amr' => 'amr', - 'audio/amr-wb' => 'awb', - 'audio/basic' => 'au', - 'audio/evrc' => 'evc', - 'audio/l16' => 'l16', - 'audio/midi' => 'mid', - 'audio/mpeg' => 'mp3', - 'audio/prs.sid' => 'sid', - 'audio/qcelp' => 'qcp', - 'audio/smv' => 'smv', - 'audio/vnd.audiokoz' => 'koz', - 'audio/vnd.digital-winds' => 'eol', - 'audio/vnd.everad.plj' => 'plj', - 'audio/vnd.lucent.voice' => 'lvp', - 'audio/vnd.nokia.mobile-xmf' => 'mxmf', - 'audio/vnd.nortel.vbk' => 'vbk', - 'audio/vnd.nuera.ecelp4800' => 'ecelp4800', - 'audio/vnd.nuera.ecelp7470' => 'ecelp7470', - 'audio/vnd.nuera.ecelp9600' => 'ecelp9600', - 'audio/vnd.sealedmedia.softseal.mpeg' => 'smp3', - 'audio/voxware' => 'vox', - 'audio/x-aiff' => 'aif', - 'audio/x-mid' => 'mid', - 'audio/x-midi' => 'mid', - 'audio/x-mpeg' => 'mp2', - 'audio/x-mpegurl' => 'mpu', - 'audio/x-pn-realaudio' => 'rm', - 'audio/x-pn-realaudio-plugin' => 'rpm', - 'audio/x-realaudio' => 'ra', - 'audio/x-wav' => 'wav', - 'chemical/x-csml' => 'csm', - 'chemical/x-embl-dl-nucleotide' => 'emb', - 'chemical/x-gaussian-cube' => 'cube', - 'chemical/x-gaussian-input' => 'gau', - 'chemical/x-jcamp-dx' => 'jdx', - 'chemical/x-mdl-molfile' => 'mol', - 'chemical/x-mdl-rxnfile' => 'rxn', - 'chemical/x-mdl-tgf' => 'tgf', - 'chemical/x-mopac-input' => 'mop', - 'chemical/x-pdb' => 'pdb', - 'chemical/x-rasmol' => 'scr', - 'chemical/x-xyz' => 'xyz', - 'drawing/dwf' => 'dwf', - 'drawing/x-dwf' => 'dwf', - 'i-world/i-vrml' => 'ivr', - 'image/bmp' => 'bmp', - 'image/cewavelet' => 'wif', - 'image/cis-cod' => 'cod', - 'image/fif' => 'fif', - 'image/gif' => 'gif', - 'image/ief' => 'ief', - 'image/jp2' => 'jp2', - 'image/jpeg' => 'jpg', - 'image/jpm' => 'jpm', - 'image/jpx' => 'jpf', - 'image/pict' => 'pic', - 'image/pjpeg' => 'jpg', - 'image/png' => 'png', - 'image/targa' => 'tga', - 'image/tiff' => 'tif', - 'image/vn-svf' => 'svf', - 'image/vnd.dgn' => 'dgn', - 'image/vnd.djvu' => 'djvu', - 'image/vnd.dwg' => 'dwg', - 'image/vnd.glocalgraphics.pgb' => 'pgb', - 'image/vnd.microsoft.icon' => 'ico', - 'image/vnd.ms-modi' => 'mdi', - 'image/vnd.sealed.png' => 'spng', - 'image/vnd.sealedmedia.softseal.gif' => 'sgif', - 'image/vnd.sealedmedia.softseal.jpg' => 'sjpg', - 'image/vnd.wap.wbmp' => 'wbmp', - 'image/x-bmp' => 'bmp', - 'image/x-cmu-raster' => 'ras', - 'image/x-freehand' => 'fh4', - 'image/x-png' => 'png', - 'image/x-portable-anymap' => 'pnm', - 'image/x-portable-bitmap' => 'pbm', - 'image/x-portable-graymap' => 'pgm', - 'image/x-portable-pixmap' => 'ppm', - 'image/x-rgb' => 'rgb', - 'image/x-xbitmap' => 'xbm', - 'image/x-xpixmap' => 'xpm', - 'image/x-xwindowdump' => 'xwd', - 'message/external-body' => '8bit', - 'message/news' => '8bit', - 'message/partial' => '8bit', - 'message/rfc822' => '8bit', - 'model/iges' => 'igs', - 'model/mesh' => 'msh', - 'model/vnd.parasolid.transmit.binary' => 'x_b', - 'model/vnd.parasolid.transmit.text' => 'x_t', - 'model/vrml' => 'wrl', - 'multipart/alternative' => '8bit', - 'multipart/appledouble' => '8bit', - 'multipart/digest' => '8bit', - 'multipart/mixed' => '8bit', - 'multipart/parallel' => '8bit', - 'text/comma-separated-values' => 'csv', - 'text/css' => 'css', - 'text/html' => 'html', - 'text/plain' => 'txt', - 'text/prs.fallenstein.rst' => 'rst', - 'text/richtext' => 'rtx', - 'text/rtf' => 'rtf', - 'text/sgml' => 'sgml', - 'text/tab-separated-values' => 'tsv', - 'text/vnd.net2phone.commcenter.command' => 'ccc', - 'text/vnd.sun.j2me.app-descriptor' => 'jad', - 'text/vnd.wap.si' => 'si', - 'text/vnd.wap.sl' => 'sl', - 'text/vnd.wap.wml' => 'wml', - 'text/vnd.wap.wmlscript' => 'wmls', - 'text/x-hdml' => 'hdml', - 'text/x-setext' => 'etx', - 'text/x-sgml' => 'sgml', - 'text/x-speech' => 'talk', - 'text/x-vcalendar' => 'vcs', - 'text/x-vcard' => 'vcf', - 'text/xml' => 'xml', - 'ulead/vrml' => 'uvr', - 'video/3gpp' => '3gp', - 'video/dl' => 'dl', - 'video/gl' => 'gl', - 'video/mj2' => 'mj2', - 'video/mpeg' => 'mpeg', - 'video/quicktime' => 'mov', - 'video/vdo' => 'vdo', - 'video/vivo' => 'viv', - 'video/vnd.fvt' => 'fvt', - 'video/vnd.mpegurl' => 'mxu', - 'video/vnd.nokia.interleaved-multimedia' => 'nim', - 'video/vnd.objectvideo' => 'mp4', - 'video/vnd.sealed.mpeg1' => 's11', - 'video/vnd.sealed.mpeg4' => 'smpg', - 'video/vnd.sealed.swf' => 'sswf', - 'video/vnd.sealedmedia.softseal.mov' => 'smov', - 'video/vnd.vivo' => 'vivo', - 'video/x-fli' => 'fli', - 'video/x-ms-asf' => 'asf', - 'video/x-ms-wmv' => 'wmv', - 'video/x-msvideo' => 'avi', - 'video/x-sgi-movie' => 'movie', - 'x-chemical/x-pdb' => 'pdb', - 'x-chemical/x-xyz' => 'xyz', - 'x-conference/x-cooltalk' => 'ice', - 'x-drawing/dwf' => 'dwf', - 'x-world/x-d96' => 'd', - 'x-world/x-svr' => 'svr', - 'x-world/x-vream' => 'vrw', - 'x-world/x-vrml' => 'wrl', - ); + /** + * Assignment of mime types to their default extensions + * @var array + */ + static protected $defaultExtensions = array( + 'application/andrew-inset' => 'ez', + 'application/appledouble' => 'base64', + 'application/applefile' => 'base64', + 'application/commonground' => 'dp', + 'application/cprplayer' => 'pqi', + 'application/dsptype' => 'tsp', + 'application/excel' => 'xls', + 'application/font-tdpfr' => 'pfr', + 'application/futuresplash' => 'spl', + 'application/hstu' => 'stk', + 'application/hyperstudio' => 'stk', + 'application/javascript' => 'js', + 'application/mac-binhex40' => 'hqx', + 'application/mac-compactpro' => 'cpt', + 'application/mbed' => 'mbd', + 'application/mirage' => 'mfp', + 'application/msword' => 'doc', + 'application/ocsp-request' => 'orq', + 'application/ocsp-response' => 'ors', + 'application/octet-stream' => 'bin', + 'application/oda' => 'oda', + 'application/ogg' => 'ogg', + 'application/pdf' => 'pdf', + 'application/x-pdf' => 'pdf', + 'application/pgp-encrypted' => '7bit', + 'application/pgp-keys' => '7bit', + 'application/pgp-signature' => 'sig', + 'application/pkcs10' => 'p10', + 'application/pkcs7-mime' => 'p7m', + 'application/pkcs7-signature' => 'p7s', + 'application/pkix-cert' => 'cer', + 'application/pkix-crl' => 'crl', + 'application/pkix-pkipath' => 'pkipath', + 'application/pkixcmp' => 'pki', + 'application/postscript' => 'ps', + 'application/presentations' => 'shw', + 'application/prs.cww' => 'cw', + 'application/prs.nprend' => 'rnd', + 'application/quest' => 'qrt', + 'application/rtf' => 'rtf', + 'application/sgml-open-catalog' => 'soc', + 'application/sieve' => 'siv', + 'application/smil' => 'smi', + 'application/toolbook' => 'tbk', + 'application/vnd.3gpp.pic-bw-large' => 'plb', + 'application/vnd.3gpp.pic-bw-small' => 'psb', + 'application/vnd.3gpp.pic-bw-var' => 'pvb', + 'application/vnd.3gpp.sms' => 'sms', + 'application/vnd.acucorp' => 'atc', + 'application/vnd.adobe.xfdf' => 'xfdf', + 'application/vnd.amiga.amu' => 'ami', + 'application/vnd.blueice.multipass' => 'mpm', + 'application/vnd.cinderella' => 'cdy', + 'application/vnd.cosmocaller' => 'cmc', + 'application/vnd.criticaltools.wbs+xml' => 'wbs', + 'application/vnd.curl' => 'curl', + 'application/vnd.data-vision.rdz' => 'rdz', + 'application/vnd.dreamfactory' => 'dfac', + 'application/vnd.fsc.weblauch' => 'fsc', + 'application/vnd.genomatix.tuxedo' => 'txd', + 'application/vnd.hbci' => 'hbci', + 'application/vnd.hhe.lesson-player' => 'les', + 'application/vnd.hp-hpgl' => 'plt', + 'application/vnd.ibm.electronic-media' => 'emm', + 'application/vnd.ibm.rights-management' => 'irm', + 'application/vnd.ibm.secure-container' => 'sc', + 'application/vnd.ipunplugged.rcprofile' => 'rcprofile', + 'application/vnd.irepository.package+xml' => 'irp', + 'application/vnd.jisp' => 'jisp', + 'application/vnd.kde.karbon' => 'karbon', + 'application/vnd.kde.kchart' => 'chrt', + 'application/vnd.kde.kformula' => 'kfo', + 'application/vnd.kde.kivio' => 'flw', + 'application/vnd.kde.kontour' => 'kon', + 'application/vnd.kde.kpresenter' => 'kpr', + 'application/vnd.kde.kspread' => 'ksp', + 'application/vnd.kde.kword' => 'kwd', + 'application/vnd.kenameapp' => 'htke', + 'application/vnd.kidspiration' => 'kia', + 'application/vnd.kinar' => 'kne', + 'application/vnd.llamagraphics.life-balance.desktop' => 'lbd', + 'application/vnd.llamagraphics.life-balance.exchange+xml' => 'lbe', + 'application/vnd.lotus-1-2-3' => 'wks', + 'application/vnd.mcd' => 'mcd', + 'application/vnd.mfmp' => 'mfm', + 'application/vnd.micrografx.flo' => 'flo', + 'application/vnd.micrografx.igx' => 'igx', + 'application/vnd.mif' => 'mif', + 'application/vnd.mophun.application' => 'mpn', + 'application/vnd.mophun.certificate' => 'mpc', + 'application/vnd.mozilla.xul+xml' => 'xul', + 'application/vnd.ms-artgalry' => 'cil', + 'application/vnd.ms-asf' => 'asf', + 'application/vnd.ms-excel' => 'xls', + 'application/vnd.ms-excel.sheet.macroenabled.12' => 'xlsm', + 'application/vnd.ms-lrm' => 'lrm', + 'application/vnd.ms-powerpoint' => 'ppt', + 'application/vnd.ms-project' => 'mpp', + 'application/vnd.ms-tnef' => 'base64', + 'application/vnd.ms-works' => 'base64', + 'application/vnd.ms-wpl' => 'wpl', + 'application/vnd.mseq' => 'mseq', + 'application/vnd.nervana' => 'ent', + 'application/vnd.nokia.radio-preset' => 'rpst', + 'application/vnd.nokia.radio-presets' => 'rpss', + 'application/vnd.oasis.opendocument.text' => 'odt', + 'application/vnd.oasis.opendocument.text-template' => 'ott', + 'application/vnd.oasis.opendocument.text-web' => 'oth', + 'application/vnd.oasis.opendocument.text-master' => 'odm', + 'application/vnd.oasis.opendocument.graphics' => 'odg', + 'application/vnd.oasis.opendocument.graphics-template' => 'otg', + 'application/vnd.oasis.opendocument.presentation' => 'odp', + 'application/vnd.oasis.opendocument.presentation-template' => 'otp', + 'application/vnd.oasis.opendocument.spreadsheet' => 'ods', + 'application/vnd.oasis.opendocument.spreadsheet-template' => 'ots', + 'application/vnd.oasis.opendocument.chart' => 'odc', + 'application/vnd.oasis.opendocument.formula' => 'odf', + 'application/vnd.oasis.opendocument.database' => 'odb', + 'application/vnd.oasis.opendocument.image' => 'odi', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => 'dotx', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx', + 'application/vnd.palm' => 'prc', + 'application/vnd.picsel' => 'efif', + 'application/vnd.pvi.ptid1' => 'pti', + 'application/vnd.quark.quarkxpress' => 'qxd', + 'application/vnd.sealed.doc' => 'sdoc', + 'application/vnd.sealed.eml' => 'seml', + 'application/vnd.sealed.mht' => 'smht', + 'application/vnd.sealed.ppt' => 'sppt', + 'application/vnd.sealed.xls' => 'sxls', + 'application/vnd.sealedmedia.softseal.html' => 'stml', + 'application/vnd.sealedmedia.softseal.pdf' => 'spdf', + 'application/vnd.seemail' => 'see', + 'application/vnd.smaf' => 'mmf', + 'application/vnd.sun.xml.calc' => 'sxc', + 'application/vnd.sun.xml.calc.template' => 'stc', + 'application/vnd.sun.xml.draw' => 'sxd', + 'application/vnd.sun.xml.draw.template' => 'std', + 'application/vnd.sun.xml.impress' => 'sxi', + 'application/vnd.sun.xml.impress.template' => 'sti', + 'application/vnd.sun.xml.math' => 'sxm', + 'application/vnd.sun.xml.writer' => 'sxw', + 'application/vnd.sun.xml.writer.global' => 'sxg', + 'application/vnd.sun.xml.writer.template' => 'stw', + 'application/vnd.sus-calendar' => 'sus', + 'application/vnd.vidsoft.vidconference' => 'vsc', + 'application/vnd.visio' => 'vsd', + 'application/vnd.visionary' => 'vis', + 'application/vnd.wap.sic' => 'sic', + 'application/vnd.wap.slc' => 'slc', + 'application/vnd.wap.wbxml' => 'wbxml', + 'application/vnd.wap.wmlc' => 'wmlc', + 'application/vnd.wap.wmlscriptc' => 'wmlsc', + 'application/vnd.webturbo' => 'wtb', + 'application/vnd.wordperfect' => 'wpd', + 'application/vnd.wqd' => 'wqd', + 'application/vnd.wv.csp+wbxml' => 'wv', + 'application/vnd.wv.csp+xml' => '8bit', + 'application/vnd.wv.ssp+xml' => '8bit', + 'application/vnd.yamaha.hv-dic' => 'hvd', + 'application/vnd.yamaha.hv-script' => 'hvs', + 'application/vnd.yamaha.hv-voice' => 'hvp', + 'application/vnd.yamaha.smaf-audio' => 'saf', + 'application/vnd.yamaha.smaf-phrase' => 'spf', + 'application/vocaltec-media-desc' => 'vmd', + 'application/vocaltec-media-file' => 'vmf', + 'application/vocaltec-talker' => 'vtk', + 'application/watcherinfo+xml' => 'wif', + 'application/wordperfect5.1' => 'wp5', + 'application/x-123' => 'wk', + 'application/x-7th_level_event' => '7ls', + 'application/x-authorware-bin' => 'aab', + 'application/x-authorware-map' => 'aam', + 'application/x-authorware-seg' => 'aas', + 'application/x-bcpio' => 'bcpio', + 'application/x-bleeper' => 'bleep', + 'application/x-bzip2' => 'bz2', + 'application/x-cdlink' => 'vcd', + 'application/x-chat' => 'chat', + 'application/x-chess-pgn' => 'pgn', + 'application/x-compress' => 'z', + 'application/x-cpio' => 'cpio', + 'application/x-cprplayer' => 'pqf', + 'application/x-csh' => 'csh', + 'application/x-cu-seeme' => 'csm', + 'application/x-cult3d-object' => 'co', + 'application/x-debian-package' => 'deb', + 'application/x-director' => 'dcr', + 'application/x-dvi' => 'dvi', + 'application/x-envoy' => 'evy', + 'application/x-futuresplash' => 'spl', + 'application/x-gtar' => 'gtar', + 'application/x-gzip' => 'gz', + 'application/x-hdf' => 'hdf', + 'application/x-hep' => 'hep', + 'application/x-html+ruby' => 'rhtml', + 'application/x-httpd-miva' => 'mv', + 'application/x-httpd-php' => 'phtml', + 'application/x-ica' => 'ica', + 'application/x-imagemap' => 'imagemap', + 'application/x-ipix' => 'ipx', + 'application/x-ipscript' => 'ips', + 'application/x-java-archive' => 'jar', + 'application/x-java-jnlp-file' => 'jnlp', + 'application/x-java-serialized-object' => 'ser', + 'application/x-java-vm' => 'class', + 'application/x-javascript' => 'js', + 'application/x-koan' => 'skp', + 'application/x-latex' => 'latex', + 'application/x-mac-compactpro' => 'cpt', + 'application/x-maker' => 'frm', + 'application/x-mathcad' => 'mcd', + 'application/x-midi' => 'mid', + 'application/x-mif' => 'mif', + 'application/x-msaccess' => 'mda', + 'application/x-msdos-program' => 'com', + 'application/x-msdownload' => 'base64', + 'application/x-msexcel' => 'xls', + 'application/x-msword' => 'doc', + 'application/x-netcdf' => 'nc', + 'application/x-ns-proxy-autoconfig' => 'pac', + 'application/x-pagemaker' => 'pm5', + 'application/x-perl' => 'pl', + 'application/x-pn-realmedia' => 'rp', + 'application/x-python' => 'py', + 'application/x-quicktimeplayer' => 'qtl', + 'application/x-rar-compressed' => 'rar', + 'application/x-ruby' => 'rb', + 'application/x-sh' => 'sh', + 'application/x-shar' => 'shar', + 'application/x-shockwave-flash' => 'swf', + 'application/x-sprite' => 'spr', + 'application/x-spss' => 'sav', + 'application/x-spt' => 'spt', + 'application/x-stuffit' => 'sit', + 'application/x-sv4cpio' => 'sv4cpio', + 'application/x-sv4crc' => 'sv4crc', + 'application/x-tar' => 'tar', + 'application/x-tcl' => 'tcl', + 'application/x-tex' => 'tex', + 'application/x-texinfo' => 'texinfo', + 'application/x-troff' => 't', + 'application/x-troff-man' => 'man', + 'application/x-troff-me' => 'me', + 'application/x-troff-ms' => 'ms', + 'application/x-twinvq' => 'vqf', + 'application/x-twinvq-plugin' => 'vqe', + 'application/x-ustar' => 'ustar', + 'application/x-vmsbackup' => 'bck', + 'application/x-wais-source' => 'src', + 'application/x-wingz' => 'wz', + 'application/x-word' => 'base64', + 'application/x-wordperfect6.1' => 'wp6', + 'application/x-x509-ca-cert' => 'crt', + 'application/x-zip-compressed' => 'zip', + 'application/xhtml+xml' => 'xhtml', + 'application/zip' => 'zip', + 'audio/3gpp' => '3gpp', + 'audio/amr' => 'amr', + 'audio/amr-wb' => 'awb', + 'audio/basic' => 'au', + 'audio/evrc' => 'evc', + 'audio/l16' => 'l16', + 'audio/midi' => 'mid', + 'audio/mpeg' => 'mp3', + 'audio/prs.sid' => 'sid', + 'audio/qcelp' => 'qcp', + 'audio/smv' => 'smv', + 'audio/vnd.audiokoz' => 'koz', + 'audio/vnd.digital-winds' => 'eol', + 'audio/vnd.everad.plj' => 'plj', + 'audio/vnd.lucent.voice' => 'lvp', + 'audio/vnd.nokia.mobile-xmf' => 'mxmf', + 'audio/vnd.nortel.vbk' => 'vbk', + 'audio/vnd.nuera.ecelp4800' => 'ecelp4800', + 'audio/vnd.nuera.ecelp7470' => 'ecelp7470', + 'audio/vnd.nuera.ecelp9600' => 'ecelp9600', + 'audio/vnd.sealedmedia.softseal.mpeg' => 'smp3', + 'audio/voxware' => 'vox', + 'audio/x-aiff' => 'aif', + 'audio/x-mid' => 'mid', + 'audio/x-midi' => 'mid', + 'audio/x-mpeg' => 'mp2', + 'audio/x-mpegurl' => 'mpu', + 'audio/x-pn-realaudio' => 'rm', + 'audio/x-pn-realaudio-plugin' => 'rpm', + 'audio/x-realaudio' => 'ra', + 'audio/x-wav' => 'wav', + 'chemical/x-csml' => 'csm', + 'chemical/x-embl-dl-nucleotide' => 'emb', + 'chemical/x-gaussian-cube' => 'cube', + 'chemical/x-gaussian-input' => 'gau', + 'chemical/x-jcamp-dx' => 'jdx', + 'chemical/x-mdl-molfile' => 'mol', + 'chemical/x-mdl-rxnfile' => 'rxn', + 'chemical/x-mdl-tgf' => 'tgf', + 'chemical/x-mopac-input' => 'mop', + 'chemical/x-pdb' => 'pdb', + 'chemical/x-rasmol' => 'scr', + 'chemical/x-xyz' => 'xyz', + 'drawing/dwf' => 'dwf', + 'drawing/x-dwf' => 'dwf', + 'i-world/i-vrml' => 'ivr', + 'image/bmp' => 'bmp', + 'image/cewavelet' => 'wif', + 'image/cis-cod' => 'cod', + 'image/fif' => 'fif', + 'image/gif' => 'gif', + 'image/ief' => 'ief', + 'image/jp2' => 'jp2', + 'image/jpeg' => 'jpg', + 'image/jpm' => 'jpm', + 'image/jpx' => 'jpf', + 'image/pict' => 'pic', + 'image/pjpeg' => 'jpg', + 'image/png' => 'png', + 'image/targa' => 'tga', + 'image/tiff' => 'tif', + 'image/vn-svf' => 'svf', + 'image/vnd.dgn' => 'dgn', + 'image/vnd.djvu' => 'djvu', + 'image/vnd.dwg' => 'dwg', + 'image/vnd.glocalgraphics.pgb' => 'pgb', + 'image/vnd.microsoft.icon' => 'ico', + 'image/vnd.ms-modi' => 'mdi', + 'image/vnd.sealed.png' => 'spng', + 'image/vnd.sealedmedia.softseal.gif' => 'sgif', + 'image/vnd.sealedmedia.softseal.jpg' => 'sjpg', + 'image/vnd.wap.wbmp' => 'wbmp', + 'image/x-bmp' => 'bmp', + 'image/x-cmu-raster' => 'ras', + 'image/x-freehand' => 'fh4', + 'image/x-png' => 'png', + 'image/x-portable-anymap' => 'pnm', + 'image/x-portable-bitmap' => 'pbm', + 'image/x-portable-graymap' => 'pgm', + 'image/x-portable-pixmap' => 'ppm', + 'image/x-rgb' => 'rgb', + 'image/x-xbitmap' => 'xbm', + 'image/x-xpixmap' => 'xpm', + 'image/x-xwindowdump' => 'xwd', + 'message/external-body' => '8bit', + 'message/news' => '8bit', + 'message/partial' => '8bit', + 'message/rfc822' => '8bit', + 'model/iges' => 'igs', + 'model/mesh' => 'msh', + 'model/vnd.parasolid.transmit.binary' => 'x_b', + 'model/vnd.parasolid.transmit.text' => 'x_t', + 'model/vrml' => 'wrl', + 'multipart/alternative' => '8bit', + 'multipart/appledouble' => '8bit', + 'multipart/digest' => '8bit', + 'multipart/mixed' => '8bit', + 'multipart/parallel' => '8bit', + 'text/comma-separated-values' => 'csv', + 'text/css' => 'css', + 'text/html' => 'html', + 'text/plain' => 'txt', + 'text/prs.fallenstein.rst' => 'rst', + 'text/richtext' => 'rtx', + 'text/rtf' => 'rtf', + 'text/sgml' => 'sgml', + 'text/tab-separated-values' => 'tsv', + 'text/vnd.net2phone.commcenter.command' => 'ccc', + 'text/vnd.sun.j2me.app-descriptor' => 'jad', + 'text/vnd.wap.si' => 'si', + 'text/vnd.wap.sl' => 'sl', + 'text/vnd.wap.wml' => 'wml', + 'text/vnd.wap.wmlscript' => 'wmls', + 'text/x-hdml' => 'hdml', + 'text/x-setext' => 'etx', + 'text/x-sgml' => 'sgml', + 'text/x-speech' => 'talk', + 'text/x-vcalendar' => 'vcs', + 'text/x-vcard' => 'vcf', + 'text/xml' => 'xml', + 'ulead/vrml' => 'uvr', + 'video/3gpp' => '3gp', + 'video/dl' => 'dl', + 'video/gl' => 'gl', + 'video/mj2' => 'mj2', + 'video/mpeg' => 'mpeg', + 'video/quicktime' => 'mov', + 'video/vdo' => 'vdo', + 'video/vivo' => 'viv', + 'video/vnd.fvt' => 'fvt', + 'video/vnd.mpegurl' => 'mxu', + 'video/vnd.nokia.interleaved-multimedia' => 'nim', + 'video/vnd.objectvideo' => 'mp4', + 'video/vnd.sealed.mpeg1' => 's11', + 'video/vnd.sealed.mpeg4' => 'smpg', + 'video/vnd.sealed.swf' => 'sswf', + 'video/vnd.sealedmedia.softseal.mov' => 'smov', + 'video/vnd.vivo' => 'vivo', + 'video/x-fli' => 'fli', + 'video/x-ms-asf' => 'asf', + 'video/x-ms-wmv' => 'wmv', + 'video/x-msvideo' => 'avi', + 'video/x-sgi-movie' => 'movie', + 'x-chemical/x-pdb' => 'pdb', + 'x-chemical/x-xyz' => 'xyz', + 'x-conference/x-cooltalk' => 'ice', + 'x-drawing/dwf' => 'dwf', + 'x-world/x-d96' => 'd', + 'x-world/x-svr' => 'svr', + 'x-world/x-vream' => 'vrw', + 'x-world/x-vrml' => 'wrl', + ); - /** - * The absolute path to the file without dots - * @var string - */ - protected $path; + /** + * The absolute path to the file without dots + * @var string + */ + protected $path; - /** - * Constructs a new file from the given path. - * - * @param string $path The path to the file - * @throws FileNotFoundException If the given path is no file - */ - public function __construct($path) - { - if (!is_file($path)) + /** + * Constructs a new file from the given path. + * + * @param string $path The path to the file + * @throws FileNotFoundException If the given path is no file + */ + public function __construct($path) { - throw new FileNotFoundException($path); + if (!is_file($path)) { + throw new FileNotFoundException($path); + } + + $this->path = realpath($path); } - $this->path = realpath($path); - } - - /** - * Alias for getPath() - * - * @return string - */ - public function __toString() - { - return $this->getPath(); - } - - /** - * Returns the file name - * - * @return string - */ - public function getName() - { - return basename($this->path); - } - - /** - * Returns the file extension (with dot) - * - * @return string - */ - public function getExtension() - { - $name = $this->getName(); - - if (false !== ($pos = strrpos($name, '.'))) + /** + * Alias for getPath() + * + * @return string + */ + public function __toString() { - return substr($name, $pos); - } - else - { - return ''; - } - } - - /** - * Returns the extension based on the mime type (with dot) - * - * If the mime type is unknown, the actual extension is returned instead. - * - * @return string - */ - public function getDefaultExtension() - { - $type = $this->getMimeType(); - - if (isset(self::$defaultExtensions[$type])) - { - return '.' . self::$defaultExtensions[$type]; - } - else - { - return $this->getExtension(); - } - } - - /** - * Returns the directory of the file - * - * @return string - */ - public function getDirectory() - { - return dirname($this->path); - } - - /** - * Returns the absolute file path without dots - * - * @returns string The file path - */ - public function getPath() - { - return $this->path; - } - - /** - * Returns the mime type of the file. - * - * The mime type is guessed using the functions finfo(), mime_content_type() - * and the system binary "file" (in this order), depending on which of those - * is available on the current operating system. - * - * @returns string The guessed mime type, e.g. "application/pdf" - */ - public function getMimeType() - { - $guesser = MimeTypeGuesser::getInstance(); - - return $guesser->guess($this->getPath()); - } - - /** - * Returns the size of this file - * - * @return integer The file size in bytes - */ - public function size() - { - if (false === ($size = filesize($this->getPath()))) - { - throw new FileException(sprintf('Could not read file size of %s', $this->getPath())); + return $this->getPath(); } - return $size; - } - - /** - * Moves the file to a new location. - * - * @param string $newPath - */ - public function move($newPath) - { - if (!rename($this->getPath(), $newPath)) + /** + * Returns the file name + * + * @return string + */ + public function getName() { - throw new FileException(sprintf('Could not move file %s to %s', $this->getPath(), $newPath)); + return basename($this->path); + } + + /** + * Returns the file extension (with dot) + * + * @return string + */ + public function getExtension() + { + $name = $this->getName(); + + if (false !== ($pos = strrpos($name, '.'))) { + return substr($name, $pos); + } else { + return ''; + } + } + + /** + * Returns the extension based on the mime type (with dot) + * + * If the mime type is unknown, the actual extension is returned instead. + * + * @return string + */ + public function getDefaultExtension() + { + $type = $this->getMimeType(); + + if (isset(self::$defaultExtensions[$type])) { + return '.' . self::$defaultExtensions[$type]; + } else { + return $this->getExtension(); + } + } + + /** + * Returns the directory of the file + * + * @return string + */ + public function getDirectory() + { + return dirname($this->path); + } + + /** + * Returns the absolute file path without dots + * + * @returns string The file path + */ + public function getPath() + { + return $this->path; + } + + /** + * Returns the mime type of the file. + * + * The mime type is guessed using the functions finfo(), mime_content_type() + * and the system binary "file" (in this order), depending on which of those + * is available on the current operating system. + * + * @returns string The guessed mime type, e.g. "application/pdf" + */ + public function getMimeType() + { + $guesser = MimeTypeGuesser::getInstance(); + + return $guesser->guess($this->getPath()); + } + + /** + * Returns the size of this file + * + * @return integer The file size in bytes + */ + public function size() + { + if (false === ($size = filesize($this->getPath()))) { + throw new FileException(sprintf('Could not read file size of %s', $this->getPath())); + } + + return $size; + } + + /** + * Moves the file to a new location. + * + * @param string $newPath + */ + public function move($newPath) + { + if (!rename($this->getPath(), $newPath)) { + throw new FileException(sprintf('Could not move file %s to %s', $this->getPath(), $newPath)); + } } - } } \ No newline at end of file diff --git a/src/Symfony/Components/File/MimeType/ContentTypeMimeTypeGuesser.php b/src/Symfony/Components/File/MimeType/ContentTypeMimeTypeGuesser.php index 4d7644095f..4696d5276a 100644 --- a/src/Symfony/Components/File/MimeType/ContentTypeMimeTypeGuesser.php +++ b/src/Symfony/Components/File/MimeType/ContentTypeMimeTypeGuesser.php @@ -20,46 +20,42 @@ use Symfony\Components\File\Exception\AccessDeniedException; */ class ContentTypeMimeTypeGuesser implements MimeTypeGuesserInterface { - /** - * Returns whether this guesser is supported on the corrent OS/PHP setup - * - * @return boolean - */ - static public function isSupported() - { - return function_exists('mime_content_type'); - } - - /** - * Guesses the mime type of the file with the given path - * - * @see MimeTypeGuesserInterface::guess() - */ - public function guess($path) - { - if (!is_file($path)) + /** + * Returns whether this guesser is supported on the corrent OS/PHP setup + * + * @return boolean + */ + static public function isSupported() { - throw new FileNotFoundException($path); + return function_exists('mime_content_type'); } - if (!is_readable($path)) + /** + * Guesses the mime type of the file with the given path + * + * @see MimeTypeGuesserInterface::guess() + */ + public function guess($path) { - throw new AccessDeniedException($path); + if (!is_file($path)) { + throw new FileNotFoundException($path); + } + + if (!is_readable($path)) { + throw new AccessDeniedException($path); + } + + if (!self::isSupported() || !is_readable($path)) { + return null; + } + + $type = mime_content_type($path); + + // remove charset (added as of PHP 5.3) + if (false !== $pos = strpos($type, ';')) { + $type = substr($type, 0, $pos); + } + + return $type; } - - if (!self::isSupported() || !is_readable($path)) - { - return null; - } - - $type = mime_content_type($path); - - // remove charset (added as of PHP 5.3) - if (false !== $pos = strpos($type, ';')) - { - $type = substr($type, 0, $pos); - } - - return $type; - } } diff --git a/src/Symfony/Components/File/MimeType/FileBinaryMimeTypeGuesser.php b/src/Symfony/Components/File/MimeType/FileBinaryMimeTypeGuesser.php index 98fc099983..3a213b3970 100644 --- a/src/Symfony/Components/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/src/Symfony/Components/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -20,42 +20,38 @@ use Symfony\Components\File\Exception\AccessDeniedException; */ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface { - /** - * Guesses the mime type of the file with the given path - * - * @see MimeTypeGuesserInterface::guess() - */ - public function guess($path) - { - if (!is_file($path)) + /** + * Guesses the mime type of the file with the given path + * + * @see MimeTypeGuesserInterface::guess() + */ + public function guess($path) { - throw new FileNotFoundException($path); + if (!is_file($path)) { + throw new FileNotFoundException($path); + } + + if (!is_readable($path)) { + throw new AccessDeniedException($path); + } + + ob_start(); + + // need to use --mime instead of -i. see #6641 + passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return); + if ($return > 0) { + ob_end_clean(); + + return null; + } + + $type = trim(ob_get_clean()); + + if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-]+)#i', $type, $match)) { + // it's not a type, but an error message + return null; + } + + return $match[1]; } - - if (!is_readable($path)) - { - throw new AccessDeniedException($path); - } - - ob_start(); - - // need to use --mime instead of -i. see #6641 - passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return); - if ($return > 0) - { - ob_end_clean(); - - return null; - } - - $type = trim(ob_get_clean()); - - if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-]+)#i', $type, $match)) - { - // it's not a type, but an error message - return null; - } - - return $match[1]; - } } \ No newline at end of file diff --git a/src/Symfony/Components/File/MimeType/FileinfoMimeTypeGuesser.php b/src/Symfony/Components/File/MimeType/FileinfoMimeTypeGuesser.php index 455a38c6ea..324ad4b476 100644 --- a/src/Symfony/Components/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/src/Symfony/Components/File/MimeType/FileinfoMimeTypeGuesser.php @@ -20,51 +20,46 @@ use Symfony\Components\File\Exception\AccessDeniedException; */ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface { - /** - * Returns whether this guesser is supported on the corrent OS/PHP setup - * - * @return boolean - */ - static public function isSupported() - { - return function_exists('finfo_open'); - } - - /** - * Guesses the mime type of the file with the given path - * - * @see MimeTypeGuesserInterface::guess() - */ - public function guess($path) - { - if (!is_file($path)) + /** + * Returns whether this guesser is supported on the corrent OS/PHP setup + * + * @return boolean + */ + static public function isSupported() { - throw new FileNotFoundException($path); + return function_exists('finfo_open'); } - if (!is_readable($path)) + /** + * Guesses the mime type of the file with the given path + * + * @see MimeTypeGuesserInterface::guess() + */ + public function guess($path) { - throw new AccessDeniedException($path); + if (!is_file($path)) { + throw new FileNotFoundException($path); + } + + if (!is_readable($path)) { + throw new AccessDeniedException($path); + } + + if (!self::isSupported()) { + return null; + } + + if (!$finfo = new \finfo(FILEINFO_MIME)) { + return null; + } + + $type = $finfo->file($path); + + // remove charset (added as of PHP 5.3) + if (false !== $pos = strpos($type, ';')) { + $type = substr($type, 0, $pos); + } + + return $type; } - - if (!self::isSupported()) - { - return null; - } - - if (!$finfo = new \finfo(FILEINFO_MIME)) - { - return null; - } - - $type = $finfo->file($path); - - // remove charset (added as of PHP 5.3) - if (false !== $pos = strpos($type, ';')) - { - $type = substr($type, 0, $pos); - } - - return $type; - } } \ No newline at end of file diff --git a/src/Symfony/Components/File/MimeType/MimeTypeGuesser.php b/src/Symfony/Components/File/MimeType/MimeTypeGuesser.php index 31c9634875..a3efcd0ce1 100644 --- a/src/Symfony/Components/File/MimeType/MimeTypeGuesser.php +++ b/src/Symfony/Components/File/MimeType/MimeTypeGuesser.php @@ -31,99 +31,92 @@ use Symfony\Components\File\Exception\AccessDeniedException; */ class MimeTypeGuesser implements MimeTypeGuesserInterface { - /** - * The singleton instance - * @var MimeTypeGuesser - */ - static private $instance = null; + /** + * The singleton instance + * @var MimeTypeGuesser + */ + static private $instance = null; - /** - * All registered MimeTypeGuesserInterface instances - * @var array - */ - protected $guessers = array(); + /** + * All registered MimeTypeGuesserInterface instances + * @var array + */ + protected $guessers = array(); - /** - * Returns the singleton instance - * - * @return MimeTypeGuesser - */ - static public function getInstance() - { - if (is_null(self::$instance)) + /** + * Returns the singleton instance + * + * @return MimeTypeGuesser + */ + static public function getInstance() { - self::$instance = new self(); + if (is_null(self::$instance)) { + self::$instance = new self(); + } + + return self::$instance; } - return self::$instance; - } - - /** - * Registers all natively provided mime type guessers - */ - private function __construct() - { - $this->register(new FileBinaryMimeTypeGuesser()); - - if (ContentTypeMimeTypeGuesser::isSupported()) + /** + * Registers all natively provided mime type guessers + */ + private function __construct() { - $this->register(new ContentTypeMimeTypeGuesser()); + $this->register(new FileBinaryMimeTypeGuesser()); + + if (ContentTypeMimeTypeGuesser::isSupported()) { + $this->register(new ContentTypeMimeTypeGuesser()); + } + + if (FileinfoMimeTypeGuesser::isSupported()) { + $this->register(new FileinfoMimeTypeGuesser()); + } } - if (FileinfoMimeTypeGuesser::isSupported()) + /** + * Registers a new mime type guesser + * + * When guessing, this guesser is preferred over previously registered ones. + * + * @param MimeTypeGuesserInterface $guesser + */ + public function register(MimeTypeGuesserInterface $guesser) { - $this->register(new FileinfoMimeTypeGuesser()); - } - } - - /** - * Registers a new mime type guesser - * - * When guessing, this guesser is preferred over previously registered ones. - * - * @param MimeTypeGuesserInterface $guesser - */ - public function register(MimeTypeGuesserInterface $guesser) - { - array_unshift($this->guessers, $guesser); - } - - /** - * Tries to guess the mime type of the given file - * - * The file is passed to each registered mime type guesser in reverse order - * of their registration (last registered is queried first). Once a guesser - * returns a value that is not NULL, this method terminates and returns the - * value. - * - * @param string $path The path to the file - * @return string The mime type or NULL, if none could be guessed - * @throws FileException If the file does not exist - */ - public function guess($path) - { - if (!is_file($path)) - { - throw new FileNotFoundException($path); + array_unshift($this->guessers, $guesser); } - if (!is_readable($path)) + /** + * Tries to guess the mime type of the given file + * + * The file is passed to each registered mime type guesser in reverse order + * of their registration (last registered is queried first). Once a guesser + * returns a value that is not NULL, this method terminates and returns the + * value. + * + * @param string $path The path to the file + * @return string The mime type or NULL, if none could be guessed + * @throws FileException If the file does not exist + */ + public function guess($path) { - throw new AccessDeniedException($path); + if (!is_file($path)) { + throw new FileNotFoundException($path); + } + + if (!is_readable($path)) { + throw new AccessDeniedException($path); + } + + $mimeType = null; + + foreach ($this->guessers as $guesser) { + $mimeType = $guesser->guess($path); + + if (!is_null($mimeType)) { + break; + } + } + + return $mimeType; } - - $mimeType = null; - - foreach ($this->guessers as $guesser) - { - $mimeType = $guesser->guess($path); - - if (!is_null($mimeType)) - { - break; - } - } - - return $mimeType; - } } \ No newline at end of file diff --git a/src/Symfony/Components/File/MimeType/MimeTypeGuesserInterface.php b/src/Symfony/Components/File/MimeType/MimeTypeGuesserInterface.php index e29ce2fd34..1f1a294814 100644 --- a/src/Symfony/Components/File/MimeType/MimeTypeGuesserInterface.php +++ b/src/Symfony/Components/File/MimeType/MimeTypeGuesserInterface.php @@ -17,13 +17,13 @@ namespace Symfony\Components\File\MimeType; */ interface MimeTypeGuesserInterface { - /** - * Guesses the mime type of the file with the given path - * - * @param string $path The path to the file - * @return string The mime type or NULL, if none could be guessed - * @throws FileNotFoundException If the file does not exist - * @throws AccessDeniedException If the file could not be read - */ - public function guess($path); + /** + * Guesses the mime type of the file with the given path + * + * @param string $path The path to the file + * @return string The mime type or NULL, if none could be guessed + * @throws FileNotFoundException If the file does not exist + * @throws AccessDeniedException If the file could not be read + */ + public function guess($path); } \ No newline at end of file diff --git a/src/Symfony/Components/File/UploadedFile.php b/src/Symfony/Components/File/UploadedFile.php index 73524a5fa0..b7aa2c9d99 100644 --- a/src/Symfony/Components/File/UploadedFile.php +++ b/src/Symfony/Components/File/UploadedFile.php @@ -20,111 +20,103 @@ use Symfony\Components\File\Exception\FileException; */ class UploadedFile extends File { - protected $originalName; - protected $mimeType; - protected $size; - protected $error; - protected $moved = false; + protected $originalName; + protected $mimeType; + protected $size; + protected $error; + protected $moved = false; - /** - * Accepts the information of the uploaded file as provided by the PHP - * global $_FILES. - * - * @param string $tmpName The full temporary path to the file - * @param string $name The original file name - * @param string $type The type of the file as provided by PHP - * @param integer $size The file size - * @param string $error The error constant of the upload. Should be - * one of PHP's UPLOAD_XXX constants. - */ - public function __construct($path, $originalName, $mimeType, $size, $error) - { - if (!ini_get('file_uploads')) + /** + * Accepts the information of the uploaded file as provided by the PHP + * global $_FILES. + * + * @param string $tmpName The full temporary path to the file + * @param string $name The original file name + * @param string $type The type of the file as provided by PHP + * @param integer $size The file size + * @param string $error The error constant of the upload. Should be + * one of PHP's UPLOAD_XXX constants. + */ + public function __construct($path, $originalName, $mimeType, $size, $error) { - throw new FileException(sprintf('Unable to create UploadedFile because "file_uploads" is disabled in your php.ini file (%s)', get_cfg_var('cfg_file_path'))); + if (!ini_get('file_uploads')) { + throw new FileException(sprintf('Unable to create UploadedFile because "file_uploads" is disabled in your php.ini file (%s)', get_cfg_var('cfg_file_path'))); + } + + parent::__construct($path); + + if (is_null($error)) { + $error = UPLOAD_ERR_OK; + } + + if (is_null($mimeType)) { + $mimeType = 'application/octet-stream'; + } + + $this->originalName = (string)$originalName; + $this->mimeType = $mimeType; + $this->size = $size; + $this->error = $error; } - parent::__construct($path); - - if (is_null($error)) + /** + * Returns the mime type of the file. + * + * The mime type is guessed using the functions finfo(), mime_content_type() + * and the system binary "file" (in this order), depending on which of those + * is available on the current operating system. + * + * @returns string The guessed mime type, e.g. "application/pdf" + */ + public function getMimeType() { - $error = UPLOAD_ERR_OK; + $mimeType = parent::getMimeType(); + + if (is_null($mimeType)) { + $mimeType = $this->mimeType; + } + + return $mimeType; } - if (is_null($mimeType)) + /** + * Returns the original file name including its extension. + * + * @returns string The file name + */ + public function getOriginalName() { - $mimeType = 'application/octet-stream'; + return $this->originalName; } - $this->originalName = (string)$originalName; - $this->mimeType = $mimeType; - $this->size = $size; - $this->error = $error; - } - - /** - * Returns the mime type of the file. - * - * The mime type is guessed using the functions finfo(), mime_content_type() - * and the system binary "file" (in this order), depending on which of those - * is available on the current operating system. - * - * @returns string The guessed mime type, e.g. "application/pdf" - */ - public function getMimeType() - { - $mimeType = parent::getMimeType(); - - if (is_null($mimeType)) + /** + * Returns the upload error. + * + * If the upload was successful, the constant UPLOAD_ERR_OK is returned. + * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. + * + * @returns integer The upload error + */ + public function getError() { - $mimeType = $this->mimeType; + return $this->error; } - return $mimeType; - } - - /** - * Returns the original file name including its extension. - * - * @returns string The file name - */ - public function getOriginalName() - { - return $this->originalName; - } - - /** - * Returns the upload error. - * - * If the upload was successful, the constant UPLOAD_ERR_OK is returned. - * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. - * - * @returns integer The upload error - */ - public function getError() - { - return $this->error; - } - - /** - * Moves the file to a new location. - * - * @param string $newPath - */ - public function move($newPath) - { - if (!$this->moved) + /** + * Moves the file to a new location. + * + * @param string $newPath + */ + public function move($newPath) { - if (!move_uploaded_file($this->getPath(), $newPath)) - { - throw new FileException(sprintf('Could not move file %s to %s', $this->getPath(), $newPath)); - } + if (!$this->moved) { + if (!move_uploaded_file($this->getPath(), $newPath)) { + throw new FileException(sprintf('Could not move file %s to %s', $this->getPath(), $newPath)); + } - $this->moved = true; + $this->moved = true; + } else { + parent::move($newPath); + } } - else - { - parent::move($newPath); - } - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/BirthdayField.php b/src/Symfony/Components/Form/BirthdayField.php index 34745cc67b..f7bbb1713c 100644 --- a/src/Symfony/Components/Form/BirthdayField.php +++ b/src/Symfony/Components/Form/BirthdayField.php @@ -20,15 +20,15 @@ namespace Symfony\Components\Form; */ class BirthdayField extends DateField { - /** - * {@inheritDoc} - */ - protected function configure() - { - $currentYear = date('Y'); + /** + * {@inheritDoc} + */ + protected function configure() + { + $currentYear = date('Y'); - $this->addOption('years', range($currentYear-120, $currentYear)); + $this->addOption('years', range($currentYear-120, $currentYear)); - parent::configure(); - } + parent::configure(); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/CheckboxField.php b/src/Symfony/Components/Form/CheckboxField.php index 1fae41e0d7..728de9d910 100644 --- a/src/Symfony/Components/Form/CheckboxField.php +++ b/src/Symfony/Components/Form/CheckboxField.php @@ -20,13 +20,13 @@ use Symfony\Components\Form\ValueTransformer\BooleanToStringTransformer; */ class CheckboxField extends ToggleField { - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render(array_merge(array( - 'type' => 'checkbox', - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render(array_merge(array( + 'type' => 'checkbox', + ), $attributes)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ChoiceField.php b/src/Symfony/Components/Form/ChoiceField.php index 91a1352824..80e5209e22 100644 --- a/src/Symfony/Components/Form/ChoiceField.php +++ b/src/Symfony/Components/Form/ChoiceField.php @@ -15,274 +15,237 @@ use Symfony\Components\Form\ValueTransformer\BooleanToStringTransformer; */ class ChoiceField extends HybridField { - /** - * Stores the preferred choices with the choices as keys - * @var array - */ - protected $preferredChoices = array(); + /** + * Stores the preferred choices with the choices as keys + * @var array + */ + protected $preferredChoices = array(); - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addRequiredOption('choices'); - $this->addOption('preferred_choices', array()); - $this->addOption('separator', '----------'); - $this->addOption('multiple', false); - $this->addOption('expanded', false); - $this->addOption('empty_value', ''); - $this->addOption('translate_choices', false); - - if (count($this->getOption('preferred_choices')) > 0) + /** + * {@inheritDoc} + */ + protected function configure() { - $this->preferredChoices = array_flip($this->getOption('preferred_choices')); + $this->addRequiredOption('choices'); + $this->addOption('preferred_choices', array()); + $this->addOption('separator', '----------'); + $this->addOption('multiple', false); + $this->addOption('expanded', false); + $this->addOption('empty_value', ''); + $this->addOption('translate_choices', false); - if (false && $diff = array_diff_key($this->options, $this->knownOptions)) - { - //throw new InvalidOptionsException(sprintf('%s does not support the following options: "%s".', get_class($this), implode('", "', array_keys($diff))), array_keys($diff)); - } - } + if (count($this->getOption('preferred_choices')) > 0) { + $this->preferredChoices = array_flip($this->getOption('preferred_choices')); - if ($this->getOption('expanded')) - { - $this->setFieldMode(self::GROUP); - - $choices = $this->getOption('choices'); - - foreach ($this->getOption('preferred_choices') as $choice) - { - $this->add($this->newChoiceField($choice, $choices[$choice])); - unset($choices[$choice]); - } - - foreach ($this->getOption('choices') as $choice => $value) - { - $this->add($this->newChoiceField($choice, $value)); - } - } - else - { - $this->setFieldMode(self::FIELD); - } - } - - /** - * Returns a new field of type radio button or checkbox. - * - * @param string $key The key for the option - * @param string $label The label for the option - */ - protected function newChoiceField($choice, $label) - { - if ($this->getOption('multiple')) - { - return new CheckboxField($choice, array( - 'value' => $choice, - 'label' => $label, - 'translate_label' => $this->getOption('translate_choices'), - )); - } - else - { - return new RadioField($choice, array( - 'value' => $choice, - 'label' => $label, - 'translate_label' => $this->getOption('translate_choices'), - )); - } - } - - /** - * {@inheritDoc} - * - * Takes care of converting the input from a single radio button - * to an array. - */ - public function bind($value) - { - if (!$this->getOption('multiple') && $this->getOption('expanded')) - { - $value = $value === null ? array() : array($value => true); - } - - parent::bind($value); - } - - /** - * Transforms a single choice or an array of choices to a format appropriate - * for the nested checkboxes/radio buttons. - * - * The result is an array with the options as keys and true/false as values, - * depending on whether a given option is selected. If this field is rendered - * as select tag, the value is not modified. - * - * @param mixed $value An array if "multiple" is set to true, a scalar - * value otherwise. - * @return mixed An array if "expanded" or "multiple" is set to true, - * a scalar value otherwise. - */ - protected function transform($value) - { - if ($this->getOption('expanded')) - { - $choices = $this->getOption('choices'); - - foreach ($choices as $choice => $_) - { - $choices[$choice] = $this->getOption('multiple') - ? in_array($choice, (array)$value, true) - : ($choice === $value); - } - - return $choices; - } - else - { - return parent::transform($value); - } - } - - /** - * Transforms a checkbox/radio button array to a single choice or an array - * of choices. - * - * The input value is an array with the choices as keys and true/false as - * values, depending on whether a given choice is selected. The output - * is an array with the selected choices or a single selected choice. - * - * @param mixed $value An array if "expanded" or "multiple" is set to true, - * a scalar value otherwise. - * @return mixed $value An array if "multiple" is set to true, a scalar - * value otherwise. - */ - protected function reverseTransform($value) - { - if ($this->getOption('expanded')) - { - $choices = array(); - - foreach ($value as $choice => $selected) - { - if ($selected) - { - $choices[] = $choice; - } - } - - if ($this->getOption('multiple')) - { - return $choices; - } - else - { - return count($choices) > 0 ? current($choices) : null; - } - } - else - { - return parent::reverseTransform($value); - } - } - - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - if ($this->getOption('expanded')) - { - $html = ""; - - foreach ($this as $field) - { - $html .= $field->render()."\n"; - } - - return $html; - } - else - { - $attrs['id'] = $this->getId(); - $attrs['name'] = $this->getName(); - $attrs['disabled'] = $this->isDisabled(); - - // Add "[]" to the name in case a select tag with multiple options is - // displayed. Otherwise only one of the selected options is sent in the - // POST request. - if ($this->getOption('multiple') && !$this->getOption('expanded')) - { - $attrs['name'] .= '[]'; - } - - if ($this->getOption('multiple')) - { - $attrs['multiple'] = 'multiple'; - } - - $selected = array_flip(array_map('strval', (array)$this->getDisplayedData())); - $html = "\n"; - - if (!$this->isRequired()) - { - $html .= $this->renderChoices(array('' => $this->getOption('empty_value')), $selected)."\n"; - } - - $choices = $this->getOption('choices'); - - if (count($this->preferredChoices) > 0) - { - $html .= $this->renderChoices(array_intersect_key($choices, $this->preferredChoices), $selected)."\n"; - $html .= $this->generator->contentTag('option', $this->getOption('separator'), array('disabled' => true))."\n"; - } - - $html .= $this->renderChoices(array_diff_key($choices, $this->preferredChoices), $selected)."\n"; - - return $this->generator->contentTag('select', $html, array_merge($attrs, $attributes)); - } - } - - /** - * Returns an array of option tags for the choice field - * - * @return array An array of option tags - */ - protected function renderChoices(array $choices, array $selected) - { - $options = array(); - - foreach ($choices as $key => $option) - { - if (is_array($option)) - { - $options[] = $this->generator->contentTag( - 'optgroup', - "\n".$this->renderChoices($option, $selected)."\n", - array('label' => $this->generator->escape($key)) - ); - } - else - { - $attributes = array('value' => $this->generator->escape($key)); - - if (isset($selected[strval($key)])) - { - $attributes['selected'] = true; + if (false && $diff = array_diff_key($this->options, $this->knownOptions)) { + //throw new InvalidOptionsException(sprintf('%s does not support the following options: "%s".', get_class($this), implode('", "', array_keys($diff))), array_keys($diff)); + } } - if ($this->getOption('translate_choices')) - { - $option = $this->translate($option); - } + if ($this->getOption('expanded')) { + $this->setFieldMode(self::GROUP); - $options[] = $this->generator->contentTag( - 'option', - $this->generator->escape($option), - $attributes - ); - } + $choices = $this->getOption('choices'); + + foreach ($this->getOption('preferred_choices') as $choice) { + $this->add($this->newChoiceField($choice, $choices[$choice])); + unset($choices[$choice]); + } + + foreach ($this->getOption('choices') as $choice => $value) { + $this->add($this->newChoiceField($choice, $value)); + } + } else { + $this->setFieldMode(self::FIELD); + } } - return implode("\n", $options); - } + /** + * Returns a new field of type radio button or checkbox. + * + * @param string $key The key for the option + * @param string $label The label for the option + */ + protected function newChoiceField($choice, $label) + { + if ($this->getOption('multiple')) { + return new CheckboxField($choice, array( + 'value' => $choice, + 'label' => $label, + 'translate_label' => $this->getOption('translate_choices'), + )); + } else { + return new RadioField($choice, array( + 'value' => $choice, + 'label' => $label, + 'translate_label' => $this->getOption('translate_choices'), + )); + } + } + + /** + * {@inheritDoc} + * + * Takes care of converting the input from a single radio button + * to an array. + */ + public function bind($value) + { + if (!$this->getOption('multiple') && $this->getOption('expanded')) { + $value = $value === null ? array() : array($value => true); + } + + parent::bind($value); + } + + /** + * Transforms a single choice or an array of choices to a format appropriate + * for the nested checkboxes/radio buttons. + * + * The result is an array with the options as keys and true/false as values, + * depending on whether a given option is selected. If this field is rendered + * as select tag, the value is not modified. + * + * @param mixed $value An array if "multiple" is set to true, a scalar + * value otherwise. + * @return mixed An array if "expanded" or "multiple" is set to true, + * a scalar value otherwise. + */ + protected function transform($value) + { + if ($this->getOption('expanded')) { + $choices = $this->getOption('choices'); + + foreach ($choices as $choice => $_) { + $choices[$choice] = $this->getOption('multiple') + ? in_array($choice, (array)$value, true) + : ($choice === $value); + } + + return $choices; + } else { + return parent::transform($value); + } + } + + /** + * Transforms a checkbox/radio button array to a single choice or an array + * of choices. + * + * The input value is an array with the choices as keys and true/false as + * values, depending on whether a given choice is selected. The output + * is an array with the selected choices or a single selected choice. + * + * @param mixed $value An array if "expanded" or "multiple" is set to true, + * a scalar value otherwise. + * @return mixed $value An array if "multiple" is set to true, a scalar + * value otherwise. + */ + protected function reverseTransform($value) + { + if ($this->getOption('expanded')) { + $choices = array(); + + foreach ($value as $choice => $selected) { + if ($selected) { + $choices[] = $choice; + } + } + + if ($this->getOption('multiple')) { + return $choices; + } else { + return count($choices) > 0 ? current($choices) : null; + } + } else { + return parent::reverseTransform($value); + } + } + + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + if ($this->getOption('expanded')) { + $html = ""; + + foreach ($this as $field) { + $html .= $field->render()."\n"; + } + + return $html; + } else { + $attrs['id'] = $this->getId(); + $attrs['name'] = $this->getName(); + $attrs['disabled'] = $this->isDisabled(); + + // Add "[]" to the name in case a select tag with multiple options is + // displayed. Otherwise only one of the selected options is sent in the + // POST request. + if ($this->getOption('multiple') && !$this->getOption('expanded')) { + $attrs['name'] .= '[]'; + } + + if ($this->getOption('multiple')) { + $attrs['multiple'] = 'multiple'; + } + + $selected = array_flip(array_map('strval', (array)$this->getDisplayedData())); + $html = "\n"; + + if (!$this->isRequired()) { + $html .= $this->renderChoices(array('' => $this->getOption('empty_value')), $selected)."\n"; + } + + $choices = $this->getOption('choices'); + + if (count($this->preferredChoices) > 0) { + $html .= $this->renderChoices(array_intersect_key($choices, $this->preferredChoices), $selected)."\n"; + $html .= $this->generator->contentTag('option', $this->getOption('separator'), array('disabled' => true))."\n"; + } + + $html .= $this->renderChoices(array_diff_key($choices, $this->preferredChoices), $selected)."\n"; + + return $this->generator->contentTag('select', $html, array_merge($attrs, $attributes)); + } + } + + /** + * Returns an array of option tags for the choice field + * + * @return array An array of option tags + */ + protected function renderChoices(array $choices, array $selected) + { + $options = array(); + + foreach ($choices as $key => $option) { + if (is_array($option)) { + $options[] = $this->generator->contentTag( + 'optgroup', + "\n".$this->renderChoices($option, $selected)."\n", + array('label' => $this->generator->escape($key)) + ); + } else { + $attributes = array('value' => $this->generator->escape($key)); + + if (isset($selected[strval($key)])) { + $attributes['selected'] = true; + } + + if ($this->getOption('translate_choices')) { + $option = $this->translate($option); + } + + $options[] = $this->generator->contentTag( + 'option', + $this->generator->escape($option), + $attributes + ); + } + } + + return implode("\n", $options); + } } diff --git a/src/Symfony/Components/Form/CollectionField.php b/src/Symfony/Components/Form/CollectionField.php index 76b7f71917..5d524949e3 100644 --- a/src/Symfony/Components/Form/CollectionField.php +++ b/src/Symfony/Components/Form/CollectionField.php @@ -21,83 +21,75 @@ use Symfony\Components\Form\Exception\UnexpectedTypeException; */ class CollectionField extends FieldGroup { - /** - * The prototype for the inner fields - * @var FieldInterface - */ - protected $prototype; + /** + * The prototype for the inner fields + * @var FieldInterface + */ + protected $prototype; - /** - * Repeats the given field twice to verify the user's input - * - * @param FieldInterface $innerField - */ - public function __construct(FieldInterface $innerField, array $options = array()) - { - $this->prototype = $innerField; - - parent::__construct($innerField->getKey(), $options); - } - - protected function configure() - { - $this->addOption('modifiable', false); - - if ($this->getOption('modifiable')) + /** + * Repeats the given field twice to verify the user's input + * + * @param FieldInterface $innerField + */ + public function __construct(FieldInterface $innerField, array $options = array()) { - $field = $this->newField('$$key$$', null); - // TESTME - $field->setRequired(false); - $this->add($field); - } - } + $this->prototype = $innerField; - public function setData($collection) - { - if (!is_array($collection) && !$collection instanceof Traversable) - { - throw new UnexpectedTypeException('The data must be an array'); + parent::__construct($innerField->getKey(), $options); } - foreach ($collection as $name => $value) + protected function configure() { - $this->add($this->newField($name, $name)); + $this->addOption('modifiable', false); + + if ($this->getOption('modifiable')) { + $field = $this->newField('$$key$$', null); + // TESTME + $field->setRequired(false); + $this->add($field); + } } - parent::setData($collection); - } - - public function bind($taintedData) - { - if (is_null($taintedData)) + public function setData($collection) { - $taintedData = array(); + if (!is_array($collection) && !$collection instanceof Traversable) { + throw new UnexpectedTypeException('The data must be an array'); + } + + foreach ($collection as $name => $value) { + $this->add($this->newField($name, $name)); + } + + parent::setData($collection); } - foreach ($this as $name => $field) + public function bind($taintedData) { - if (!isset($taintedData[$name]) && $this->getOption('modifiable') && $name != '$$key$$') - { - $this->remove($name); - } + if (is_null($taintedData)) { + $taintedData = array(); + } + + foreach ($this as $name => $field) { + if (!isset($taintedData[$name]) && $this->getOption('modifiable') && $name != '$$key$$') { + $this->remove($name); + } + } + + foreach ($taintedData as $name => $value) { + if (!isset($this[$name]) && $this->getOption('modifiable')) { + $this->add($this->newField($name, $name)); + } + } + + return parent::bind($taintedData); } - foreach ($taintedData as $name => $value) + protected function newField($key, $propertyPath) { - if (!isset($this[$name]) && $this->getOption('modifiable')) - { - $this->add($this->newField($name, $name)); - } + $field = clone $this->prototype; + $field->setKey($key); + $field->setPropertyPath($propertyPath === null ? null : '['.$propertyPath.']'); + return $field; } - - return parent::bind($taintedData); - } - - protected function newField($key, $propertyPath) - { - $field = clone $this->prototype; - $field->setKey($key); - $field->setPropertyPath($propertyPath === null ? null : '['.$propertyPath.']'); - return $field; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Configurable.php b/src/Symfony/Components/Form/Configurable.php index bba553c3c1..29eccd0d0b 100644 --- a/src/Symfony/Components/Form/Configurable.php +++ b/src/Symfony/Components/Form/Configurable.php @@ -19,124 +19,119 @@ use Symfony\Components\Form\Exception\InvalidOptionsException; */ abstract class Configurable { - /** - * The options and their values - * @var array - */ - private $options = array(); + /** + * The options and their values + * @var array + */ + private $options = array(); - /** - * The names of the valid options - * @var array - */ - private $knownOptions = array(); + /** + * The names of the valid options + * @var array + */ + private $knownOptions = array(); - /** - * The names of the required options - * @var array - */ - private $requiredOptions = array(); + /** + * The names of the required options + * @var array + */ + private $requiredOptions = array(); - /** - * The allowed values for each option - * @var array - */ - private $allowedValues = array(); + /** + * The allowed values for each option + * @var array + */ + private $allowedValues = array(); - /** - * Reads, validates and stores the given options - * - * @param array $options - */ - public function __construct(array $options = array()) - { - $this->options = array_merge($this->options, $options); - - $this->configure(); - - // check option names - if ($diff = array_diff_key($this->options, $this->knownOptions)) + /** + * Reads, validates and stores the given options + * + * @param array $options + */ + public function __construct(array $options = array()) { - throw new InvalidOptionsException(sprintf('%s does not support the following options: "%s".', get_class($this), implode('", "', array_keys($diff))), array_keys($diff)); + $this->options = array_merge($this->options, $options); + + $this->configure(); + + // check option names + if ($diff = array_diff_key($this->options, $this->knownOptions)) { + throw new InvalidOptionsException(sprintf('%s does not support the following options: "%s".', get_class($this), implode('", "', array_keys($diff))), array_keys($diff)); + } + + // check required options + if ($diff = array_diff_key($this->requiredOptions, $this->options)) { + throw new MissingOptionsException(sprintf('%s requires the following options: \'%s\'.', get_class($this), implode('", "', array_keys($diff))), array_keys($diff)); + } } - // check required options - if ($diff = array_diff_key($this->requiredOptions, $this->options)) + /** + * Configures the valid options + * + * This method should call addOption() or addRequiredOption() for every + * accepted option. + */ + protected function configure() { - throw new MissingOptionsException(sprintf('%s requires the following options: \'%s\'.', get_class($this), implode('", "', array_keys($diff))), array_keys($diff)); - } - } - - /** - * Configures the valid options - * - * This method should call addOption() or addRequiredOption() for every - * accepted option. - */ - protected function configure() - { - } - - /** - * Returns an option value. - * - * @param string $name The option name - * - * @return mixed The option value - */ - public function getOption($name) - { - return array_key_exists($name, $this->options) ? $this->options[$name] : null; - } - - /** - * Adds a new option value with a default value. - * - * @param string $name The option name - * @param mixed $value The default value - */ - protected function addOption($name, $value = null, array $allowedValues = array()) - { - $this->knownOptions[$name] = true; - - if (!array_key_exists($name, $this->options)) - { - $this->options[$name] = $value; } - if (count($allowedValues) > 0 && !in_array($this->options[$name], $allowedValues)) + /** + * Returns an option value. + * + * @param string $name The option name + * + * @return mixed The option value + */ + public function getOption($name) { - throw new InvalidOptionsException(sprintf('The option "%s" is expected to be one of "%s", but is "%s"', $name, implode('", "', $allowedValues), $this->options[$name]), array($name)); + return array_key_exists($name, $this->options) ? $this->options[$name] : null; } - } - /** - * Adds a required option. - * - * @param string $name The option name - */ - protected function addRequiredOption($name, array $allowedValues = array()) - { - $this->knownOptions[$name] = true; - $this->requiredOptions[$name] = true; - - // only test if the option is set, otherwise an error will be thrown - // anyway - if (isset($this->options[$name]) && count($allowedValues) > 0 && !in_array($this->options[$name], $allowedValues)) + /** + * Adds a new option value with a default value. + * + * @param string $name The option name + * @param mixed $value The default value + */ + protected function addOption($name, $value = null, array $allowedValues = array()) { - throw new InvalidOptionsException(sprintf('The option "%s" is expected to be one of "%s", but is "%s"', $name, implode('", "', $allowedValues), $this->options[$name]), array($name)); - } - } + $this->knownOptions[$name] = true; - /** - * Returns true if the option exists. - * - * @param string $name The option name - * - * @return bool true if the option is set, false otherwise - */ - public function hasOption($name) - { - return isset($this->options[$name]); - } + if (!array_key_exists($name, $this->options)) { + $this->options[$name] = $value; + } + + if (count($allowedValues) > 0 && !in_array($this->options[$name], $allowedValues)) { + throw new InvalidOptionsException(sprintf('The option "%s" is expected to be one of "%s", but is "%s"', $name, implode('", "', $allowedValues), $this->options[$name]), array($name)); + } + } + + /** + * Adds a required option. + * + * @param string $name The option name + */ + protected function addRequiredOption($name, array $allowedValues = array()) + { + $this->knownOptions[$name] = true; + $this->requiredOptions[$name] = true; + + // only test if the option is set, otherwise an error will be thrown + // anyway + if (isset($this->options[$name]) && count($allowedValues) > 0 && !in_array($this->options[$name], $allowedValues)) { + throw new InvalidOptionsException(sprintf('The option "%s" is expected to be one of "%s", but is "%s"', $name, implode('", "', $allowedValues), $this->options[$name]), array($name)); + } + } + + /** + * Returns true if the option exists. + * + * @param string $name The option name + * + * @return bool true if the option is set, false otherwise + */ + public function hasOption($name) + { + return isset($this->options[$name]); + } } diff --git a/src/Symfony/Components/Form/Configurator/ConfiguratorInterface.php b/src/Symfony/Components/Form/Configurator/ConfiguratorInterface.php index 88c8f12943..bb3d6e9f48 100644 --- a/src/Symfony/Components/Form/Configurator/ConfiguratorInterface.php +++ b/src/Symfony/Components/Form/Configurator/ConfiguratorInterface.php @@ -4,11 +4,11 @@ namespace Symfony\Components\Form\Configurator; interface ConfiguratorInterface { - public function initialize($object); + public function initialize($object); - public function getClass($fieldName); + public function getClass($fieldName); - public function getOptions($fieldName); + public function getOptions($fieldName); - public function isRequired($fieldName); + public function isRequired($fieldName); } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Configurator/ValidatorConfigurator.php b/src/Symfony/Components/Form/Configurator/ValidatorConfigurator.php index 0effe49033..6a9bb9f1a0 100644 --- a/src/Symfony/Components/Form/Configurator/ValidatorConfigurator.php +++ b/src/Symfony/Components/Form/Configurator/ValidatorConfigurator.php @@ -4,32 +4,32 @@ namespace Symfony\Components\Form\Configurator; class ValidatorConfigurator implements ConfiguratorInterface { - protected $metaData = null; - protected $classMetaData = null; + protected $metaData = null; + protected $classMetaData = null; - public function __construct(MetaDataInterface $metaData) - { - $this->metaData = $metaData; - } + public function __construct(MetaDataInterface $metaData) + { + $this->metaData = $metaData; + } - public function initialize($object) - { - $this->classMetaData = $this->metaData->getClassMetaData(get_class($object)); - } + public function initialize($object) + { + $this->classMetaData = $this->metaData->getClassMetaData(get_class($object)); + } - public function getClass($fieldName) - { + public function getClass($fieldName) + { - } + } - public function getOptions($fieldName) - { + public function getOptions($fieldName) + { - } + } - public function isRequired($fieldName) - { - return $this->classMetaData->getPropertyMetaData($fieldName)->hasConstraint('NotNull') - || $this->classMetaData->getPropertyMetaData($fieldName)->hasConstraint('NotEmpty'); - } + public function isRequired($fieldName) + { + return $this->classMetaData->getPropertyMetaData($fieldName)->hasConstraint('NotNull') + || $this->classMetaData->getPropertyMetaData($fieldName)->hasConstraint('NotEmpty'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/DateField.php b/src/Symfony/Components/Form/DateField.php index a0122ea0a8..f2a6e9d8ee 100644 --- a/src/Symfony/Components/Form/DateField.php +++ b/src/Symfony/Components/Form/DateField.php @@ -19,244 +19,224 @@ use Symfony\Components\Form\ValueTransformer\DateTimeToArrayTransformer; class DateField extends HybridField { - const FULL = 'full'; - const LONG = 'long'; - const MEDIUM = 'medium'; - const SHORT = 'short'; + const FULL = 'full'; + const LONG = 'long'; + const MEDIUM = 'medium'; + const SHORT = 'short'; - const DATETIME = 'datetime'; - const STRING = 'string'; - const TIMESTAMP = 'timestamp'; - const RAW = 'raw'; + const DATETIME = 'datetime'; + const STRING = 'string'; + const TIMESTAMP = 'timestamp'; + const RAW = 'raw'; - const INPUT = 'input'; - const CHOICE = 'choice'; + const INPUT = 'input'; + const CHOICE = 'choice'; - protected static $formats = array( - self::FULL, - self::LONG, - self::MEDIUM, - self::SHORT, - ); - - protected static $intlFormats = array( - self::FULL => \IntlDateFormatter::FULL, - self::LONG => \IntlDateFormatter::LONG, - self::MEDIUM => \IntlDateFormatter::MEDIUM, - self::SHORT => \IntlDateFormatter::SHORT, - ); - - protected static $widgets = array( - self::INPUT, - self::CHOICE, - ); - - protected static $types = array( - self::DATETIME, - self::STRING, - self::TIMESTAMP, - self::RAW, - ); - - /** - * The ICU formatter instance - * @var \IntlDateFormatter - */ - protected $formatter; - - /** - * Configures the text field. - * - * Available options: - * - * * widget: How to render the field ("input" or "select"). Default: "input" - * * years: An array of years for the year select tag (optional) - * * months: An array of months for the month select tag (optional) - * * days: An array of days for the day select tag (optional) - * * format: See DateValueTransformer. Default: medium - * * type: The type of the date ("date", "datetime" or "timestamp"). Default: "date" - * * data_timezone: The timezone of the data - * * user_timezone: The timezone of the user entering a new value - * * pattern: The pattern for the select boxes when "widget" is "select". - * You can use the placeholders "%year%", "%month%" and "%day%". - * Default: locale dependent - * - * @param array $options Options for this field - * @throws \InvalidArgumentException Thrown if you want to show a timestamp with the select widget. - */ - protected function configure() - { - $this->addOption('years', range(date('Y') - 5, date('Y') + 5)); - $this->addOption('months', range(1, 12)); - $this->addOption('days', range(1, 31)); - $this->addOption('format', self::MEDIUM, self::$formats); - $this->addOption('type', self::DATETIME, self::$types); - $this->addOption('data_timezone', 'UTC'); - $this->addOption('user_timezone', 'UTC'); - $this->addOption('widget', self::CHOICE, self::$widgets); - $this->addOption('pattern'); - - $this->formatter = new \IntlDateFormatter( - $this->locale, - self::$intlFormats[$this->getOption('format')], - \IntlDateFormatter::NONE + protected static $formats = array( + self::FULL, + self::LONG, + self::MEDIUM, + self::SHORT, ); - $transformers = array(); + protected static $intlFormats = array( + self::FULL => \IntlDateFormatter::FULL, + self::LONG => \IntlDateFormatter::LONG, + self::MEDIUM => \IntlDateFormatter::MEDIUM, + self::SHORT => \IntlDateFormatter::SHORT, + ); - if ($this->getOption('type') === self::STRING) + protected static $widgets = array( + self::INPUT, + self::CHOICE, + ); + + protected static $types = array( + self::DATETIME, + self::STRING, + self::TIMESTAMP, + self::RAW, + ); + + /** + * The ICU formatter instance + * @var \IntlDateFormatter + */ + protected $formatter; + + /** + * Configures the text field. + * + * Available options: + * + * * widget: How to render the field ("input" or "select"). Default: "input" + * * years: An array of years for the year select tag (optional) + * * months: An array of months for the month select tag (optional) + * * days: An array of days for the day select tag (optional) + * * format: See DateValueTransformer. Default: medium + * * type: The type of the date ("date", "datetime" or "timestamp"). Default: "date" + * * data_timezone: The timezone of the data + * * user_timezone: The timezone of the user entering a new value + * * pattern: The pattern for the select boxes when "widget" is "select". + * You can use the placeholders "%year%", "%month%" and "%day%". + * Default: locale dependent + * + * @param array $options Options for this field + * @throws \InvalidArgumentException Thrown if you want to show a timestamp with the select widget. + */ + protected function configure() { - $transformers[] = new StringToDateTimeTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - 'format' => 'Y-m-d', - )); - } - else if ($this->getOption('type') === self::TIMESTAMP) - { - $transformers[] = new TimestampToDateTimeTransformer(array( - 'output_timezone' => $this->getOption('data_timezone'), - 'input_timezone' => $this->getOption('data_timezone'), - )); - } - else if ($this->getOption('type') === self::RAW) - { - $transformers[] = new ReversedTransformer(new DateTimeToArrayTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - 'fields' => array('year', 'month', 'day'), - ))); + $this->addOption('years', range(date('Y') - 5, date('Y') + 5)); + $this->addOption('months', range(1, 12)); + $this->addOption('days', range(1, 31)); + $this->addOption('format', self::MEDIUM, self::$formats); + $this->addOption('type', self::DATETIME, self::$types); + $this->addOption('data_timezone', 'UTC'); + $this->addOption('user_timezone', 'UTC'); + $this->addOption('widget', self::CHOICE, self::$widgets); + $this->addOption('pattern'); + + $this->formatter = new \IntlDateFormatter( + $this->locale, + self::$intlFormats[$this->getOption('format')], + \IntlDateFormatter::NONE + ); + + $transformers = array(); + + if ($this->getOption('type') === self::STRING) { + $transformers[] = new StringToDateTimeTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + 'format' => 'Y-m-d', + )); + } else if ($this->getOption('type') === self::TIMESTAMP) { + $transformers[] = new TimestampToDateTimeTransformer(array( + 'output_timezone' => $this->getOption('data_timezone'), + 'input_timezone' => $this->getOption('data_timezone'), + )); + } else if ($this->getOption('type') === self::RAW) { + $transformers[] = new ReversedTransformer(new DateTimeToArrayTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + 'fields' => array('year', 'month', 'day'), + ))); + } + + if ($this->getOption('widget') === self::INPUT) { + $transformers[] = new DateTimeToLocalizedStringTransformer(array( + 'date_format' => $this->getOption('format'), + 'time_format' => DateTimeToLocalizedStringTransformer::NONE, + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('user_timezone'), + )); + + $this->setFieldMode(self::FIELD); + } else { + $transformers[] = new DateTimeToArrayTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('user_timezone'), + )); + + $this->setFieldMode(self::GROUP); + + $this->add(new ChoiceField('year', array( + 'choices' => $this->generatePaddedChoices($this->getOption('years'), 4), + ))); + $this->add(new ChoiceField('month', array( + 'choices' => $this->generateMonthChoices($this->getOption('months')), + ))); + $this->add(new ChoiceField('day', array( + 'choices' => $this->generatePaddedChoices($this->getOption('days'), 2), + ))); + } + + if (count($transformers) > 0) { + $this->setValueTransformer(new ValueTransformerChain($transformers)); + } } - if ($this->getOption('widget') === self::INPUT) + /** + * Generates an array of choices for the given values + * + * If the values are shorter than $padLength characters, they are padded with + * zeros on the left side. + * + * @param array $values The available choices + * @param integer $padLength The length to pad the choices + * @return array An array with the input values as keys and the + * padded values as values + */ + protected function generatePaddedChoices(array $values, $padLength) { - $transformers[] = new DateTimeToLocalizedStringTransformer(array( - 'date_format' => $this->getOption('format'), - 'time_format' => DateTimeToLocalizedStringTransformer::NONE, - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('user_timezone'), - )); + $choices = array(); - $this->setFieldMode(self::FIELD); - } - else - { - $transformers[] = new DateTimeToArrayTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('user_timezone'), - )); + foreach ($values as $value) { + $choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT); + } - $this->setFieldMode(self::GROUP); - - $this->add(new ChoiceField('year', array( - 'choices' => $this->generatePaddedChoices($this->getOption('years'), 4), - ))); - $this->add(new ChoiceField('month', array( - 'choices' => $this->generateMonthChoices($this->getOption('months')), - ))); - $this->add(new ChoiceField('day', array( - 'choices' => $this->generatePaddedChoices($this->getOption('days'), 2), - ))); + return $choices; } - if (count($transformers) > 0) + /** + * Generates an array of localized month choices + * + * @param array $months The month numbers to generate + * @return array The localized months respecting the configured + * locale and date format + */ + protected function generateMonthChoices(array $months) { - $this->setValueTransformer(new ValueTransformerChain($transformers)); - } - } + $pattern = $this->formatter->getPattern(); - /** - * Generates an array of choices for the given values - * - * If the values are shorter than $padLength characters, they are padded with - * zeros on the left side. - * - * @param array $values The available choices - * @param integer $padLength The length to pad the choices - * @return array An array with the input values as keys and the - * padded values as values - */ - protected function generatePaddedChoices(array $values, $padLength) - { - $choices = array(); + if (preg_match('/M+/', $pattern, $matches)) { + $this->formatter->setPattern($matches[0]); + $choices = array(); - foreach ($values as $value) - { - $choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT); + foreach ($months as $month) { + $choices[$month] = $this->formatter->format(gmmktime(0, 0, 0, $month)); + } + + $this->formatter->setPattern($pattern); + } else { + $choices = $this->generatePaddedChoices($months, 2); + } + + return $choices; } - return $choices; - } - - /** - * Generates an array of localized month choices - * - * @param array $months The month numbers to generate - * @return array The localized months respecting the configured - * locale and date format - */ - protected function generateMonthChoices(array $months) - { - $pattern = $this->formatter->getPattern(); - - if (preg_match('/M+/', $pattern, $matches)) + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) { - $this->formatter->setPattern($matches[0]); - $choices = array(); + if ($this->getOption('widget') === self::INPUT) { + return $this->generator->tag('input', array_merge(array( + 'id' => $this->getId(), + 'name' => $this->getName(), + 'value' => $this->getDisplayedData(), + 'type' => 'text', + ), $attributes)); + } else { + // set order as specified in the pattern + if ($this->getOption('pattern')) { + $pattern = $this->getOption('pattern'); + } + // set right order with respect to locale (e.g.: de_DE=dd.MM.yy; en_US=M/d/yy) + // lookup various formats at http://userguide.icu-project.org/formatparse/datetime + else if (preg_match('/^([yMd]+).+([yMd]+).+([yMd]+)$/', $this->formatter->getPattern())) { + $pattern = preg_replace(array('/y+/', '/M+/', '/d+/'), array('%year%', '%month%', '%day%'), $this->formatter->getPattern()); + } + // default fallback + else { + $pattern = '%year%-%month%-%day%'; + } - foreach ($months as $month) - { - $choices[$month] = $this->formatter->format(gmmktime(0, 0, 0, $month)); - } - - $this->formatter->setPattern($pattern); + return str_replace(array('%year%', '%month%', '%day%'), array( + $this->get('year')->render($attributes), + $this->get('month')->render($attributes), + $this->get('day')->render($attributes), + ), $pattern); + } } - else - { - $choices = $this->generatePaddedChoices($months, 2); - } - - return $choices; - } - - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - if ($this->getOption('widget') === self::INPUT) - { - return $this->generator->tag('input', array_merge(array( - 'id' => $this->getId(), - 'name' => $this->getName(), - 'value' => $this->getDisplayedData(), - 'type' => 'text', - ), $attributes)); - } - else - { - // set order as specified in the pattern - if ($this->getOption('pattern')) - { - $pattern = $this->getOption('pattern'); - } - // set right order with respect to locale (e.g.: de_DE=dd.MM.yy; en_US=M/d/yy) - // lookup various formats at http://userguide.icu-project.org/formatparse/datetime - else if (preg_match('/^([yMd]+).+([yMd]+).+([yMd]+)$/', $this->formatter->getPattern())) - { - $pattern = preg_replace(array('/y+/', '/M+/', '/d+/'), array('%year%', '%month%', '%day%'), $this->formatter->getPattern()); - } - // default fallback - else - { - $pattern = '%year%-%month%-%day%'; - } - - return str_replace(array('%year%', '%month%', '%day%'), array( - $this->get('year')->render($attributes), - $this->get('month')->render($attributes), - $this->get('day')->render($attributes), - ), $pattern); - } - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/DateTimeField.php b/src/Symfony/Components/Form/DateTimeField.php index 675b8b9da8..a1a50b18d3 100644 --- a/src/Symfony/Components/Form/DateTimeField.php +++ b/src/Symfony/Components/Form/DateTimeField.php @@ -14,115 +14,112 @@ use Symfony\Components\Form\ValueTransformer\ValueTransformerChain; */ class DateTimeField extends FieldGroup { - const DATETIME = 'datetime'; - const STRING = 'string'; - const TIMESTAMP = 'timestamp'; + const DATETIME = 'datetime'; + const STRING = 'string'; + const TIMESTAMP = 'timestamp'; - protected static $types = array( - self::DATETIME, - self::STRING, - self::TIMESTAMP, - ); + protected static $types = array( + self::DATETIME, + self::STRING, + self::TIMESTAMP, + ); - protected static $dateWidgets = array( - DateField::CHOICE, - DateField::INPUT, - ); + protected static $dateWidgets = array( + DateField::CHOICE, + DateField::INPUT, + ); - protected static $timeWidgets = array( - TimeField::CHOICE, - TimeField::INPUT, - ); + protected static $timeWidgets = array( + TimeField::CHOICE, + TimeField::INPUT, + ); - /** - * {@inheritDoc} - */ - public function configure() - { - $this->addOption('years', range(date('Y') - 5, date('Y') + 5)); - $this->addOption('months', range(1, 12)); - $this->addOption('days', range(1, 31)); - $this->addOption('hours', range(0, 23)); - $this->addOption('minutes', range(0, 59)); - $this->addOption('seconds', range(0, 59)); - $this->addOption('data_timezone', 'UTC'); - $this->addOption('user_timezone', 'UTC'); - $this->addOption('date_widget', DateField::INPUT, self::$dateWidgets); - $this->addOption('time_widget', TimeField::CHOICE, self::$timeWidgets); - $this->addOption('type', self::DATETIME, self::$types); - $this->addOption('with_seconds', false); - - $this->add(new DateField('date', array( - 'type' => DateField::RAW, - 'widget' => $this->getOption('date_widget'), - 'data_timezone' => $this->getOption('user_timezone'), - 'user_timezone' => $this->getOption('user_timezone'), - 'years' => $this->getOption('years'), - 'months' => $this->getOption('months'), - 'days' => $this->getOption('days'), - ))); - $this->add(new TimeField('time', array( - 'type' => TimeField::RAW, - 'widget' => $this->getOption('time_widget'), - 'data_timezone' => $this->getOption('user_timezone'), - 'user_timezone' => $this->getOption('user_timezone'), - 'with_seconds' => $this->getOption('with_seconds'), - 'hours' => $this->getOption('hours'), - 'minutes' => $this->getOption('minutes'), - 'seconds' => $this->getOption('seconds'), - ))); - - $transformers = array(); - - if ($this->getOption('type') == self::STRING) + /** + * {@inheritDoc} + */ + public function configure() { - $transformers[] = new StringToDateTimeTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - )); - } - else if ($this->getOption('type') == self::TIMESTAMP) - { - $transformers[] = new TimestampToDateTimeTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - )); + $this->addOption('years', range(date('Y') - 5, date('Y') + 5)); + $this->addOption('months', range(1, 12)); + $this->addOption('days', range(1, 31)); + $this->addOption('hours', range(0, 23)); + $this->addOption('minutes', range(0, 59)); + $this->addOption('seconds', range(0, 59)); + $this->addOption('data_timezone', 'UTC'); + $this->addOption('user_timezone', 'UTC'); + $this->addOption('date_widget', DateField::INPUT, self::$dateWidgets); + $this->addOption('time_widget', TimeField::CHOICE, self::$timeWidgets); + $this->addOption('type', self::DATETIME, self::$types); + $this->addOption('with_seconds', false); + + $this->add(new DateField('date', array( + 'type' => DateField::RAW, + 'widget' => $this->getOption('date_widget'), + 'data_timezone' => $this->getOption('user_timezone'), + 'user_timezone' => $this->getOption('user_timezone'), + 'years' => $this->getOption('years'), + 'months' => $this->getOption('months'), + 'days' => $this->getOption('days'), + ))); + $this->add(new TimeField('time', array( + 'type' => TimeField::RAW, + 'widget' => $this->getOption('time_widget'), + 'data_timezone' => $this->getOption('user_timezone'), + 'user_timezone' => $this->getOption('user_timezone'), + 'with_seconds' => $this->getOption('with_seconds'), + 'hours' => $this->getOption('hours'), + 'minutes' => $this->getOption('minutes'), + 'seconds' => $this->getOption('seconds'), + ))); + + $transformers = array(); + + if ($this->getOption('type') == self::STRING) { + $transformers[] = new StringToDateTimeTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + )); + } else if ($this->getOption('type') == self::TIMESTAMP) { + $transformers[] = new TimestampToDateTimeTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + )); + } + + $transformers[] = new DateTimeToArrayTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('user_timezone'), + )); + + $this->setValueTransformer(new ValueTransformerChain($transformers)); } - $transformers[] = new DateTimeToArrayTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('user_timezone'), - )); + /** + * {@inheritDoc} + */ + protected function transform($value) + { + $value = parent::transform($value); - $this->setValueTransformer(new ValueTransformerChain($transformers)); - } + return array('date' => $value, 'time' => $value); + } - /** - * {@inheritDoc} - */ - protected function transform($value) - { - $value = parent::transform($value); + /** + * {@inheritDoc} + */ + protected function reverseTransform($value) + { + return parent::reverseTransform(array_merge($value['date'], $value['time'])); + } - return array('date' => $value, 'time' => $value); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + $html = $this->get('date')->render($attributes)."\n"; + $html .= $this->get('time')->render($attributes); - /** - * {@inheritDoc} - */ - protected function reverseTransform($value) - { - return parent::reverseTransform(array_merge($value['date'], $value['time'])); - } - - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - $html = $this->get('date')->render($attributes)."\n"; - $html .= $this->get('time')->render($attributes); - - return $html; - } + return $html; + } } diff --git a/src/Symfony/Components/Form/Exception/InvalidOptionsException.php b/src/Symfony/Components/Form/Exception/InvalidOptionsException.php index 5cbfa166e3..1baf91a1da 100644 --- a/src/Symfony/Components/Form/Exception/InvalidOptionsException.php +++ b/src/Symfony/Components/Form/Exception/InvalidOptionsException.php @@ -4,17 +4,17 @@ namespace Symfony\Components\Form\Exception; class InvalidOptionsException extends FormException { - private $options; + private $options; - public function __construct($message, array $options) - { - parent::__construct($message); + public function __construct($message, array $options) + { + parent::__construct($message); - $this->options = $options; - } + $this->options = $options; + } - public function getOptions() - { - return $this->options; - } + public function getOptions() + { + return $this->options; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Exception/MissingOptionsException.php b/src/Symfony/Components/Form/Exception/MissingOptionsException.php index a5a6decd5a..e0ef3259d7 100644 --- a/src/Symfony/Components/Form/Exception/MissingOptionsException.php +++ b/src/Symfony/Components/Form/Exception/MissingOptionsException.php @@ -4,17 +4,17 @@ namespace Symfony\Components\Form\Exception; class MissingOptionsException extends FormException { - private $options; + private $options; - public function __construct($message, array $options) - { - parent::__construct($message); + public function __construct($message, array $options) + { + parent::__construct($message); - $this->options = $options; - } + $this->options = $options; + } - public function getOptions() - { - return $this->options; - } + public function getOptions() + { + return $this->options; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Field.php b/src/Symfony/Components/Form/Field.php index dffa3c029a..2467a9558e 100644 --- a/src/Symfony/Components/Form/Field.php +++ b/src/Symfony/Components/Form/Field.php @@ -13,693 +13,623 @@ use Symfony\Components\I18N\TranslatorInterface; abstract class Field extends Configurable implements FieldInterface { - /** - * The object used for generating HTML code - * @var HtmlGeneratorInterface - */ - protected $generator = null; + /** + * The object used for generating HTML code + * @var HtmlGeneratorInterface + */ + protected $generator = null; - protected $taintedData = null; - protected $locale = null; - protected $translator = null; + protected $taintedData = null; + protected $locale = null; + protected $translator = null; - private $errors = array(); - private $key = ''; - private $parent = null; - private $renderer = null; - private $bound = false; - private $required = null; - private $data = null; - private $transformedData = null; - private $valueTransformer = null; - private $propertyPath = null; + private $errors = array(); + private $key = ''; + private $parent = null; + private $renderer = null; + private $bound = false; + private $required = null; + private $data = null; + private $transformedData = null; + private $valueTransformer = null; + private $propertyPath = null; - public function __construct($key, array $options = array()) - { - $this->addOption('trim', true); - $this->addOption('required', true); - $this->addOption('disabled', false); - $this->addOption('property_path', (string)$key); - - $this->key = (string)$key; - $this->locale = \Locale::getDefault(); - $this->generator = new HtmlGenerator(); - - parent::__construct($options); - - $this->transformedData = $this->transform($this->data); - $this->required = $this->getOption('required'); - - $this->setPropertyPath($this->getOption('property_path')); - } - - /** - * Clones this field. - */ - public function __clone() - { - // TODO - } - - /** - * Returns the data of the field as it is displayed to the user. - * - * @return string|array When the field is not bound, the transformed - * default data is returned. When the field is bound, - * the bound data is returned. - */ - public function getDisplayedData() - { - return $this->getTransformedData(); - } - - /** - * Returns the data transformed by the value transformer - * - * @return string - */ - protected function getTransformedData() - { - return $this->transformedData; - } - - /** - * {@inheritDoc} - */ - public function setPropertyPath($propertyPath) - { - $this->propertyPath = empty($propertyPath) ? null : new PropertyPath($propertyPath); - } - - /** - * {@inheritDoc} - */ - public function getPropertyPath() - { - return $this->propertyPath; - } - - /** - * {@inheritDoc} - */ - public function setKey($key) - { - $this->key = (string)$key; - } - - /** - * {@inheritDoc} - */ - public function getKey() - { - return $this->key; - } - - /** - * {@inheritDoc} - */ - public function getName() - { - return is_null($this->parent) ? $this->key : $this->parent->getName().'['.$this->key.']'; - } - - /** - * {@inheritDoc} - */ - public function getId() - { - return is_null($this->parent) ? $this->key : $this->parent->getId().'_'.$this->key; - } - - /** - * {@inheritDoc} - */ - public function setRequired($required) - { - $this->required = $required; - } - - /** - * {@inheritDoc} - */ - public function isRequired() - { - if (is_null($this->parent) || $this->parent->isRequired()) + public function __construct($key, array $options = array()) { - return $this->required; - } - else - { - return false; - } - } + $this->addOption('trim', true); + $this->addOption('required', true); + $this->addOption('disabled', false); + $this->addOption('property_path', (string)$key); - /** - * {@inheritDoc} - */ - public function isDisabled() - { - if (is_null($this->parent) || !$this->parent->isDisabled()) - { - return $this->getOption('disabled'); - } - else - { - return true; - } - } + $this->key = (string)$key; + $this->locale = \Locale::getDefault(); + $this->generator = new HtmlGenerator(); - /** - * {@inheritDoc} - */ - public function setGenerator(HtmlGeneratorInterface $generator) - { - $this->generator = $generator; - } + parent::__construct($options); - /** - * {@inheritDoc} - */ - public function isMultipart() - { - return false; - } + $this->transformedData = $this->transform($this->data); + $this->required = $this->getOption('required'); - /** - * Returns true if the widget is hidden. - * - * @return Boolean true if the widget is hidden, false otherwise - */ - public function isHidden() - { - return false; - } - - /** - * {@inheritDoc} - */ - public function setParent(FieldInterface $parent = null) - { - $this->parent = $parent; - } - - /** - * Returns the parent field. - * - * @return FieldInterface The parent field - */ - public function getParent() - { - return $this->parent; - } - - /** - * Updates the field with default data - * - * @see FieldInterface - */ - public function setData($data) - { - $this->data = $data; - $this->transformedData = $this->transform($data); - } - - /** - * Binds POST data to the field, transforms and validates it. - * - * @param string|array $taintedData The POST data - * @return boolean Whether the form is valid - * @throws AlreadyBoundException when the field is already bound - */ - public function bind($taintedData) - { - $this->transformedData = is_array($taintedData) || is_object($taintedData) ? $taintedData : (string)$taintedData; - $this->bound = true; - $this->errors = array(); - - if (is_string($this->transformedData) && $this->getOption('trim')) - { - $this->transformedData = trim($this->transformedData); + $this->setPropertyPath($this->getOption('property_path')); } - try + /** + * Clones this field. + */ + public function __clone() { - $this->data = $this->processData($data = $this->reverseTransform($this->transformedData)); - $this->transformedData = $this->transform($this->data); - } - catch (TransformationFailedException $e) - { - // TODO better text - // TESTME - $this->addError('invalid (localized)'); - } - } - - /** - * Processes the bound reverse-transformed data. - * - * This method can be overridden if you want to modify the data entered - * by the user. Note that the data is already in reverse transformed format. - * - * This method will not be called if reverse transformation fails. - * - * @param mixed $data - * @return mixed - */ - protected function processData($data) - { - return $data; - } - - /** - * Returns the normalized data of the field. - * - * @return mixed When the field is not bound, the default data is returned. - * When the field is bound, the normalized bound data is - * returned if the field is valid, null otherwise. - */ - public function getData() - { - return $this->data; - } - - /** - * Adds an error to the field. - * - * @see FieldInterface - */ - public function addError($message, PropertyPath $path = null, $type = null) - { - $this->errors[] = $message; - } - - /** - * Returns whether the field is bound. - * - * @return boolean true if the form is bound to input values, false otherwise - */ - public function isBound() - { - return $this->bound; - } - - /** - * Returns whether the field is valid. - * - * @return boolean - */ - public function isValid() - { - return $this->isBound() ? count($this->errors)==0 : false; // TESTME - } - - /** - * Returns weather there are errors. - * - * @return boolean true if form is bound and not valid - */ - public function hasErrors() - { - return $this->isBound() && !$this->isValid(); - } - - /** - * Returns all errors - * - * @return array An array of errors that occured during binding - */ - public function getErrors() - { - return $this->errors; - } - - /** - * Sets the locale of this field. - * - * @see Localizable - */ - public function setLocale($locale) - { - $this->locale = $locale; - - if ($this->valueTransformer !== null && $this->valueTransformer instanceof Localizable) - { - $this->valueTransformer->setLocale($locale); - } - } - - /** - * Sets the translator of this field. - * - * @see Translatable - */ - public function setTranslator(TranslatorInterface $translator) - { - $this->translator = $translator; - - if ($this->valueTransformer !== null && $this->valueTransformer instanceof Translatable) - { - $this->valueTransformer->setTranslator($translator); - } - } - - /** - * Translates the text using the associated translator, if available - * - * If no translator is available, the original text is returned without - * modification. - * - * @param string $text The text to translate - * @param array $parameters The parameters to insert in the text - * @return string The translated text - */ - protected function translate($text, array $parameters = array()) - { - if ($this->translator !== null) - { - $text = $this->translator->translate($text, $parameters); + // TODO } - return $text; - } - - /** - * Injects the locale and the translator into the given object, if set. - * - * The locale is injected only if the object implements Localizable. The - * translator is injected only if the object implements Translatable. - * - * @param object $object - */ - protected function injectLocaleAndTranslator($object) - { - if ($object instanceof Localizable) + /** + * Returns the data of the field as it is displayed to the user. + * + * @return string|array When the field is not bound, the transformed + * default data is returned. When the field is bound, + * the bound data is returned. + */ + public function getDisplayedData() { - $object->setLocale($this->locale); + return $this->getTransformedData(); } - if (!is_null($this->translator) && $object instanceof Translatable) + /** + * Returns the data transformed by the value transformer + * + * @return string + */ + protected function getTransformedData() { - $object->setTranslator($this->translator); - } - } - - /** - * Sets the ValueTransformer. - * - * @param ValueTransformerInterface $valueTransformer - */ - public function setValueTransformer(ValueTransformerInterface $valueTransformer) - { - $this->injectLocaleAndTranslator($valueTransformer); - - $this->valueTransformer = $valueTransformer; - } - - /** - * Returns the ValueTransformer. - * - * @return ValueTransformerInterface - */ - public function getValueTransformer() - { - return $this->valueTransformer; - } - - /** - * Transforms the value if a value transformer is set. - * - * @param mixed $value The value to transform - * @return string - */ - protected function transform($value) - { - if ($value === null) - { - return ''; - } - else if (null === $this->valueTransformer) - { - return $value; - } - else - { - return $this->valueTransformer->transform($value); - } - } - - /** - * Reverse transforms a value if a value transformer is set. - * - * @param string $value The value to reverse transform - * @return mixed - */ - protected function reverseTransform($value) - { - if ($value === '') - { - return null; - } - else if (null === $this->valueTransformer) - { - return $value; - } - else - { - return $this->valueTransformer->reverseTransform($value); - } - } - - /** - * {@inheritDoc} - */ - public function updateFromObject(&$objectOrArray) - { - // TODO throw exception if not object or array - - if ($this->propertyPath !== null) - { - $this->propertyPath->rewind(); - $this->setData($this->readPropertyPath($objectOrArray, $this->propertyPath)); - } - else - { - // pass object through if the property path is empty - $this->setData($objectOrArray); - } - } - - /** - * {@inheritDoc} - */ - public function updateObject(&$objectOrArray) - { - // TODO throw exception if not object or array - - if ($this->propertyPath !== null) - { - $this->propertyPath->rewind(); - $this->updatePropertyPath($objectOrArray, $this->propertyPath); - } - } - - /** - * Recursively reads the value of the property path in the data - * - * @param array|object $objectOrArray An object or array - * @param PropertyPath $propertyPath A property path pointing to a property - * in the object/array. - */ - protected function readPropertyPath(&$objectOrArray, PropertyPath $propertyPath) - { - if (is_object($objectOrArray)) - { - $value = $this->readProperty($objectOrArray, $propertyPath); - } - // arrays need to be treated separately (due to PHP bug?) - // http://bugs.php.net/bug.php?id=52133 - else - { - if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) - { - $objectOrArray[$propertyPath->getCurrent()] = array(); - } - - $value =& $objectOrArray[$propertyPath->getCurrent()]; + return $this->transformedData; } - if ($propertyPath->hasNext()) + /** + * {@inheritDoc} + */ + public function setPropertyPath($propertyPath) { - $propertyPath->next(); - - return $this->readPropertyPath($value, $propertyPath); + $this->propertyPath = empty($propertyPath) ? null : new PropertyPath($propertyPath); } - else - { - return $value; - } - } - protected function updatePropertyPath(&$objectOrArray, PropertyPath $propertyPath) - { - if ($propertyPath->hasNext()) + /** + * {@inheritDoc} + */ + public function getPropertyPath() { - if (is_object($objectOrArray)) - { - $value = $this->readProperty($objectOrArray, $propertyPath); - } - // arrays need to be treated separately (due to PHP bug?) - // http://bugs.php.net/bug.php?id=52133 - else - { - if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) - { - $objectOrArray[$propertyPath->getCurrent()] = array(); + return $this->propertyPath; + } + + /** + * {@inheritDoc} + */ + public function setKey($key) + { + $this->key = (string)$key; + } + + /** + * {@inheritDoc} + */ + public function getKey() + { + return $this->key; + } + + /** + * {@inheritDoc} + */ + public function getName() + { + return is_null($this->parent) ? $this->key : $this->parent->getName().'['.$this->key.']'; + } + + /** + * {@inheritDoc} + */ + public function getId() + { + return is_null($this->parent) ? $this->key : $this->parent->getId().'_'.$this->key; + } + + /** + * {@inheritDoc} + */ + public function setRequired($required) + { + $this->required = $required; + } + + /** + * {@inheritDoc} + */ + public function isRequired() + { + if (is_null($this->parent) || $this->parent->isRequired()) { + return $this->required; + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + public function isDisabled() + { + if (is_null($this->parent) || !$this->parent->isDisabled()) { + return $this->getOption('disabled'); + } else { + return true; + } + } + + /** + * {@inheritDoc} + */ + public function setGenerator(HtmlGeneratorInterface $generator) + { + $this->generator = $generator; + } + + /** + * {@inheritDoc} + */ + public function isMultipart() + { + return false; + } + + /** + * Returns true if the widget is hidden. + * + * @return Boolean true if the widget is hidden, false otherwise + */ + public function isHidden() + { + return false; + } + + /** + * {@inheritDoc} + */ + public function setParent(FieldInterface $parent = null) + { + $this->parent = $parent; + } + + /** + * Returns the parent field. + * + * @return FieldInterface The parent field + */ + public function getParent() + { + return $this->parent; + } + + /** + * Updates the field with default data + * + * @see FieldInterface + */ + public function setData($data) + { + $this->data = $data; + $this->transformedData = $this->transform($data); + } + + /** + * Binds POST data to the field, transforms and validates it. + * + * @param string|array $taintedData The POST data + * @return boolean Whether the form is valid + * @throws AlreadyBoundException when the field is already bound + */ + public function bind($taintedData) + { + $this->transformedData = is_array($taintedData) || is_object($taintedData) ? $taintedData : (string)$taintedData; + $this->bound = true; + $this->errors = array(); + + if (is_string($this->transformedData) && $this->getOption('trim')) { + $this->transformedData = trim($this->transformedData); } - $value =& $objectOrArray[$propertyPath->getCurrent()]; - } - - $propertyPath->next(); - - $this->updatePropertyPath($value, $propertyPath); + try { + $this->data = $this->processData($data = $this->reverseTransform($this->transformedData)); + $this->transformedData = $this->transform($this->data); + } catch (TransformationFailedException $e) { + // TODO better text + // TESTME + $this->addError('invalid (localized)'); + } } - else + + /** + * Processes the bound reverse-transformed data. + * + * This method can be overridden if you want to modify the data entered + * by the user. Note that the data is already in reverse transformed format. + * + * This method will not be called if reverse transformation fails. + * + * @param mixed $data + * @return mixed + */ + protected function processData($data) { - $this->updateProperty($objectOrArray, $propertyPath); + return $data; } - } - /** - * Reads a specific element of the given data - * - * If the data is an array, the value at index $element is returned. - * - * If the data is an object, either the result of get{$element}(), - * is{$element}() or the property $element is returned. If none of these - * is publicly available, an exception is thrown - * - * @param object $object The data to read - * @param string $element The element to read from the data - * @return mixed The value of the element - */ - protected function readProperty($object, PropertyPath $propertyPath) - { - if ($propertyPath->isIndex()) + /** + * Returns the normalized data of the field. + * + * @return mixed When the field is not bound, the default data is returned. + * When the field is bound, the normalized bound data is + * returned if the field is valid, null otherwise. + */ + public function getData() { - if (!$object instanceof \ArrayAccess) - { - throw new InvalidPropertyException(sprintf('Index "%s" cannot be read from object of type "%s" because it doesn\'t implement \ArrayAccess', $propertyPath->getCurrent(), get_class($object))); - } - - return $object[$propertyPath->getCurrent()]; + return $this->data; } - else - { - $reflClass = new \ReflectionClass($object); - $getter = 'get'.ucfirst($propertyPath->getCurrent()); - $isser = 'is'.ucfirst($propertyPath->getCurrent()); - $property = $propertyPath->getCurrent(); - if ($reflClass->hasMethod($getter)) - { - if (!$reflClass->getMethod($getter)->isPublic()) - { - throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $getter, $reflClass->getName())); + /** + * Adds an error to the field. + * + * @see FieldInterface + */ + public function addError($message, PropertyPath $path = null, $type = null) + { + $this->errors[] = $message; + } + + /** + * Returns whether the field is bound. + * + * @return boolean true if the form is bound to input values, false otherwise + */ + public function isBound() + { + return $this->bound; + } + + /** + * Returns whether the field is valid. + * + * @return boolean + */ + public function isValid() + { + return $this->isBound() ? count($this->errors)==0 : false; // TESTME + } + + /** + * Returns weather there are errors. + * + * @return boolean true if form is bound and not valid + */ + public function hasErrors() + { + return $this->isBound() && !$this->isValid(); + } + + /** + * Returns all errors + * + * @return array An array of errors that occured during binding + */ + public function getErrors() + { + return $this->errors; + } + + /** + * Sets the locale of this field. + * + * @see Localizable + */ + public function setLocale($locale) + { + $this->locale = $locale; + + if ($this->valueTransformer !== null && $this->valueTransformer instanceof Localizable) { + $this->valueTransformer->setLocale($locale); + } + } + + /** + * Sets the translator of this field. + * + * @see Translatable + */ + public function setTranslator(TranslatorInterface $translator) + { + $this->translator = $translator; + + if ($this->valueTransformer !== null && $this->valueTransformer instanceof Translatable) { + $this->valueTransformer->setTranslator($translator); + } + } + + /** + * Translates the text using the associated translator, if available + * + * If no translator is available, the original text is returned without + * modification. + * + * @param string $text The text to translate + * @param array $parameters The parameters to insert in the text + * @return string The translated text + */ + protected function translate($text, array $parameters = array()) + { + if ($this->translator !== null) { + $text = $this->translator->translate($text, $parameters); } - return $object->$getter(); - } - else if ($reflClass->hasMethod($isser)) - { - if (!$reflClass->getMethod($isser)->isPublic()) - { - throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $isser, $reflClass->getName())); + return $text; + } + + /** + * Injects the locale and the translator into the given object, if set. + * + * The locale is injected only if the object implements Localizable. The + * translator is injected only if the object implements Translatable. + * + * @param object $object + */ + protected function injectLocaleAndTranslator($object) + { + if ($object instanceof Localizable) { + $object->setLocale($this->locale); } - return $object->$isser(); - } - else if ($reflClass->hasProperty($property)) - { - if (!$reflClass->getProperty($property)->isPublic()) - { - throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "get%s()" or "is%s()"?', $property, $reflClass->getName(), ucfirst($property), ucfirst($property))); + if (!is_null($this->translator) && $object instanceof Translatable) { + $object->setTranslator($this->translator); + } + } + + /** + * Sets the ValueTransformer. + * + * @param ValueTransformerInterface $valueTransformer + */ + public function setValueTransformer(ValueTransformerInterface $valueTransformer) + { + $this->injectLocaleAndTranslator($valueTransformer); + + $this->valueTransformer = $valueTransformer; + } + + /** + * Returns the ValueTransformer. + * + * @return ValueTransformerInterface + */ + public function getValueTransformer() + { + return $this->valueTransformer; + } + + /** + * Transforms the value if a value transformer is set. + * + * @param mixed $value The value to transform + * @return string + */ + protected function transform($value) + { + if ($value === null) { + return ''; + } else if (null === $this->valueTransformer) { + return $value; + } else { + return $this->valueTransformer->transform($value); + } + } + + /** + * Reverse transforms a value if a value transformer is set. + * + * @param string $value The value to reverse transform + * @return mixed + */ + protected function reverseTransform($value) + { + if ($value === '') { + return null; + } else if (null === $this->valueTransformer) { + return $value; + } else { + return $this->valueTransformer->reverseTransform($value); + } + } + + /** + * {@inheritDoc} + */ + public function updateFromObject(&$objectOrArray) + { + // TODO throw exception if not object or array + + if ($this->propertyPath !== null) { + $this->propertyPath->rewind(); + $this->setData($this->readPropertyPath($objectOrArray, $this->propertyPath)); + } else { + // pass object through if the property path is empty + $this->setData($objectOrArray); + } + } + + /** + * {@inheritDoc} + */ + public function updateObject(&$objectOrArray) + { + // TODO throw exception if not object or array + + if ($this->propertyPath !== null) { + $this->propertyPath->rewind(); + $this->updatePropertyPath($objectOrArray, $this->propertyPath); + } + } + + /** + * Recursively reads the value of the property path in the data + * + * @param array|object $objectOrArray An object or array + * @param PropertyPath $propertyPath A property path pointing to a property + * in the object/array. + */ + protected function readPropertyPath(&$objectOrArray, PropertyPath $propertyPath) + { + if (is_object($objectOrArray)) { + $value = $this->readProperty($objectOrArray, $propertyPath); + } + // arrays need to be treated separately (due to PHP bug?) + // http://bugs.php.net/bug.php?id=52133 + else { + if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) { + $objectOrArray[$propertyPath->getCurrent()] = array(); + } + + $value =& $objectOrArray[$propertyPath->getCurrent()]; } - return $object->$property; - } - else - { - throw new InvalidPropertyException(sprintf('Neither property "%s" nor method "%s()" nor method "%s()" exists in class "%s"', $property, $getter, $isser, $reflClass->getName())); - } + if ($propertyPath->hasNext()) { + $propertyPath->next(); + + return $this->readPropertyPath($value, $propertyPath); + } else { + return $value; + } } - } - protected function updateProperty(&$objectOrArray, PropertyPath $propertyPath) - { - if (is_object($objectOrArray) && $propertyPath->isIndex()) + protected function updatePropertyPath(&$objectOrArray, PropertyPath $propertyPath) { - if (!$objectOrArray instanceof \ArrayAccess) - { - throw new InvalidPropertyException(sprintf('Index "%s" cannot be modified in object of type "%s" because it doesn\'t implement \ArrayAccess', $propertyPath->getCurrent(), get_class($objectOrArray))); - } + if ($propertyPath->hasNext()) { + if (is_object($objectOrArray)) { + $value = $this->readProperty($objectOrArray, $propertyPath); + } + // arrays need to be treated separately (due to PHP bug?) + // http://bugs.php.net/bug.php?id=52133 + else { + if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) { + $objectOrArray[$propertyPath->getCurrent()] = array(); + } - $objectOrArray[$propertyPath->getCurrent()] = $this->getData(); + $value =& $objectOrArray[$propertyPath->getCurrent()]; + } + + $propertyPath->next(); + + $this->updatePropertyPath($value, $propertyPath); + } else { + $this->updateProperty($objectOrArray, $propertyPath); + } } - else if (is_object($objectOrArray)) - { - $reflClass = new \ReflectionClass($objectOrArray); - $setter = 'set'.ucfirst($propertyPath->getCurrent()); - $property = $propertyPath->getCurrent(); - if ($reflClass->hasMethod($setter)) - { - if (!$reflClass->getMethod($setter)->isPublic()) - { - throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName())); + /** + * Reads a specific element of the given data + * + * If the data is an array, the value at index $element is returned. + * + * If the data is an object, either the result of get{$element}(), + * is{$element}() or the property $element is returned. If none of these + * is publicly available, an exception is thrown + * + * @param object $object The data to read + * @param string $element The element to read from the data + * @return mixed The value of the element + */ + protected function readProperty($object, PropertyPath $propertyPath) + { + if ($propertyPath->isIndex()) { + if (!$object instanceof \ArrayAccess) { + throw new InvalidPropertyException(sprintf('Index "%s" cannot be read from object of type "%s" because it doesn\'t implement \ArrayAccess', $propertyPath->getCurrent(), get_class($object))); + } + + return $object[$propertyPath->getCurrent()]; + } else { + $reflClass = new \ReflectionClass($object); + $getter = 'get'.ucfirst($propertyPath->getCurrent()); + $isser = 'is'.ucfirst($propertyPath->getCurrent()); + $property = $propertyPath->getCurrent(); + + if ($reflClass->hasMethod($getter)) { + if (!$reflClass->getMethod($getter)->isPublic()) { + throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $getter, $reflClass->getName())); + } + + return $object->$getter(); + } else if ($reflClass->hasMethod($isser)) { + if (!$reflClass->getMethod($isser)->isPublic()) { + throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $isser, $reflClass->getName())); + } + + return $object->$isser(); + } else if ($reflClass->hasProperty($property)) { + if (!$reflClass->getProperty($property)->isPublic()) { + throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "get%s()" or "is%s()"?', $property, $reflClass->getName(), ucfirst($property), ucfirst($property))); + } + + return $object->$property; + } else { + throw new InvalidPropertyException(sprintf('Neither property "%s" nor method "%s()" nor method "%s()" exists in class "%s"', $property, $getter, $isser, $reflClass->getName())); + } + } + } + + protected function updateProperty(&$objectOrArray, PropertyPath $propertyPath) + { + if (is_object($objectOrArray) && $propertyPath->isIndex()) { + if (!$objectOrArray instanceof \ArrayAccess) { + throw new InvalidPropertyException(sprintf('Index "%s" cannot be modified in object of type "%s" because it doesn\'t implement \ArrayAccess', $propertyPath->getCurrent(), get_class($objectOrArray))); + } + + $objectOrArray[$propertyPath->getCurrent()] = $this->getData(); + } else if (is_object($objectOrArray)) { + $reflClass = new \ReflectionClass($objectOrArray); + $setter = 'set'.ucfirst($propertyPath->getCurrent()); + $property = $propertyPath->getCurrent(); + + if ($reflClass->hasMethod($setter)) { + if (!$reflClass->getMethod($setter)->isPublic()) { + throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName())); + } + + $objectOrArray->$setter($this->getData()); + } else if ($reflClass->hasProperty($property)) { + if (!$reflClass->getProperty($property)->isPublic()) { + throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "set%s()"?', $property, $reflClass->getName(), ucfirst($property))); + } + + $objectOrArray->$property = $this->getData(); + } else { + throw new InvalidPropertyException(sprintf('Neither element "%s" nor method "%s()" exists in class "%s"', $property, $setter, $reflClass->getName())); + } + } else { + $objectOrArray[$propertyPath->getCurrent()] = $this->getData(); + } + } + + /** + * {@inheritDoc} + */ + public function renderErrors() + { + $html = ''; + + if ($this->hasErrors()) { + $html .= "\n"; } - $objectOrArray->$setter($this->getData()); - } - else if ($reflClass->hasProperty($property)) - { - if (!$reflClass->getProperty($property)->isPublic()) - { - throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "set%s()"?', $property, $reflClass->getName(), ucfirst($property))); - } - - $objectOrArray->$property = $this->getData(); - } - else - { - throw new InvalidPropertyException(sprintf('Neither element "%s" nor method "%s()" exists in class "%s"', $property, $setter, $reflClass->getName())); - } + return $html; } - else - { - $objectOrArray[$propertyPath->getCurrent()] = $this->getData(); - } - } - - /** - * {@inheritDoc} - */ - public function renderErrors() - { - $html = ''; - - if ($this->hasErrors()) - { - $html .= "\n"; - } - - return $html; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/FieldGroup.php b/src/Symfony/Components/Form/FieldGroup.php index eefa368957..a78f85672f 100644 --- a/src/Symfony/Components/Form/FieldGroup.php +++ b/src/Symfony/Components/Form/FieldGroup.php @@ -29,609 +29,565 @@ use Symfony\Components\I18N\TranslatorInterface; */ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterface { - /** - * Contains all the fields of this group - * @var array - */ - protected $fields = array(); + /** + * Contains all the fields of this group + * @var array + */ + protected $fields = array(); - /** - * Contains the names of bound values who don't belong to any fields - * @var array - */ - protected $extraFields = array(); + /** + * Contains the names of bound values who don't belong to any fields + * @var array + */ + protected $extraFields = array(); - /** - * Constructor - * - * @see FieldInterface::__construct() - */ - public function __construct($key, array $options = array()) - { - // set the default renderer before calling the configure() method - $this->setRenderer(new TableRenderer()); - - parent::__construct($key, $options); - } - - /** - * Clones this group - */ - public function __clone() - { - foreach ($this->fields as $name => $field) + /** + * Constructor + * + * @see FieldInterface::__construct() + */ + public function __construct($key, array $options = array()) { - $this->fields[$name] = clone $field; - } - } + // set the default renderer before calling the configure() method + $this->setRenderer(new TableRenderer()); - /** - * Adds a new field to this group. A field must have a unique name within - * the group. Otherwise the existing field is overwritten. - * - * If you add a nested group, this group should also be represented in the - * object hierarchy. If you want to add a group that operates on the same - * hierarchy level, use merge(). - * - * - * class Entity - * { - * public $location; - * } - * - * class Location - * { - * public $longitude; - * public $latitude; - * } - * - * $entity = new Entity(); - * $entity->location = new Location(); - * - * $form = new Form('entity', $entity, $validator); - * - * $locationGroup = new FieldGroup('location'); - * $locationGroup->add(new TextField('longitude')); - * $locationGroup->add(new TextField('latitude')); - * - * $form->add($locationGroup); - * - * - * @param FieldInterface $field - */ - public function add(FieldInterface $field) - { - if ($this->isBound()) - { - throw new AlreadyBoundException('You cannot add fields after binding a form'); + parent::__construct($key, $options); } - $this->fields[$field->getKey()] = $field; - - $field->setParent($this); - $field->setLocale($this->locale); - $field->setGenerator($this->generator); - - if ($this->translator !== null) + /** + * Clones this group + */ + public function __clone() { - $field->setTranslator($this->translator); - } - - $data = $this->getTransformedData(); - - // if the property "data" is NULL, getTransformedData() returns an empty - // string - if (!empty($data) && $field->getPropertyPath() !== null) - { - $field->updateFromObject($data); - } - - return $field; - } - - /** - * Merges a field group into this group. The group must have a unique name - * within the group. Otherwise the existing field is overwritten. - * - * Contrary to added groups, merged groups operate on the same object as - * the group they are merged into. - * - * - * class Entity - * { - * public $longitude; - * public $latitude; - * } - * - * $entity = new Entity(); - * - * $form = new Form('entity', $entity, $validator); - * - * $locationGroup = new FieldGroup('location'); - * $locationGroup->add(new TextField('longitude')); - * $locationGroup->add(new TextField('latitude')); - * - * $form->merge($locationGroup); - * - * - * @param FieldGroup $group - */ - public function merge(FieldGroup $group) - { - if ($group->isBound()) - { - throw new AlreadyBoundException('A bound form group cannot be merged'); - } - - foreach ($group as $field) - { - $group->remove($field->getKey()); - $this->add($field); - - if (($path = $group->getPropertyPath()) !== null) - { - $field->setPropertyPath($path.'.'.$field->getPropertyPath()); - } - } - - return $this; - } - - /** - * Removes the field with the given key. - * - * @param string $key - */ - public function remove($key) - { - $this->fields[$key]->setParent(null); - - unset($this->fields[$key]); - } - - /** - * Returns whether a field with the given key exists. - * - * @param string $key - * @return boolean - */ - public function has($key) - { - return isset($this->fields[$key]); - } - - /** - * Returns the field with the given key. - * - * @param string $key - * @return FieldInterface - */ - public function get($key) - { - if (isset($this->fields[$key])) - { - return $this->fields[$key]; - } - - throw new \InvalidArgumentException(sprintf('Field "%s" does not exist.', $key)); - } - - /** - * Returns all fields in this group - * - * @return array - */ - public function getFields() - { - return $this->fields; - } - - /** - * Returns an array of hidden fields from the current schema. - * - * @param boolean $recursive Whether to recur through embedded schemas - * - * @return array - */ - public function getHiddenFields($recursive = true) - { - $fields = array(); - - foreach ($this->fields as $field) - { - if ($field instanceof FieldGroup) - { - if ($recursive) - { - $fields = array_merge($fields, $field->getHiddenFields($recursive)); + foreach ($this->fields as $name => $field) { + $this->fields[$name] = clone $field; } - } - else if ($field->isHidden()) - { - $fields[] = $field; - } } - return $fields; - } - - /** - * Initializes the field group with an object to operate on - * - * @see FieldInterface - */ - public function setData($data) - { - parent::setData($data); - - // get transformed data and pass its values to child fields - $data = $this->getTransformedData(); - - if (!empty($data) && !is_array($data) && !is_object($data)) + /** + * Adds a new field to this group. A field must have a unique name within + * the group. Otherwise the existing field is overwritten. + * + * If you add a nested group, this group should also be represented in the + * object hierarchy. If you want to add a group that operates on the same + * hierarchy level, use merge(). + * + * + * class Entity + * { + * public $location; + * } + * + * class Location + * { + * public $longitude; + * public $latitude; + * } + * + * $entity = new Entity(); + * $entity->location = new Location(); + * + * $form = new Form('entity', $entity, $validator); + * + * $locationGroup = new FieldGroup('location'); + * $locationGroup->add(new TextField('longitude')); + * $locationGroup->add(new TextField('latitude')); + * + * $form->add($locationGroup); + * + * + * @param FieldInterface $field + */ + public function add(FieldInterface $field) { - throw new \InvalidArgumentException(sprintf('Expected argument of type object or array, %s given', gettype($data))); - } - - if (!empty($data)) - { - $iterator = new RecursiveFieldsWithPropertyPathIterator($this); - $iterator = new \RecursiveIteratorIterator($iterator); - - foreach ($iterator as $field) - { - $field->updateFromObject($data); - } - } - } - - /** - * Returns the data of the field as it is displayed to the user. - * - * @see FieldInterface - */ - public function getDisplayedData() - { - $values = array(); - - foreach ($this->fields as $key => $field) - { - $values[$key] = $field->getDisplayedData(); - } - - return $values; - } - - /** - * Binds POST data to the field, transforms and validates it. - * - * @param string|array $taintedData The POST data - * @return boolean Whether the form is valid - */ - public function bind($taintedData) - { - if ($taintedData === null) - { - $taintedData = array(); - } - - if (!is_array($taintedData)) - { - throw new UnexpectedTypeException('You must pass an array parameter to the bind() method'); - } - - foreach ($this->fields as $key => $field) - { - if (!isset($taintedData[$key])) - { - $taintedData[$key] = null; - } - } - - foreach ($taintedData as $key => $value) - { - if ($this->has($key)) - { - $this->fields[$key]->bind($value); - } - } - - $data = $this->getTransformedData(); - $iterator = new RecursiveFieldsWithPropertyPathIterator($this); - $iterator = new \RecursiveIteratorIterator($iterator); - - foreach ($iterator as $field) - { - $field->updateObject($data); - } - - // bind and reverse transform the data - parent::bind($data); - - $this->extraFields = array(); - - foreach ($taintedData as $key => $value) - { - if (!$this->has($key)) - { - $this->extraFields[] = $key; - } - } - } - - /** - * Returns whether this form was bound with extra fields - * - * @return boolean - */ - public function isBoundWithExtraFields() - { - // TODO: integrate the field names in the error message - return count($this->extraFields) > 0; - } - - /** - * Returns whether the field is valid. - * - * @return boolean - */ - public function isValid() - { - if (!parent::isValid()) - { - return false; - } - - foreach ($this->fields as $field) - { - if (!$field->isValid()) - { - return false; - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - public function addError($message, PropertyPath $path = null, $type = null) - { - if ($path !== null) - { - if ($type === self::FIELD_ERROR && $path->hasNext()) - { - $path->next(); - - if ($this->has($path->getCurrent()) && !$this->get($path->getCurrent())->isHidden()) - { - $this->get($path->getCurrent())->addError($message, $path, $type); - - return; + if ($this->isBound()) { + throw new AlreadyBoundException('You cannot add fields after binding a form'); } - } - else if ($type === self::DATA_ERROR) - { + + $this->fields[$field->getKey()] = $field; + + $field->setParent($this); + $field->setLocale($this->locale); + $field->setGenerator($this->generator); + + if ($this->translator !== null) { + $field->setTranslator($this->translator); + } + + $data = $this->getTransformedData(); + + // if the property "data" is NULL, getTransformedData() returns an empty + // string + if (!empty($data) && $field->getPropertyPath() !== null) { + $field->updateFromObject($data); + } + + return $field; + } + + /** + * Merges a field group into this group. The group must have a unique name + * within the group. Otherwise the existing field is overwritten. + * + * Contrary to added groups, merged groups operate on the same object as + * the group they are merged into. + * + * + * class Entity + * { + * public $longitude; + * public $latitude; + * } + * + * $entity = new Entity(); + * + * $form = new Form('entity', $entity, $validator); + * + * $locationGroup = new FieldGroup('location'); + * $locationGroup->add(new TextField('longitude')); + * $locationGroup->add(new TextField('latitude')); + * + * $form->merge($locationGroup); + * + * + * @param FieldGroup $group + */ + public function merge(FieldGroup $group) + { + if ($group->isBound()) { + throw new AlreadyBoundException('A bound form group cannot be merged'); + } + + foreach ($group as $field) { + $group->remove($field->getKey()); + $this->add($field); + + if (($path = $group->getPropertyPath()) !== null) { + $field->setPropertyPath($path.'.'.$field->getPropertyPath()); + } + } + + return $this; + } + + /** + * Removes the field with the given key. + * + * @param string $key + */ + public function remove($key) + { + $this->fields[$key]->setParent(null); + + unset($this->fields[$key]); + } + + /** + * Returns whether a field with the given key exists. + * + * @param string $key + * @return boolean + */ + public function has($key) + { + return isset($this->fields[$key]); + } + + /** + * Returns the field with the given key. + * + * @param string $key + * @return FieldInterface + */ + public function get($key) + { + if (isset($this->fields[$key])) { + return $this->fields[$key]; + } + + throw new \InvalidArgumentException(sprintf('Field "%s" does not exist.', $key)); + } + + /** + * Returns all fields in this group + * + * @return array + */ + public function getFields() + { + return $this->fields; + } + + /** + * Returns an array of hidden fields from the current schema. + * + * @param boolean $recursive Whether to recur through embedded schemas + * + * @return array + */ + public function getHiddenFields($recursive = true) + { + $fields = array(); + + foreach ($this->fields as $field) { + if ($field instanceof FieldGroup) { + if ($recursive) { + $fields = array_merge($fields, $field->getHiddenFields($recursive)); + } + } else if ($field->isHidden()) { + $fields[] = $field; + } + } + + return $fields; + } + + /** + * Initializes the field group with an object to operate on + * + * @see FieldInterface + */ + public function setData($data) + { + parent::setData($data); + + // get transformed data and pass its values to child fields + $data = $this->getTransformedData(); + + if (!empty($data) && !is_array($data) && !is_object($data)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type object or array, %s given', gettype($data))); + } + + if (!empty($data)) { + $iterator = new RecursiveFieldsWithPropertyPathIterator($this); + $iterator = new \RecursiveIteratorIterator($iterator); + + foreach ($iterator as $field) { + $field->updateFromObject($data); + } + } + } + + /** + * Returns the data of the field as it is displayed to the user. + * + * @see FieldInterface + */ + public function getDisplayedData() + { + $values = array(); + + foreach ($this->fields as $key => $field) { + $values[$key] = $field->getDisplayedData(); + } + + return $values; + } + + /** + * Binds POST data to the field, transforms and validates it. + * + * @param string|array $taintedData The POST data + * @return boolean Whether the form is valid + */ + public function bind($taintedData) + { + if ($taintedData === null) { + $taintedData = array(); + } + + if (!is_array($taintedData)) { + throw new UnexpectedTypeException('You must pass an array parameter to the bind() method'); + } + + foreach ($this->fields as $key => $field) { + if (!isset($taintedData[$key])) { + $taintedData[$key] = null; + } + } + + foreach ($taintedData as $key => $value) { + if ($this->has($key)) { + $this->fields[$key]->bind($value); + } + } + + $data = $this->getTransformedData(); $iterator = new RecursiveFieldsWithPropertyPathIterator($this); $iterator = new \RecursiveIteratorIterator($iterator); - foreach ($iterator as $field) - { - if (null !== ($fieldPath = $field->getPropertyPath())) - { - $fieldPath->rewind(); - - if ($fieldPath->getCurrent() === $path->getCurrent() && !$field->isHidden()) - { - if ($path->hasNext()) - { - $path->next(); - } - - $field->addError($message, $path, $type); - - return; - } - } + foreach ($iterator as $field) { + $field->updateObject($data); + } + + // bind and reverse transform the data + parent::bind($data); + + $this->extraFields = array(); + + foreach ($taintedData as $key => $value) { + if (!$this->has($key)) { + $this->extraFields[] = $key; + } } - } } - parent::addError($message); - } - - /** - * Returns whether the field requires a multipart form. - * - * @return boolean - */ - public function isMultipart() - { - foreach ($this->fields as $field) + /** + * Returns whether this form was bound with extra fields + * + * @return boolean + */ + public function isBoundWithExtraFields() { - if ($field->isMultipart()) - { + // TODO: integrate the field names in the error message + return count($this->extraFields) > 0; + } + + /** + * Returns whether the field is valid. + * + * @return boolean + */ + public function isValid() + { + if (!parent::isValid()) { + return false; + } + + foreach ($this->fields as $field) { + if (!$field->isValid()) { + return false; + } + } + return true; - } } - return false; - } - - /** - * Sets the renderer. - * - * @param RendererInterface $renderer - */ - public function setRenderer(RendererInterface $renderer) - { - $this->renderer = $renderer; - } - - /** - * Returns the current renderer. - * - * @return RendererInterface - */ - public function getRenderer() - { - return $this->renderer; - } - - /** - * Delegates the rendering of the field to the renderer set. - * - * @return string The rendered widget - */ - public function render(array $attributes = array()) - { - $this->injectLocaleAndTranslator($this->renderer); - - return $this->renderer->render($this, $attributes); - } - - /** - * Delegates the rendering of the field to the renderer set. - * - * @return string The rendered widget - */ - public function renderErrors() - { - $this->injectLocaleAndTranslator($this->renderer); - - return $this->renderer->renderErrors($this); - } - /** - * Renders hidden form fields. - * - * @param boolean $recursive False will prevent hidden fields from embedded forms from rendering - * - * @return string - */ - public function renderHiddenFields($recursive = true) - { - $output = ''; - - foreach ($this->getHiddenFields($recursive) as $field) + /** + * {@inheritDoc} + */ + public function addError($message, PropertyPath $path = null, $type = null) { - $output .= $field->render(); + if ($path !== null) { + if ($type === self::FIELD_ERROR && $path->hasNext()) { + $path->next(); + + if ($this->has($path->getCurrent()) && !$this->get($path->getCurrent())->isHidden()) { + $this->get($path->getCurrent())->addError($message, $path, $type); + + return; + } + } else if ($type === self::DATA_ERROR) { + $iterator = new RecursiveFieldsWithPropertyPathIterator($this); + $iterator = new \RecursiveIteratorIterator($iterator); + + foreach ($iterator as $field) { + if (null !== ($fieldPath = $field->getPropertyPath())) { + $fieldPath->rewind(); + + if ($fieldPath->getCurrent() === $path->getCurrent() && !$field->isHidden()) { + if ($path->hasNext()) { + $path->next(); + } + + $field->addError($message, $path, $type); + + return; + } + } + } + } + } + + parent::addError($message); } - return $output; - } - - /** - * Returns true if the bound field exists (implements the \ArrayAccess interface). - * - * @param string $key The key of the bound field - * - * @return Boolean true if the widget exists, false otherwise - */ - public function offsetExists($key) - { - return $this->has($key); - } - - /** - * Returns the form field associated with the name (implements the \ArrayAccess interface). - * - * @param string $key The offset of the value to get - * - * @return Field A form field instance - */ - public function offsetGet($key) - { - return $this->get($key); - } - - /** - * Throws an exception saying that values cannot be set (implements the \ArrayAccess interface). - * - * @param string $offset (ignored) - * @param string $value (ignored) - * - * @throws \LogicException - */ - public function offsetSet($key, $field) - { - throw new \LogicException('Use the method add() to add fields'); - } - - /** - * Throws an exception saying that values cannot be unset (implements the \ArrayAccess interface). - * - * @param string $key - * - * @throws \LogicException - */ - public function offsetUnset($key) - { - return $this->remove($key); - } - - /** - * Returns the iterator for this group. - * - * @return \ArrayIterator - */ - public function getIterator() - { - return new \ArrayIterator($this->fields); - } - - /** - * Returns the number of form fields (implements the \Countable interface). - * - * @return integer The number of embedded form fields - */ - public function count() - { - return count($this->fields); - } - - /** - * Sets the locale of this field. - * - * @see Localizable - */ - public function setLocale($locale) - { - parent::setLocale($locale); - - foreach ($this->fields as $field) + /** + * Returns whether the field requires a multipart form. + * + * @return boolean + */ + public function isMultipart() { - $field->setLocale($locale); + foreach ($this->fields as $field) { + if ($field->isMultipart()) { + return true; + } + } + + return false; } - } - /** - * Sets the translator of this field. - * - * @see Translatable - */ - public function setTranslator(TranslatorInterface $translator) - { - parent::setTranslator($translator); - - foreach ($this->fields as $field) + /** + * Sets the renderer. + * + * @param RendererInterface $renderer + */ + public function setRenderer(RendererInterface $renderer) { - $field->setTranslator($translator); + $this->renderer = $renderer; } - } - /** - * Distributes the generator among all nested fields - * - * @param HtmlGeneratorInterface $generator - */ - public function setGenerator(HtmlGeneratorInterface $generator) - { - parent::setGenerator($generator); - - // TESTME - foreach ($this->fields as $field) + /** + * Returns the current renderer. + * + * @return RendererInterface + */ + public function getRenderer() { - $field->setGenerator($generator); + return $this->renderer; + } + + /** + * Delegates the rendering of the field to the renderer set. + * + * @return string The rendered widget + */ + public function render(array $attributes = array()) + { + $this->injectLocaleAndTranslator($this->renderer); + + return $this->renderer->render($this, $attributes); + } + + /** + * Delegates the rendering of the field to the renderer set. + * + * @return string The rendered widget + */ + public function renderErrors() + { + $this->injectLocaleAndTranslator($this->renderer); + + return $this->renderer->renderErrors($this); + } + /** + * Renders hidden form fields. + * + * @param boolean $recursive False will prevent hidden fields from embedded forms from rendering + * + * @return string + */ + public function renderHiddenFields($recursive = true) + { + $output = ''; + + foreach ($this->getHiddenFields($recursive) as $field) { + $output .= $field->render(); + } + + return $output; + } + + /** + * Returns true if the bound field exists (implements the \ArrayAccess interface). + * + * @param string $key The key of the bound field + * + * @return Boolean true if the widget exists, false otherwise + */ + public function offsetExists($key) + { + return $this->has($key); + } + + /** + * Returns the form field associated with the name (implements the \ArrayAccess interface). + * + * @param string $key The offset of the value to get + * + * @return Field A form field instance + */ + public function offsetGet($key) + { + return $this->get($key); + } + + /** + * Throws an exception saying that values cannot be set (implements the \ArrayAccess interface). + * + * @param string $offset (ignored) + * @param string $value (ignored) + * + * @throws \LogicException + */ + public function offsetSet($key, $field) + { + throw new \LogicException('Use the method add() to add fields'); + } + + /** + * Throws an exception saying that values cannot be unset (implements the \ArrayAccess interface). + * + * @param string $key + * + * @throws \LogicException + */ + public function offsetUnset($key) + { + return $this->remove($key); + } + + /** + * Returns the iterator for this group. + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->fields); + } + + /** + * Returns the number of form fields (implements the \Countable interface). + * + * @return integer The number of embedded form fields + */ + public function count() + { + return count($this->fields); + } + + /** + * Sets the locale of this field. + * + * @see Localizable + */ + public function setLocale($locale) + { + parent::setLocale($locale); + + foreach ($this->fields as $field) { + $field->setLocale($locale); + } + } + + /** + * Sets the translator of this field. + * + * @see Translatable + */ + public function setTranslator(TranslatorInterface $translator) + { + parent::setTranslator($translator); + + foreach ($this->fields as $field) { + $field->setTranslator($translator); + } + } + + /** + * Distributes the generator among all nested fields + * + * @param HtmlGeneratorInterface $generator + */ + public function setGenerator(HtmlGeneratorInterface $generator) + { + parent::setGenerator($generator); + + // TESTME + foreach ($this->fields as $field) { + $field->setGenerator($generator); + } } - } } diff --git a/src/Symfony/Components/Form/FieldInterface.php b/src/Symfony/Components/Form/FieldInterface.php index 1b4381ac85..e213c583eb 100644 --- a/src/Symfony/Components/Form/FieldInterface.php +++ b/src/Symfony/Components/Form/FieldInterface.php @@ -12,248 +12,248 @@ use Symfony\Components\I18N\TranslatorInterface; */ interface FieldInterface extends Localizable, Translatable { - /** - * Marks a constraint violation in a form field - * @var integer - */ - const FIELD_ERROR = 0; + /** + * Marks a constraint violation in a form field + * @var integer + */ + const FIELD_ERROR = 0; - /** - * Marks a constraint violation in the data of a form field - * @var integer - */ - const DATA_ERROR = 1; + /** + * Marks a constraint violation in the data of a form field + * @var integer + */ + const DATA_ERROR = 1; - /** - * Clones this field. - */ - public function __clone(); + /** + * Clones this field. + */ + public function __clone(); - /** - * Sets the parent field. - * - * @param FieldInterface $parent The parent field - */ - public function setParent(FieldInterface $parent = null); + /** + * Sets the parent field. + * + * @param FieldInterface $parent The parent field + */ + public function setParent(FieldInterface $parent = null); - /** - * Sets the key by which the field is identified in field groups. - * - * Once this field is nested in a field group, i.e. after setParent() was - * called for the first time, this method should throw an exception. - * - * @param string $key The key of the field - * @throws BadMethodCallException When the field already has a parent - */ - public function setKey($key); + /** + * Sets the key by which the field is identified in field groups. + * + * Once this field is nested in a field group, i.e. after setParent() was + * called for the first time, this method should throw an exception. + * + * @param string $key The key of the field + * @throws BadMethodCallException When the field already has a parent + */ + public function setKey($key); - /** - * Returns the key by which the field is identified in field groups. - * - * @return string The key of the field. - */ - public function getKey(); + /** + * Returns the key by which the field is identified in field groups. + * + * @return string The key of the field. + */ + public function getKey(); - /** - * Returns the name of the field. - * - * @return string When the field has no parent, the name is equal to its - * key. If the field has a parent, the name is composed of - * the parent's name and the field's key, where the field's - * key is wrapped in squared brackets - * (e.g. "parent_name[field_key]") - */ - public function getName(); + /** + * Returns the name of the field. + * + * @return string When the field has no parent, the name is equal to its + * key. If the field has a parent, the name is composed of + * the parent's name and the field's key, where the field's + * key is wrapped in squared brackets + * (e.g. "parent_name[field_key]") + */ + public function getName(); - /** - * Returns the ID of the field. - * - * @return string The ID of a field is equal to its name, where all - * sequences of squared brackets are replaced by a single - * underscore (e.g. if the name is "parent_name[field_key]", - * the ID is "parent_name_field_key"). - */ - public function getId(); + /** + * Returns the ID of the field. + * + * @return string The ID of a field is equal to its name, where all + * sequences of squared brackets are replaced by a single + * underscore (e.g. if the name is "parent_name[field_key]", + * the ID is "parent_name_field_key"). + */ + public function getId(); - /** - * Sets the property path - * - * The property path determines the property or a sequence of properties - * that a field updates in the data of the field group. - * - * @param string $propertyPath - */ - public function setPropertyPath($propertyPath); + /** + * Sets the property path + * + * The property path determines the property or a sequence of properties + * that a field updates in the data of the field group. + * + * @param string $propertyPath + */ + public function setPropertyPath($propertyPath); - /** - * Returns the property path of the field - * - * @return PropertyPath - */ - public function getPropertyPath(); + /** + * Returns the property path of the field + * + * @return PropertyPath + */ + public function getPropertyPath(); - /** - * Writes a property value of the object into the field - * - * The chosen property is determined by the field's property path. - * - * @param array|object $objectOrArray - */ - public function updateFromObject(&$objectOrArray); + /** + * Writes a property value of the object into the field + * + * The chosen property is determined by the field's property path. + * + * @param array|object $objectOrArray + */ + public function updateFromObject(&$objectOrArray); - /** - * Writes a the field value into a property of the object - * - * The chosen property is determined by the field's property path. - * - * @param array|object $objectOrArray - */ - public function updateObject(&$objectOrArray); + /** + * Writes a the field value into a property of the object + * + * The chosen property is determined by the field's property path. + * + * @param array|object $objectOrArray + */ + public function updateObject(&$objectOrArray); - /** - * Returns the normalized data of the field. - * - * @return mixed When the field is not bound, the default data is returned. - * When the field is bound, the normalized bound data is - * returned if the field is valid, null otherwise. - */ - public function getData(); + /** + * Returns the normalized data of the field. + * + * @return mixed When the field is not bound, the default data is returned. + * When the field is bound, the normalized bound data is + * returned if the field is valid, null otherwise. + */ + public function getData(); - /** - * Returns the data of the field as it is displayed to the user. - * - * @return string|array When the field is not bound, the transformed - * default data is returned. When the field is bound, - * the bound data is returned. - */ - public function getDisplayedData(); + /** + * Returns the data of the field as it is displayed to the user. + * + * @return string|array When the field is not bound, the transformed + * default data is returned. When the field is bound, + * the bound data is returned. + */ + public function getDisplayedData(); - /** - * Sets the default data - * - * @param mixed $default The default data - * @throws UnexpectedTypeException If the default data is invalid - */ - public function setData($default); + /** + * Sets the default data + * + * @param mixed $default The default data + * @throws UnexpectedTypeException If the default data is invalid + */ + public function setData($default); - /** - * Binds POST data to the field, transforms and validates it. - * - * @param string|array $taintedData The POST data - * @return boolean Whether the form is valid - * @throws InvalidConfigurationException when the field is not configured - * correctly - */ - public function bind($taintedData); + /** + * Binds POST data to the field, transforms and validates it. + * + * @param string|array $taintedData The POST data + * @return boolean Whether the form is valid + * @throws InvalidConfigurationException when the field is not configured + * correctly + */ + public function bind($taintedData); - /** - * Recursively adds constraint violations to the fields - * - * Violations in the form fields usually have property paths like: - * - * - * iterator[firstName].data - * iterator[firstName].displayedData - * iterator[Address].iterator[street].displayedData - * ... - * - * - * Violations in the form data usually have property paths like: - * - * - * data.firstName - * data.Address.street - * ... - * - * - * @param FieldInterface $field - * @param PropertyPath $path - * @param ConstraintViolation$violation - */ - public function addError($message, PropertyPath $path = null, $type = null); + /** + * Recursively adds constraint violations to the fields + * + * Violations in the form fields usually have property paths like: + * + * + * iterator[firstName].data + * iterator[firstName].displayedData + * iterator[Address].iterator[street].displayedData + * ... + * + * + * Violations in the form data usually have property paths like: + * + * + * data.firstName + * data.Address.street + * ... + * + * + * @param FieldInterface $field + * @param PropertyPath $path + * @param ConstraintViolation$violation + */ + public function addError($message, PropertyPath $path = null, $type = null); - /** - * Renders this field. - * - * @param array $attributes The attributes to include in the rendered - * output - * @return string The rendered output of this field - */ - public function render(array $attributes = array()); + /** + * Renders this field. + * + * @param array $attributes The attributes to include in the rendered + * output + * @return string The rendered output of this field + */ + public function render(array $attributes = array()); - /** - * Renders the errors of this field. - * - * @return string The rendered output of the field errors - */ - public function renderErrors(); + /** + * Renders the errors of this field. + * + * @return string The rendered output of the field errors + */ + public function renderErrors(); - /** - * Returns whether the field is bound. - * - * @return boolean - */ - public function isBound(); + /** + * Returns whether the field is bound. + * + * @return boolean + */ + public function isBound(); - /** - * Returns whether the field is valid. - * - * @return boolean - */ - public function isValid(); + /** + * Returns whether the field is valid. + * + * @return boolean + */ + public function isValid(); - /** - * Returns whether the field requires a multipart form. - * - * @return boolean - */ - public function isMultipart(); + /** + * Returns whether the field requires a multipart form. + * + * @return boolean + */ + public function isMultipart(); - /** - * Returns whether the field is required to be filled out. - * - * If the field has a parent and the parent is not required, this method - * will always return false. Otherwise the value set with setRequired() - * is returned. - * - * @return boolean - */ - public function isRequired(); + /** + * Returns whether the field is required to be filled out. + * + * If the field has a parent and the parent is not required, this method + * will always return false. Otherwise the value set with setRequired() + * is returned. + * + * @return boolean + */ + public function isRequired(); - /** - * Returns whether this field is disabled - * - * The content of a disabled field is displayed, but not allowed to be - * modified. The validation of modified, disabled fields should fail. - * - * Fields whose parents are disabled are considered disabled regardless of - * their own state. - * - * @return boolean - */ - public function isDisabled(); + /** + * Returns whether this field is disabled + * + * The content of a disabled field is displayed, but not allowed to be + * modified. The validation of modified, disabled fields should fail. + * + * Fields whose parents are disabled are considered disabled regardless of + * their own state. + * + * @return boolean + */ + public function isDisabled(); - /** - * Returns whether the field is hidden - * - * @return boolean - */ - public function isHidden(); + /** + * Returns whether the field is hidden + * + * @return boolean + */ + public function isHidden(); - /** - * Sets whether this field is required to be filled out when submitted. - * - * @param boolean $required - */ - public function setRequired($required); + /** + * Sets whether this field is required to be filled out when submitted. + * + * @param boolean $required + */ + public function setRequired($required); - /** - * Sets the generator used for rendering HTML. - * - * Usually there is one generator instance shared between all fields of a - * form. - * - * @param string $charset - */ - public function setGenerator(HtmlGeneratorInterface $generator); + /** + * Sets the generator used for rendering HTML. + * + * Usually there is one generator instance shared between all fields of a + * form. + * + * @param string $charset + */ + public function setGenerator(HtmlGeneratorInterface $generator); } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Form.php b/src/Symfony/Components/Form/Form.php index 6bd0892db1..8d7a9dd017 100644 --- a/src/Symfony/Components/Form/Form.php +++ b/src/Symfony/Components/Form/Form.php @@ -34,528 +34,491 @@ use Symfony\Components\File\UploadedFile; */ class Form extends FieldGroup { - protected static $defaultCsrfSecret = null; - protected static $defaultCsrfProtection = false; - protected static $defaultCsrfFieldName = '_csrf_token'; - protected static $defaultLocale = null; - protected static $defaultTranslator = null; + protected static $defaultCsrfSecret = null; + protected static $defaultCsrfProtection = false; + protected static $defaultCsrfFieldName = '_csrf_token'; + protected static $defaultLocale = null; + protected static $defaultTranslator = null; - protected $validator = null; - protected $validationGroups = null; + protected $validator = null; + protected $validationGroups = null; - private $csrfSecret = null; - private $csrfFieldName = null; + private $csrfSecret = null; + private $csrfFieldName = null; - /** - * Constructor. - * - * @param array $defaults An array of field default values - * @param array $options An array of options - * @param string $defaultCsrfSecret A Csrf secret - */ - public function __construct($name, $object, ValidatorInterface $validator, array $options = array()) - { - $this->generator = new HtmlGenerator(); - $this->validator = $validator; - - parent::__construct($name, $options); - - $this->setData($object); - $this->setCsrfFieldName(self::$defaultCsrfFieldName); - - if (self::$defaultCsrfSecret !== null) + /** + * Constructor. + * + * @param array $defaults An array of field default values + * @param array $options An array of options + * @param string $defaultCsrfSecret A Csrf secret + */ + public function __construct($name, $object, ValidatorInterface $validator, array $options = array()) { - $this->setCsrfSecret(self::$defaultCsrfSecret); - } - else - { - $this->setCsrfSecret(md5(__FILE__.php_uname())); - } + $this->generator = new HtmlGenerator(); + $this->validator = $validator; - if (self::$defaultCsrfProtection !== false) - { - $this->enableCsrfProtection(); - } + parent::__construct($name, $options); - if (self::$defaultLocale !== null) - { - $this->setLocale(self::$defaultLocale); - } + $this->setData($object); + $this->setCsrfFieldName(self::$defaultCsrfFieldName); - if (self::$defaultTranslator !== null) - { - $this->setTranslator(self::$defaultTranslator); - } - } - - /** - * Sets the charset used for rendering HTML - * - * This method overrides the internal HTML generator! If you want to use - * your own generator, use setGenerator() instead. - * - * @param string $charset - */ - public function setCharset($charset) - { - $this->setGenerator(new HtmlGenerator($charset)); - } - - /** - * Sets the validation groups for this form. - * - * @param array|string $validationGroups - */ - public function setValidationGroups($validationGroups) - { - $this->validationGroups = $validationGroups === null ? $validationGroups : (array) $validationGroups; - } - - /** - * Returns the validation groups for this form. - * - * @return array - */ - public function getValidationGroups() - { - return $this->validationGroups; - } - - /** - * Sets the default locale for newly created forms. - * - * @param string $defaultLocale - */ - static public function setDefaultLocale($defaultLocale) - { - self::$defaultLocale = $defaultLocale; - } - - /** - * Returns the default locale for newly created forms. - * - * @return string - */ - static public function getDefaultLocale() - { - return self::$defaultLocale; - } - - /** - * Sets the default translator for newly created forms. - * - * @param TranslatorInterface $defaultTranslator - */ - static public function setDefaultTranslator(TranslatorInterface $defaultTranslator) - { - self::$defaultTranslator = $defaultTranslator; - } - - /** - * Returns the default translator for newly created forms. - * - * @return TranslatorInterface - */ - static public function getDefaultTranslator() - { - return self::$defaultTranslator; - } - - /** - * Binds the form with values and files. - * - * This method is final because it is very easy to break a form when - * overriding this method and adding logic that depends on $taintedFiles. - * You should override doBind() instead where the uploaded files are - * already merged into the data array. - * - * @param array $taintedValues The form data of the $_POST array - * @param array $taintedFiles The form data of the $_FILES array - * @return boolean Whether the form is valid - */ - final public function bind($taintedValues, array $taintedFiles = null) - { - if ($taintedFiles === null) - { - if ($this->isMultipart() && $this->getParent() === null) - { - throw new \InvalidArgumentException('You must provide a files array for multipart forms'); - } - - $taintedFiles = array(); - } - else - { - $taintedFiles = self::convertFileInformation(self::fixPhpFilesArray($taintedFiles)); - } - - $this->doBind(self::deepArrayUnion($taintedValues, $taintedFiles)); - - if ($this->getParent() === null) - { - if ($violations = $this->validator->validate($this, $this->getValidationGroups())) - { - foreach ($violations as $violation) - { - $propertyPath = new PropertyPath($violation->getPropertyPath()); - - if ($propertyPath->getCurrent() == 'data') - { - $type = self::DATA_ERROR; - $propertyPath->next(); // point at the first data element - } - else - { - $type = self::FIELD_ERROR; - } - - $this->addError($violation->getMessage(), $propertyPath, $type); + if (self::$defaultCsrfSecret !== null) { + $this->setCsrfSecret(self::$defaultCsrfSecret); + } else { + $this->setCsrfSecret(md5(__FILE__.php_uname())); } - } - } - } - /** - * Binds the form with the given data. - * - * @param array $taintedData The data to bind to the form - * @return boolean Whether the form is valid - */ - protected function doBind(array $taintedData) - { - parent::bind($taintedData); - } + if (self::$defaultCsrfProtection !== false) { + $this->enableCsrfProtection(); + } - /** - * Gets the stylesheet paths associated with the form. - * - * @return array An array of stylesheet paths - */ - public function getStylesheets() - { - return $this->getWidget()->getStylesheets(); - } + if (self::$defaultLocale !== null) { + $this->setLocale(self::$defaultLocale); + } - /** - * Gets the JavaScript paths associated with the form. - * - * @return array An array of JavaScript paths - */ - public function getJavaScripts() - { - return $this->getWidget()->getJavaScripts(); - } - - /** - * Returns a CSRF token for the set CSRF secret - * - * If you want to change the algorithm used to compute the token, you - * can override this method. - * - * @param string $secret The secret string to use (null to use the current secret) - * - * @return string A token string - */ - protected function getCsrfToken() - { - return md5($this->csrfSecret.session_id().get_class($this)); - } - - /** - * @return true if this form is CSRF protected - */ - public function isCsrfProtected() - { - return $this->has($this->getCsrfFieldName()); - } - - /** - * Enables CSRF protection for this form. - */ - public function enableCsrfProtection() - { - if (!$this->isCsrfProtected()) - { - $field = new HiddenField($this->getCsrfFieldName(), array( - 'property_path' => null, - )); - $field->setData($this->getCsrfToken()); - $this->add($field); - } - } - - /** - * Disables CSRF protection for this form. - */ - public function disableCsrfProtection() - { - if ($this->isCsrfProtected()) - { - $this->remove($this->getCsrfFieldName()); - } - } - - /** - * Sets the CSRF field name used in this form - * - * @param string $name The CSRF field name - */ - public function setCsrfFieldName($name) - { - $this->csrfFieldName = $name; - } - - /** - * Returns the CSRF field name used in this form - * - * @return string The CSRF field name - */ - public function getCsrfFieldName() - { - return $this->csrfFieldName; - } - - /** - * Sets the CSRF secret used in this form - * - * @param string $secret - */ - public function setCsrfSecret($secret) - { - $this->csrfSecret = $secret; - } - - /** - * Returns the CSRF secret used in this form - * - * @return string - */ - public function getCsrfSecret() - { - return $this->csrfSecret; - } - - /** - * Returns whether the CSRF token is valid - * - * @return boolean - */ - public function isCsrfTokenValid() - { - if (!$this->isCsrfProtected()) - { - return true; - } - else - { - return $this->get($this->getCsrfFieldName())->getDisplayedData() === $this->getCsrfToken(); - } - } - - /** - * Enables CSRF protection for all new forms - */ - static public function enableDefaultCsrfProtection() - { - self::$defaultCsrfProtection = true; - } - - /** - * Disables Csrf protection for all forms. - */ - static public function disableDefaultCsrfProtection() - { - self::$defaultCsrfProtection = false; - } - - /** - * Sets the CSRF field name used in all new CSRF protected forms - * - * @param string $name The CSRF field name - */ - static public function setDefaultCsrfFieldName($name) - { - self::$defaultCsrfFieldName = $name; - } - - /** - * Returns the default CSRF field name - * - * @return string The CSRF field name - */ - static public function getDefaultCsrfFieldName() - { - return self::$defaultCsrfFieldName; - } - - /** - * Sets the CSRF secret used in all new CSRF protected forms - * - * @param string $secret - */ - static public function setDefaultCsrfSecret($secret) - { - self::$defaultCsrfSecret = $secret; - } - - /** - * Returns the default CSRF secret - * - * @return string - */ - static public function getDefaultCsrfSecret() - { - return self::$defaultCsrfSecret; - } - - /** - * Renders the form tag. - * - * This method only renders the opening form tag. - * You need to close it after the form rendering. - * - * This method takes into account the multipart widgets. - * - * @param string $url The URL for the action - * @param array $attributes An array of HTML attributes - * - * @return string An HTML representation of the opening form tag - */ - public function renderFormTag($url, array $attributes = array()) - { - return sprintf('', $this->generator->attributes(array_merge(array( - 'action' => $url, - 'method' => isset($attributes['method']) ? strtolower($attributes['method']) : 'post', - 'enctype' => $this->isMultipart() ? 'multipart/form-data' : null, - ), $attributes))); - } - - /** - * Returns whether the maximum POST size was reached in this request. - * - * @return boolean - */ - public function isPostMaxSizeReached() - { - if (isset($_SERVER['CONTENT_LENGTH'])) - { - $length = (int) $_SERVER['CONTENT_LENGTH']; - $max = trim(ini_get('post_max_size')); - - switch (strtolower(substr($max, -1))) - { - // The 'G' modifier is available since PHP 5.1.0 - case 'g': - $max *= 1024; - case 'm': - $max *= 1024; - case 'k': - $max *= 1024; - } - - return $length > $max; - } - else - { - return false; - } - } - - /** - * Merges two arrays without reindexing numeric keys. - * - * @param array $array1 An array to merge - * @param array $array2 An array to merge - * - * @return array The merged array - */ - static protected function deepArrayUnion($array1, $array2) - { - foreach ($array2 as $key => $value) - { - if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) - { - $array1[$key] = self::deepArrayUnion($array1[$key], $value); - } - else - { - $array1[$key] = $value; - } + if (self::$defaultTranslator !== null) { + $this->setTranslator(self::$defaultTranslator); + } } - return $array1; - } - - /** - * Fixes a malformed PHP $_FILES array. - * - * PHP has a bug that the format of the $_FILES array differs, depending on - * whether the uploaded file fields had normal field names or array-like - * field names ("normal" vs. "parent[child]"). - * - * This method fixes the array to look like the "normal" $_FILES array. - * - * @param array $data - * @return array - */ - static protected function fixPhpFilesArray(array $data) - { - $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type'); - $keys = array_keys($data); - sort($keys); - - $files = $data; - - if ($fileKeys == $keys && isset($data['name']) && is_array($data['name'])) + /** + * Sets the charset used for rendering HTML + * + * This method overrides the internal HTML generator! If you want to use + * your own generator, use setGenerator() instead. + * + * @param string $charset + */ + public function setCharset($charset) { - foreach ($fileKeys as $k) - { - unset($files[$k]); - } - - foreach (array_keys($data['name']) as $key) - { - $files[$key] = self::fixPhpFilesArray(array( - 'error' => $data['error'][$key], - 'name' => $data['name'][$key], - 'type' => $data['type'][$key], - 'tmp_name' => $data['tmp_name'][$key], - 'size' => $data['size'][$key], - )); - } + $this->setGenerator(new HtmlGenerator($charset)); } - return $files; - } - - /** - * Converts uploaded files to instances of clsas UploadedFile. - * - * @param array $files A (multi-dimensional) array of uploaded file information - * @return array A (multi-dimensional) array of UploadedFile instances - */ - static protected function convertFileInformation(array $files) - { - $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type'); - - foreach ($files as $key => $data) + /** + * Sets the validation groups for this form. + * + * @param array|string $validationGroups + */ + public function setValidationGroups($validationGroups) { - if (is_array($data)) - { + $this->validationGroups = $validationGroups === null ? $validationGroups : (array) $validationGroups; + } + + /** + * Returns the validation groups for this form. + * + * @return array + */ + public function getValidationGroups() + { + return $this->validationGroups; + } + + /** + * Sets the default locale for newly created forms. + * + * @param string $defaultLocale + */ + static public function setDefaultLocale($defaultLocale) + { + self::$defaultLocale = $defaultLocale; + } + + /** + * Returns the default locale for newly created forms. + * + * @return string + */ + static public function getDefaultLocale() + { + return self::$defaultLocale; + } + + /** + * Sets the default translator for newly created forms. + * + * @param TranslatorInterface $defaultTranslator + */ + static public function setDefaultTranslator(TranslatorInterface $defaultTranslator) + { + self::$defaultTranslator = $defaultTranslator; + } + + /** + * Returns the default translator for newly created forms. + * + * @return TranslatorInterface + */ + static public function getDefaultTranslator() + { + return self::$defaultTranslator; + } + + /** + * Binds the form with values and files. + * + * This method is final because it is very easy to break a form when + * overriding this method and adding logic that depends on $taintedFiles. + * You should override doBind() instead where the uploaded files are + * already merged into the data array. + * + * @param array $taintedValues The form data of the $_POST array + * @param array $taintedFiles The form data of the $_FILES array + * @return boolean Whether the form is valid + */ + final public function bind($taintedValues, array $taintedFiles = null) + { + if ($taintedFiles === null) { + if ($this->isMultipart() && $this->getParent() === null) { + throw new \InvalidArgumentException('You must provide a files array for multipart forms'); + } + + $taintedFiles = array(); + } else { + $taintedFiles = self::convertFileInformation(self::fixPhpFilesArray($taintedFiles)); + } + + $this->doBind(self::deepArrayUnion($taintedValues, $taintedFiles)); + + if ($this->getParent() === null) { + if ($violations = $this->validator->validate($this, $this->getValidationGroups())) { + foreach ($violations as $violation) { + $propertyPath = new PropertyPath($violation->getPropertyPath()); + + if ($propertyPath->getCurrent() == 'data') { + $type = self::DATA_ERROR; + $propertyPath->next(); // point at the first data element + } else { + $type = self::FIELD_ERROR; + } + + $this->addError($violation->getMessage(), $propertyPath, $type); + } + } + } + } + + /** + * Binds the form with the given data. + * + * @param array $taintedData The data to bind to the form + * @return boolean Whether the form is valid + */ + protected function doBind(array $taintedData) + { + parent::bind($taintedData); + } + + /** + * Gets the stylesheet paths associated with the form. + * + * @return array An array of stylesheet paths + */ + public function getStylesheets() + { + return $this->getWidget()->getStylesheets(); + } + + /** + * Gets the JavaScript paths associated with the form. + * + * @return array An array of JavaScript paths + */ + public function getJavaScripts() + { + return $this->getWidget()->getJavaScripts(); + } + + /** + * Returns a CSRF token for the set CSRF secret + * + * If you want to change the algorithm used to compute the token, you + * can override this method. + * + * @param string $secret The secret string to use (null to use the current secret) + * + * @return string A token string + */ + protected function getCsrfToken() + { + return md5($this->csrfSecret.session_id().get_class($this)); + } + + /** + * @return true if this form is CSRF protected + */ + public function isCsrfProtected() + { + return $this->has($this->getCsrfFieldName()); + } + + /** + * Enables CSRF protection for this form. + */ + public function enableCsrfProtection() + { + if (!$this->isCsrfProtected()) { + $field = new HiddenField($this->getCsrfFieldName(), array( + 'property_path' => null, + )); + $field->setData($this->getCsrfToken()); + $this->add($field); + } + } + + /** + * Disables CSRF protection for this form. + */ + public function disableCsrfProtection() + { + if ($this->isCsrfProtected()) { + $this->remove($this->getCsrfFieldName()); + } + } + + /** + * Sets the CSRF field name used in this form + * + * @param string $name The CSRF field name + */ + public function setCsrfFieldName($name) + { + $this->csrfFieldName = $name; + } + + /** + * Returns the CSRF field name used in this form + * + * @return string The CSRF field name + */ + public function getCsrfFieldName() + { + return $this->csrfFieldName; + } + + /** + * Sets the CSRF secret used in this form + * + * @param string $secret + */ + public function setCsrfSecret($secret) + { + $this->csrfSecret = $secret; + } + + /** + * Returns the CSRF secret used in this form + * + * @return string + */ + public function getCsrfSecret() + { + return $this->csrfSecret; + } + + /** + * Returns whether the CSRF token is valid + * + * @return boolean + */ + public function isCsrfTokenValid() + { + if (!$this->isCsrfProtected()) { + return true; + } else { + return $this->get($this->getCsrfFieldName())->getDisplayedData() === $this->getCsrfToken(); + } + } + + /** + * Enables CSRF protection for all new forms + */ + static public function enableDefaultCsrfProtection() + { + self::$defaultCsrfProtection = true; + } + + /** + * Disables Csrf protection for all forms. + */ + static public function disableDefaultCsrfProtection() + { + self::$defaultCsrfProtection = false; + } + + /** + * Sets the CSRF field name used in all new CSRF protected forms + * + * @param string $name The CSRF field name + */ + static public function setDefaultCsrfFieldName($name) + { + self::$defaultCsrfFieldName = $name; + } + + /** + * Returns the default CSRF field name + * + * @return string The CSRF field name + */ + static public function getDefaultCsrfFieldName() + { + return self::$defaultCsrfFieldName; + } + + /** + * Sets the CSRF secret used in all new CSRF protected forms + * + * @param string $secret + */ + static public function setDefaultCsrfSecret($secret) + { + self::$defaultCsrfSecret = $secret; + } + + /** + * Returns the default CSRF secret + * + * @return string + */ + static public function getDefaultCsrfSecret() + { + return self::$defaultCsrfSecret; + } + + /** + * Renders the form tag. + * + * This method only renders the opening form tag. + * You need to close it after the form rendering. + * + * This method takes into account the multipart widgets. + * + * @param string $url The URL for the action + * @param array $attributes An array of HTML attributes + * + * @return string An HTML representation of the opening form tag + */ + public function renderFormTag($url, array $attributes = array()) + { + return sprintf('', $this->generator->attributes(array_merge(array( + 'action' => $url, + 'method' => isset($attributes['method']) ? strtolower($attributes['method']) : 'post', + 'enctype' => $this->isMultipart() ? 'multipart/form-data' : null, + ), $attributes))); + } + + /** + * Returns whether the maximum POST size was reached in this request. + * + * @return boolean + */ + public function isPostMaxSizeReached() + { + if (isset($_SERVER['CONTENT_LENGTH'])) { + $length = (int) $_SERVER['CONTENT_LENGTH']; + $max = trim(ini_get('post_max_size')); + + switch (strtolower(substr($max, -1))) { + // The 'G' modifier is available since PHP 5.1.0 + case 'g': + $max *= 1024; + case 'm': + $max *= 1024; + case 'k': + $max *= 1024; + } + + return $length > $max; + } else { + return false; + } + } + + /** + * Merges two arrays without reindexing numeric keys. + * + * @param array $array1 An array to merge + * @param array $array2 An array to merge + * + * @return array The merged array + */ + static protected function deepArrayUnion($array1, $array2) + { + foreach ($array2 as $key => $value) { + if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) { + $array1[$key] = self::deepArrayUnion($array1[$key], $value); + } else { + $array1[$key] = $value; + } + } + + return $array1; + } + + /** + * Fixes a malformed PHP $_FILES array. + * + * PHP has a bug that the format of the $_FILES array differs, depending on + * whether the uploaded file fields had normal field names or array-like + * field names ("normal" vs. "parent[child]"). + * + * This method fixes the array to look like the "normal" $_FILES array. + * + * @param array $data + * @return array + */ + static protected function fixPhpFilesArray(array $data) + { + $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type'); $keys = array_keys($data); sort($keys); - if ($keys == $fileKeys) - { - $files[$key] = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']); + $files = $data; + + if ($fileKeys == $keys && isset($data['name']) && is_array($data['name'])) { + foreach ($fileKeys as $k) { + unset($files[$k]); + } + + foreach (array_keys($data['name']) as $key) { + $files[$key] = self::fixPhpFilesArray(array( + 'error' => $data['error'][$key], + 'name' => $data['name'][$key], + 'type' => $data['type'][$key], + 'tmp_name' => $data['tmp_name'][$key], + 'size' => $data['size'][$key], + )); + } } - else - { - $files[$key] = self::convertFileInformation($data); - } - } + + return $files; } - return $files; - } + /** + * Converts uploaded files to instances of clsas UploadedFile. + * + * @param array $files A (multi-dimensional) array of uploaded file information + * @return array A (multi-dimensional) array of UploadedFile instances + */ + static protected function convertFileInformation(array $files) + { + $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type'); + + foreach ($files as $key => $data) { + if (is_array($data)) { + $keys = array_keys($data); + sort($keys); + + if ($keys == $fileKeys) { + $files[$key] = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']); + } else { + $files[$key] = self::convertFileInformation($data); + } + } + } + + return $files; + } } diff --git a/src/Symfony/Components/Form/HiddenField.php b/src/Symfony/Components/Form/HiddenField.php index e2d1938811..bd0e0b34a2 100644 --- a/src/Symfony/Components/Form/HiddenField.php +++ b/src/Symfony/Components/Form/HiddenField.php @@ -19,21 +19,21 @@ use Symfony\Components\Form\Renderer\InputHiddenRenderer; */ class HiddenField extends InputField { - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render(array_merge(array( - 'type' => 'hidden', - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render(array_merge(array( + 'type' => 'hidden', + ), $attributes)); + } - /** - * {@inheritDoc} - */ - public function isHidden() - { - return true; - } + /** + * {@inheritDoc} + */ + public function isHidden() + { + return true; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/HtmlGenerator.php b/src/Symfony/Components/Form/HtmlGenerator.php index 77d62b4b9f..ec5817d859 100644 --- a/src/Symfony/Components/Form/HtmlGenerator.php +++ b/src/Symfony/Components/Form/HtmlGenerator.php @@ -10,136 +10,128 @@ namespace Symfony\Components\Form; */ class HtmlGenerator implements HtmlGeneratorInterface { - /** - * Whether to produce XHTML compliant code - * @var boolean - */ - protected static $xhtml = true; + /** + * Whether to produce XHTML compliant code + * @var boolean + */ + protected static $xhtml = true; - /** - * The charset used during generating - * @var string - */ - protected $charset; + /** + * The charset used during generating + * @var string + */ + protected $charset; - /** - * Sets the charset used for rendering - * - * @param string $charset - */ - public function __construct($charset = 'UTF-8') - { - $this->charset = $charset; - } - - /** - * Sets the XHTML generation flag. - * - * @param bool $boolean true if renderers must be generated as XHTML, false otherwise - */ - static public function setXhtml($boolean) - { - self::$xhtml = (boolean) $boolean; - } - - /** - * Returns whether to generate XHTML tags or not. - * - * @return bool true if renderers must be generated as XHTML, false otherwise - */ - static public function isXhtml() - { - return self::$xhtml; - } - - /** - * {@inheritDoc} - */ - public function tag($tag, $attributes = array()) - { - if (empty($tag)) + /** + * Sets the charset used for rendering + * + * @param string $charset + */ + public function __construct($charset = 'UTF-8') { - return ''; + $this->charset = $charset; } - return sprintf('<%s%s%s', $tag, $this->attributes($attributes), self::$xhtml ? ' />' : (strtolower($tag) == 'input' ? '>' : sprintf('>', $tag))); - } - - /** - * {@inheritDoc} - */ - public function contentTag($tag, $content = null, $attributes = array()) - { - if (empty($tag)) + /** + * Sets the XHTML generation flag. + * + * @param bool $boolean true if renderers must be generated as XHTML, false otherwise + */ + static public function setXhtml($boolean) { - return ''; + self::$xhtml = (boolean) $boolean; } - return sprintf('<%s%s>%s', $tag, $this->attributes($attributes), $content, $tag); - } - - /** - * {@inheritDoc} - */ - public function attribute($name, $value) - { - if (true === $value) + /** + * Returns whether to generate XHTML tags or not. + * + * @return bool true if renderers must be generated as XHTML, false otherwise + */ + static public function isXhtml() { - return self::$xhtml ? sprintf('%s="%s"', $name, $this->escape($name)) : $this->escape($name); + return self::$xhtml; } - else + + /** + * {@inheritDoc} + */ + public function tag($tag, $attributes = array()) { - return sprintf('%s="%s"', $name, $this->escape($value)); + if (empty($tag)) { + return ''; + } + + return sprintf('<%s%s%s', $tag, $this->attributes($attributes), self::$xhtml ? ' />' : (strtolower($tag) == 'input' ? '>' : sprintf('>', $tag))); } - } - /** - * {@inheritDoc} - */ - public function attributes(array $attributes) - { - return implode('', array_map(array($this, 'attributesCallback'), array_keys($attributes), array_values($attributes))); - } - - /** - * Prepares an attribute key and value for HTML representation. - * - * It removes empty attributes, except for the value one. - * - * @param string $name The attribute name - * @param string $value The attribute value - * - * @return string The HTML representation of the HTML key attribute pair. - */ - private function attributesCallback($name, $value) - { - if (false === $value || null === $value || ('' === $value && 'value' != $name)) + /** + * {@inheritDoc} + */ + public function contentTag($tag, $content = null, $attributes = array()) { - return ''; + if (empty($tag)) { + return ''; + } + + return sprintf('<%s%s>%s', $tag, $this->attributes($attributes), $content, $tag); } - else + + /** + * {@inheritDoc} + */ + public function attribute($name, $value) { - return ' '.$this->attribute($name, $value); + if (true === $value) { + return self::$xhtml ? sprintf('%s="%s"', $name, $this->escape($name)) : $this->escape($name); + } else { + return sprintf('%s="%s"', $name, $this->escape($value)); + } } - } - /** - * {@inheritDoc} - */ - public function escape($value) - { - return $this->fixDoubleEscape(htmlspecialchars((string) $value, ENT_QUOTES, $this->charset)); - } + /** + * {@inheritDoc} + */ + public function attributes(array $attributes) + { + return implode('', array_map(array($this, 'attributesCallback'), array_keys($attributes), array_values($attributes))); + } - /** - * Fixes double escaped strings. - * - * @param string $escaped string to fix - * - * @return string A single escaped string - */ - protected function fixDoubleEscape($escaped) - { - return preg_replace('/&([a-z]+|(#\d+)|(#x[\da-f]+));/i', '&$1;', $escaped); - } + /** + * Prepares an attribute key and value for HTML representation. + * + * It removes empty attributes, except for the value one. + * + * @param string $name The attribute name + * @param string $value The attribute value + * + * @return string The HTML representation of the HTML key attribute pair. + */ + private function attributesCallback($name, $value) + { + if (false === $value || null === $value || ('' === $value && 'value' != $name)) { + return ''; + } else { + return ' '.$this->attribute($name, $value); + } + } + + /** + * {@inheritDoc} + */ + public function escape($value) + { + return $this->fixDoubleEscape(htmlspecialchars((string) $value, ENT_QUOTES, $this->charset)); + } + + /** + * Fixes double escaped strings. + * + * @param string $escaped string to fix + * + * @return string A single escaped string + */ + protected function fixDoubleEscape($escaped) + { + return preg_replace('/&([a-z]+|(#\d+)|(#x[\da-f]+));/i', '&$1;', $escaped); + } } diff --git a/src/Symfony/Components/Form/HtmlGeneratorInterface.php b/src/Symfony/Components/Form/HtmlGeneratorInterface.php index 6d8176298e..7fb496ade5 100644 --- a/src/Symfony/Components/Form/HtmlGeneratorInterface.php +++ b/src/Symfony/Components/Form/HtmlGeneratorInterface.php @@ -9,55 +9,55 @@ namespace Symfony\Components\Form; */ interface HtmlGeneratorInterface { - /** - * Escapes a value for safe output in HTML - * - * Double escaping of already-escaped sequences is avoided by this method. - * - * @param string $value The unescaped or partially escaped value - * - * @return string The fully escaped value - */ - public function escape($value); + /** + * Escapes a value for safe output in HTML + * + * Double escaping of already-escaped sequences is avoided by this method. + * + * @param string $value The unescaped or partially escaped value + * + * @return string The fully escaped value + */ + public function escape($value); - /** - * Generates the HTML code for a tag attribute - * - * @param string $name The attribute name - * @param string $value The attribute value - * - * @return string The HTML code of the attribute - */ - public function attribute($name, $value); + /** + * Generates the HTML code for a tag attribute + * + * @param string $name The attribute name + * @param string $value The attribute value + * + * @return string The HTML code of the attribute + */ + public function attribute($name, $value); - /** - * Generates the HTML code for multiple tag attributes - * - * @param array $attributes An array with attribute names as keys and - * attribute values as elements - * - * @return string The HTML code of the attribute list - */ - public function attributes(array $attributes); + /** + * Generates the HTML code for multiple tag attributes + * + * @param array $attributes An array with attribute names as keys and + * attribute values as elements + * + * @return string The HTML code of the attribute list + */ + public function attributes(array $attributes); - /** - * Generates the HTML code for a tag without content - * - * @param string $tag The name of the tag - * @param array $attributes The attributes for the tag - * - * @return string The HTML code for the tag - */ - public function tag($tag, $attributes = array()); + /** + * Generates the HTML code for a tag without content + * + * @param string $tag The name of the tag + * @param array $attributes The attributes for the tag + * + * @return string The HTML code for the tag + */ + public function tag($tag, $attributes = array()); - /** - * Generates the HTML code for a tag with content - * - * @param string $tag The name of the tag - * @param string $content The content of the tag - * @param array $attributes The attributes for the tag - * - * @return string The HTML code for the tag - */ - public function contentTag($tag, $content, $attributes = array()); + /** + * Generates the HTML code for a tag with content + * + * @param string $tag The name of the tag + * @param string $content The content of the tag + * @param array $attributes The attributes for the tag + * + * @return string The HTML code for the tag + */ + public function contentTag($tag, $content, $attributes = array()); } diff --git a/src/Symfony/Components/Form/HybridField.php b/src/Symfony/Components/Form/HybridField.php index cbf303b9a7..aa5da65970 100644 --- a/src/Symfony/Components/Form/HybridField.php +++ b/src/Symfony/Components/Form/HybridField.php @@ -14,88 +14,77 @@ namespace Symfony\Components\Form; */ class HybridField extends FieldGroup { - const FIELD = 0; - const GROUP = 1; + const FIELD = 0; + const GROUP = 1; - protected $mode = self::FIELD; + protected $mode = self::FIELD; - /** - * Sets the current mode of the field - * - * Note that you can't switch modes anymore once you have added children to - * this field. - * - * @param integer $mode One of the constants HybridField::FIELD and - * HybridField::GROUP. - */ - public function setFieldMode($mode) - { - if (count($this) > 0 && $mode === self::FIELD) + /** + * Sets the current mode of the field + * + * Note that you can't switch modes anymore once you have added children to + * this field. + * + * @param integer $mode One of the constants HybridField::FIELD and + * HybridField::GROUP. + */ + public function setFieldMode($mode) { - throw new FormException('Switching to mode FIELD is not allowed after adding nested fields'); + if (count($this) > 0 && $mode === self::FIELD) { + throw new FormException('Switching to mode FIELD is not allowed after adding nested fields'); + } + + $this->mode = $mode; } - $this->mode = $mode; - } - - /** - * {@inheritDoc} - * - * @throws FormException When the field is in mode HybridField::FIELD adding - * subfields is not allowed - */ - public function add(FieldInterface $field) - { - if ($this->mode === self::FIELD) + /** + * {@inheritDoc} + * + * @throws FormException When the field is in mode HybridField::FIELD adding + * subfields is not allowed + */ + public function add(FieldInterface $field) { - throw new FormException('You cannot add nested fields while in mode FIELD'); + if ($this->mode === self::FIELD) { + throw new FormException('You cannot add nested fields while in mode FIELD'); + } + + return parent::add($field); } - return parent::add($field); - } + /** + * {@inheritDoc} + */ + public function getDisplayedData() + { + if ($this->mode === self::GROUP) { + return parent::getDisplayedData(); + } else { + return Field::getDisplayedData(); + } + } - /** - * {@inheritDoc} - */ - public function getDisplayedData() - { - if ($this->mode === self::GROUP) + /** + * {@inheritDoc} + */ + public function setData($data) { - return parent::getDisplayedData(); + if ($this->mode === self::GROUP) { + parent::setData($data); + } else { + Field::setData($data); + } } - else - { - return Field::getDisplayedData(); - } - } - /** - * {@inheritDoc} - */ - public function setData($data) - { - if ($this->mode === self::GROUP) + /** + * {@inheritDoc} + */ + public function bind($data) { - parent::setData($data); + if ($this->mode === self::GROUP) { + parent::bind($data); + } else { + Field::bind($data); + } } - else - { - Field::setData($data); - } - } - - /** - * {@inheritDoc} - */ - public function bind($data) - { - if ($this->mode === self::GROUP) - { - parent::bind($data); - } - else - { - Field::bind($data); - } - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/InputField.php b/src/Symfony/Components/Form/InputField.php index 726b2bf936..ae2c984439 100644 --- a/src/Symfony/Components/Form/InputField.php +++ b/src/Symfony/Components/Form/InputField.php @@ -9,16 +9,16 @@ namespace Symfony\Components\Form; */ abstract class InputField extends Field { - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return $this->generator->tag('input', array_merge(array( - 'id' => $this->getId(), - 'name' => $this->getName(), - 'value' => $this->getDisplayedData(), - 'disabled' => $this->isDisabled(), - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return $this->generator->tag('input', array_merge(array( + 'id' => $this->getId(), + 'name' => $this->getName(), + 'value' => $this->getDisplayedData(), + 'disabled' => $this->isDisabled(), + ), $attributes)); + } } diff --git a/src/Symfony/Components/Form/IntegerField.php b/src/Symfony/Components/Form/IntegerField.php index 02be601849..3b4031476c 100644 --- a/src/Symfony/Components/Form/IntegerField.php +++ b/src/Symfony/Components/Form/IntegerField.php @@ -17,21 +17,21 @@ namespace Symfony\Components\Form; */ class IntegerField extends NumberField { - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('precision', 0); + /** + * {@inheritDoc} + */ + protected function configure() + { + $this->addOption('precision', 0); - parent::configure(); - } + parent::configure(); + } - /** - * {@inheritDoc} - */ - public function getData() - { - return (int)parent::getData(); - } + /** + * {@inheritDoc} + */ + public function getData() + { + return (int)parent::getData(); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Iterator/RecursiveFieldsWithPropertyPathIterator.php b/src/Symfony/Components/Form/Iterator/RecursiveFieldsWithPropertyPathIterator.php index 5bad7c5b35..84f8c19baa 100644 --- a/src/Symfony/Components/Form/Iterator/RecursiveFieldsWithPropertyPathIterator.php +++ b/src/Symfony/Components/Form/Iterator/RecursiveFieldsWithPropertyPathIterator.php @@ -6,18 +6,18 @@ use Symfony\Components\Form\FieldGroupInterface; class RecursiveFieldsWithPropertyPathIterator extends \IteratorIterator implements \RecursiveIterator { - public function __construct(FieldGroupInterface $group) - { - parent::__construct($group); - } + public function __construct(FieldGroupInterface $group) + { + parent::__construct($group); + } - public function getChildren() - { - return new self($this->current()); - } + public function getChildren() + { + return new self($this->current()); + } - public function hasChildren() - { - return $this->current() instanceof FieldGroupInterface && $this->current()->getPropertyPath() === null; - } + public function hasChildren() + { + return $this->current() instanceof FieldGroupInterface && $this->current()->getPropertyPath() === null; + } } diff --git a/src/Symfony/Components/Form/Localizable.php b/src/Symfony/Components/Form/Localizable.php index 8684ba2420..5e935f56c9 100644 --- a/src/Symfony/Components/Form/Localizable.php +++ b/src/Symfony/Components/Form/Localizable.php @@ -9,10 +9,10 @@ namespace Symfony\Components\Form; */ interface Localizable { - /** - * Sets the locale of the class. - * - * @param string $locale - */ - public function setLocale($locale); + /** + * Sets the locale of the class. + * + * @param string $locale + */ + public function setLocale($locale); } \ No newline at end of file diff --git a/src/Symfony/Components/Form/MoneyField.php b/src/Symfony/Components/Form/MoneyField.php index 780fc9429d..8d2c4e9f36 100644 --- a/src/Symfony/Components/Form/MoneyField.php +++ b/src/Symfony/Components/Form/MoneyField.php @@ -19,93 +19,83 @@ use Symfony\Components\Form\ValueTransformer\MoneyToLocalizedStringTransformer; */ class MoneyField extends NumberField { - /** - * Stores patterns for different locales and cultures - * - * A pattern decides which currency symbol is displayed and where it is in - * relation to the number. - * - * @var array - */ - protected static $patterns = array(); + /** + * Stores patterns for different locales and cultures + * + * A pattern decides which currency symbol is displayed and where it is in + * relation to the number. + * + * @var array + */ + protected static $patterns = array(); - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('precision', 2); - $this->addOption('divisor', 1); - $this->addOption('currency'); - - parent::configure(); - - $this->setValueTransformer(new MoneyToLocalizedStringTransformer(array( - 'precision' => $this->getOption('precision'), - 'grouping' => $this->getOption('grouping'), - 'divisor' => $this->getOption('divisor'), - ))); - } - - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - $input = parent::render($attributes); - - if ($this->getOption('currency')) + /** + * {@inheritDoc} + */ + protected function configure() { - return str_replace('%widget%', $input, $this->getPattern($this->locale, $this->getOption('currency'))); - } - else - { - return $input; - } - } + $this->addOption('precision', 2); + $this->addOption('divisor', 1); + $this->addOption('currency'); - /** - * Returns the pattern for this locale - * - * The pattern contains the placeholder "%widget%" where the HTML tag should - * be inserted - * - * @param string $locale - */ - protected static function getPattern($locale, $currency) - { - if (!isset(self::$patterns[$locale])) - { - self::$patterns[$locale] = array(); + parent::configure(); + + $this->setValueTransformer(new MoneyToLocalizedStringTransformer(array( + 'precision' => $this->getOption('precision'), + 'grouping' => $this->getOption('grouping'), + 'divisor' => $this->getOption('divisor'), + ))); } - if (!isset(self::$patterns[$locale][$currency])) + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) { - $format = new \NumberFormatter($locale, \NumberFormatter::CURRENCY); - $pattern = $format->formatCurrency('123', $currency); + $input = parent::render($attributes); - // the spacings between currency symbol and number are ignored, because - // a single space leads to better readability in combination with input - // fields - - // the regex also considers non-break spaces (0xC2 or 0xA0 in UTF-8) - - preg_match('/^([^\s\xc2\xa0]*)[\s\xc2\xa0]*123[,.]00[\s\xc2\xa0]*([^\s\xc2\xa0]*)$/', $pattern, $matches); - - if (!empty($matches[1])) - { - self::$patterns[$locale] = $matches[1].' %widget%'; - } - else if (!empty($matches[2])) - { - self::$patterns[$locale] = '%widget% '.$matches[2]; - } - else - { - self::$patterns[$locale] = '%widget%'; - } + if ($this->getOption('currency')) { + return str_replace('%widget%', $input, $this->getPattern($this->locale, $this->getOption('currency'))); + } else { + return $input; + } } - return self::$patterns[$locale]; - } + /** + * Returns the pattern for this locale + * + * The pattern contains the placeholder "%widget%" where the HTML tag should + * be inserted + * + * @param string $locale + */ + protected static function getPattern($locale, $currency) + { + if (!isset(self::$patterns[$locale])) { + self::$patterns[$locale] = array(); + } + + if (!isset(self::$patterns[$locale][$currency])) { + $format = new \NumberFormatter($locale, \NumberFormatter::CURRENCY); + $pattern = $format->formatCurrency('123', $currency); + + // the spacings between currency symbol and number are ignored, because + // a single space leads to better readability in combination with input + // fields + + // the regex also considers non-break spaces (0xC2 or 0xA0 in UTF-8) + + preg_match('/^([^\s\xc2\xa0]*)[\s\xc2\xa0]*123[,.]00[\s\xc2\xa0]*([^\s\xc2\xa0]*)$/', $pattern, $matches); + + if (!empty($matches[1])) { + self::$patterns[$locale] = $matches[1].' %widget%'; + } else if (!empty($matches[2])) { + self::$patterns[$locale] = '%widget% '.$matches[2]; + } else { + self::$patterns[$locale] = '%widget%'; + } + } + + return self::$patterns[$locale]; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/NumberField.php b/src/Symfony/Components/Form/NumberField.php index 11a1e0b23c..e5faf7f4b8 100644 --- a/src/Symfony/Components/Form/NumberField.php +++ b/src/Symfony/Components/Form/NumberField.php @@ -20,28 +20,28 @@ use Symfony\Components\Form\ValueTransformer\NumberToLocalizedStringTransformer; */ class NumberField extends InputField { - /** - * {@inheritDoc} - */ - protected function configure() - { - // default precision is locale specific (usually around 3) - $this->addOption('precision'); - $this->addOption('grouping', false); + /** + * {@inheritDoc} + */ + protected function configure() + { + // default precision is locale specific (usually around 3) + $this->addOption('precision'); + $this->addOption('grouping', false); - $this->setValueTransformer(new NumberToLocalizedStringTransformer(array( - 'precision' => $this->getOption('precision'), - 'grouping' => $this->getOption('grouping'), - ))); - } + $this->setValueTransformer(new NumberToLocalizedStringTransformer(array( + 'precision' => $this->getOption('precision'), + 'grouping' => $this->getOption('grouping'), + ))); + } - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render(array_merge(array( - 'type' => 'text', - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render(array_merge(array( + 'type' => 'text', + ), $attributes)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/PasswordField.php b/src/Symfony/Components/Form/PasswordField.php index d45eef38be..9831c0f7d9 100644 --- a/src/Symfony/Components/Form/PasswordField.php +++ b/src/Symfony/Components/Form/PasswordField.php @@ -19,24 +19,24 @@ use Symfony\Components\Form\Renderer\InputPasswordRenderer; */ class PasswordField extends TextField { - /** - * {@inheritDoc} - */ - protected function configure() - { - parent::configure(); + /** + * {@inheritDoc} + */ + protected function configure() + { + parent::configure(); - $this->addOption('always_empty', true); - } + $this->addOption('always_empty', true); + } - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render(array_merge(array( - 'value' => $this->getOption('always_empty') && !$this->isBound() ? '' : $this->getDisplayedData(), - 'type' => 'password', - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render(array_merge(array( + 'value' => $this->getOption('always_empty') && !$this->isBound() ? '' : $this->getDisplayedData(), + 'type' => 'password', + ), $attributes)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/PercentField.php b/src/Symfony/Components/Form/PercentField.php index 0a746b063d..832641f003 100644 --- a/src/Symfony/Components/Form/PercentField.php +++ b/src/Symfony/Components/Form/PercentField.php @@ -19,28 +19,28 @@ use Symfony\Components\Form\ValueTransformer\PercentToLocalizedStringTransformer */ class PercentField extends NumberField { - const FRACTIONAL = 'fractional'; - const INTEGER = 'integer'; + const FRACTIONAL = 'fractional'; + const INTEGER = 'integer'; - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('precision', 0); - $this->addOption('type', self::FRACTIONAL); + /** + * {@inheritDoc} + */ + protected function configure() + { + $this->addOption('precision', 0); + $this->addOption('type', self::FRACTIONAL); - $this->setValueTransformer(new PercentToLocalizedStringTransformer(array( - 'precision' => $this->getOption('precision'), - 'type' => $this->getOption('type'), - ))); - } + $this->setValueTransformer(new PercentToLocalizedStringTransformer(array( + 'precision' => $this->getOption('precision'), + 'type' => $this->getOption('type'), + ))); + } - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render($attributes).' %'; - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render($attributes).' %'; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/PropertyPath.php b/src/Symfony/Components/Form/PropertyPath.php index fbfed0338b..85c0926e38 100644 --- a/src/Symfony/Components/Form/PropertyPath.php +++ b/src/Symfony/Components/Form/PropertyPath.php @@ -11,152 +11,145 @@ use Symfony\Components\Form\Exception\InvalidPropertyPathException; */ class PropertyPath { - /** - * The current index of the traversal - * @var integer - */ - protected $currentIndex = 0; + /** + * The current index of the traversal + * @var integer + */ + protected $currentIndex = 0; - /** - * The elements of the property path - * @var array - */ - protected $elements = array(); + /** + * The elements of the property path + * @var array + */ + protected $elements = array(); - /** - * Contains a boolean for each property in $elements denoting whether this - * element is a property. It is an index otherwise. - * @var array - */ - protected $isProperty = array(); + /** + * Contains a boolean for each property in $elements denoting whether this + * element is a property. It is an index otherwise. + * @var array + */ + protected $isProperty = array(); - /** - * String representation of the path - * @var string - */ - protected $string; + /** + * String representation of the path + * @var string + */ + protected $string; - /** - * Parses the given property path - * - * @param string $propertyPath - */ - public function __construct($propertyPath) - { - if (empty($propertyPath)) + /** + * Parses the given property path + * + * @param string $propertyPath + */ + public function __construct($propertyPath) { - throw new InvalidPropertyPathException('The property path must not be empty'); + if (empty($propertyPath)) { + throw new InvalidPropertyPathException('The property path must not be empty'); + } + + $this->string = $propertyPath; + $position = 0; + $remaining = $propertyPath; + + // first element is evaluated differently - no leading dot for properties + $pattern = '/^((\w+)|\[(\w+)\])(.*)/'; + + while (preg_match($pattern, $remaining, $matches)) { + if (!empty($matches[2])) { + $this->elements[] = $matches[2]; + $this->isProperty[] = true; + } else { + $this->elements[] = $matches[3]; + $this->isProperty[] = false; + } + + $position += strlen($matches[1]); + $remaining = $matches[4]; + $pattern = '/^(\.(\w+)|\[(\w+)\])(.*)/'; + } + + if (!empty($remaining)) { + throw new InvalidPropertyPathException(sprintf( + 'Could not parse property path "%s". Unexpected token "%s" at position %d', + $propertyPath, + $remaining{0}, + $position + )); + } } - $this->string = $propertyPath; - $position = 0; - $remaining = $propertyPath; - - // first element is evaluated differently - no leading dot for properties - $pattern = '/^((\w+)|\[(\w+)\])(.*)/'; - - while (preg_match($pattern, $remaining, $matches)) + /** + * Returns the string representation of the property path + * + * @return string + */ + public function __toString() { - if (!empty($matches[2])) - { - $this->elements[] = $matches[2]; - $this->isProperty[] = true; - } - else - { - $this->elements[] = $matches[3]; - $this->isProperty[] = false; - } - - $position += strlen($matches[1]); - $remaining = $matches[4]; - $pattern = '/^(\.(\w+)|\[(\w+)\])(.*)/'; + return $this->string; } - if (!empty($remaining)) + /** + * Returns the current element of the path + * + * @return string + */ + public function getCurrent() { - throw new InvalidPropertyPathException(sprintf( - 'Could not parse property path "%s". Unexpected token "%s" at position %d', - $propertyPath, - $remaining{0}, - $position - )); - } - } - - /** - * Returns the string representation of the property path - * - * @return string - */ - public function __toString() - { - return $this->string; - } - - /** - * Returns the current element of the path - * - * @return string - */ - public function getCurrent() - { - return $this->elements[$this->currentIndex]; - } - - /** - * Returns whether the current element is a property - * - * @return boolean - */ - public function isProperty() - { - return $this->isProperty[$this->currentIndex]; - } - - /** - * Returns whether the currente element is an array index - * - * @return boolean - */ - public function isIndex() - { - return !$this->isProperty(); - } - - /** - * Returns whether there is a next element in the path - * - * @return boolean - */ - public function hasNext() - { - return isset($this->elements[$this->currentIndex + 1]); - } - - /** - * Sets the internal cursor to the next element in the path - * - * Use hasNext() to verify whether there is a next element before calling this - * method, otherwise an exception will be thrown. - * - * @throws OutOfBoundsException If there is no next element - */ - public function next() - { - if (!$this->hasNext()) - { - throw new \OutOfBoundsException('There is no next element in the path'); + return $this->elements[$this->currentIndex]; } - ++$this->currentIndex; - } + /** + * Returns whether the current element is a property + * + * @return boolean + */ + public function isProperty() + { + return $this->isProperty[$this->currentIndex]; + } - /** - * Sets the internal cursor to the first element in the path - */ - public function rewind() - { - $this->currentIndex = 0; - } + /** + * Returns whether the currente element is an array index + * + * @return boolean + */ + public function isIndex() + { + return !$this->isProperty(); + } + + /** + * Returns whether there is a next element in the path + * + * @return boolean + */ + public function hasNext() + { + return isset($this->elements[$this->currentIndex + 1]); + } + + /** + * Sets the internal cursor to the next element in the path + * + * Use hasNext() to verify whether there is a next element before calling this + * method, otherwise an exception will be thrown. + * + * @throws OutOfBoundsException If there is no next element + */ + public function next() + { + if (!$this->hasNext()) { + throw new \OutOfBoundsException('There is no next element in the path'); + } + + ++$this->currentIndex; + } + + /** + * Sets the internal cursor to the first element in the path + */ + public function rewind() + { + $this->currentIndex = 0; + } } diff --git a/src/Symfony/Components/Form/RadioField.php b/src/Symfony/Components/Form/RadioField.php index e899c90b5c..3f5ffb6af6 100644 --- a/src/Symfony/Components/Form/RadioField.php +++ b/src/Symfony/Components/Form/RadioField.php @@ -20,14 +20,14 @@ use Symfony\Components\Form\ValueTransformer\BooleanToStringTransformer; */ class RadioField extends ToggleField { - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render(array_merge(array( - 'type' => 'radio', - 'name' => $this->getParent() ? $this->getParent()->getName() : $this->getName(), - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render(array_merge(array( + 'type' => 'radio', + 'name' => $this->getParent() ? $this->getParent()->getName() : $this->getName(), + ), $attributes)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Renderer/Renderer.php b/src/Symfony/Components/Form/Renderer/Renderer.php index 68bb57bb0a..7244dd3d8b 100644 --- a/src/Symfony/Components/Form/Renderer/Renderer.php +++ b/src/Symfony/Components/Form/Renderer/Renderer.php @@ -13,79 +13,77 @@ use Symfony\Components\Form\Configurable; */ abstract class Renderer extends Configurable implements RendererInterface { - /** - * The generator used for rendering the HTML - * @var HtmlGeneratorInterface - */ - protected $generator; + /** + * The generator used for rendering the HTML + * @var HtmlGeneratorInterface + */ + protected $generator; - /** - * Gets the stylesheet paths associated with the renderer. - * - * The array keys are files and values are the media names (separated by a ,): - * - * array('/path/to/file.css' => 'all', '/another/file.css' => 'screen,print') - * - * @return array An array of stylesheet paths - */ - public function getStylesheets() - { - return array(); - } - - /** - * Gets the JavaScript paths associated with the renderer. - * - * @return array An array of JavaScript paths - */ - public function getJavaScripts() - { - return array(); - } - - /** - * {@inheritDoc} - */ - public function renderErrors(FieldInterface $field) - { - $html = ''; - - if ($field->hasErrors()) + /** + * Gets the stylesheet paths associated with the renderer. + * + * The array keys are files and values are the media names (separated by a ,): + * + * array('/path/to/file.css' => 'all', '/another/file.css' => 'screen,print') + * + * @return array An array of stylesheet paths + */ + public function getStylesheets() { - $html .= "
    \n"; - - foreach ($field->getErrors() as $error) - { - $html .= "
  • " . $error . "
  • \n"; - } - - $html .= "
\n"; + return array(); } - return $html; - } + /** + * Gets the JavaScript paths associated with the renderer. + * + * @return array An array of JavaScript paths + */ + public function getJavaScripts() + { + return array(); + } - /** - * {@inheritDoc} - */ - public function setTranslator(TranslatorInterface $translator) - { - // TODO - } + /** + * {@inheritDoc} + */ + public function renderErrors(FieldInterface $field) + { + $html = ''; - /** - * {@inheritDoc} - */ - public function setLocale($locale) - { - // TODO - } + if ($field->hasErrors()) { + $html .= "
    \n"; - /** - * {@inheritDoc} - */ - public function setGenerator(HtmlGeneratorInterface $generator) - { - $this->generator = $generator; - } + foreach ($field->getErrors() as $error) { + $html .= "
  • " . $error . "
  • \n"; + } + + $html .= "
\n"; + } + + return $html; + } + + /** + * {@inheritDoc} + */ + public function setTranslator(TranslatorInterface $translator) + { + // TODO + } + + /** + * {@inheritDoc} + */ + public function setLocale($locale) + { + // TODO + } + + /** + * {@inheritDoc} + */ + public function setGenerator(HtmlGeneratorInterface $generator) + { + $this->generator = $generator; + } } diff --git a/src/Symfony/Components/Form/Renderer/RendererInterface.php b/src/Symfony/Components/Form/Renderer/RendererInterface.php index 6a028c2cee..5c13ba116b 100644 --- a/src/Symfony/Components/Form/Renderer/RendererInterface.php +++ b/src/Symfony/Components/Form/Renderer/RendererInterface.php @@ -14,32 +14,32 @@ use Symfony\Components\Form\Translatable; */ interface RendererInterface extends Localizable, Translatable { - /** - * Sets the generator used for rendering the HTML - * - * @param HtmlGeneratorInterface $generator - */ - public function setGenerator(HtmlGeneratorInterface $generator); + /** + * Sets the generator used for rendering the HTML + * + * @param HtmlGeneratorInterface $generator + */ + public function setGenerator(HtmlGeneratorInterface $generator); - /** - * Returns the textual representation of the given field. - * - * @param FieldInterface $field The form field - * @param array $attributes The attributes to include in the - * rendered output - * @return string The rendered output - * @throws InvalidArgumentException If the $field is not instance of the - * expected class - */ - public function render(FieldInterface $field, array $attributes = array()); + /** + * Returns the textual representation of the given field. + * + * @param FieldInterface $field The form field + * @param array $attributes The attributes to include in the + * rendered output + * @return string The rendered output + * @throws InvalidArgumentException If the $field is not instance of the + * expected class + */ + public function render(FieldInterface $field, array $attributes = array()); - /** - * Returns the textual representation of the errors of the given field. - * - * @param FieldInterface $field The form field - * @return string The rendered output - * @throws InvalidArgumentException If the $field is not instance of the - * expected class - */ - public function renderErrors(FieldInterface $field); + /** + * Returns the textual representation of the errors of the given field. + * + * @param FieldInterface $field The form field + * @return string The rendered output + * @throws InvalidArgumentException If the $field is not instance of the + * expected class + */ + public function renderErrors(FieldInterface $field); } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Renderer/TableRenderer.php b/src/Symfony/Components/Form/Renderer/TableRenderer.php index cbeb3b71d4..cb37d3a8ac 100644 --- a/src/Symfony/Components/Form/Renderer/TableRenderer.php +++ b/src/Symfony/Components/Form/Renderer/TableRenderer.php @@ -20,36 +20,34 @@ use Symfony\Components\Form\Field\ChoiceField; */ class TableRenderer extends Renderer { - /** - * {@inheritDoc} - */ - public function render(FieldInterface $group, array $attributes = array()) - { - $html = "\n"; - - foreach ($group as $field) + /** + * {@inheritDoc} + */ + public function render(FieldInterface $group, array $attributes = array()) { - $label = self::humanize($field->getKey()); + $html = "
\n"; - $html .= "\n"; - $html .= "\n"; - $html .= ""; - $html .= "\n"; + foreach ($group as $field) { + $label = self::humanize($field->getKey()); + + $html .= "\n"; + $html .= "\n"; + $html .= ""; + $html .= "\n"; + } + + $html .= "
\n"; - if ($field->hasErrors()) - { - $html .= $field->renderErrors()."\n"; - } - $html .= $field->render()."\n"; - $html .= "
\n"; + if ($field->hasErrors()) { + $html .= $field->renderErrors()."\n"; + } + $html .= $field->render()."\n"; + $html .= "
\n"; + + return $html; } - $html .= "\n"; - - return $html; - } - - protected static function humanize($text) - { - return ucfirst(strtolower(str_replace('_', ' ', $text))); - } + protected static function humanize($text) + { + return ucfirst(strtolower(str_replace('_', ' ', $text))); + } } diff --git a/src/Symfony/Components/Form/RepeatedField.php b/src/Symfony/Components/Form/RepeatedField.php index 710f8bb96f..3795575c49 100644 --- a/src/Symfony/Components/Form/RepeatedField.php +++ b/src/Symfony/Components/Form/RepeatedField.php @@ -17,72 +17,71 @@ namespace Symfony\Components\Form; */ class RepeatedField extends FieldGroup { - /** - * The prototype for the inner fields - * @var FieldInterface - */ - protected $prototype; + /** + * The prototype for the inner fields + * @var FieldInterface + */ + protected $prototype; - /** - * Repeats the given field twice to verify the user's input - * - * @param FieldInterface $innerField - */ - public function __construct(FieldInterface $innerField, array $options = array()) - { - $this->prototype = $innerField; - - parent::__construct($innerField->getKey(), $options); - } - - /** - * {@inheritDoc} - */ - protected function configure() - { - $field = clone $this->prototype; - $field->setKey('first'); - $field->setPropertyPath('first'); - $this->add($field); - - $field = clone $this->prototype; - $field->setKey('second'); - $field->setPropertyPath('second'); - $this->add($field); - } - - /** - * Returns whether both entered values are equal - * - * @return bool - */ - public function isFirstEqualToSecond() - { - return $this->get('first')->getData() === $this->get('second')->getData(); - } - - /** - * Sets the values of both fields to this value - * - * @param mixed $data - */ - public function setData($data) - { - parent::setData(array('first' => $data, 'second' => $data)); - } - - /** - * Return only value of first password field. - * - * @return string The password. - */ - public function getData() - { - if ($this->isBound() && $this->isFirstEqualToSecond()) + /** + * Repeats the given field twice to verify the user's input + * + * @param FieldInterface $innerField + */ + public function __construct(FieldInterface $innerField, array $options = array()) { - return $this->get('first')->getData(); + $this->prototype = $innerField; + + parent::__construct($innerField->getKey(), $options); } - return null; - } + /** + * {@inheritDoc} + */ + protected function configure() + { + $field = clone $this->prototype; + $field->setKey('first'); + $field->setPropertyPath('first'); + $this->add($field); + + $field = clone $this->prototype; + $field->setKey('second'); + $field->setPropertyPath('second'); + $this->add($field); + } + + /** + * Returns whether both entered values are equal + * + * @return bool + */ + public function isFirstEqualToSecond() + { + return $this->get('first')->getData() === $this->get('second')->getData(); + } + + /** + * Sets the values of both fields to this value + * + * @param mixed $data + */ + public function setData($data) + { + parent::setData(array('first' => $data, 'second' => $data)); + } + + /** + * Return only value of first password field. + * + * @return string The password. + */ + public function getData() + { + if ($this->isBound() && $this->isFirstEqualToSecond()) { + return $this->get('first')->getData(); + } + + return null; + } } diff --git a/src/Symfony/Components/Form/TextField.php b/src/Symfony/Components/Form/TextField.php index 7b0528f7ab..ece1dd8789 100644 --- a/src/Symfony/Components/Form/TextField.php +++ b/src/Symfony/Components/Form/TextField.php @@ -19,24 +19,24 @@ use Symfony\Components\Form\Renderer\InputTextRenderer; */ class TextField extends InputField { - /** - * {@inheritDoc} - */ - protected function configure() - { - parent::configure(); + /** + * {@inheritDoc} + */ + protected function configure() + { + parent::configure(); - $this->addOption('max_length'); - } + $this->addOption('max_length'); + } - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - return parent::render(array_merge(array( - 'type' => 'text', - 'maxlength' => $this->getOption('max_length'), - ), $attributes)); - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + return parent::render(array_merge(array( + 'type' => 'text', + 'maxlength' => $this->getOption('max_length'), + ), $attributes)); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/TextareaField.php b/src/Symfony/Components/Form/TextareaField.php index 94678b213d..7049889ff6 100644 --- a/src/Symfony/Components/Form/TextareaField.php +++ b/src/Symfony/Components/Form/TextareaField.php @@ -19,18 +19,18 @@ use Symfony\Components\Form\Renderer\TextareaRenderer; */ class TextareaField extends Field { - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - $content = $this->generator->escape($this->getDisplayedData()); + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + $content = $this->generator->escape($this->getDisplayedData()); - return $this->generator->contentTag('textarea', $content, array_merge(array( - 'id' => $this->getId(), - 'name' => $this->getName(), - 'rows' => 30, - 'cols' => 4, - ), $attributes)); - } + return $this->generator->contentTag('textarea', $content, array_merge(array( + 'id' => $this->getId(), + 'name' => $this->getName(), + 'rows' => 30, + 'cols' => 4, + ), $attributes)); + } } diff --git a/src/Symfony/Components/Form/TimeField.php b/src/Symfony/Components/Form/TimeField.php index 81c2750f4e..e88ddf9318 100644 --- a/src/Symfony/Components/Form/TimeField.php +++ b/src/Symfony/Components/Form/TimeField.php @@ -11,147 +11,134 @@ use Symfony\Components\Form\ValueTransformer\ValueTransformerChain; class TimeField extends FieldGroup { - const INPUT = 'input'; - const CHOICE = 'choice'; + const INPUT = 'input'; + const CHOICE = 'choice'; - const DATETIME = 'datetime'; - const STRING = 'string'; - const TIMESTAMP = 'timestamp'; - const RAW = 'raw'; + const DATETIME = 'datetime'; + const STRING = 'string'; + const TIMESTAMP = 'timestamp'; + const RAW = 'raw'; - protected static $widgets = array( - self::INPUT, - self::CHOICE, - ); + protected static $widgets = array( + self::INPUT, + self::CHOICE, + ); - protected static $types = array( - self::DATETIME, - self::STRING, - self::TIMESTAMP, - self::RAW, - ); + protected static $types = array( + self::DATETIME, + self::STRING, + self::TIMESTAMP, + self::RAW, + ); - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('hours', range(0, 23)); - $this->addOption('minutes', range(0, 59)); - $this->addOption('seconds', range(0, 59)); - $this->addOption('widget', self::CHOICE, self::$widgets); - $this->addOption('type', self::DATETIME, self::$types); - $this->addOption('data_timezone', 'UTC'); - $this->addOption('user_timezone', 'UTC'); - $this->addOption('with_seconds', false); - - if ($this->getOption('widget') == self::INPUT) + /** + * {@inheritDoc} + */ + protected function configure() { - $this->add(new TextField('hour', array('max_length' => 2))); - $this->add(new TextField('minute', array('max_length' => 2))); + $this->addOption('hours', range(0, 23)); + $this->addOption('minutes', range(0, 59)); + $this->addOption('seconds', range(0, 59)); + $this->addOption('widget', self::CHOICE, self::$widgets); + $this->addOption('type', self::DATETIME, self::$types); + $this->addOption('data_timezone', 'UTC'); + $this->addOption('user_timezone', 'UTC'); + $this->addOption('with_seconds', false); - if ($this->getOption('with_seconds')) - { - $this->add(new TextField('second', array('max_length' => 2))); - } - } - else - { - $this->add(new ChoiceField('hour', array( - 'choices' => $this->generatePaddedChoices($this->getOption('hours'), 2), - ))); - $this->add(new ChoiceField('minute', array( - 'choices' => $this->generatePaddedChoices($this->getOption('minutes'), 2), - ))); + if ($this->getOption('widget') == self::INPUT) { + $this->add(new TextField('hour', array('max_length' => 2))); + $this->add(new TextField('minute', array('max_length' => 2))); - if ($this->getOption('with_seconds')) - { - $this->add(new ChoiceField('second', array( - 'choices' => $this->generatePaddedChoices($this->getOption('seconds'), 2), - ))); - } + if ($this->getOption('with_seconds')) { + $this->add(new TextField('second', array('max_length' => 2))); + } + } else { + $this->add(new ChoiceField('hour', array( + 'choices' => $this->generatePaddedChoices($this->getOption('hours'), 2), + ))); + $this->add(new ChoiceField('minute', array( + 'choices' => $this->generatePaddedChoices($this->getOption('minutes'), 2), + ))); + + if ($this->getOption('with_seconds')) { + $this->add(new ChoiceField('second', array( + 'choices' => $this->generatePaddedChoices($this->getOption('seconds'), 2), + ))); + } + } + + $transformers = array(); + + if ($this->getOption('type') == self::STRING) { + $transformers[] = new StringToDateTimeTransformer(array( + 'format' => 'H:i:s', + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + )); + } else if ($this->getOption('type') == self::TIMESTAMP) { + $transformers[] = new TimestampToDateTimeTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + )); + } else if ($this->getOption('type') === self::RAW) { + $transformers[] = new ReversedTransformer(new DateTimeToArrayTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('data_timezone'), + 'fields' => array('hour', 'minute', 'second'), + ))); + } + + $transformers[] = new DateTimeToArrayTransformer(array( + 'input_timezone' => $this->getOption('data_timezone'), + 'output_timezone' => $this->getOption('user_timezone'), + // if the field is rendered as choice field, the values should be trimmed + // of trailing zeros to render the selected choices correctly + 'pad' => $this->getOption('widget') == self::INPUT, + )); + + $this->setValueTransformer(new ValueTransformerChain($transformers)); } - $transformers = array(); + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + if ($this->getOption('widget') == self::INPUT) { + $attributes = array_merge(array( + 'size' => '1', + ), $attributes); + } - if ($this->getOption('type') == self::STRING) - { - $transformers[] = new StringToDateTimeTransformer(array( - 'format' => 'H:i:s', - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - )); - } - else if ($this->getOption('type') == self::TIMESTAMP) - { - $transformers[] = new TimestampToDateTimeTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - )); - } - else if ($this->getOption('type') === self::RAW) - { - $transformers[] = new ReversedTransformer(new DateTimeToArrayTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('data_timezone'), - 'fields' => array('hour', 'minute', 'second'), - ))); + $html = $this->get('hour')->render($attributes); + $html .= ':' . $this->get('minute')->render($attributes); + + if ($this->getOption('with_seconds')) { + $html .= ':' . $this->get('second')->render($attributes); + } + + return $html; } - $transformers[] = new DateTimeToArrayTransformer(array( - 'input_timezone' => $this->getOption('data_timezone'), - 'output_timezone' => $this->getOption('user_timezone'), - // if the field is rendered as choice field, the values should be trimmed - // of trailing zeros to render the selected choices correctly - 'pad' => $this->getOption('widget') == self::INPUT, - )); - - $this->setValueTransformer(new ValueTransformerChain($transformers)); - } - - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - if ($this->getOption('widget') == self::INPUT) + /** + * Generates an array of choices for the given values + * + * If the values are shorter than $padLength characters, they are padded with + * zeros on the left side. + * + * @param array $values The available choices + * @param integer $padLength The length to pad the choices + * @return array An array with the input values as keys and the + * padded values as values + */ + protected function generatePaddedChoices(array $values, $padLength) { - $attributes = array_merge(array( - 'size' => '1', - ), $attributes); + $choices = array(); + + foreach ($values as $value) { + $choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT); + } + + return $choices; } - - $html = $this->get('hour')->render($attributes); - $html .= ':' . $this->get('minute')->render($attributes); - - if ($this->getOption('with_seconds')) - { - $html .= ':' . $this->get('second')->render($attributes); - } - - return $html; - } - - /** - * Generates an array of choices for the given values - * - * If the values are shorter than $padLength characters, they are padded with - * zeros on the left side. - * - * @param array $values The available choices - * @param integer $padLength The length to pad the choices - * @return array An array with the input values as keys and the - * padded values as values - */ - protected function generatePaddedChoices(array $values, $padLength) - { - $choices = array(); - - foreach ($values as $value) - { - $choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT); - } - - return $choices; - } } diff --git a/src/Symfony/Components/Form/TimezoneField.php b/src/Symfony/Components/Form/TimezoneField.php index c3f6bc35e9..4741185156 100644 --- a/src/Symfony/Components/Form/TimezoneField.php +++ b/src/Symfony/Components/Form/TimezoneField.php @@ -4,82 +4,73 @@ namespace Symfony\Components\Form; class TimezoneField extends ChoiceField { - /** - * Stores the available timezone choices - * @var array - */ - protected static $timezones = array(); + /** + * Stores the available timezone choices + * @var array + */ + protected static $timezones = array(); - /** - * {@inheritDoc} - */ - public function configure() - { - $this->addOption('choices', self::getTimezoneChoices()); - - parent::configure(); - } - - /** - * Preselects the server timezone if the field is empty and required - * - * {@inheritDoc} - */ - public function getDisplayedData() - { - $data = parent::getDisplayedData(); - - if ($data == null && $this->isRequired()) + /** + * {@inheritDoc} + */ + public function configure() { - $data = date_default_timezone_get(); + $this->addOption('choices', self::getTimezoneChoices()); + + parent::configure(); } - return $data; - } - - /** - * Returns the timezone choices - * - * The choices are generated from the ICU function - * \DateTimeZone::listIdentifiers(). They are cached during a single request, - * so multiple timezone fields on the same page don't lead to unnecessary - * overhead. - * - * @return array The timezone choices - */ - protected static function getTimezoneChoices() - { - if (count(self::$timezones) == 0) + /** + * Preselects the server timezone if the field is empty and required + * + * {@inheritDoc} + */ + public function getDisplayedData() { - foreach (\DateTimeZone::listIdentifiers() as $timezone) - { - $parts = explode('/', $timezone); + $data = parent::getDisplayedData(); - if (count($parts) > 2) - { - $region = $parts[0]; - $name = $parts[1].' - '.$parts[2]; - } - else if (count($parts) > 1) - { - $region = $parts[0]; - $name = $parts[1]; - } - else - { - $region = 'Other'; - $name = $parts[0]; + if ($data == null && $this->isRequired()) { + $data = date_default_timezone_get(); } - if (!isset(self::$timezones[$region])) - { - self::$timezones[$region] = array(); - } - - self::$timezones[$region][$timezone] = str_replace('_', ' ', $name); - } + return $data; } - return self::$timezones; - } + /** + * Returns the timezone choices + * + * The choices are generated from the ICU function + * \DateTimeZone::listIdentifiers(). They are cached during a single request, + * so multiple timezone fields on the same page don't lead to unnecessary + * overhead. + * + * @return array The timezone choices + */ + protected static function getTimezoneChoices() + { + if (count(self::$timezones) == 0) { + foreach (\DateTimeZone::listIdentifiers() as $timezone) { + $parts = explode('/', $timezone); + + if (count($parts) > 2) { + $region = $parts[0]; + $name = $parts[1].' - '.$parts[2]; + } else if (count($parts) > 1) { + $region = $parts[0]; + $name = $parts[1]; + } else { + $region = 'Other'; + $name = $parts[0]; + } + + if (!isset(self::$timezones[$region])) { + self::$timezones[$region] = array(); + } + + self::$timezones[$region][$timezone] = str_replace('_', ' ', $name); + } + } + + return self::$timezones; + } } diff --git a/src/Symfony/Components/Form/ToggleField.php b/src/Symfony/Components/Form/ToggleField.php index 2d4543026c..11f8f06c18 100644 --- a/src/Symfony/Components/Form/ToggleField.php +++ b/src/Symfony/Components/Form/ToggleField.php @@ -20,40 +20,38 @@ use Symfony\Components\Form\ValueTransformer\BooleanToStringTransformer; */ abstract class ToggleField extends InputField { - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('value'); - $this->addOption('label'); - $this->addOption('translate_label', false); - - $this->setValueTransformer(new BooleanToStringTransformer()); - } - - /** - * {@inheritDoc} - */ - public function render(array $attributes = array()) - { - $html = parent::render(array_merge(array( - 'value' => $this->getOption('value'), - 'checked' => ((string)$this->getDisplayedData() !== '' && $this->getDisplayedData() !== 0), - ), $attributes)); - - if ($label = $this->getOption('label')) + /** + * {@inheritDoc} + */ + protected function configure() { - if ($this->getOption('translate_label')) - { - $label = $this->translate($label); - } + $this->addOption('value'); + $this->addOption('label'); + $this->addOption('translate_label', false); - $html .= ' '.$this->generator->contentTag('label', $label, array( - 'for' => $this->getId(), - )); + $this->setValueTransformer(new BooleanToStringTransformer()); } - return $html; - } + /** + * {@inheritDoc} + */ + public function render(array $attributes = array()) + { + $html = parent::render(array_merge(array( + 'value' => $this->getOption('value'), + 'checked' => ((string)$this->getDisplayedData() !== '' && $this->getDisplayedData() !== 0), + ), $attributes)); + + if ($label = $this->getOption('label')) { + if ($this->getOption('translate_label')) { + $label = $this->translate($label); + } + + $html .= ' '.$this->generator->contentTag('label', $label, array( + 'for' => $this->getId(), + )); + } + + return $html; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/Translatable.php b/src/Symfony/Components/Form/Translatable.php index 0c28a3430f..07f87328fa 100644 --- a/src/Symfony/Components/Form/Translatable.php +++ b/src/Symfony/Components/Form/Translatable.php @@ -11,10 +11,10 @@ use Symfony\Components\I18N\TranslatorInterface; */ interface Translatable { - /** - * Sets the translator unit of the class. - * - * @param TranslatorInterface $translator - */ - public function setTranslator(TranslatorInterface $translator); + /** + * Sets the translator unit of the class. + * + * @param TranslatorInterface $translator + */ + public function setTranslator(TranslatorInterface $translator); } diff --git a/src/Symfony/Components/Form/ValueTransformer/BaseDateTimeTransformer.php b/src/Symfony/Components/Form/ValueTransformer/BaseDateTimeTransformer.php index 6a6fc92bbe..72ff3d4033 100644 --- a/src/Symfony/Components/Form/ValueTransformer/BaseDateTimeTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/BaseDateTimeTransformer.php @@ -4,41 +4,40 @@ namespace Symfony\Components\Form\ValueTransformer; abstract class BaseDateTimeTransformer extends BaseValueTransformer { - const NONE = 'none'; - const FULL = 'full'; - const LONG = 'long'; - const MEDIUM = 'medium'; - const SHORT = 'short'; + const NONE = 'none'; + const FULL = 'full'; + const LONG = 'long'; + const MEDIUM = 'medium'; + const SHORT = 'short'; - protected static $formats = array( - self::NONE, - self::FULL, - self::LONG, - self::MEDIUM, - self::SHORT, - ); + protected static $formats = array( + self::NONE, + self::FULL, + self::LONG, + self::MEDIUM, + self::SHORT, + ); - /** - * Returns the appropriate IntLDateFormatter constant for the given format - * - * @param string $format One of "short", "medium", "long" and "full" - * @return integer - */ - protected function getIntlFormatConstant($format) - { - switch ($format) + /** + * Returns the appropriate IntLDateFormatter constant for the given format + * + * @param string $format One of "short", "medium", "long" and "full" + * @return integer + */ + protected function getIntlFormatConstant($format) { - case self::FULL: - return \IntlDateFormatter::FULL; - case self::LONG: - return \IntlDateFormatter::LONG; - case self::SHORT: - return \IntldateFormatter::SHORT; - case self::MEDIUM: - return \IntlDateFormatter::MEDIUM; - case self::NONE: - default: - return \IntlDateFormatter::NONE; + switch ($format) { + case self::FULL: + return \IntlDateFormatter::FULL; + case self::LONG: + return \IntlDateFormatter::LONG; + case self::SHORT: + return \IntldateFormatter::SHORT; + case self::MEDIUM: + return \IntlDateFormatter::MEDIUM; + case self::NONE: + default: + return \IntlDateFormatter::NONE; + } } - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/BaseValueTransformer.php b/src/Symfony/Components/Form/ValueTransformer/BaseValueTransformer.php index ace8eb4a20..680a713536 100644 --- a/src/Symfony/Components/Form/ValueTransformer/BaseValueTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/BaseValueTransformer.php @@ -11,32 +11,32 @@ use Symfony\Components\Form\Configurable; */ abstract class BaseValueTransformer extends Configurable implements ValueTransformerInterface { - /** - * The locale of this transformer as accepted by the class Locale - * @var string - */ - protected $locale; + /** + * The locale of this transformer as accepted by the class Locale + * @var string + */ + protected $locale; - /** - * Constructor. - * - * @param array $options An array of options - * - * @throws \InvalidArgumentException when a option is not supported - * @throws \RuntimeException when a required option is not given - */ - public function __construct(array $options = array()) - { - $this->locale = \Locale::getDefault(); + /** + * Constructor. + * + * @param array $options An array of options + * + * @throws \InvalidArgumentException when a option is not supported + * @throws \RuntimeException when a required option is not given + */ + public function __construct(array $options = array()) + { + $this->locale = \Locale::getDefault(); - parent::__construct($options); - } + parent::__construct($options); + } - /** - * {@inheritDoc} - */ - public function setLocale($locale) - { - $this->locale = $locale; - } + /** + * {@inheritDoc} + */ + public function setLocale($locale) + { + $this->locale = $locale; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/BooleanToStringTransformer.php b/src/Symfony/Components/Form/ValueTransformer/BooleanToStringTransformer.php index b6951b6e42..5bfa3feebe 100644 --- a/src/Symfony/Components/Form/ValueTransformer/BooleanToStringTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/BooleanToStringTransformer.php @@ -10,36 +10,34 @@ namespace Symfony\Components\Form\ValueTransformer; */ class BooleanToStringTransformer extends BaseValueTransformer { - /** - * Transforms a boolean into a string. - * - * @param boolean $value Boolean value. - * @return string String value. - */ - public function transform($value) - { - if (!is_bool($value)) + /** + * Transforms a boolean into a string. + * + * @param boolean $value Boolean value. + * @return string String value. + */ + public function transform($value) { - throw new \InvalidArgumentException(sprintf('Expected argument of type boolean but got %s.', gettype($value))); + if (!is_bool($value)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type boolean but got %s.', gettype($value))); + } + + return true === $value ? '1' : ''; } - return true === $value ? '1' : ''; - } - - /** - * Transforms a string into a boolean. - * - * @param string $value String value. - * @return boolean Boolean value. - */ - public function reverseTransform($value) - { - if (!is_string($value)) + /** + * Transforms a string into a boolean. + * + * @param string $value String value. + * @return boolean Boolean value. + */ + public function reverseTransform($value) { - throw new \InvalidArgumentException(sprintf('Expected argument of type string but got %s.', gettype($value))); - } + if (!is_string($value)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type string but got %s.', gettype($value))); + } - return $value !== ''; - } + return $value !== ''; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/DateTimeToArrayTransformer.php b/src/Symfony/Components/Form/ValueTransformer/DateTimeToArrayTransformer.php index 6cd10ff491..14c1d6acba 100644 --- a/src/Symfony/Components/Form/ValueTransformer/DateTimeToArrayTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/DateTimeToArrayTransformer.php @@ -19,92 +19,86 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class DateTimeToArrayTransformer extends BaseDateTimeTransformer { - /** - * {@inheritDoc} - */ - protected function configure() - { - parent::configure(); - - $this->addOption('input_timezone', 'UTC'); - $this->addOption('output_timezone', 'UTC'); - $this->addOption('pad', false); - $this->addOption('fields', array('year', 'month', 'day', 'hour', 'minute', 'second')); - } - - /** - * Transforms a normalized date into a localized date string/array. - * - * @param DateTime $dateTime Normalized date. - * @return string|array Localized date array. - */ - public function transform($dateTime) - { - if (!$dateTime instanceof \DateTime) + /** + * {@inheritDoc} + */ + protected function configure() { - throw new \InvalidArgumentException('Expected value of type \DateTime'); + parent::configure(); + + $this->addOption('input_timezone', 'UTC'); + $this->addOption('output_timezone', 'UTC'); + $this->addOption('pad', false); + $this->addOption('fields', array('year', 'month', 'day', 'hour', 'minute', 'second')); } - $inputTimezone = $this->getOption('input_timezone'); - $outputTimezone = $this->getOption('output_timezone'); - - if ($inputTimezone != $outputTimezone) + /** + * Transforms a normalized date into a localized date string/array. + * + * @param DateTime $dateTime Normalized date. + * @return string|array Localized date array. + */ + public function transform($dateTime) { - $dateTime->setTimezone(new \DateTimeZone($outputTimezone)); + if (!$dateTime instanceof \DateTime) { + throw new \InvalidArgumentException('Expected value of type \DateTime'); + } + + $inputTimezone = $this->getOption('input_timezone'); + $outputTimezone = $this->getOption('output_timezone'); + + if ($inputTimezone != $outputTimezone) { + $dateTime->setTimezone(new \DateTimeZone($outputTimezone)); + } + + $result = array_intersect_key(array( + 'year' => $dateTime->format('Y'), + 'month' => $dateTime->format('m'), + 'day' => $dateTime->format('d'), + 'hour' => $dateTime->format('H'), + 'minute' => $dateTime->format('i'), + 'second' => $dateTime->format('s'), + ), array_flip($this->getOption('fields'))); + + if (!$this->getOption('pad')) { + foreach ($result as &$entry) { + $entry = (int)$entry; + } + } + + return $result; } - $result = array_intersect_key(array( - 'year' => $dateTime->format('Y'), - 'month' => $dateTime->format('m'), - 'day' => $dateTime->format('d'), - 'hour' => $dateTime->format('H'), - 'minute' => $dateTime->format('i'), - 'second' => $dateTime->format('s'), - ), array_flip($this->getOption('fields'))); - - if (!$this->getOption('pad')) + /** + * Transforms a localized date string/array into a normalized date. + * + * @param array $value Localized date string/array + * @return DateTime Normalized date + */ + public function reverseTransform($value) { - foreach ($result as &$entry) - { - $entry = (int)$entry; - } + $inputTimezone = $this->getOption('input_timezone'); + $outputTimezone = $this->getOption('output_timezone'); + + if (!is_array($value)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type array, %s given', gettype($value))); + } + + $dateTime = new \DateTime(sprintf( + '%s-%s-%s %s:%s:%s %s', + isset($value['year']) ? $value['year'] : 1970, + isset($value['month']) ? $value['month'] : 1, + isset($value['day']) ? $value['day'] : 1, + isset($value['hour']) ? $value['hour'] : 0, + isset($value['minute']) ? $value['minute'] : 0, + isset($value['second']) ? $value['second'] : 0, + $outputTimezone + )); + + if ($inputTimezone != $outputTimezone) { + $dateTime->setTimezone(new \DateTimeZone($inputTimezone)); + } + + return $dateTime; } - - return $result; - } - - /** - * Transforms a localized date string/array into a normalized date. - * - * @param array $value Localized date string/array - * @return DateTime Normalized date - */ - public function reverseTransform($value) - { - $inputTimezone = $this->getOption('input_timezone'); - $outputTimezone = $this->getOption('output_timezone'); - - if (!is_array($value)) - { - throw new \InvalidArgumentException(sprintf('Expected argument of type array, %s given', gettype($value))); - } - - $dateTime = new \DateTime(sprintf( - '%s-%s-%s %s:%s:%s %s', - isset($value['year']) ? $value['year'] : 1970, - isset($value['month']) ? $value['month'] : 1, - isset($value['day']) ? $value['day'] : 1, - isset($value['hour']) ? $value['hour'] : 0, - isset($value['minute']) ? $value['minute'] : 0, - isset($value['second']) ? $value['second'] : 0, - $outputTimezone - )); - - if ($inputTimezone != $outputTimezone) - { - $dateTime->setTimezone(new \DateTimeZone($inputTimezone)); - } - - return $dateTime; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformer.php b/src/Symfony/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformer.php index 5d4a0b8fad..b4659bcd2a 100644 --- a/src/Symfony/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformer.php @@ -19,104 +19,96 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer { - /** - * {@inheritDoc} - */ - protected function configure() - { - parent::configure(); - - $this->addOption('date_format', self::MEDIUM); - $this->addOption('time_format', self::SHORT); - $this->addOption('input_timezone', 'UTC'); - $this->addOption('output_timezone', 'UTC'); - - if (!in_array($this->getOption('date_format'), self::$formats, true)) + /** + * {@inheritDoc} + */ + protected function configure() { - throw new \InvalidArgumentException(sprintf('The option "date_format" is expected to be one of "%s". Is "%s"', implode('", "', self::$formats), $this->getOption('time_format'))); + parent::configure(); + + $this->addOption('date_format', self::MEDIUM); + $this->addOption('time_format', self::SHORT); + $this->addOption('input_timezone', 'UTC'); + $this->addOption('output_timezone', 'UTC'); + + if (!in_array($this->getOption('date_format'), self::$formats, true)) { + throw new \InvalidArgumentException(sprintf('The option "date_format" is expected to be one of "%s". Is "%s"', implode('", "', self::$formats), $this->getOption('time_format'))); + } + + if (!in_array($this->getOption('time_format'), self::$formats, true)) { + throw new \InvalidArgumentException(sprintf('The option "time_format" is expected to be one of "%s". Is "%s"', implode('", "', self::$formats), $this->getOption('time_format'))); + } } - if (!in_array($this->getOption('time_format'), self::$formats, true)) + /** + * Transforms a normalized date into a localized date string/array. + * + * @param DateTime $dateTime Normalized date. + * @return string|array Localized date string/array. + */ + public function transform($dateTime) { - throw new \InvalidArgumentException(sprintf('The option "time_format" is expected to be one of "%s". Is "%s"', implode('", "', self::$formats), $this->getOption('time_format'))); - } - } + if (!$dateTime instanceof \DateTime) { + throw new \InvalidArgumentException('Expected value of type \DateTime'); + } - /** - * Transforms a normalized date into a localized date string/array. - * - * @param DateTime $dateTime Normalized date. - * @return string|array Localized date string/array. - */ - public function transform($dateTime) - { - if (!$dateTime instanceof \DateTime) - { - throw new \InvalidArgumentException('Expected value of type \DateTime'); + $inputTimezone = $this->getOption('input_timezone'); + + // convert time to UTC before passing it to the formatter + if ($inputTimezone != 'UTC') { + $dateTime->setTimezone(new \DateTimeZone('UTC')); + } + + $value = $this->getIntlDateFormatter()->format((int)$dateTime->format('U')); + + if (intl_get_error_code() != 0) { + throw new TransformationFailedException(intl_get_error_message()); + } + + return $value; } - $inputTimezone = $this->getOption('input_timezone'); - - // convert time to UTC before passing it to the formatter - if ($inputTimezone != 'UTC') + /** + * Transforms a localized date string/array into a normalized date. + * + * @param string|array $value Localized date string/array + * @return DateTime Normalized date + */ + public function reverseTransform($value) { - $dateTime->setTimezone(new \DateTimeZone('UTC')); + $inputTimezone = $this->getOption('input_timezone'); + + if (!is_string($value)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value))); + } + + $timestamp = $this->getIntlDateFormatter()->parse($value); + + if (intl_get_error_code() != 0) { + throw new TransformationFailedException(intl_get_error_message()); + } + + // read timestamp into DateTime object - the formatter delivers in UTC + $dateTime = new \DateTime(sprintf('@%s UTC', $timestamp)); + + if ($inputTimezone != 'UTC') { + $dateTime->setTimezone(new \DateTimeZone($inputTimezone)); + } + + return $dateTime; } - $value = $this->getIntlDateFormatter()->format((int)$dateTime->format('U')); - - if (intl_get_error_code() != 0) + /** + * Returns a preconfigured IntlDateFormatter instance + * + * @return \IntlDateFormatter + */ + protected function getIntlDateFormatter() { - throw new TransformationFailedException(intl_get_error_message()); + $dateFormat = $this->getIntlFormatConstant($this->getOption('date_format')); + $timeFormat = $this->getIntlFormatConstant($this->getOption('time_format')); + $timezone = $this->getOption('output_timezone'); + + return new \IntlDateFormatter($this->locale, $dateFormat, $timeFormat, $timezone); } - - return $value; - } - - /** - * Transforms a localized date string/array into a normalized date. - * - * @param string|array $value Localized date string/array - * @return DateTime Normalized date - */ - public function reverseTransform($value) - { - $inputTimezone = $this->getOption('input_timezone'); - - if (!is_string($value)) - { - throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value))); - } - - $timestamp = $this->getIntlDateFormatter()->parse($value); - - if (intl_get_error_code() != 0) - { - throw new TransformationFailedException(intl_get_error_message()); - } - - // read timestamp into DateTime object - the formatter delivers in UTC - $dateTime = new \DateTime(sprintf('@%s UTC', $timestamp)); - - if ($inputTimezone != 'UTC') - { - $dateTime->setTimezone(new \DateTimeZone($inputTimezone)); - } - - return $dateTime; - } - - /** - * Returns a preconfigured IntlDateFormatter instance - * - * @return \IntlDateFormatter - */ - protected function getIntlDateFormatter() - { - $dateFormat = $this->getIntlFormatConstant($this->getOption('date_format')); - $timeFormat = $this->getIntlFormatConstant($this->getOption('time_format')); - $timezone = $this->getOption('output_timezone'); - - return new \IntlDateFormatter($this->locale, $dateFormat, $timeFormat, $timezone); - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/MoneyToLocalizedStringTransformer.php b/src/Symfony/Components/Form/ValueTransformer/MoneyToLocalizedStringTransformer.php index 6ff97a71dc..b8f8f8ca6d 100644 --- a/src/Symfony/Components/Form/ValueTransformer/MoneyToLocalizedStringTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/MoneyToLocalizedStringTransformer.php @@ -12,43 +12,42 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransformer { - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('grouping', true); - $this->addOption('precision', 2); - $this->addOption('divisor', 1); - - parent::configure(); - } - - /** - * Transforms a normalized format into a localized money string. - * - * @param number $value Normalized number - * @return string Localized money string. - */ - public function transform($value) - { - if (!is_numeric($value)) + /** + * {@inheritDoc} + */ + protected function configure() { - throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); + $this->addOption('grouping', true); + $this->addOption('precision', 2); + $this->addOption('divisor', 1); + + parent::configure(); } - return parent::transform($value / $this->getOption('divisor')); - } + /** + * Transforms a normalized format into a localized money string. + * + * @param number $value Normalized number + * @return string Localized money string. + */ + public function transform($value) + { + if (!is_numeric($value)) { + throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); + } - /** - * Transforms a localized money string into a normalized format. - * - * @param string $value Localized money string - * @return number Normalized number - */ - public function reverseTransform($value) - { - return parent::reverseTransform($value) * $this->getOption('divisor'); - } + return parent::transform($value / $this->getOption('divisor')); + } + + /** + * Transforms a localized money string into a normalized format. + * + * @param string $value Localized money string + * @return number Normalized number + */ + public function reverseTransform($value) + { + return parent::reverseTransform($value) * $this->getOption('divisor'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/NumberToLocalizedStringTransformer.php b/src/Symfony/Components/Form/ValueTransformer/NumberToLocalizedStringTransformer.php index 07106200a3..107c20b63e 100644 --- a/src/Symfony/Components/Form/ValueTransformer/NumberToLocalizedStringTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/NumberToLocalizedStringTransformer.php @@ -13,80 +13,75 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class NumberToLocalizedStringTransformer extends BaseValueTransformer { - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('precision', null); - $this->addOption('grouping', false); - - parent::configure(); - } - - /** - * Transforms a number type into localized number. - * - * @param number $value Number value. - * @return string Localized value. - */ - public function transform($value) - { - if (!is_numeric($value)) + /** + * {@inheritDoc} + */ + protected function configure() { - throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); + $this->addOption('precision', null); + $this->addOption('grouping', false); + + parent::configure(); } - $formatter = $this->getNumberFormatter(); - $value = $formatter->format($value); - - if (intl_is_failure($formatter->getErrorCode())) + /** + * Transforms a number type into localized number. + * + * @param number $value Number value. + * @return string Localized value. + */ + public function transform($value) { - throw new TransformationFailedException($formatter->getErrorMessage()); + if (!is_numeric($value)) { + throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); + } + + $formatter = $this->getNumberFormatter(); + $value = $formatter->format($value); + + if (intl_is_failure($formatter->getErrorCode())) { + throw new TransformationFailedException($formatter->getErrorMessage()); + } + + return $value; } - return $value; - } - - /** - * Transforms a localized number into an integer or float - * - * @param string $value - */ - public function reverseTransform($value) - { - if (!is_string($value)) + /** + * Transforms a localized number into an integer or float + * + * @param string $value + */ + public function reverseTransform($value) { - throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value))); + if (!is_string($value)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value))); + } + + $formatter = $this->getNumberFormatter(); + $value = $formatter->parse($value); + + if (intl_is_failure($formatter->getErrorCode())) { + throw new TransformationFailedException($formatter->getErrorMessage()); + } + + return $value; } - $formatter = $this->getNumberFormatter(); - $value = $formatter->parse($value); - - if (intl_is_failure($formatter->getErrorCode())) + /** + * Returns a preconfigured \NumberFormatter instance + * + * @return \NumberFormatter + */ + protected function getNumberFormatter() { - throw new TransformationFailedException($formatter->getErrorMessage()); + $formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL); + + if ($this->getOption('precision') !== null) { + $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->getOption('precision')); + } + + $formatter->setAttribute(\NumberFormatter::GROUPING_USED, $this->getOption('grouping')); + + return $formatter; } - - return $value; - } - - /** - * Returns a preconfigured \NumberFormatter instance - * - * @return \NumberFormatter - */ - protected function getNumberFormatter() - { - $formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL); - - if ($this->getOption('precision') !== null) - { - $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->getOption('precision')); - } - - $formatter->setAttribute(\NumberFormatter::GROUPING_USED, $this->getOption('grouping')); - - return $formatter; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/PercentToLocalizedStringTransformer.php b/src/Symfony/Components/Form/ValueTransformer/PercentToLocalizedStringTransformer.php index 17a258cd05..72e2c04ab5 100644 --- a/src/Symfony/Components/Form/ValueTransformer/PercentToLocalizedStringTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/PercentToLocalizedStringTransformer.php @@ -12,101 +12,94 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class PercentToLocalizedStringTransformer extends BaseValueTransformer { - const FRACTIONAL = 'fractional'; - const INTEGER = 'integer'; + const FRACTIONAL = 'fractional'; + const INTEGER = 'integer'; - protected static $types = array( - self::FRACTIONAL, - self::INTEGER, - ); + protected static $types = array( + self::FRACTIONAL, + self::INTEGER, + ); - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('type', self::FRACTIONAL); - $this->addOption('precision', 0); - - if (!in_array($this->getOption('type'), self::$types, true)) + /** + * {@inheritDoc} + */ + protected function configure() { - throw new \InvalidArgumentException(sprintf('The option "type" is expected to be one of "%s"', implode('", "', self::$types))); + $this->addOption('type', self::FRACTIONAL); + $this->addOption('precision', 0); + + if (!in_array($this->getOption('type'), self::$types, true)) { + throw new \InvalidArgumentException(sprintf('The option "type" is expected to be one of "%s"', implode('", "', self::$types))); + } + + parent::configure(); } - parent::configure(); - } - - /** - * Transforms between a normalized format (integer or float) into a percentage value. - * - * @param number $value Normalized value. - * @return number Percentage value. - */ - public function transform($value) - { - if (!is_numeric($value)) + /** + * Transforms between a normalized format (integer or float) into a percentage value. + * + * @param number $value Normalized value. + * @return number Percentage value. + */ + public function transform($value) { - throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); + if (!is_numeric($value)) { + throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); + } + + if (self::FRACTIONAL == $this->getOption('type')) { + $value *= 100; + } + + $formatter = $this->getNumberFormatter(); + $value = $formatter->format($value); + + if (intl_is_failure($formatter->getErrorCode())) { + throw new TransformationFailedException($formatter->getErrorMessage()); + } + + // replace the UTF-8 non break spaces + return $value; } - if (self::FRACTIONAL == $this->getOption('type')) + /** + * Transforms between a percentage value into a normalized format (integer or float). + * + * @param number $value Percentage value. + * @return number Normalized value. + */ + public function reverseTransform($value) { - $value *= 100; + if (!is_string($value)) { + throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value))); + } + + $formatter = $this->getNumberFormatter(); + // replace normal spaces so that the formatter can read them + $value = $formatter->parse(str_replace(' ', ' ', $value)); + + if (intl_is_failure($formatter->getErrorCode())) { + throw new TransformationFailedException($formatter->getErrorMessage()); + } + + if (self::FRACTIONAL == $this->getOption('type')) { + $value /= 100; + } + + return $value; } - $formatter = $this->getNumberFormatter(); - $value = $formatter->format($value); - - if (intl_is_failure($formatter->getErrorCode())) + /** + * Returns a preconfigured \NumberFormatter instance + * + * @return \NumberFormatter + */ + protected function getNumberFormatter() { - throw new TransformationFailedException($formatter->getErrorMessage()); + $formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL); + + $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->getOption('precision')); + + return $formatter; } - - // replace the UTF-8 non break spaces - return $value; - } - - /** - * Transforms between a percentage value into a normalized format (integer or float). - * - * @param number $value Percentage value. - * @return number Normalized value. - */ - public function reverseTransform($value) - { - if (!is_string($value)) - { - throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value))); - } - - $formatter = $this->getNumberFormatter(); - // replace normal spaces so that the formatter can read them - $value = $formatter->parse(str_replace(' ', ' ', $value)); - - if (intl_is_failure($formatter->getErrorCode())) - { - throw new TransformationFailedException($formatter->getErrorMessage()); - } - - if (self::FRACTIONAL == $this->getOption('type')) - { - $value /= 100; - } - - return $value; - } - - /** - * Returns a preconfigured \NumberFormatter instance - * - * @return \NumberFormatter - */ - protected function getNumberFormatter() - { - $formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL); - - $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->getOption('precision')); - - return $formatter; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/ReversedTransformer.php b/src/Symfony/Components/Form/ValueTransformer/ReversedTransformer.php index 68181358c4..bc5a2f3ee3 100644 --- a/src/Symfony/Components/Form/ValueTransformer/ReversedTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/ReversedTransformer.php @@ -12,43 +12,43 @@ namespace Symfony\Components\Form\ValueTransformer; */ class ReversedTransformer implements ValueTransformerInterface { - /** - * The reversed transformer - * @var ValueTransformerInterface - */ - protected $reversedTransformer; + /** + * The reversed transformer + * @var ValueTransformerInterface + */ + protected $reversedTransformer; - /** - * Reverses this transformer - * - * @param ValueTransformerInterface $innerTransformer - */ - public function __construct(ValueTransformerInterface $reversedTransformer) - { - $this->reversedTransformer = $reversedTransformer; - } + /** + * Reverses this transformer + * + * @param ValueTransformerInterface $innerTransformer + */ + public function __construct(ValueTransformerInterface $reversedTransformer) + { + $this->reversedTransformer = $reversedTransformer; + } - /** - * {@inheritDoc} - */ - public function transform($value) - { - return $this->reversedTransformer->reverseTransform($value); - } + /** + * {@inheritDoc} + */ + public function transform($value) + { + return $this->reversedTransformer->reverseTransform($value); + } - /** - * {@inheritDoc} - */ - public function reverseTransform($value) - { - return $this->reversedTransformer->transform($value); - } + /** + * {@inheritDoc} + */ + public function reverseTransform($value) + { + return $this->reversedTransformer->transform($value); + } - /** - * {@inheritDoc} - */ - public function setLocale($locale) - { - $this->reversedTransformer->setLocale($locale); - } + /** + * {@inheritDoc} + */ + public function setLocale($locale) + { + $this->reversedTransformer->setLocale($locale); + } } diff --git a/src/Symfony/Components/Form/ValueTransformer/StringToDateTimeTransformer.php b/src/Symfony/Components/Form/ValueTransformer/StringToDateTimeTransformer.php index e8dc5bf327..23def01321 100644 --- a/src/Symfony/Components/Form/ValueTransformer/StringToDateTimeTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/StringToDateTimeTransformer.php @@ -12,60 +12,55 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class StringToDateTimeTransformer extends BaseValueTransformer { - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('input_timezone', 'UTC'); - $this->addOption('output_timezone', 'UTC'); - $this->addOption('format', 'Y-m-d H:i:s'); - } - - /** - * Transforms a date string in the configured timezone into a DateTime object - * - * @param string $value A value as produced by PHP's date() function - * @return DateTime A DateTime object - */ - public function transform($value) - { - $inputTimezone = $this->getOption('input_timezone'); - $outputTimezone = $this->getOption('output_timezone'); - - try + /** + * {@inheritDoc} + */ + protected function configure() { - $dateTime = new \DateTime("$value $inputTimezone"); - - if ($inputTimezone != $outputTimezone) - { - $dateTime->setTimeZone(new \DateTimeZone($outputTimezone)); - } - - return $dateTime; - } - catch (\Exception $e) - { - throw new \InvalidArgumentException('Expected a valid date string. ' . $e->getMessage(), 0, $e); - } - } - - /** - * Transforms a DateTime object into a date string with the configured format - * and timezone - * - * @param DateTime $value A DateTime object - * @return string A value as produced by PHP's date() function - */ - public function reverseTransform($value) - { - if (!$value instanceof \DateTime) - { - throw new \InvalidArgumentException('Expected value of type \DateTime'); + $this->addOption('input_timezone', 'UTC'); + $this->addOption('output_timezone', 'UTC'); + $this->addOption('format', 'Y-m-d H:i:s'); } - $value->setTimezone(new \DateTimeZone($this->getOption('input_timezone'))); + /** + * Transforms a date string in the configured timezone into a DateTime object + * + * @param string $value A value as produced by PHP's date() function + * @return DateTime A DateTime object + */ + public function transform($value) + { + $inputTimezone = $this->getOption('input_timezone'); + $outputTimezone = $this->getOption('output_timezone'); - return $value->format($this->getOption('format')); - } + try { + $dateTime = new \DateTime("$value $inputTimezone"); + + if ($inputTimezone != $outputTimezone) { + $dateTime->setTimeZone(new \DateTimeZone($outputTimezone)); + } + + return $dateTime; + } catch (\Exception $e) { + throw new \InvalidArgumentException('Expected a valid date string. ' . $e->getMessage(), 0, $e); + } + } + + /** + * Transforms a DateTime object into a date string with the configured format + * and timezone + * + * @param DateTime $value A DateTime object + * @return string A value as produced by PHP's date() function + */ + public function reverseTransform($value) + { + if (!$value instanceof \DateTime) { + throw new \InvalidArgumentException('Expected value of type \DateTime'); + } + + $value->setTimezone(new \DateTimeZone($this->getOption('input_timezone'))); + + return $value->format($this->getOption('format')); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/TimestampToDateTimeTransformer.php b/src/Symfony/Components/Form/ValueTransformer/TimestampToDateTimeTransformer.php index 4e126402d4..fd68e00de5 100644 --- a/src/Symfony/Components/Form/ValueTransformer/TimestampToDateTimeTransformer.php +++ b/src/Symfony/Components/Form/ValueTransformer/TimestampToDateTimeTransformer.php @@ -12,58 +12,53 @@ use \Symfony\Components\Form\ValueTransformer\ValueTransformerException; */ class TimestampToDateTimeTransformer extends BaseValueTransformer { - /** - * {@inheritDoc} - */ - protected function configure() - { - $this->addOption('input_timezone', 'UTC'); - $this->addOption('output_timezone', 'UTC'); - } - - /** - * Transforms a timestamp in the configured timezone into a DateTime object - * - * @param string $value A value as produced by PHP's date() function - * @return DateTime A DateTime object - */ - public function transform($value) - { - $inputTimezone = $this->getOption('input_timezone'); - $outputTimezone = $this->getOption('output_timezone'); - - try + /** + * {@inheritDoc} + */ + protected function configure() { - $dateTime = new \DateTime("@$value $inputTimezone"); - - if ($inputTimezone != $outputTimezone) - { - $dateTime->setTimezone(new \DateTimeZone($outputTimezone)); - } - - return $dateTime; - } - catch (\Exception $e) - { - throw new \InvalidArgumentException('Expected a valid timestamp. ' . $e->getMessage(), 0, $e); - } - } - - /** - * Transforms a DateTime object into a timestamp in the configured timezone - * - * @param DateTime $value A DateTime object - * @return integer A timestamp - */ - public function reverseTransform($value) - { - if (!$value instanceof \DateTime) - { - throw new \InvalidArgumentException('Expected value of type \DateTime'); + $this->addOption('input_timezone', 'UTC'); + $this->addOption('output_timezone', 'UTC'); } - $value->setTimezone(new \DateTimeZone($this->getOption('input_timezone'))); + /** + * Transforms a timestamp in the configured timezone into a DateTime object + * + * @param string $value A value as produced by PHP's date() function + * @return DateTime A DateTime object + */ + public function transform($value) + { + $inputTimezone = $this->getOption('input_timezone'); + $outputTimezone = $this->getOption('output_timezone'); - return (int)$value->format('U'); - } + try { + $dateTime = new \DateTime("@$value $inputTimezone"); + + if ($inputTimezone != $outputTimezone) { + $dateTime->setTimezone(new \DateTimeZone($outputTimezone)); + } + + return $dateTime; + } catch (\Exception $e) { + throw new \InvalidArgumentException('Expected a valid timestamp. ' . $e->getMessage(), 0, $e); + } + } + + /** + * Transforms a DateTime object into a timestamp in the configured timezone + * + * @param DateTime $value A DateTime object + * @return integer A timestamp + */ + public function reverseTransform($value) + { + if (!$value instanceof \DateTime) { + throw new \InvalidArgumentException('Expected value of type \DateTime'); + } + + $value->setTimezone(new \DateTimeZone($this->getOption('input_timezone'))); + + return (int)$value->format('U'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Form/ValueTransformer/ValueTransformerChain.php b/src/Symfony/Components/Form/ValueTransformer/ValueTransformerChain.php index c92e47a5e4..dfb1d67025 100644 --- a/src/Symfony/Components/Form/ValueTransformer/ValueTransformerChain.php +++ b/src/Symfony/Components/Form/ValueTransformer/ValueTransformerChain.php @@ -9,73 +9,70 @@ namespace Symfony\Components\Form\ValueTransformer; */ class ValueTransformerChain implements ValueTransformerInterface { - /** - * The value transformers - * @var array - */ - protected $transformers; + /** + * The value transformers + * @var array + */ + protected $transformers; - /** - * Uses the given value transformers to transform values - * - * @param array $transformers - */ - public function __construct(array $transformers) - { - $this->transformers = $transformers; - } - - /** - * Passes the value through the transform() method of all nested transformers - * - * The transformers receive the value in the same order as they were passed - * to the constructor. Each transformer receives the result of the previous - * transformer as input. The output of the last transformer is returned - * by this method. - * - * @param mixed $value The original value - * @return mixed The transformed value - */ - public function transform($value) - { - foreach ($this->transformers as $transformer) + /** + * Uses the given value transformers to transform values + * + * @param array $transformers + */ + public function __construct(array $transformers) { - $value = $transformer->transform($value); + $this->transformers = $transformers; } - return $value; - } - - /** - * Passes the value through the reverseTransform() method of all nested - * transformers - * - * The transformers receive the value in the reverse order as they were passed - * to the constructor. Each transformer receives the result of the previous - * transformer as input. The output of the last transformer is returned - * by this method. - * - * @param mixed $value The transformed value - * @return mixed The reverse-transformed value - */ - public function reverseTransform($value) - { - for ($i = count($this->transformers) - 1; $i >= 0; --$i) + /** + * Passes the value through the transform() method of all nested transformers + * + * The transformers receive the value in the same order as they were passed + * to the constructor. Each transformer receives the result of the previous + * transformer as input. The output of the last transformer is returned + * by this method. + * + * @param mixed $value The original value + * @return mixed The transformed value + */ + public function transform($value) { - $value = $this->transformers[$i]->reverseTransform($value); + foreach ($this->transformers as $transformer) { + $value = $transformer->transform($value); + } + + return $value; } - return $value; - } - - /** - * {@inheritDoc} - */ - public function setLocale($locale) - { - foreach ($this->transformers as $transformer) + /** + * Passes the value through the reverseTransform() method of all nested + * transformers + * + * The transformers receive the value in the reverse order as they were passed + * to the constructor. Each transformer receives the result of the previous + * transformer as input. The output of the last transformer is returned + * by this method. + * + * @param mixed $value The transformed value + * @return mixed The reverse-transformed value + */ + public function reverseTransform($value) { - $transformer->setLocale($locale); + for ($i = count($this->transformers) - 1; $i >= 0; --$i) { + $value = $this->transformers[$i]->reverseTransform($value); + } + + return $value; + } + + /** + * {@inheritDoc} + */ + public function setLocale($locale) + { + foreach ($this->transformers as $transformer) { + $transformer->setLocale($locale); + } } - } } diff --git a/src/Symfony/Components/Form/ValueTransformer/ValueTransformerInterface.php b/src/Symfony/Components/Form/ValueTransformer/ValueTransformerInterface.php index b98c1379c9..a2f093c31d 100644 --- a/src/Symfony/Components/Form/ValueTransformer/ValueTransformerInterface.php +++ b/src/Symfony/Components/Form/ValueTransformer/ValueTransformerInterface.php @@ -11,28 +11,28 @@ use Symfony\Components\Form\Localizable; */ interface ValueTransformerInterface extends Localizable { - /** - * Transforms a value from the original representation to a transformed - * representation. - * - * @param mixed $value The value in the original representation - * @return mixed The value in the transformed representation - * @throws InvalidArgument Exception when the argument is no string - * @throws ValueTransformer Exception when the transformation fails - */ - public function transform($value); + /** + * Transforms a value from the original representation to a transformed + * representation. + * + * @param mixed $value The value in the original representation + * @return mixed The value in the transformed representation + * @throws InvalidArgument Exception when the argument is no string + * @throws ValueTransformer Exception when the transformation fails + */ + public function transform($value); - /** - * Transforms a value from the transformed representation to its original - * representation. - * - * This method must be able to deal with null values. - * - * @param mixed $value The value in the transformed representation - * @return mixed The value in the original representation - * @throws InvalidArgument Exception when the argument is not of the - * expected type - * @throws ValueTransformer Exception when the transformation fails - */ - public function reverseTransform($value); + /** + * Transforms a value from the transformed representation to its original + * representation. + * + * This method must be able to deal with null values. + * + * @param mixed $value The value in the transformed representation + * @return mixed The value in the original representation + * @throws InvalidArgument Exception when the argument is not of the + * expected type + * @throws ValueTransformer Exception when the transformation fails + */ + public function reverseTransform($value); } \ No newline at end of file diff --git a/src/Symfony/Components/I18N/TranslatorInterface.php b/src/Symfony/Components/I18N/TranslatorInterface.php index f134536ebd..6b3cefdc09 100644 --- a/src/Symfony/Components/I18N/TranslatorInterface.php +++ b/src/Symfony/Components/I18N/TranslatorInterface.php @@ -9,14 +9,14 @@ namespace Symfony\Components\I18N; */ interface TranslatorInterface { - /** - * Translates a given text string. - * - * @param string $text The text to translate - * @param array $parameters The parameters to inject into the text - * @param string $locale The locale of the translated text. If null, - * the preconfigured locale of the translator - * or the system's default culture is used. - */ - public function translate($text, array $parameters = array(), $locale = null); + /** + * Translates a given text string. + * + * @param string $text The text to translate + * @param array $parameters The parameters to inject into the text + * @param string $locale The locale of the translated text. If null, + * the preconfigured locale of the translator + * or the system's default culture is used. + */ + public function translate($text, array $parameters = array(), $locale = null); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraint.php b/src/Symfony/Components/Validator/Constraint.php index 70395b6fe9..af95f2fb2d 100644 --- a/src/Symfony/Components/Validator/Constraint.php +++ b/src/Symfony/Components/Validator/Constraint.php @@ -19,160 +19,145 @@ use Symfony\Components\Validator\Exception\ConstraintDefinitionException; */ class Constraint { - const DEFAULT_GROUP = 'Default'; + const DEFAULT_GROUP = 'Default'; - public $groups = self::DEFAULT_GROUP; + public $groups = self::DEFAULT_GROUP; - /** - * Initializes the constraint with options - * - * You should pass an associative array. The keys should be the names of - * existing properties in this class. The values should be the value for these - * properties. - * - * Alternatively you can override the method defaultOption() to return the - * name of an existing property. If no associative array is passed, this - * property is set instead. - * - * You can force that certain options are set by overriding - * requiredOptions() to return the names of these options. If any - * option is not set here, an exception is thrown. - * - * @param mixed $options The options (as associative array) - * or the value for the default - * option (any other type) - * @throws InvalidOptionsException When you pass the names of non-existing - * options - * @throws MissingOptionsException When you don't pass any of the options - * returned by requiredOptions() - * @throws ConstraintDefinitionException When you don't pass an associative - * array, but defaultOption() returns - * NULL - */ - public function __construct($options = null) - { - $invalidOptions = array(); - $missingOptions = array_flip((array)$this->requiredOptions()); - - if (is_array($options) && count($options) == 1 && isset($options['value'])) + /** + * Initializes the constraint with options + * + * You should pass an associative array. The keys should be the names of + * existing properties in this class. The values should be the value for these + * properties. + * + * Alternatively you can override the method defaultOption() to return the + * name of an existing property. If no associative array is passed, this + * property is set instead. + * + * You can force that certain options are set by overriding + * requiredOptions() to return the names of these options. If any + * option is not set here, an exception is thrown. + * + * @param mixed $options The options (as associative array) + * or the value for the default + * option (any other type) + * @throws InvalidOptionsException When you pass the names of non-existing + * options + * @throws MissingOptionsException When you don't pass any of the options + * returned by requiredOptions() + * @throws ConstraintDefinitionException When you don't pass an associative + * array, but defaultOption() returns + * NULL + */ + public function __construct($options = null) { - $options = $options['value']; - } + $invalidOptions = array(); + $missingOptions = array_flip((array)$this->requiredOptions()); - if (is_array($options) && count($options) > 0 && is_string(key($options))) - { - foreach ($options as $option => $value) - { - if (property_exists($this, $option)) - { - $this->$option = $value; - unset($missingOptions[$option]); + if (is_array($options) && count($options) == 1 && isset($options['value'])) { + $options = $options['value']; } - else - { - $invalidOptions[] = $option; + + if (is_array($options) && count($options) > 0 && is_string(key($options))) { + foreach ($options as $option => $value) { + if (property_exists($this, $option)) { + $this->$option = $value; + unset($missingOptions[$option]); + } else { + $invalidOptions[] = $option; + } + } + } else if ($options) { + $option = $this->defaultOption(); + + if (is_null($option)) { + throw new ConstraintDefinitionException( + sprintf('No default option is configured for constraint %s', get_class($this)) + ); + } + + if (property_exists($this, $option)) { + $this->$option = $options; + unset($missingOptions[$option]); + } else { + $invalidOptions[] = $option; + } } - } + + if (count($invalidOptions) > 0) { + throw new InvalidOptionsException( + sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), get_class($this)), + $invalidOptions + ); + } + + if (count($missingOptions) > 0) { + throw new MissingOptionsException( + sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), get_class($this)), + array_keys($missingOptions) + ); + } + + $this->groups = (array)$this->groups; } - else if ($options) + + /** + * Unsupported operation. + */ + public function __set($option, $value) { - $option = $this->defaultOption(); - - if (is_null($option)) - { - throw new ConstraintDefinitionException( - sprintf('No default option is configured for constraint %s', get_class($this)) - ); - } - - if (property_exists($this, $option)) - { - $this->$option = $options; - unset($missingOptions[$option]); - } - else - { - $invalidOptions[] = $option; - } + throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option)); } - if (count($invalidOptions) > 0) + /** + * Adds the given group if this constraint is in the Default group + * + * @param string $group + */ + public function addImplicitGroupName($group) { - throw new InvalidOptionsException( - sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), get_class($this)), - $invalidOptions - ); + if (in_array(Constraint::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups)) { + $this->groups[] = $group; + } } - if (count($missingOptions) > 0) + /** + * Returns the name of the default option + * + * Override this method to define a default option. + * + * @return string + * @see __construct() + */ + public function defaultOption() { - throw new MissingOptionsException( - sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), get_class($this)), - array_keys($missingOptions) - ); + return null; } - $this->groups = (array)$this->groups; - } - - /** - * Unsupported operation. - */ - public function __set($option, $value) - { - throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option)); - } - - /** - * Adds the given group if this constraint is in the Default group - * - * @param string $group - */ - public function addImplicitGroupName($group) - { - if (in_array(Constraint::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups)) + /** + * Returns the name of the required options + * + * Override this method if you want to define required options. + * + * @return array + * @see __construct() + */ + public function requiredOptions() { - $this->groups[] = $group; + return array(); } - } - /** - * Returns the name of the default option - * - * Override this method to define a default option. - * - * @return string - * @see __construct() - */ - public function defaultOption() - { - return null; - } - - /** - * Returns the name of the required options - * - * Override this method if you want to define required options. - * - * @return array - * @see __construct() - */ - public function requiredOptions() - { - return array(); - } - - /** - * Returns the name of the class that validates this constraint - * - * By default, this is the fully qualified name of the constraint class - * suffixed with "Validator". You can override this method to change that - * behaviour. - * - * @return string - */ - public function validatedBy() - { - return get_class($this) . 'Validator'; - } + /** + * Returns the name of the class that validates this constraint + * + * By default, this is the fully qualified name of the constraint class + * suffixed with "Validator". You can override this method to change that + * behaviour. + * + * @return string + */ + public function validatedBy() + { + return get_class($this) . 'Validator'; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ConstraintValidator.php b/src/Symfony/Components/Validator/ConstraintValidator.php index d04f180540..dc4cd140c1 100644 --- a/src/Symfony/Components/Validator/ConstraintValidator.php +++ b/src/Symfony/Components/Validator/ConstraintValidator.php @@ -4,30 +4,30 @@ namespace Symfony\Components\Validator; abstract class ConstraintValidator implements ConstraintValidatorInterface { - protected $context; - private $messageTemplate; - private $messageParameters; + protected $context; + private $messageTemplate; + private $messageParameters; - public function initialize(ValidationContext $context) - { - $this->context = $context; - $this->messageTemplate = ''; - $this->messageParameters = array(); - } + public function initialize(ValidationContext $context) + { + $this->context = $context; + $this->messageTemplate = ''; + $this->messageParameters = array(); + } - public function getMessageTemplate() - { - return $this->messageTemplate; - } + public function getMessageTemplate() + { + return $this->messageTemplate; + } - public function getMessageParameters() - { - return $this->messageParameters; - } + public function getMessageParameters() + { + return $this->messageParameters; + } - protected function setMessage($template, array $parameters = array()) - { - $this->messageTemplate = $template; - $this->messageParameters = $parameters; - } + protected function setMessage($template, array $parameters = array()) + { + $this->messageTemplate = $template; + $this->messageParameters = $parameters; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ConstraintValidatorFactory.php b/src/Symfony/Components/Validator/ConstraintValidatorFactory.php index d8c34c5247..a91cf8ac08 100644 --- a/src/Symfony/Components/Validator/ConstraintValidatorFactory.php +++ b/src/Symfony/Components/Validator/ConstraintValidatorFactory.php @@ -7,17 +7,16 @@ use Symfony\Components\Validator\Constraint; class ConstraintValidatorFactory implements ConstraintValidatorFactoryInterface { - protected $validators = array(); + protected $validators = array(); - public function getInstance(Constraint $constraint) - { - $className = $constraint->validatedBy(); - - if (!isset($this->validators[$className])) + public function getInstance(Constraint $constraint) { - $this->validators[$className] = new $className(); - } + $className = $constraint->validatedBy(); - return $this->validators[$className]; - } + if (!isset($this->validators[$className])) { + $this->validators[$className] = new $className(); + } + + return $this->validators[$className]; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ConstraintValidatorFactoryInterface.php b/src/Symfony/Components/Validator/ConstraintValidatorFactoryInterface.php index 7304a3eaaa..e490c677c5 100644 --- a/src/Symfony/Components/Validator/ConstraintValidatorFactoryInterface.php +++ b/src/Symfony/Components/Validator/ConstraintValidatorFactoryInterface.php @@ -6,5 +6,5 @@ use Symfony\Components\Validator\Constraint; interface ConstraintValidatorFactoryInterface { - public function getInstance(Constraint $constraint); + public function getInstance(Constraint $constraint); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ConstraintValidatorInterface.php b/src/Symfony/Components/Validator/ConstraintValidatorInterface.php index 1656bb95d4..7d2005ba12 100644 --- a/src/Symfony/Components/Validator/ConstraintValidatorInterface.php +++ b/src/Symfony/Components/Validator/ConstraintValidatorInterface.php @@ -4,11 +4,11 @@ namespace Symfony\Components\Validator; interface ConstraintValidatorInterface { - public function initialize(ValidationContext $context); + public function initialize(ValidationContext $context); - public function isValid($value, Constraint $constraint); + public function isValid($value, Constraint $constraint); - public function getMessageTemplate(); + public function getMessageTemplate(); - public function getMessageParameters(); + public function getMessageParameters(); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ConstraintViolation.php b/src/Symfony/Components/Validator/ConstraintViolation.php index c2b54b1f61..e45e82d14e 100644 --- a/src/Symfony/Components/Validator/ConstraintViolation.php +++ b/src/Symfony/Components/Validator/ConstraintViolation.php @@ -4,36 +4,36 @@ namespace Symfony\Components\Validator; class ConstraintViolation { - protected $message; - protected $root; - protected $propertyPath; - protected $invalidValue; + protected $message; + protected $root; + protected $propertyPath; + protected $invalidValue; - public function __construct($message, $root, $propertyPath, $invalidValue) - { - $this->message = $message; - $this->root = $root; - $this->propertyPath = $propertyPath; - $this->invalidValue = $invalidValue; - } + public function __construct($message, $root, $propertyPath, $invalidValue) + { + $this->message = $message; + $this->root = $root; + $this->propertyPath = $propertyPath; + $this->invalidValue = $invalidValue; + } - public function getMessage() - { - return $this->message; - } + public function getMessage() + { + return $this->message; + } - public function getRoot() - { - return $this->root; - } + public function getRoot() + { + return $this->root; + } - public function getPropertyPath() - { - return $this->propertyPath; - } + public function getPropertyPath() + { + return $this->propertyPath; + } - public function getInvalidValue() - { - return $this->invalidValue; - } + public function getInvalidValue() + { + return $this->invalidValue; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ConstraintViolationList.php b/src/Symfony/Components/Validator/ConstraintViolationList.php index 6512dafbad..28201f69c3 100644 --- a/src/Symfony/Components/Validator/ConstraintViolationList.php +++ b/src/Symfony/Components/Validator/ConstraintViolationList.php @@ -4,46 +4,44 @@ namespace Symfony\Components\Validator; class ConstraintViolationList implements \IteratorAggregate, \Countable { - protected $violations = array(); + protected $violations = array(); - public function __toString() - { - $string = ''; - - foreach ($this->violations as $violation) + public function __toString() { - $param = $violation->getMessageParameters(); - $message = str_replace(array_keys($param), $param, $violation->getMessageTemplate()); - $string .= <<violations as $violation) { + $param = $violation->getMessageParameters(); + $message = str_replace(array_keys($param), $param, $violation->getMessageTemplate()); + $string .= <<getRoot()}.{$violation->getPropertyPath()}: - $message + $message EOF; + } + + return $string; } - return $string; - } - - public function add(ConstraintViolation $violation) - { - $this->violations[] = $violation; - } - - public function addAll(ConstraintViolationList $violations) - { - foreach ($violations->violations as $violation) + public function add(ConstraintViolation $violation) { - $this->violations[] = $violation; + $this->violations[] = $violation; } - } - public function getIterator() - { - return new \ArrayIterator($this->violations); - } + public function addAll(ConstraintViolationList $violations) + { + foreach ($violations->violations as $violation) { + $this->violations[] = $violation; + } + } - public function count() - { - return count($this->violations); - } + public function getIterator() + { + return new \ArrayIterator($this->violations); + } + + public function count() + { + return count($this->violations); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/All.php b/src/Symfony/Components/Validator/Constraints/All.php index 458f6c2e7d..bfa25bf2b0 100644 --- a/src/Symfony/Components/Validator/Constraints/All.php +++ b/src/Symfony/Components/Validator/Constraints/All.php @@ -4,15 +4,15 @@ namespace Symfony\Components\Validator\Constraints; class All extends \Symfony\Components\Validator\Constraint { - public $constraints = array(); + public $constraints = array(); - public function defaultOption() - { - return 'constraints'; - } + public function defaultOption() + { + return 'constraints'; + } - public function requiredOptions() - { - return array('constraints'); - } + public function requiredOptions() + { + return array('constraints'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/AllValidator.php b/src/Symfony/Components/Validator/Constraints/AllValidator.php index 1df9baf22c..c7cd3d106c 100644 --- a/src/Symfony/Components/Validator/Constraints/AllValidator.php +++ b/src/Symfony/Components/Validator/Constraints/AllValidator.php @@ -8,34 +8,30 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class AllValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_array($value) && !$value instanceof \Traversable) { + throw new UnexpectedTypeException($value, 'array or Traversable'); + } + + $walker = $this->context->getGraphWalker(); + $group = $this->context->getGroup(); + $propertyPath = $this->context->getPropertyPath(); + + // cannot simply cast to array, because then the object is converted to an + // array instead of wrapped inside + $constraints = is_array($constraint->constraints) ? $constraint->constraints : array($constraint->constraints); + + foreach ($value as $key => $element) { + foreach ($constraints as $constr) { + $walker->walkConstraint($constr, $element, $group, $propertyPath.'['.$key.']'); + } + } + + return true; } - - if (!is_array($value) && !$value instanceof \Traversable) - { - throw new UnexpectedTypeException($value, 'array or Traversable'); - } - - $walker = $this->context->getGraphWalker(); - $group = $this->context->getGroup(); - $propertyPath = $this->context->getPropertyPath(); - - // cannot simply cast to array, because then the object is converted to an - // array instead of wrapped inside - $constraints = is_array($constraint->constraints) ? $constraint->constraints : array($constraint->constraints); - - foreach ($value as $key => $element) - { - foreach ($constraints as $constr) - { - $walker->walkConstraint($constr, $element, $group, $propertyPath.'['.$key.']'); - } - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/AssertFalse.php b/src/Symfony/Components/Validator/Constraints/AssertFalse.php index f83e3e613f..1dddbe3bab 100644 --- a/src/Symfony/Components/Validator/Constraints/AssertFalse.php +++ b/src/Symfony/Components/Validator/Constraints/AssertFalse.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class AssertFalse extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.AssertFalse.message'; + public $message = 'Symfony.Validator.AssertFalse.message'; } diff --git a/src/Symfony/Components/Validator/Constraints/AssertFalseValidator.php b/src/Symfony/Components/Validator/Constraints/AssertFalseValidator.php index b8a5c58d70..b71d366c10 100644 --- a/src/Symfony/Components/Validator/Constraints/AssertFalseValidator.php +++ b/src/Symfony/Components/Validator/Constraints/AssertFalseValidator.php @@ -7,20 +7,18 @@ use Symfony\Components\Validator\ConstraintValidator; class AssertFalseValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if ($value) { + $this->setMessage($constraint->message); + + return false; + } + + return true; } - - if ($value) - { - $this->setMessage($constraint->message); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/AssertTrue.php b/src/Symfony/Components/Validator/Constraints/AssertTrue.php index 29ce4d04ff..c9008204eb 100644 --- a/src/Symfony/Components/Validator/Constraints/AssertTrue.php +++ b/src/Symfony/Components/Validator/Constraints/AssertTrue.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class AssertTrue extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.AssertTrue.message'; + public $message = 'Symfony.Validator.AssertTrue.message'; } diff --git a/src/Symfony/Components/Validator/Constraints/AssertTrueValidator.php b/src/Symfony/Components/Validator/Constraints/AssertTrueValidator.php index b860394330..27c6dcf389 100644 --- a/src/Symfony/Components/Validator/Constraints/AssertTrueValidator.php +++ b/src/Symfony/Components/Validator/Constraints/AssertTrueValidator.php @@ -7,20 +7,18 @@ use Symfony\Components\Validator\ConstraintValidator; class AssertTrueValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!$value) { + $this->setMessage($constraint->message); + + return false; + } + + return true; } - - if (!$value) - { - $this->setMessage($constraint->message); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/AssertType.php b/src/Symfony/Components/Validator/Constraints/AssertType.php index 1d02a5ccbb..68bd8c7eec 100644 --- a/src/Symfony/Components/Validator/Constraints/AssertType.php +++ b/src/Symfony/Components/Validator/Constraints/AssertType.php @@ -4,22 +4,22 @@ namespace Symfony\Components\Validator\Constraints; class AssertType extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.AssertType.message'; - public $type; + public $message = 'Symfony.Validator.AssertType.message'; + public $type; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'type'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'type'; + } - /** - * {@inheritDoc} - */ - public function requiredOptions() - { - return array('type'); - } + /** + * {@inheritDoc} + */ + public function requiredOptions() + { + return array('type'); + } } diff --git a/src/Symfony/Components/Validator/Constraints/AssertTypeValidator.php b/src/Symfony/Components/Validator/Constraints/AssertTypeValidator.php index e0621f3a2b..5a9fdb8bf4 100644 --- a/src/Symfony/Components/Validator/Constraints/AssertTypeValidator.php +++ b/src/Symfony/Components/Validator/Constraints/AssertTypeValidator.php @@ -7,30 +7,26 @@ use Symfony\Components\Validator\ConstraintValidator; class AssertTypeValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + $type = $constraint->type == 'boolean' ? 'bool' : $constraint->type; + $function = 'is_' . $type; + + if (function_exists($function) && call_user_func($function, $value)) { + return true; + } else if ($value instanceof $constraint->type) { + return true; + } + + $this->setMessage($constraint->message, array( + 'value' => $value, + 'type' => $constraint->type, + )); + + return false; } - - $type = $constraint->type == 'boolean' ? 'bool' : $constraint->type; - $function = 'is_' . $type; - - if (function_exists($function) && call_user_func($function, $value)) - { - return true; - } - else if ($value instanceof $constraint->type) - { - return true; - } - - $this->setMessage($constraint->message, array( - 'value' => $value, - 'type' => $constraint->type, - )); - - return false; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Blank.php b/src/Symfony/Components/Validator/Constraints/Blank.php index b6bbdd879e..fff948957a 100644 --- a/src/Symfony/Components/Validator/Constraints/Blank.php +++ b/src/Symfony/Components/Validator/Constraints/Blank.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class Blank extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Blank.message'; + public $message = 'Symfony.Validator.Blank.message'; } diff --git a/src/Symfony/Components/Validator/Constraints/BlankValidator.php b/src/Symfony/Components/Validator/Constraints/BlankValidator.php index 30e14cffae..0175d36c58 100644 --- a/src/Symfony/Components/Validator/Constraints/BlankValidator.php +++ b/src/Symfony/Components/Validator/Constraints/BlankValidator.php @@ -7,15 +7,14 @@ use Symfony\Components\Validator\ConstraintValidator; class BlankValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value !== '' && $value !== null) + public function isValid($value, Constraint $constraint) { - $this->setMessage($constraint->message, array('value' => $value)); + if ($value !== '' && $value !== null) { + $this->setMessage($constraint->message, array('value' => $value)); - return false; + return false; + } + + return true; } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Choice.php b/src/Symfony/Components/Validator/Constraints/Choice.php index bede7d586c..2ed12965b6 100644 --- a/src/Symfony/Components/Validator/Constraints/Choice.php +++ b/src/Symfony/Components/Validator/Constraints/Choice.php @@ -12,20 +12,20 @@ namespace Symfony\Components\Validator\Constraints; class Choice extends \Symfony\Components\Validator\Constraint { - public $choices; - public $callback; - public $multiple = false; - public $min = null; - public $max = null; - public $message = 'Symfony.Validator.Choice.message'; - public $minMessage = 'Symfony.Validator.Choice.minMessage'; - public $maxMessage = 'Symfony.Validator.Choice.maxMessage'; + public $choices; + public $callback; + public $multiple = false; + public $min = null; + public $max = null; + public $message = 'Symfony.Validator.Choice.message'; + public $minMessage = 'Symfony.Validator.Choice.minMessage'; + public $maxMessage = 'Symfony.Validator.Choice.maxMessage'; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'choices'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'choices'; + } } diff --git a/src/Symfony/Components/Validator/Constraints/ChoiceValidator.php b/src/Symfony/Components/Validator/Constraints/ChoiceValidator.php index c828deb446..0ff04a27e6 100644 --- a/src/Symfony/Components/Validator/Constraints/ChoiceValidator.php +++ b/src/Symfony/Components/Validator/Constraints/ChoiceValidator.php @@ -24,78 +24,60 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; */ class ChoiceValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if (!$constraint->choices && !$constraint->callback) + public function isValid($value, Constraint $constraint) { - throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice'); - } - - if ($value === null) - { - return true; - } - - if ($constraint->multiple && !is_array($value)) - { - throw new UnexpectedTypeException($value, 'array'); - } - - if ($constraint->callback) - { - if (is_callable(array($this->context->getCurrentClass(), $constraint->callback))) - { - $choices = call_user_func(array($this->context->getCurrentClass(), $constraint->callback)); - } - else if (is_callable($constraint->callback)) - { - $choices = call_user_func($constraint->callback); - } - else - { - throw new ConstraintDefinitionException('The Choice constraint expects a valid callback'); - } - } - else - { - $choices = $constraint->choices; - } - - if ($constraint->multiple) - { - foreach ($value as $_value) - { - if (!in_array($_value, $choices, true)) - { - $this->setMessage($constraint->message, array('value' => $_value)); - - return false; + if (!$constraint->choices && !$constraint->callback) { + throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice'); } - } - $count = count($value); + if ($value === null) { + return true; + } - if ($constraint->min !== null && $count < $constraint->min) - { - $this->setMessage($constraint->minMessage, array('limit' => $constraint->min)); + if ($constraint->multiple && !is_array($value)) { + throw new UnexpectedTypeException($value, 'array'); + } - return false; - } + if ($constraint->callback) { + if (is_callable(array($this->context->getCurrentClass(), $constraint->callback))) { + $choices = call_user_func(array($this->context->getCurrentClass(), $constraint->callback)); + } else if (is_callable($constraint->callback)) { + $choices = call_user_func($constraint->callback); + } else { + throw new ConstraintDefinitionException('The Choice constraint expects a valid callback'); + } + } else { + $choices = $constraint->choices; + } - if ($constraint->max !== null && $count > $constraint->max) - { - $this->setMessage($constraint->maxMessage, array('limit' => $constraint->max)); + if ($constraint->multiple) { + foreach ($value as $_value) { + if (!in_array($_value, $choices, true)) { + $this->setMessage($constraint->message, array('value' => $_value)); - return false; - } + return false; + } + } + + $count = count($value); + + if ($constraint->min !== null && $count < $constraint->min) { + $this->setMessage($constraint->minMessage, array('limit' => $constraint->min)); + + return false; + } + + if ($constraint->max !== null && $count > $constraint->max) { + $this->setMessage($constraint->maxMessage, array('limit' => $constraint->max)); + + return false; + } + } elseif (!in_array($value, $choices, true)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + return true; } - elseif (!in_array($value, $choices, true)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - return true; - } } diff --git a/src/Symfony/Components/Validator/Constraints/Collection.php b/src/Symfony/Components/Validator/Constraints/Collection.php index 4724b2e8e0..bc542b6f2f 100644 --- a/src/Symfony/Components/Validator/Constraints/Collection.php +++ b/src/Symfony/Components/Validator/Constraints/Collection.php @@ -4,14 +4,14 @@ namespace Symfony\Components\Validator\Constraints; class Collection extends \Symfony\Components\Validator\Constraint { - public $fields; - public $allowExtraFields = false; - public $allowMissingFields = false; - public $extraFieldsMessage = 'Symfony.Validator.Collection.extraFieldsMessage'; - public $missingFieldsMessage = 'Symfony.Validator.Collection.missingFieldsMessage'; + public $fields; + public $allowExtraFields = false; + public $allowMissingFields = false; + public $extraFieldsMessage = 'Symfony.Validator.Collection.extraFieldsMessage'; + public $missingFieldsMessage = 'Symfony.Validator.Collection.missingFieldsMessage'; - public function requiredOptions() - { - return array('fields'); - } + public function requiredOptions() + { + return array('fields'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/CollectionValidator.php b/src/Symfony/Components/Validator/Constraints/CollectionValidator.php index 513c00780c..dd5cca78d9 100644 --- a/src/Symfony/Components/Validator/Constraints/CollectionValidator.php +++ b/src/Symfony/Components/Validator/Constraints/CollectionValidator.php @@ -9,69 +9,59 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class CollectionValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; - } - - if (!is_array($value) && !($value instanceof \Traversable && $value instanceof \ArrayAccess)) - { - throw new UnexpectedTypeException($value, 'array or Traversable and ArrayAccess'); - } - - $walker = $this->context->getGraphWalker(); - $group = $this->context->getGroup(); - $propertyPath = $this->context->getPropertyPath(); - - $missingFields = array(); - $extraFields = array(); - - foreach ($value as $field => $fieldValue) - { - $extraFields[$field] = $fieldValue; - } - - foreach ($constraint->fields as $field => $constraints) - { - if (array_key_exists($field, $value)) - { - // cannot simply cast to array, because then the object is converted to an - // array instead of wrapped inside - $constraints = is_array($constraints) ? $constraints : array($constraints); - - foreach ($constraints as $constr) - { - $walker->walkConstraint($constr, $value[$field], $group, $propertyPath.'['.$field.']'); + if ($value === null) { + return true; } - unset($extraFields[$field]); - } - else - { - $missingFields[] = $field; - } + if (!is_array($value) && !($value instanceof \Traversable && $value instanceof \ArrayAccess)) { + throw new UnexpectedTypeException($value, 'array or Traversable and ArrayAccess'); + } + + $walker = $this->context->getGraphWalker(); + $group = $this->context->getGroup(); + $propertyPath = $this->context->getPropertyPath(); + + $missingFields = array(); + $extraFields = array(); + + foreach ($value as $field => $fieldValue) { + $extraFields[$field] = $fieldValue; + } + + foreach ($constraint->fields as $field => $constraints) { + if (array_key_exists($field, $value)) { + // cannot simply cast to array, because then the object is converted to an + // array instead of wrapped inside + $constraints = is_array($constraints) ? $constraints : array($constraints); + + foreach ($constraints as $constr) { + $walker->walkConstraint($constr, $value[$field], $group, $propertyPath.'['.$field.']'); + } + + unset($extraFields[$field]); + } else { + $missingFields[] = $field; + } + } + + if (count($extraFields) > 0 && !$constraint->allowExtraFields) { + $this->setMessage($constraint->extraFieldsMessage, array( + 'fields' => '"'.implode('", "', array_keys($extraFields)).'"' + )); + + return false; + } + + if (count($missingFields) > 0 && !$constraint->allowMissingFields) { + $this->setMessage($constraint->missingFieldsMessage, array( + 'fields' => '"'.implode('", "', $missingFields).'"' + )); + + return false; + } + + return true; } - - if (count($extraFields) > 0 && !$constraint->allowExtraFields) - { - $this->setMessage($constraint->extraFieldsMessage, array( - 'fields' => '"'.implode('", "', array_keys($extraFields)).'"' - )); - - return false; - } - - if (count($missingFields) > 0 && !$constraint->allowMissingFields) - { - $this->setMessage($constraint->missingFieldsMessage, array( - 'fields' => '"'.implode('", "', $missingFields).'"' - )); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Date.php b/src/Symfony/Components/Validator/Constraints/Date.php index 9e774f5dab..ddaddc0bc7 100644 --- a/src/Symfony/Components/Validator/Constraints/Date.php +++ b/src/Symfony/Components/Validator/Constraints/Date.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class Date extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Date.message'; + public $message = 'Symfony.Validator.Date.message'; } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/DateTime.php b/src/Symfony/Components/Validator/Constraints/DateTime.php index 1587f5ad10..7d169acf6f 100644 --- a/src/Symfony/Components/Validator/Constraints/DateTime.php +++ b/src/Symfony/Components/Validator/Constraints/DateTime.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class DateTime extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.DateTime.message'; + public $message = 'Symfony.Validator.DateTime.message'; } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/DateTimeValidator.php b/src/Symfony/Components/Validator/Constraints/DateTimeValidator.php index c84da73125..139828b813 100644 --- a/src/Symfony/Components/Validator/Constraints/DateTimeValidator.php +++ b/src/Symfony/Components/Validator/Constraints/DateTimeValidator.php @@ -8,29 +8,26 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class DateTimeValidator extends ConstraintValidator { - const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/'; + const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/'; - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + if (!preg_match(self::PATTERN, $value, $matches)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + return checkdate($matches[2], $matches[3], $matches[1]); } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - if (!preg_match(self::PATTERN, $value, $matches)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - return checkdate($matches[2], $matches[3], $matches[1]); - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/DateValidator.php b/src/Symfony/Components/Validator/Constraints/DateValidator.php index 7b749c5c85..6ce0ec9585 100644 --- a/src/Symfony/Components/Validator/Constraints/DateValidator.php +++ b/src/Symfony/Components/Validator/Constraints/DateValidator.php @@ -8,29 +8,26 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class DateValidator extends ConstraintValidator { - const PATTERN = '/^(\d{4})-(\d{2})-(\d{2})$/'; + const PATTERN = '/^(\d{4})-(\d{2})-(\d{2})$/'; - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + if (!preg_match(self::PATTERN, $value, $matches)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + return checkdate($matches[2], $matches[3], $matches[1]); } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - if (!preg_match(self::PATTERN, $value, $matches)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - return checkdate($matches[2], $matches[3], $matches[1]); - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Email.php b/src/Symfony/Components/Validator/Constraints/Email.php index 28c38153c8..8d2786128b 100644 --- a/src/Symfony/Components/Validator/Constraints/Email.php +++ b/src/Symfony/Components/Validator/Constraints/Email.php @@ -4,6 +4,6 @@ namespace Symfony\Components\Validator\Constraints; class Email extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Email.message'; - public $checkMX = false; + public $message = 'Symfony.Validator.Email.message'; + public $checkMX = false; } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/EmailValidator.php b/src/Symfony/Components/Validator/Constraints/EmailValidator.php index 8e126bd87c..41555eb8eb 100644 --- a/src/Symfony/Components/Validator/Constraints/EmailValidator.php +++ b/src/Symfony/Components/Validator/Constraints/EmailValidator.php @@ -8,81 +8,71 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class EmailValidator extends ConstraintValidator { - const PATTERN = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i'; + const PATTERN = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i'; - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; - } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - if (!preg_match(self::PATTERN, $value)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - if ($constraint->checkMX) - { - $host = substr($value, strpos($value, '@')); - - if (!$this->checkMX($host)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - } - - return true; - } - - /** - * Check DNA Records for MX type (from Doctrine EmailValidator) - * - * @param string $host Host name - * @return boolean - * @licence This software consists of voluntary contributions made by many individuals - * and is licensed under the LGPL. For more information, see - * . - */ - private function checkMX($host) - { - // We have different behavior here depending of OS and PHP version - if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.3.0', '<')) { - $output = array(); - - @exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output); - - if (empty($output)) - { - throw new ValidatorError('Unable to execute DNS lookup. Are you sure PHP can call exec()?'); - } - - foreach ($output as $line) - { - if (preg_match('/^'.$host.'/', $line)) - { - return true; + if ($value === null) { + return true; } - } - return false; + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + if (!preg_match(self::PATTERN, $value)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + if ($constraint->checkMX) { + $host = substr($value, strpos($value, '@')); + + if (!$this->checkMX($host)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + } + + return true; } - else if (function_exists('checkdnsrr')) + + /** + * Check DNA Records for MX type (from Doctrine EmailValidator) + * + * @param string $host Host name + * @return boolean + * @licence This software consists of voluntary contributions made by many individuals + * and is licensed under the LGPL. For more information, see + * . + */ + private function checkMX($host) { - return checkdnsrr($host, 'MX'); - } + // We have different behavior here depending of OS and PHP version + if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.3.0', '<')) { + $output = array(); - throw new ValidatorError('Could not retrieve DNS record information. Remove check_mx = true to prevent this warning'); - } + @exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output); + + if (empty($output)) { + throw new ValidatorError('Unable to execute DNS lookup. Are you sure PHP can call exec()?'); + } + + foreach ($output as $line) { + if (preg_match('/^'.$host.'/', $line)) { + return true; + } + } + + return false; + } else if (function_exists('checkdnsrr')) { + return checkdnsrr($host, 'MX'); + } + + throw new ValidatorError('Could not retrieve DNS record information. Remove check_mx = true to prevent this warning'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/File.php b/src/Symfony/Components/Validator/Constraints/File.php index bddc344354..1c02a69bb0 100644 --- a/src/Symfony/Components/Validator/Constraints/File.php +++ b/src/Symfony/Components/Validator/Constraints/File.php @@ -4,10 +4,10 @@ namespace Symfony\Components\Validator\Constraints; class File extends \Symfony\Components\Validator\Constraint { - public $maxSize = null; - public $mimeTypes = array(); - public $notFoundMessage = 'Symfony.Validator.File.notFoundMessage'; - public $notReadableMessage = 'Symfony.Validator.File.notReadableMessage'; - public $maxSizeMessage = 'Symfony.Validator.File.maxSizeMessage'; - public $mimeTypesMessage = 'Symfony.Validator.File.mimeTypesMessage'; + public $maxSize = null; + public $mimeTypes = array(); + public $notFoundMessage = 'Symfony.Validator.File.notFoundMessage'; + public $notReadableMessage = 'Symfony.Validator.File.notReadableMessage'; + public $maxSizeMessage = 'Symfony.Validator.File.maxSizeMessage'; + public $mimeTypesMessage = 'Symfony.Validator.File.mimeTypesMessage'; } diff --git a/src/Symfony/Components/Validator/Constraints/FileValidator.php b/src/Symfony/Components/Validator/Constraints/FileValidator.php index 42a47ce86c..15528543b7 100644 --- a/src/Symfony/Components/Validator/Constraints/FileValidator.php +++ b/src/Symfony/Components/Validator/Constraints/FileValidator.php @@ -10,90 +10,74 @@ use Symfony\Components\File\File; class FileValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !$value instanceof File && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $path = $value instanceof File ? $value->getPath() : (string)$value; + + if (!file_exists($path)) { + $this->setMessage($constraint->notFoundMessage, array('file' => $path)); + + return false; + } + + if (!is_readable($path)) { + $this->setMessage($constraint->notReadableMessage, array('file' => $path)); + + return false; + } + + if ($constraint->maxSize) { + if (ctype_digit((string)$constraint->maxSize)) { + $size = filesize($path); + $limit = $constraint->maxSize; + $suffix = ' bytes'; + } else if (preg_match('/^(\d)k$/', $constraint->maxSize, $matches)) { + $size = round(filesize($path) / 1000, 2); + $limit = $matches[1]; + $suffix = ' kB'; + } else if (preg_match('/^(\d)M$/', $constraint->maxSize, $matches)) { + $size = round(filesize($path) / 1000000, 2); + $limit = $matches[1]; + $suffix = ' MB'; + } else { + throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); + } + + if ($size > $limit) { + $this->setMessage($constraint->maxSizeMessage, array( + 'size' => $size . $suffix, + 'limit' => $limit . $suffix, + 'file' => $path, + )); + + return false; + } + } + + if ($constraint->mimeTypes) { + if (!$value instanceof File) { + throw new ConstraintValidationException(); + } + + if (!in_array($value->getMimeType(), (array)$constraint->mimeTypes)) { + $this->setMessage($constraint->mimeTypesMessage, array( + 'type' => '"'.$value->getMimeType().'"', + 'types' => '"'.implode('", "', (array)$constraint->mimeTypes).'"', + 'file' => $path, + )); + + return false; + } + } + + return true; } - - if (!is_scalar($value) && !$value instanceof File && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $path = $value instanceof File ? $value->getPath() : (string)$value; - - if (!file_exists($path)) - { - $this->setMessage($constraint->notFoundMessage, array('file' => $path)); - - return false; - } - - if (!is_readable($path)) - { - $this->setMessage($constraint->notReadableMessage, array('file' => $path)); - - return false; - } - - if ($constraint->maxSize) - { - if (ctype_digit((string)$constraint->maxSize)) - { - $size = filesize($path); - $limit = $constraint->maxSize; - $suffix = ' bytes'; - } - else if (preg_match('/^(\d)k$/', $constraint->maxSize, $matches)) - { - $size = round(filesize($path) / 1000, 2); - $limit = $matches[1]; - $suffix = ' kB'; - } - else if (preg_match('/^(\d)M$/', $constraint->maxSize, $matches)) - { - $size = round(filesize($path) / 1000000, 2); - $limit = $matches[1]; - $suffix = ' MB'; - } - else - { - throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); - } - - if ($size > $limit) - { - $this->setMessage($constraint->maxSizeMessage, array( - 'size' => $size . $suffix, - 'limit' => $limit . $suffix, - 'file' => $path, - )); - - return false; - } - } - - if ($constraint->mimeTypes) - { - if (!$value instanceof File) - { - throw new ConstraintValidationException(); - } - - if (!in_array($value->getMimeType(), (array)$constraint->mimeTypes)) - { - $this->setMessage($constraint->mimeTypesMessage, array( - 'type' => '"'.$value->getMimeType().'"', - 'types' => '"'.implode('", "', (array)$constraint->mimeTypes).'"', - 'file' => $path, - )); - - return false; - } - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Max.php b/src/Symfony/Components/Validator/Constraints/Max.php index c0d90ed23e..00daad5f66 100644 --- a/src/Symfony/Components/Validator/Constraints/Max.php +++ b/src/Symfony/Components/Validator/Constraints/Max.php @@ -4,22 +4,22 @@ namespace Symfony\Components\Validator\Constraints; class Max extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Max.message'; - public $limit; + public $message = 'Symfony.Validator.Max.message'; + public $limit; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'limit'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'limit'; + } - /** - * {@inheritDoc} - */ - public function requiredOptions() - { - return array('limit'); - } + /** + * {@inheritDoc} + */ + public function requiredOptions() + { + return array('limit'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/MaxLength.php b/src/Symfony/Components/Validator/Constraints/MaxLength.php index b9ba30d0eb..d076225127 100644 --- a/src/Symfony/Components/Validator/Constraints/MaxLength.php +++ b/src/Symfony/Components/Validator/Constraints/MaxLength.php @@ -4,23 +4,23 @@ namespace Symfony\Components\Validator\Constraints; class MaxLength extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.MaxLength.message'; - public $limit; - public $charset = 'UTF-8'; + public $message = 'Symfony.Validator.MaxLength.message'; + public $limit; + public $charset = 'UTF-8'; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'limit'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'limit'; + } - /** - * {@inheritDoc} - */ - public function requiredOptions() - { - return array('limit'); - } + /** + * {@inheritDoc} + */ + public function requiredOptions() + { + return array('limit'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/MaxLengthValidator.php b/src/Symfony/Components/Validator/Constraints/MaxLengthValidator.php index ef5e458f7a..d98c2ca01b 100644 --- a/src/Symfony/Components/Validator/Constraints/MaxLengthValidator.php +++ b/src/Symfony/Components/Validator/Constraints/MaxLengthValidator.php @@ -8,32 +8,29 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class MaxLengthValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + $length = function_exists('mb_strlen') ? mb_strlen($value, $constraint->charset) : strlen($value); + + if ($length > $constraint->limit) { + $this->setMessage($constraint->message, array( + 'value' => $value, + 'limit' => $constraint->limit, + )); + + return false; + } + + return true; } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - $length = function_exists('mb_strlen') ? mb_strlen($value, $constraint->charset) : strlen($value); - - if ($length > $constraint->limit) - { - $this->setMessage($constraint->message, array( - 'value' => $value, - 'limit' => $constraint->limit, - )); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/MaxValidator.php b/src/Symfony/Components/Validator/Constraints/MaxValidator.php index 96e2e580b1..4de42643c2 100644 --- a/src/Symfony/Components/Validator/Constraints/MaxValidator.php +++ b/src/Symfony/Components/Validator/Constraints/MaxValidator.php @@ -8,28 +8,25 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class MaxValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_numeric($value)) { + throw new UnexpectedTypeException($value, 'numeric'); + } + + if ($value > $constraint->limit) { + $this->setMessage($constraint->message, array( + 'value' => $value, + 'limit' => $constraint->limit, + )); + + return false; + } + + return true; } - - if (!is_numeric($value)) - { - throw new UnexpectedTypeException($value, 'numeric'); - } - - if ($value > $constraint->limit) - { - $this->setMessage($constraint->message, array( - 'value' => $value, - 'limit' => $constraint->limit, - )); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Min.php b/src/Symfony/Components/Validator/Constraints/Min.php index ca42ff9b19..bec41d8cc0 100644 --- a/src/Symfony/Components/Validator/Constraints/Min.php +++ b/src/Symfony/Components/Validator/Constraints/Min.php @@ -4,22 +4,22 @@ namespace Symfony\Components\Validator\Constraints; class Min extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Min.message'; - public $limit; + public $message = 'Symfony.Validator.Min.message'; + public $limit; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'limit'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'limit'; + } - /** - * {@inheritDoc} - */ - public function requiredOptions() - { - return array('limit'); - } + /** + * {@inheritDoc} + */ + public function requiredOptions() + { + return array('limit'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/MinLength.php b/src/Symfony/Components/Validator/Constraints/MinLength.php index 8e06977dc0..1659e48066 100644 --- a/src/Symfony/Components/Validator/Constraints/MinLength.php +++ b/src/Symfony/Components/Validator/Constraints/MinLength.php @@ -4,23 +4,23 @@ namespace Symfony\Components\Validator\Constraints; class MinLength extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.MinLength.message'; - public $limit; - public $charset = 'UTF-8'; + public $message = 'Symfony.Validator.MinLength.message'; + public $limit; + public $charset = 'UTF-8'; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'limit'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'limit'; + } - /** - * {@inheritDoc} - */ - public function requiredOptions() - { - return array('limit'); - } + /** + * {@inheritDoc} + */ + public function requiredOptions() + { + return array('limit'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/MinLengthValidator.php b/src/Symfony/Components/Validator/Constraints/MinLengthValidator.php index d89c0fc70f..db728a85ce 100644 --- a/src/Symfony/Components/Validator/Constraints/MinLengthValidator.php +++ b/src/Symfony/Components/Validator/Constraints/MinLengthValidator.php @@ -8,32 +8,29 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class MinLengthValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + $length = function_exists('mb_strlen') ? mb_strlen($value, $constraint->charset) : strlen($value); + + if ($length < $constraint->limit) { + $this->setMessage($constraint->message, array( + 'value' => $value, + 'limit' => $constraint->limit, + )); + + return false; + } + + return true; } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - $length = function_exists('mb_strlen') ? mb_strlen($value, $constraint->charset) : strlen($value); - - if ($length < $constraint->limit) - { - $this->setMessage($constraint->message, array( - 'value' => $value, - 'limit' => $constraint->limit, - )); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/MinValidator.php b/src/Symfony/Components/Validator/Constraints/MinValidator.php index d1580cf9c2..289f9dd887 100644 --- a/src/Symfony/Components/Validator/Constraints/MinValidator.php +++ b/src/Symfony/Components/Validator/Constraints/MinValidator.php @@ -8,28 +8,25 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class MinValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_numeric($value)) { + throw new UnexpectedTypeException($value, 'numeric'); + } + + if ($value < $constraint->limit) { + $this->setMessage($constraint->message, array( + 'value' => $value, + 'limit' => $constraint->limit, + )); + + return false; + } + + return true; } - - if (!is_numeric($value)) - { - throw new UnexpectedTypeException($value, 'numeric'); - } - - if ($value < $constraint->limit) - { - $this->setMessage($constraint->message, array( - 'value' => $value, - 'limit' => $constraint->limit, - )); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/NotBlank.php b/src/Symfony/Components/Validator/Constraints/NotBlank.php index b507500b3d..1b61409402 100644 --- a/src/Symfony/Components/Validator/Constraints/NotBlank.php +++ b/src/Symfony/Components/Validator/Constraints/NotBlank.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class NotBlank extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.NotBlank.message'; + public $message = 'Symfony.Validator.NotBlank.message'; } diff --git a/src/Symfony/Components/Validator/Constraints/NotBlankValidator.php b/src/Symfony/Components/Validator/Constraints/NotBlankValidator.php index e77a98420d..02802bc72f 100644 --- a/src/Symfony/Components/Validator/Constraints/NotBlankValidator.php +++ b/src/Symfony/Components/Validator/Constraints/NotBlankValidator.php @@ -7,15 +7,14 @@ use Symfony\Components\Validator\ConstraintValidator; class NotBlankValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === '' || $value === null) + public function isValid($value, Constraint $constraint) { - $this->setMessage($constraint->message); + if ($value === '' || $value === null) { + $this->setMessage($constraint->message); - return false; + return false; + } + + return true; } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/NotNull.php b/src/Symfony/Components/Validator/Constraints/NotNull.php index f66598ddc5..45a4e4d33c 100644 --- a/src/Symfony/Components/Validator/Constraints/NotNull.php +++ b/src/Symfony/Components/Validator/Constraints/NotNull.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class NotNull extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.NotNull.message'; + public $message = 'Symfony.Validator.NotNull.message'; } diff --git a/src/Symfony/Components/Validator/Constraints/NotNullValidator.php b/src/Symfony/Components/Validator/Constraints/NotNullValidator.php index 64f8bc38ef..6190ab3f8a 100644 --- a/src/Symfony/Components/Validator/Constraints/NotNullValidator.php +++ b/src/Symfony/Components/Validator/Constraints/NotNullValidator.php @@ -7,15 +7,14 @@ use Symfony\Components\Validator\ConstraintValidator; class NotNullValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if (is_null($value)) + public function isValid($value, Constraint $constraint) { - $this->setMessage($constraint->message); + if (is_null($value)) { + $this->setMessage($constraint->message); - return false; + return false; + } + + return true; } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Null.php b/src/Symfony/Components/Validator/Constraints/Null.php index 55a647c88a..27bd12b840 100644 --- a/src/Symfony/Components/Validator/Constraints/Null.php +++ b/src/Symfony/Components/Validator/Constraints/Null.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class Null extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Null.message'; + public $message = 'Symfony.Validator.Null.message'; } diff --git a/src/Symfony/Components/Validator/Constraints/NullValidator.php b/src/Symfony/Components/Validator/Constraints/NullValidator.php index 8162d59546..caa4aa6c5d 100644 --- a/src/Symfony/Components/Validator/Constraints/NullValidator.php +++ b/src/Symfony/Components/Validator/Constraints/NullValidator.php @@ -7,15 +7,14 @@ use Symfony\Components\Validator\ConstraintValidator; class NullValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if (!is_null($value)) + public function isValid($value, Constraint $constraint) { - $this->setMessage($constraint->message, array('value' => $value)); + if (!is_null($value)) { + $this->setMessage($constraint->message, array('value' => $value)); - return false; + return false; + } + + return true; } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Regex.php b/src/Symfony/Components/Validator/Constraints/Regex.php index d2f9ae0c7e..89beaf0c83 100644 --- a/src/Symfony/Components/Validator/Constraints/Regex.php +++ b/src/Symfony/Components/Validator/Constraints/Regex.php @@ -4,23 +4,23 @@ namespace Symfony\Components\Validator\Constraints; class Regex extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Regex.message'; - public $pattern; - public $match = true; + public $message = 'Symfony.Validator.Regex.message'; + public $pattern; + public $match = true; - /** - * {@inheritDoc} - */ - public function defaultOption() - { - return 'pattern'; - } + /** + * {@inheritDoc} + */ + public function defaultOption() + { + return 'pattern'; + } - /** - * {@inheritDoc} - */ - public function requiredOptions() - { - return array('pattern'); - } + /** + * {@inheritDoc} + */ + public function requiredOptions() + { + return array('pattern'); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/RegexValidator.php b/src/Symfony/Components/Validator/Constraints/RegexValidator.php index 2d406d5609..73e482b51a 100644 --- a/src/Symfony/Components/Validator/Constraints/RegexValidator.php +++ b/src/Symfony/Components/Validator/Constraints/RegexValidator.php @@ -8,31 +8,29 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class RegexValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + if ( + ($constraint->match && !preg_match($constraint->pattern, $value)) + || + (!$constraint->match && preg_match($constraint->pattern, $value)) + ) + { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + return true; } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - if ( - ($constraint->match && !preg_match($constraint->pattern, $value)) - || - (!$constraint->match && preg_match($constraint->pattern, $value)) - ) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Time.php b/src/Symfony/Components/Validator/Constraints/Time.php index 195801ea26..ab311e2cd4 100644 --- a/src/Symfony/Components/Validator/Constraints/Time.php +++ b/src/Symfony/Components/Validator/Constraints/Time.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Constraints; class Time extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Time.message'; + public $message = 'Symfony.Validator.Time.message'; } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/TimeValidator.php b/src/Symfony/Components/Validator/Constraints/TimeValidator.php index 2020b8728a..669fc29531 100644 --- a/src/Symfony/Components/Validator/Constraints/TimeValidator.php +++ b/src/Symfony/Components/Validator/Constraints/TimeValidator.php @@ -8,29 +8,26 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class TimeValidator extends ConstraintValidator { - const PATTERN = '/(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/'; + const PATTERN = '/(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/'; - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + if (!preg_match(self::PATTERN, $value)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + return true; } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - if (!preg_match(self::PATTERN, $value)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Url.php b/src/Symfony/Components/Validator/Constraints/Url.php index 20bc46a856..3aac6c7cd3 100644 --- a/src/Symfony/Components/Validator/Constraints/Url.php +++ b/src/Symfony/Components/Validator/Constraints/Url.php @@ -4,6 +4,6 @@ namespace Symfony\Components\Validator\Constraints; class Url extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Url.message'; - public $protocols = array('http', 'https', 'ftp', 'ftps'); + public $message = 'Symfony.Validator.Url.message'; + public $protocols = array('http', 'https', 'ftp', 'ftps'); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/UrlValidator.php b/src/Symfony/Components/Validator/Constraints/UrlValidator.php index 2fc3c6c376..d8f2c7f476 100644 --- a/src/Symfony/Components/Validator/Constraints/UrlValidator.php +++ b/src/Symfony/Components/Validator/Constraints/UrlValidator.php @@ -8,40 +8,37 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class UrlValidator extends ConstraintValidator { - const PATTERN = '~^ - (%s):// # protocol - ( - ([a-z0-9-]+\.)+[a-z]{2,6} # a domain name - | # or - \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # a IP address - ) - (:[0-9]+)? # a port (optional) - (/?|/\S+) # a /, nothing or a / with something - $~ix'; + const PATTERN = '~^ + (%s):// # protocol + ( + ([a-z0-9-]+\.)+[a-z]{2,6} # a domain name + | # or + \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # a IP address + ) + (:[0-9]+)? # a port (optional) + (/?|/\S+) # a /, nothing or a / with something + $~ix'; - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; + if ($value === null) { + return true; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $value = (string)$value; + + $pattern = sprintf(self::PATTERN, implode('|', $constraint->protocols)); + + if (!preg_match($pattern, $value)) { + $this->setMessage($constraint->message, array('value' => $value)); + + return false; + } + + return true; } - - if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) - { - throw new UnexpectedTypeException($value, 'string'); - } - - $value = (string)$value; - - $pattern = sprintf(self::PATTERN, implode('|', $constraint->protocols)); - - if (!preg_match($pattern, $value)) - { - $this->setMessage($constraint->message, array('value' => $value)); - - return false; - } - - return true; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Valid.php b/src/Symfony/Components/Validator/Constraints/Valid.php index fe3bdedcac..7eed86a38b 100644 --- a/src/Symfony/Components/Validator/Constraints/Valid.php +++ b/src/Symfony/Components/Validator/Constraints/Valid.php @@ -4,6 +4,6 @@ namespace Symfony\Components\Validator\Constraints; class Valid extends \Symfony\Components\Validator\Constraint { - public $message = 'Symfony.Validator.Valid.message'; - public $class; + public $message = 'Symfony.Validator.Valid.message'; + public $class; } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/ValidValidator.php b/src/Symfony/Components/Validator/Constraints/ValidValidator.php index af700a108d..2b2f54bdd0 100644 --- a/src/Symfony/Components/Validator/Constraints/ValidValidator.php +++ b/src/Symfony/Components/Validator/Constraints/ValidValidator.php @@ -9,41 +9,32 @@ use Symfony\Components\Validator\Exception\UnexpectedTypeException; class ValidValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value === null) + public function isValid($value, Constraint $constraint) { - return true; - } + if ($value === null) { + return true; + } - $walker = $this->context->getGraphWalker(); - $group = $this->context->getGroup(); - $propertyPath = $this->context->getPropertyPath(); - $factory = $this->context->getClassMetadataFactory(); + $walker = $this->context->getGraphWalker(); + $group = $this->context->getGroup(); + $propertyPath = $this->context->getPropertyPath(); + $factory = $this->context->getClassMetadataFactory(); - if (is_array($value)) - { - foreach ($value as $key => $element) - { - $walker->walkConstraint($constraint, $element, $group, $propertyPath.'['.$key.']'); - } - } - else if (!is_object($value)) - { - throw new UnexpectedTypeException($value, 'object or array'); - } - else if ($constraint->class && !$value instanceof $constraint->class) - { - $this->setMessage($constraint->message, array('class' => $constraint->class)); + if (is_array($value)) { + foreach ($value as $key => $element) { + $walker->walkConstraint($constraint, $element, $group, $propertyPath.'['.$key.']'); + } + } else if (!is_object($value)) { + throw new UnexpectedTypeException($value, 'object or array'); + } else if ($constraint->class && !$value instanceof $constraint->class) { + $this->setMessage($constraint->message, array('class' => $constraint->class)); - return false; - } - else - { - $metadata = $factory->getClassMetadata(get_class($value)); - $walker->walkClass($metadata, $value, $group, $propertyPath); - } + return false; + } else { + $metadata = $factory->getClassMetadata(get_class($value)); + $walker->walkClass($metadata, $value, $group, $propertyPath); + } - return true; - } + return true; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Constraints/Validation.php b/src/Symfony/Components/Validator/Constraints/Validation.php index 05999bf9f3..9482238df8 100644 --- a/src/Symfony/Components/Validator/Constraints/Validation.php +++ b/src/Symfony/Components/Validator/Constraints/Validation.php @@ -4,10 +4,10 @@ namespace Symfony\Components\Validator\Constraints; class Validation { - public $constraints; + public $constraints; - public function __construct(array $constraints) - { - $this->constraints = $constraints['value']; - } + public function __construct(array $constraints) + { + $this->constraints = $constraints['value']; + } } diff --git a/src/Symfony/Components/Validator/DependencyInjectionValidatorFactory.php b/src/Symfony/Components/Validator/DependencyInjectionValidatorFactory.php index 52f2856afc..022b0338f9 100644 --- a/src/Symfony/Components/Validator/DependencyInjectionValidatorFactory.php +++ b/src/Symfony/Components/Validator/DependencyInjectionValidatorFactory.php @@ -3,56 +3,55 @@ namespace Symfony\Components\Validator; use Symfony\Components\DependencyInjection\ContainerInterface, - Symfony\Components\Validator\ConstraintValidatorFactoryInterface, - Symfony\Components\Validator\Constraint, - Symfony\Components\Validator\ConstraintValidatorInterface; + Symfony\Components\Validator\ConstraintValidatorFactoryInterface, + Symfony\Components\Validator\Constraint, + Symfony\Components\Validator\ConstraintValidatorInterface; class DependencyInjectionValidatorFactory implements ConstraintValidatorFactoryInterface { - protected $container; + protected $container; - /** - * @param ContainerInterface $container - */ - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - /** - * Gets contraint validator service, setting it if it doesn't exist - * Throws exception if validator service is not instance of ConstraintValidatorInterface - * @param Constraint $constraint - * @return ConstraintValidatorInterface - * @throws \LogicException - */ - public function getInstance(Constraint $constraint) - { - $className = $constraint->validatedBy(); - $id = $this->getServiceIdFromClass($className); - - if (!$this->container->hasService($id)) + /** + * @param ContainerInterface $container + */ + public function __construct(ContainerInterface $container) { - $this->container->setService($id, new $className()); + $this->container = $container; } - $validator = $this->container->getService($id); + /** + * Gets contraint validator service, setting it if it doesn't exist + * Throws exception if validator service is not instance of ConstraintValidatorInterface + * @param Constraint $constraint + * @return ConstraintValidatorInterface + * @throws \LogicException + */ + public function getInstance(Constraint $constraint) + { + $className = $constraint->validatedBy(); + $id = $this->getServiceIdFromClass($className); - if (!$validator instanceof ConstraintValidatorInterface) { - throw new \LogicException('Service ' . $id . ' is not instance of ConstraintValidatorInterface'); + if (!$this->container->hasService($id)) { + $this->container->setService($id, new $className()); + } + + $validator = $this->container->getService($id); + + if (!$validator instanceof ConstraintValidatorInterface) { + throw new \LogicException('Service ' . $id . ' is not instance of ConstraintValidatorInterface'); + } + + return $validator; } - return $validator; - } - - /** - * Gets service id, corresponding to full class name of ConstraintValidator - * @param string $className - * @return string - */ - protected function getServiceIdFromClass($className) - { - return str_replace('\\', '.', $className); - } + /** + * Gets service id, corresponding to full class name of ConstraintValidator + * @param string $className + * @return string + */ + protected function getServiceIdFromClass($className) + { + return str_replace('\\', '.', $className); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Exception/InvalidOptionsException.php b/src/Symfony/Components/Validator/Exception/InvalidOptionsException.php index cc832fc876..1175c279d4 100644 --- a/src/Symfony/Components/Validator/Exception/InvalidOptionsException.php +++ b/src/Symfony/Components/Validator/Exception/InvalidOptionsException.php @@ -4,17 +4,17 @@ namespace Symfony\Components\Validator\Exception; class InvalidOptionsException extends ValidatorException { - private $options; + private $options; - public function __construct($message, array $options) - { - parent::__construct($message); + public function __construct($message, array $options) + { + parent::__construct($message); - $this->options = $options; - } + $this->options = $options; + } - public function getOptions() - { - return $this->options; - } + public function getOptions() + { + return $this->options; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Exception/MissingOptionsException.php b/src/Symfony/Components/Validator/Exception/MissingOptionsException.php index 9ba107c804..479f3033df 100644 --- a/src/Symfony/Components/Validator/Exception/MissingOptionsException.php +++ b/src/Symfony/Components/Validator/Exception/MissingOptionsException.php @@ -4,17 +4,17 @@ namespace Symfony\Components\Validator\Exception; class MissingOptionsException extends ValidatorException { - private $options; + private $options; - public function __construct($message, array $options) - { - parent::__construct($message); + public function __construct($message, array $options) + { + parent::__construct($message); - $this->options = $options; - } + $this->options = $options; + } - public function getOptions() - { - return $this->options; - } + public function getOptions() + { + return $this->options; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Exception/UnexpectedTypeException.php b/src/Symfony/Components/Validator/Exception/UnexpectedTypeException.php index 04c90e99be..44e10704ec 100644 --- a/src/Symfony/Components/Validator/Exception/UnexpectedTypeException.php +++ b/src/Symfony/Components/Validator/Exception/UnexpectedTypeException.php @@ -4,8 +4,8 @@ namespace Symfony\Components\Validator\Exception; class UnexpectedTypeException extends ValidatorException { - public function __construct($value, $expectedType) - { - parent::__construct(sprintf('Expected argument of type %s, %s given', $expectedType, gettype($value))); - } + public function __construct($value, $expectedType) + { + parent::__construct(sprintf('Expected argument of type %s, %s given', $expectedType, gettype($value))); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Extension/DependencyInjectionValidatorFactory.php b/src/Symfony/Components/Validator/Extension/DependencyInjectionValidatorFactory.php index 9b095cbdc3..795b97fd7b 100644 --- a/src/Symfony/Components/Validator/Extension/DependencyInjectionValidatorFactory.php +++ b/src/Symfony/Components/Validator/Extension/DependencyInjectionValidatorFactory.php @@ -21,55 +21,53 @@ use Symfony\Components\Validator\ConstraintValidatorInterface; class DependencyInjectionValidatorFactory implements ConstraintValidatorFactoryInterface { - protected $container; + protected $container; - /** - * @param ContainerInterface $container - */ - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - /** - * Returns a contraint validator from the container service, setting it if it - * doesn't exist yet - * - * Throws an exception if validator service is not instance of - * ConstraintValidatorInterface. - * - * @param Constraint $constraint - * @return ConstraintValidatorInterface - * @throws \LogicException - */ - public function getInstance(Constraint $constraint) - { - $className = $constraint->validatedBy(); - $id = $this->getServiceIdFromClass($className); - - if (!$this->container->hasService($id)) + /** + * @param ContainerInterface $container + */ + public function __construct(ContainerInterface $container) { - $this->container->setService($id, new $className()); + $this->container = $container; } - $validator = $this->container->getService($id); - - if (!$validator instanceof ConstraintValidatorInterface) + /** + * Returns a contraint validator from the container service, setting it if it + * doesn't exist yet + * + * Throws an exception if validator service is not instance of + * ConstraintValidatorInterface. + * + * @param Constraint $constraint + * @return ConstraintValidatorInterface + * @throws \LogicException + */ + public function getInstance(Constraint $constraint) { - throw new \LogicException('Service "' . $id . '" is not instance of ConstraintValidatorInterface'); + $className = $constraint->validatedBy(); + $id = $this->getServiceIdFromClass($className); + + if (!$this->container->hasService($id)) { + $this->container->setService($id, new $className()); + } + + $validator = $this->container->getService($id); + + if (!$validator instanceof ConstraintValidatorInterface) { + throw new \LogicException('Service "' . $id . '" is not instance of ConstraintValidatorInterface'); + } + + return $validator; } - return $validator; - } - - /** - * Returns the matching service ID for the given validator class name - * - * @param string $className - * @return string - */ - protected function getServiceIdFromClass($className) - { - return str_replace('\\', '.', $className); - } + /** + * Returns the matching service ID for the given validator class name + * + * @param string $className + * @return string + */ + protected function getServiceIdFromClass($className) + { + return str_replace('\\', '.', $className); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/GraphWalker.php b/src/Symfony/Components/Validator/GraphWalker.php index e5e78d1fca..b28557283b 100644 --- a/src/Symfony/Components/Validator/GraphWalker.php +++ b/src/Symfony/Components/Validator/GraphWalker.php @@ -14,84 +14,77 @@ use Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterfac class GraphWalker { - protected $context; - protected $validatorFactory; - protected $metadataFactory; + protected $context; + protected $validatorFactory; + protected $metadataFactory; - public function __construct($root, ClassMetadataFactoryInterface $metadataFactory, ConstraintValidatorFactoryInterface $factory, MessageInterpolatorInterface $messageInterpolator) - { - $this->context = new ValidationContext($root, $this, $metadataFactory, $messageInterpolator); - $this->validatorFactory = $factory; - $this->metadataFactory = $metadataFactory; - } - - public function getViolations() - { - return $this->context->getViolations(); - } - - public function walkClass(ClassMetadata $metadata, $object, $group, $propertyPath) - { - $this->context->setCurrentClass($metadata->getClassName()); - - foreach ($metadata->findConstraints($group) as $constraint) + public function __construct($root, ClassMetadataFactoryInterface $metadataFactory, ConstraintValidatorFactoryInterface $factory, MessageInterpolatorInterface $messageInterpolator) { - $this->walkConstraint($constraint, $object, $group, $propertyPath); + $this->context = new ValidationContext($root, $this, $metadataFactory, $messageInterpolator); + $this->validatorFactory = $factory; + $this->metadataFactory = $metadataFactory; } - if ($object !== null) + public function getViolations() { - foreach ($metadata->getConstrainedProperties() as $property) - { - $localPropertyPath = empty($propertyPath) ? $property : $propertyPath.'.'.$property; - - $this->walkProperty($metadata, $property, $object, $group, $localPropertyPath); - } + return $this->context->getViolations(); } - } - public function walkProperty(ClassMetadata $metadata, $property, $object, $group, $propertyPath) - { - foreach ($metadata->getMemberMetadatas($property) as $member) + public function walkClass(ClassMetadata $metadata, $object, $group, $propertyPath) { - $this->walkMember($member, $member->getValue($object), $group, $propertyPath); - } - } + $this->context->setCurrentClass($metadata->getClassName()); - public function walkPropertyValue(ClassMetadata $metadata, $property, $value, $group, $propertyPath) - { - foreach ($metadata->getMemberMetadatas($property) as $member) + foreach ($metadata->findConstraints($group) as $constraint) { + $this->walkConstraint($constraint, $object, $group, $propertyPath); + } + + if ($object !== null) { + foreach ($metadata->getConstrainedProperties() as $property) { + $localPropertyPath = empty($propertyPath) ? $property : $propertyPath.'.'.$property; + + $this->walkProperty($metadata, $property, $object, $group, $localPropertyPath); + } + } + } + + public function walkProperty(ClassMetadata $metadata, $property, $object, $group, $propertyPath) { - $this->walkMember($member, $value, $group, $propertyPath); + foreach ($metadata->getMemberMetadatas($property) as $member) { + $this->walkMember($member, $member->getValue($object), $group, $propertyPath); + } } - } - protected function walkMember(MemberMetadata $metadata, $value, $group, $propertyPath) - { - $this->context->setCurrentProperty($metadata->getPropertyName()); - - foreach ($metadata->findConstraints($group) as $constraint) + public function walkPropertyValue(ClassMetadata $metadata, $property, $value, $group, $propertyPath) { - $this->walkConstraint($constraint, $value, $group, $propertyPath); + foreach ($metadata->getMemberMetadatas($property) as $member) { + $this->walkMember($member, $value, $group, $propertyPath); + } } - } - public function walkConstraint(Constraint $constraint, $value, $group, $propertyPath) - { - $validator = $this->validatorFactory->getInstance($constraint); - - $this->context->setPropertyPath($propertyPath); - $this->context->setGroup($group); - - $validator->initialize($this->context); - - if (!$validator->isValid($value, $constraint)) + protected function walkMember(MemberMetadata $metadata, $value, $group, $propertyPath) { - $this->context->addViolation( - $validator->getMessageTemplate(), - $validator->getMessageParameters(), - $value - ); + $this->context->setCurrentProperty($metadata->getPropertyName()); + + foreach ($metadata->findConstraints($group) as $constraint) { + $this->walkConstraint($constraint, $value, $group, $propertyPath); + } + } + + public function walkConstraint(Constraint $constraint, $value, $group, $propertyPath) + { + $validator = $this->validatorFactory->getInstance($constraint); + + $this->context->setPropertyPath($propertyPath); + $this->context->setGroup($group); + + $validator->initialize($this->context); + + if (!$validator->isValid($value, $constraint)) { + $this->context->addViolation( + $validator->getMessageTemplate(), + $validator->getMessageParameters(), + $value + ); + } } - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/GroupChain.php b/src/Symfony/Components/Validator/GroupChain.php index be61163fc4..207377d31f 100644 --- a/src/Symfony/Components/Validator/GroupChain.php +++ b/src/Symfony/Components/Validator/GroupChain.php @@ -6,34 +6,32 @@ use Symfony\Components\Validator\Mapping\ClassMetadata; class GroupChain { - protected $groups = array(); - protected $groupSequences = array(); + protected $groups = array(); + protected $groupSequences = array(); - public function addGroup($group) - { - $this->groups[$group] = $group; - } - - public function addGroupSequence(array $groups) - { - if (count($groups) == 0) + public function addGroup($group) { - throw new \InvalidArgumentException('A group sequence must contain at least one group'); + $this->groups[$group] = $group; } - if (!in_array($groups, $this->groupSequences, true)) + public function addGroupSequence(array $groups) { - $this->groupSequences[] = $groups; + if (count($groups) == 0) { + throw new \InvalidArgumentException('A group sequence must contain at least one group'); + } + + if (!in_array($groups, $this->groupSequences, true)) { + $this->groupSequences[] = $groups; + } } - } - public function getGroups() - { - return $this->groups; - } + public function getGroups() + { + return $this->groups; + } - public function getGroupSequences() - { - return $this->groupSequences; - } + public function getGroupSequences() + { + return $this->groupSequences; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/ClassMetadata.php b/src/Symfony/Components/Validator/Mapping/ClassMetadata.php index d2554dca5e..d0dc74e2dc 100644 --- a/src/Symfony/Components/Validator/Mapping/ClassMetadata.php +++ b/src/Symfony/Components/Validator/Mapping/ClassMetadata.php @@ -7,227 +7,215 @@ use Symfony\Components\Validator\Exception\ValidatorException; class ClassMetadata extends ElementMetadata { - private $name; - private $shortName; - private $members = array(); - private $properties = array(); - private $getters = array(); - private $groupSequence = array(); - private $reflClass; + private $name; + private $shortName; + private $members = array(); + private $properties = array(); + private $getters = array(); + private $groupSequence = array(); + private $reflClass; - /** - * Constructs a metadata for the given class - * - * @param string $class - */ - public function __construct($class) - { - $this->name = $class; - $this->shortName = substr($class, strrpos($class, '\\') + 1); - } - - /** - * Returns the fully qualified name of the class - * - * @return string The fully qualified class name - */ - public function getClassName() - { - return $this->name; - } - - /** - * Returns the class name without namespace - * - * @return string The local class name in the namespace - */ - public function getShortClassName() - { - return $this->shortName; - } - - /** - * {@inheritDoc} - */ - public function addConstraint(Constraint $constraint) - { - $constraint->addImplicitGroupName($this->getShortClassName()); - - parent::addConstraint($constraint); - } - - /** - * Adds a constraint to the given property - * - * @param string $property The name of the property - * @param Constraint $constraint The constraint - * @return ClassMetadata This object - */ - public function addPropertyConstraint($property, Constraint $constraint) - { - if (!isset($this->properties[$property])) + /** + * Constructs a metadata for the given class + * + * @param string $class + */ + public function __construct($class) { - $this->properties[$property] = new PropertyMetadata($this->getClassName(), $property); - - $this->addMemberMetadata($this->properties[$property]); + $this->name = $class; + $this->shortName = substr($class, strrpos($class, '\\') + 1); } - $constraint->addImplicitGroupName($this->getShortClassName()); - - $this->properties[$property]->addConstraint($constraint); - - return $this; - } - - /** - * Adds a constraint to the getter of the given property - * - * The name of the getter is assumed to be the name of the property with an - * uppercased first letter and either the prefix "get" or "is". - * - * @param string $property The name of the property - * @param Constraint $constraint The constraint - * @return ClassMetadata This object - */ - public function addGetterConstraint($property, Constraint $constraint) - { - if (!isset($this->getters[$property])) + /** + * Returns the fully qualified name of the class + * + * @return string The fully qualified class name + */ + public function getClassName() { - $this->getters[$property] = new GetterMetadata($this->getClassName(), $property); - - $this->addMemberMetadata($this->getters[$property]); + return $this->name; } - $constraint->addImplicitGroupName($this->getShortClassName()); - - $this->getters[$property]->addConstraint($constraint); - - return $this; - } - - /** - * Merges the constraints of the given metadata into this object - * - * @param ClassMetadata $source The source metadata - */ - public function mergeConstraints(ClassMetadata $source) - { - foreach ($source->getConstraints() as $constraint) + /** + * Returns the class name without namespace + * + * @return string The local class name in the namespace + */ + public function getShortClassName() { - $this->addConstraint(clone $constraint); + return $this->shortName; } - foreach ($source->getConstrainedProperties() as $property) + /** + * {@inheritDoc} + */ + public function addConstraint(Constraint $constraint) { - foreach ($source->getMemberMetadatas($property) as $member) - { - $member = clone $member; + $constraint->addImplicitGroupName($this->getShortClassName()); - foreach ($member->getConstraints() as $constraint) - { - $constraint->addImplicitGroupName($this->getShortClassName()); + parent::addConstraint($constraint); + } + + /** + * Adds a constraint to the given property + * + * @param string $property The name of the property + * @param Constraint $constraint The constraint + * @return ClassMetadata This object + */ + public function addPropertyConstraint($property, Constraint $constraint) + { + if (!isset($this->properties[$property])) { + $this->properties[$property] = new PropertyMetadata($this->getClassName(), $property); + + $this->addMemberMetadata($this->properties[$property]); } - $this->addMemberMetadata($member); + $constraint->addImplicitGroupName($this->getShortClassName()); - if (!$member->isPrivate()) - { - $property = $member->getPropertyName(); + $this->properties[$property]->addConstraint($constraint); - if ($member instanceof PropertyMetadata && !isset($this->properties[$property])) - { - $this->properties[$property] = $member; - } - else if ($member instanceof GetterMetadata && !isset($this->getters[$property])) - { - $this->getters[$property] = $member; - } + return $this; + } + + /** + * Adds a constraint to the getter of the given property + * + * The name of the getter is assumed to be the name of the property with an + * uppercased first letter and either the prefix "get" or "is". + * + * @param string $property The name of the property + * @param Constraint $constraint The constraint + * @return ClassMetadata This object + */ + public function addGetterConstraint($property, Constraint $constraint) + { + if (!isset($this->getters[$property])) { + $this->getters[$property] = new GetterMetadata($this->getClassName(), $property); + + $this->addMemberMetadata($this->getters[$property]); } - } + + $constraint->addImplicitGroupName($this->getShortClassName()); + + $this->getters[$property]->addConstraint($constraint); + + return $this; } - } - /** - * Adds a member metadata - * - * @param MemberMetadata $metadata - */ - protected function addMemberMetadata(MemberMetadata $metadata) - { - $property = $metadata->getPropertyName(); - - if (!isset($this->members[$property])) + /** + * Merges the constraints of the given metadata into this object + * + * @param ClassMetadata $source The source metadata + */ + public function mergeConstraints(ClassMetadata $source) { - $this->members[$property] = array(); + foreach ($source->getConstraints() as $constraint) { + $this->addConstraint(clone $constraint); + } + + foreach ($source->getConstrainedProperties() as $property) { + foreach ($source->getMemberMetadatas($property) as $member) { + $member = clone $member; + + foreach ($member->getConstraints() as $constraint) { + $constraint->addImplicitGroupName($this->getShortClassName()); + } + + $this->addMemberMetadata($member); + + if (!$member->isPrivate()) { + $property = $member->getPropertyName(); + + if ($member instanceof PropertyMetadata && !isset($this->properties[$property])) { + $this->properties[$property] = $member; + } else if ($member instanceof GetterMetadata && !isset($this->getters[$property])) { + $this->getters[$property] = $member; + } + } + } + } } - $this->members[$property][] = $metadata; - } - - /** - * Returns all metadatas of members describing the given property - * - * @param string $property The name of the property - */ - public function getMemberMetadatas($property) - { - return $this->members[$property]; - } - - /** - * Returns all properties for which constraints are defined - * - * @return array An array of property names - */ - public function getConstrainedProperties() - { - return array_keys($this->members); - } - - /** - * Sets the default group sequence for this class - * - * @param array $groups An array of group names - */ - public function setGroupSequence(array $groups) - { - $this->groupSequence = $groups; - - return $this; - } - - /** - * Returns whether this class has an overridden default group sequence - * - * @return boolean - */ - public function hasGroupSequence() - { - return count($this->groupSequence) > 0; - } - - /** - * Returns the default group sequence for this class - * - * @return array An array of group names - */ - public function getGroupSequence() - { - return $this->groupSequence; - } - - /** - * Returns a ReflectionClass instance for this class - * - * @return ReflectionClass - */ - public function getReflectionClass() - { - if (!$this->reflClass) + /** + * Adds a member metadata + * + * @param MemberMetadata $metadata + */ + protected function addMemberMetadata(MemberMetadata $metadata) { - $this->reflClass = new \ReflectionClass($this->getClassName()); + $property = $metadata->getPropertyName(); + + if (!isset($this->members[$property])) { + $this->members[$property] = array(); + } + + $this->members[$property][] = $metadata; } - return $this->reflClass; - } + /** + * Returns all metadatas of members describing the given property + * + * @param string $property The name of the property + */ + public function getMemberMetadatas($property) + { + return $this->members[$property]; + } + + /** + * Returns all properties for which constraints are defined + * + * @return array An array of property names + */ + public function getConstrainedProperties() + { + return array_keys($this->members); + } + + /** + * Sets the default group sequence for this class + * + * @param array $groups An array of group names + */ + public function setGroupSequence(array $groups) + { + $this->groupSequence = $groups; + + return $this; + } + + /** + * Returns whether this class has an overridden default group sequence + * + * @return boolean + */ + public function hasGroupSequence() + { + return count($this->groupSequence) > 0; + } + + /** + * Returns the default group sequence for this class + * + * @return array An array of group names + */ + public function getGroupSequence() + { + return $this->groupSequence; + } + + /** + * Returns a ReflectionClass instance for this class + * + * @return ReflectionClass + */ + public function getReflectionClass() + { + if (!$this->reflClass) { + $this->reflClass = new \ReflectionClass($this->getClassName()); + } + + return $this->reflClass; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/ClassMetadataFactory.php b/src/Symfony/Components/Validator/Mapping/ClassMetadataFactory.php index dce68ec90f..964ae6e009 100644 --- a/src/Symfony/Components/Validator/Mapping/ClassMetadataFactory.php +++ b/src/Symfony/Components/Validator/Mapping/ClassMetadataFactory.php @@ -6,40 +6,37 @@ use Symfony\Components\Validator\Mapping\Loader\LoaderInterface; class ClassMetadataFactory implements ClassMetadataFactoryInterface { - protected $loader; + protected $loader; - protected $loadedClasses = array(); + protected $loadedClasses = array(); - public function __construct(LoaderInterface $loader) - { - $this->loader = $loader; - } - - public function getClassMetadata($class) - { - $class = ltrim($class, '\\'); - - if (!isset($this->loadedClasses[$class])) + public function __construct(LoaderInterface $loader) { - $metadata = new ClassMetadata($class); - - // Include constraints from the parent class - if ($parent = $metadata->getReflectionClass()->getParentClass()) - { - $metadata->mergeConstraints($this->getClassMetadata($parent->getName())); - } - - // Include constraints from all implemented interfaces - foreach ($metadata->getReflectionClass()->getInterfaces() as $interface) - { - $metadata->mergeConstraints($this->getClassMetadata($interface->getName())); - } - - $this->loader->loadClassMetadata($metadata); - - $this->loadedClasses[$class] = $metadata; + $this->loader = $loader; } - return $this->loadedClasses[$class]; - } + public function getClassMetadata($class) + { + $class = ltrim($class, '\\'); + + if (!isset($this->loadedClasses[$class])) { + $metadata = new ClassMetadata($class); + + // Include constraints from the parent class + if ($parent = $metadata->getReflectionClass()->getParentClass()) { + $metadata->mergeConstraints($this->getClassMetadata($parent->getName())); + } + + // Include constraints from all implemented interfaces + foreach ($metadata->getReflectionClass()->getInterfaces() as $interface) { + $metadata->mergeConstraints($this->getClassMetadata($interface->getName())); + } + + $this->loader->loadClassMetadata($metadata); + + $this->loadedClasses[$class] = $metadata; + } + + return $this->loadedClasses[$class]; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/ClassMetadataFactoryInterface.php b/src/Symfony/Components/Validator/Mapping/ClassMetadataFactoryInterface.php index 8ed5934e32..df59477702 100644 --- a/src/Symfony/Components/Validator/Mapping/ClassMetadataFactoryInterface.php +++ b/src/Symfony/Components/Validator/Mapping/ClassMetadataFactoryInterface.php @@ -4,5 +4,5 @@ namespace Symfony\Components\Validator\Mapping; interface ClassMetadataFactoryInterface { - function getClassMetadata($class); + function getClassMetadata($class); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/ElementMetadata.php b/src/Symfony/Components/Validator/Mapping/ElementMetadata.php index f38550073e..34892f5e3a 100644 --- a/src/Symfony/Components/Validator/Mapping/ElementMetadata.php +++ b/src/Symfony/Components/Validator/Mapping/ElementMetadata.php @@ -7,78 +7,75 @@ use Symfony\Components\Validator\Constraint; class ElementMetadata { - private $constraints = array(); - private $constraintsByGroup = array(); + private $constraints = array(); + private $constraintsByGroup = array(); - /** - * Clones this object - */ - public function __clone() - { - $constraints = $this->constraints; - - $this->constraints = array(); - $this->constraintsByGroup = array(); - - foreach ($constraints as $constraint) + /** + * Clones this object + */ + public function __clone() { - $this->addConstraint(clone $constraint); - } - } + $constraints = $this->constraints; - /** - * Adds a constraint to this element - * - * @param Constraint $constraint - */ - public function addConstraint(Constraint $constraint) - { - $this->constraints[] = $constraint; + $this->constraints = array(); + $this->constraintsByGroup = array(); - foreach ($constraint->groups as $group) - { - if (!isset($this->constraintsByGroup[$group])) - { - $this->constraintsByGroup[$group] = array(); - } - - $this->constraintsByGroup[$group][] = $constraint; + foreach ($constraints as $constraint) { + $this->addConstraint(clone $constraint); + } } - return $this; - } + /** + * Adds a constraint to this element + * + * @param Constraint $constraint + */ + public function addConstraint(Constraint $constraint) + { + $this->constraints[] = $constraint; - /** - * Returns all constraints of this element - * - * @return array An array of Constraint instances - */ - public function getConstraints() - { - return $this->constraints; - } + foreach ($constraint->groups as $group) { + if (!isset($this->constraintsByGroup[$group])) { + $this->constraintsByGroup[$group] = array(); + } - /** - * Returns whether this element has any constraints - * - * @return boolean - */ - public function hasConstraints() - { - return count($this->constraints) > 0; - } + $this->constraintsByGroup[$group][] = $constraint; + } - /** - * Returns the constraints of the given group - * - * @param string $group The group name - * @return array An array with all Constraint instances belonging to - * the group - */ - public function findConstraints($group) - { - return isset($this->constraintsByGroup[$group]) - ? $this->constraintsByGroup[$group] - : array(); - } + return $this; + } + + /** + * Returns all constraints of this element + * + * @return array An array of Constraint instances + */ + public function getConstraints() + { + return $this->constraints; + } + + /** + * Returns whether this element has any constraints + * + * @return boolean + */ + public function hasConstraints() + { + return count($this->constraints) > 0; + } + + /** + * Returns the constraints of the given group + * + * @param string $group The group name + * @return array An array with all Constraint instances belonging to + * the group + */ + public function findConstraints($group) + { + return isset($this->constraintsByGroup[$group]) + ? $this->constraintsByGroup[$group] + : array(); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/GetterMetadata.php b/src/Symfony/Components/Validator/Mapping/GetterMetadata.php index ec11449358..8e6c95a77c 100644 --- a/src/Symfony/Components/Validator/Mapping/GetterMetadata.php +++ b/src/Symfony/Components/Validator/Mapping/GetterMetadata.php @@ -6,46 +6,41 @@ use Symfony\Components\Validator\Exception\ValidatorException; class GetterMetadata extends MemberMetadata { - /** - * Constructor. - * - * @param string $class The class the getter is defined on - * @param string $property The property which the getter returns - */ - public function __construct($class, $property) - { - $getMethod = 'get'.ucfirst($property); - $isMethod = 'is'.ucfirst($property); + /** + * Constructor. + * + * @param string $class The class the getter is defined on + * @param string $property The property which the getter returns + */ + public function __construct($class, $property) + { + $getMethod = 'get'.ucfirst($property); + $isMethod = 'is'.ucfirst($property); - if (method_exists($class, $getMethod)) - { - $method = $getMethod; - } - else if (method_exists($class, $isMethod)) - { - $method = $isMethod; - } - else - { - throw new ValidatorException(sprintf('Neither method %s nor %s exists in class %s', $getMethod, $isMethod, $class)); + if (method_exists($class, $getMethod)) { + $method = $getMethod; + } else if (method_exists($class, $isMethod)) { + $method = $isMethod; + } else { + throw new ValidatorException(sprintf('Neither method %s nor %s exists in class %s', $getMethod, $isMethod, $class)); + } + + parent::__construct($class, $method, $property); } - parent::__construct($class, $method, $property); - } + /** + * {@inheritDoc} + */ + public function getValue($object) + { + return $this->getReflectionMember()->invoke($object); + } - /** - * {@inheritDoc} - */ - public function getValue($object) - { - return $this->getReflectionMember()->invoke($object); - } - - /** - * {@inheritDoc} - */ - protected function newReflectionMember() - { - return new \ReflectionMethod($this->getClassName(), $this->getName()); - } + /** + * {@inheritDoc} + */ + protected function newReflectionMember() + { + return new \ReflectionMethod($this->getClassName(), $this->getName()); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/AnnotationLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/AnnotationLoader.php index d0eb7b8d89..93a0299517 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/AnnotationLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/AnnotationLoader.php @@ -8,63 +8,55 @@ use Doctrine\Common\Annotations\AnnotationReader; class AnnotationLoader implements LoaderInterface { - protected $reader; + protected $reader; - public function __construct() - { - $this->reader = new AnnotationReader(); - $this->reader->setDefaultAnnotationNamespace('Symfony\Components\Validator\Constraints\\'); - $this->reader->setAutoloadAnnotations(true); - } - - /** - * {@inheritDoc} - */ - public function loadClassMetadata(ClassMetadata $metadata) - { - $annotClass = 'Symfony\Components\Validator\Constraints\Validation'; - $reflClass = $metadata->getReflectionClass(); - $loaded = false; - - if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) + public function __construct() { - foreach ($annot->constraints as $constraint) - { - $metadata->addConstraint($constraint); - } - - $loaded = true; + $this->reader = new AnnotationReader(); + $this->reader->setDefaultAnnotationNamespace('Symfony\Components\Validator\Constraints\\'); + $this->reader->setAutoloadAnnotations(true); } - foreach ($reflClass->getProperties() as $property) + /** + * {@inheritDoc} + */ + public function loadClassMetadata(ClassMetadata $metadata) { - if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) - { - foreach ($annot->constraints as $constraint) - { - $metadata->addPropertyConstraint($property->getName(), $constraint); + $annotClass = 'Symfony\Components\Validator\Constraints\Validation'; + $reflClass = $metadata->getReflectionClass(); + $loaded = false; + + if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) { + foreach ($annot->constraints as $constraint) { + $metadata->addConstraint($constraint); + } + + $loaded = true; } - $loaded = true; - } - } + foreach ($reflClass->getProperties() as $property) { + if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) { + foreach ($annot->constraints as $constraint) { + $metadata->addPropertyConstraint($property->getName(), $constraint); + } - foreach ($reflClass->getMethods() as $method) - { - if ($annot = $this->reader->getMethodAnnotation($method, $annotClass)) - { - foreach ($annot->constraints as $constraint) - { - // TODO: clean this up - $name = lcfirst(substr($method->getName(), 0, 3)=='get' ? substr($method->getName(), 3) : substr($method->getName(), 2)); - - $metadata->addGetterConstraint($name, $constraint); + $loaded = true; + } } - $loaded = true; - } - } + foreach ($reflClass->getMethods() as $method) { + if ($annot = $this->reader->getMethodAnnotation($method, $annotClass)) { + foreach ($annot->constraints as $constraint) { + // TODO: clean this up + $name = lcfirst(substr($method->getName(), 0, 3)=='get' ? substr($method->getName(), 3) : substr($method->getName(), 2)); - return $loaded; - } + $metadata->addGetterConstraint($name, $constraint); + } + + $loaded = true; + } + } + + return $loaded; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/FileLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/FileLoader.php index 7e8278f01d..4403abe04a 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/FileLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/FileLoader.php @@ -8,20 +8,18 @@ use Symfony\Components\Validator\Mapping\GroupMetadata; abstract class FileLoader implements LoaderInterface { - protected $file; + protected $file; - public function __construct($file) - { - if (!file_exists($file)) + public function __construct($file) { - throw new MappingException(sprintf('The mapping file %s does not exist', $file)); - } + if (!file_exists($file)) { + throw new MappingException(sprintf('The mapping file %s does not exist', $file)); + } - if (!is_readable($file)) - { - throw new MappingException(sprintf('The mapping file %s is not readable', $file)); - } + if (!is_readable($file)) { + throw new MappingException(sprintf('The mapping file %s is not readable', $file)); + } - $this->file = $file; - } + $this->file = $file; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/FilesLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/FilesLoader.php index 7a6b865a2c..ba9764a3ee 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/FilesLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/FilesLoader.php @@ -13,33 +13,33 @@ namespace Symfony\Components\Validator\Mapping\Loader; */ abstract class FilesLoader extends LoaderChain { - /** - * Array of mapping files - * @param array $paths - */ - public function __construct(array $paths) - { - parent::__construct($this->getFileLoaders($paths)); - } - - /** - * Array of mapping files - * @param array $paths - * @return array - array of metadata loaders - */ - protected function getFileLoaders($paths) - { - $loaders = array(); - foreach ($paths as $path) { - $loaders[] = $this->getFileLoaderInstance($path); + /** + * Array of mapping files + * @param array $paths + */ + public function __construct(array $paths) + { + parent::__construct($this->getFileLoaders($paths)); } - return $loaders; - } - /** - * Takes mapping file path - * @param string $file - * @return Symfony\Components\Validator\Mapping\Loader\LoaderInterface - */ - abstract protected function getFileLoaderInstance($file); + /** + * Array of mapping files + * @param array $paths + * @return array - array of metadata loaders + */ + protected function getFileLoaders($paths) + { + $loaders = array(); + foreach ($paths as $path) { + $loaders[] = $this->getFileLoaderInstance($path); + } + return $loaders; + } + + /** + * Takes mapping file path + * @param string $file + * @return Symfony\Components\Validator\Mapping\Loader\LoaderInterface + */ + abstract protected function getFileLoaderInstance($file); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/LoaderChain.php b/src/Symfony/Components/Validator/Mapping/Loader/LoaderChain.php index 5c14f01926..b6c2628fc9 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/LoaderChain.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/LoaderChain.php @@ -17,40 +17,37 @@ use Symfony\Components\Validator\Mapping\ClassMetadata; */ class LoaderChain implements LoaderInterface { - protected $loaders; + protected $loaders; - /** - * Acccepts a list of LoaderInterface instances - * - * @param array $loaders An array of LoaderInterface instances - * @throws MappingException If any of the loaders does not implement - * LoaderInterface - */ - public function __construct(array $loaders) - { - foreach ($loaders as $loader) + /** + * Acccepts a list of LoaderInterface instances + * + * @param array $loaders An array of LoaderInterface instances + * @throws MappingException If any of the loaders does not implement + * LoaderInterface + */ + public function __construct(array $loaders) { - if (!$loader instanceof LoaderInterface) - { - throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader))); - } + foreach ($loaders as $loader) { + if (!$loader instanceof LoaderInterface) { + throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader))); + } + } + + $this->loaders = $loaders; } - $this->loaders = $loaders; - } - - /** - * {@inheritDoc} - */ - public function loadClassMetadata(ClassMetadata $metadata) - { - $success = false; - - foreach ($this->loaders as $loader) + /** + * {@inheritDoc} + */ + public function loadClassMetadata(ClassMetadata $metadata) { - $success = $loader->loadClassMetadata($metadata) || $success; - } + $success = false; - return $success; - } + foreach ($this->loaders as $loader) { + $success = $loader->loadClassMetadata($metadata) || $success; + } + + return $success; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/LoaderInterface.php b/src/Symfony/Components/Validator/Mapping/Loader/LoaderInterface.php index f28a03b4b5..6ef2f7666e 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/LoaderInterface.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/LoaderInterface.php @@ -6,9 +6,9 @@ use Symfony\Components\Validator\Mapping\ClassMetadata; interface LoaderInterface { - /** - * @param ClassMetadata $metadata - * @return boolean - */ - function loadClassMetadata(ClassMetadata $metadata); + /** + * @param ClassMetadata $metadata + * @return boolean + */ + function loadClassMetadata(ClassMetadata $metadata); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/StaticMethodLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/StaticMethodLoader.php index 78773f3c46..009445d8ef 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/StaticMethodLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/StaticMethodLoader.php @@ -7,34 +7,32 @@ use Symfony\Components\Validator\Mapping\ClassMetadata; class StaticMethodLoader implements LoaderInterface { - protected $methodName; + protected $methodName; - public function __construct($methodName) - { - $this->methodName = $methodName; - } - - /** - * {@inheritDoc} - */ - public function loadClassMetadata(ClassMetadata $metadata) - { - $reflClass = $metadata->getReflectionClass(); - - if ($reflClass->hasMethod($this->methodName)) + public function __construct($methodName) { - $reflMethod = $reflClass->getMethod($this->methodName); - - if (!$reflMethod->isStatic()) - { - throw new MappingException(sprintf('The method %s::%s should be static', $reflClass->getName(), $this->methodName)); - } - - $reflMethod->invoke(null, $metadata); - - return true; + $this->methodName = $methodName; } - return false; - } + /** + * {@inheritDoc} + */ + public function loadClassMetadata(ClassMetadata $metadata) + { + $reflClass = $metadata->getReflectionClass(); + + if ($reflClass->hasMethod($this->methodName)) { + $reflMethod = $reflClass->getMethod($this->methodName); + + if (!$reflMethod->isStatic()) { + throw new MappingException(sprintf('The method %s::%s should be static', $reflClass->getName(), $this->methodName)); + } + + $reflMethod->invoke(null, $metadata); + + return true; + } + + return false; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/XmlFileLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/XmlFileLoader.php index d533381578..7a41029421 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/XmlFileLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/XmlFileLoader.php @@ -7,231 +7,186 @@ use Symfony\Components\Validator\Mapping\ClassMetadata; class XmlFileLoader extends FileLoader { - /** - * An array of SimpleXMLElement instances - * @val array - */ - protected $classes = null; + /** + * An array of SimpleXMLElement instances + * @val array + */ + protected $classes = null; - /** - * {@inheritDoc} - */ - public function loadClassMetadata(ClassMetadata $metadata) - { - if (is_null($this->classes)) + /** + * {@inheritDoc} + */ + public function loadClassMetadata(ClassMetadata $metadata) { - $this->classes = array(); - $xml = $this->parseFile($this->file); + if (is_null($this->classes)) { + $this->classes = array(); + $xml = $this->parseFile($this->file); - foreach ($xml->class as $class) - { - $this->classes[(string)$class['name']] = $class; - } + foreach ($xml->class as $class) { + $this->classes[(string)$class['name']] = $class; + } + } + + if (isset($this->classes[$metadata->getClassName()])) { + $xml = $this->classes[$metadata->getClassName()]; + + foreach ($this->parseConstraints($xml->constraint) as $constraint) { + $metadata->addConstraint($constraint); + } + + foreach ($xml->property as $property) { + foreach ($this->parseConstraints($property->constraint) as $constraint) { + $metadata->addPropertyConstraint((string)$property['name'], $constraint); + } + } + + foreach ($xml->getter as $getter) { + foreach ($this->parseConstraints($getter->constraint) as $constraint) { + $metadata->addGetterConstraint((string)$getter['property'], $constraint); + } + } + + return true; + } + + return false; } - if (isset($this->classes[$metadata->getClassName()])) + /** + * Parses a collection of "constraint" XML nodes + * + * @param SimpleXMLElement $nodes The XML nodes + * @return array The Constraint instances + */ + protected function parseConstraints(\SimpleXMLElement $nodes) { - $xml = $this->classes[$metadata->getClassName()]; + $constraints = array(); - foreach ($this->parseConstraints($xml->constraint) as $constraint) - { - $metadata->addConstraint($constraint); - } + foreach ($nodes as $node) { + $className = 'Symfony\\Components\\Validator\\Constraints\\'.$node['name']; - foreach ($xml->property as $property) - { - foreach ($this->parseConstraints($property->constraint) as $constraint) - { - $metadata->addPropertyConstraint((string)$property['name'], $constraint); + if (count($node) > 0) { + if (count($node->value) > 0) { + $options = $this->parseValues($node->value); + } else if (count($node->constraint) > 0) { + $options = $this->parseConstraints($node->constraint); + } else if (count($node->option) > 0) { + $options = $this->parseOptions($node->option); + } else { + $options = array(); + } + } else if (strlen((string)$node) > 0) { + $options = trim($node); + } else { + $options = null; + } + + $constraints[] = new $className($options); } - } - foreach ($xml->getter as $getter) - { - foreach ($this->parseConstraints($getter->constraint) as $constraint) - { - $metadata->addGetterConstraint((string)$getter['property'], $constraint); - } - } - - return true; + return $constraints; } - return false; - } - - /** - * Parses a collection of "constraint" XML nodes - * - * @param SimpleXMLElement $nodes The XML nodes - * @return array The Constraint instances - */ - protected function parseConstraints(\SimpleXMLElement $nodes) - { - $constraints = array(); - - foreach ($nodes as $node) + /** + * Parses a collection of "value" XML nodes + * + * @param SimpleXMLElement $nodes The XML nodes + * @return array The values + */ + protected function parseValues(\SimpleXMLElement $nodes) { - $className = 'Symfony\\Components\\Validator\\Constraints\\'.$node['name']; + $values = array(); - if (count($node) > 0) - { - if (count($node->value) > 0) - { - $options = $this->parseValues($node->value); - } - else if (count($node->constraint) > 0) - { - $options = $this->parseConstraints($node->constraint); - } - else if (count($node->option) > 0) - { - $options = $this->parseOptions($node->option); - } - else - { - $options = array(); - } - } - else if (strlen((string)$node) > 0) - { - $options = trim($node); - } - else - { - $options = null; - } + foreach ($nodes as $node) { + if (count($node) > 0) { + if (count($node->value) > 0) { + $value = $this->parseValues($node->value); + } else if (count($node->constraint) > 0) { + $value = $this->parseConstraints($node->constraint); + } else { + $value = array(); + } + } else { + $value = trim($node); + } - $constraints[] = new $className($options); + if (isset($node['key'])) { + $values[(string)$node['key']] = $value; + } else { + $values[] = $value; + } + } + + return $values; } - return $constraints; - } - - /** - * Parses a collection of "value" XML nodes - * - * @param SimpleXMLElement $nodes The XML nodes - * @return array The values - */ - protected function parseValues(\SimpleXMLElement $nodes) - { - $values = array(); - - foreach ($nodes as $node) + /** + * Parses a collection of "option" XML nodes + * + * @param SimpleXMLElement $nodes The XML nodes + * @return array The options + */ + protected function parseOptions(\SimpleXMLElement $nodes) { - if (count($node) > 0) - { - if (count($node->value) > 0) - { - $value = $this->parseValues($node->value); - } - else if (count($node->constraint) > 0) - { - $value = $this->parseConstraints($node->constraint); - } - else - { - $value = array(); - } - } - else - { - $value = trim($node); - } + $options = array(); - if (isset($node['key'])) - { - $values[(string)$node['key']] = $value; - } - else - { - $values[] = $value; - } + foreach ($nodes as $node) { + if (count($node) > 0) { + if (count($node->value) > 0) { + $value = $this->parseValues($node->value); + } else if (count($node->constraint) > 0) { + $value = $this->parseConstraints($node->constraint); + } else { + $value = array(); + } + } else { + $value = trim($node); + } + + $options[(string)$node['name']] = $value; + } + + return $options; } - return $values; - } - - /** - * Parses a collection of "option" XML nodes - * - * @param SimpleXMLElement $nodes The XML nodes - * @return array The options - */ - protected function parseOptions(\SimpleXMLElement $nodes) - { - $options = array(); - - foreach ($nodes as $node) + /** + * @param string $file + * @return SimpleXMLElement + */ + protected function parseFile($file) { - if (count($node) > 0) - { - if (count($node->value) > 0) - { - $value = $this->parseValues($node->value); + $dom = new \DOMDocument(); + libxml_use_internal_errors(true); + if (!$dom->load($file, LIBXML_COMPACT)) { + throw new MappingException(implode("\n", $this->getXmlErrors())); } - else if (count($node->constraint) > 0) - { - $value = $this->parseConstraints($node->constraint); + if (!$dom->schemaValidate(__DIR__.'/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd')) { + throw new MappingException(implode("\n", $this->getXmlErrors())); } - else - { - $value = array(); + $dom->validateOnParse = true; + $dom->normalizeDocument(); + libxml_use_internal_errors(false); + + return simplexml_import_dom($dom); + } + + protected function getXmlErrors() + { + $errors = array(); + foreach (libxml_get_errors() as $error) { + $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', + LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', + $error->code, + trim($error->message), + $error->file ? $error->file : 'n/a', + $error->line, + $error->column + ); } - } - else - { - $value = trim($node); - } - $options[(string)$node['name']] = $value; + libxml_clear_errors(); + libxml_use_internal_errors(false); + + return $errors; } - - return $options; - } - - /** - * @param string $file - * @return SimpleXMLElement - */ - protected function parseFile($file) - { - $dom = new \DOMDocument(); - libxml_use_internal_errors(true); - if (!$dom->load($file, LIBXML_COMPACT)) - { - throw new MappingException(implode("\n", $this->getXmlErrors())); - } - if (!$dom->schemaValidate(__DIR__.'/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd')) - { - throw new MappingException(implode("\n", $this->getXmlErrors())); - } - $dom->validateOnParse = true; - $dom->normalizeDocument(); - libxml_use_internal_errors(false); - - return simplexml_import_dom($dom); - } - - protected function getXmlErrors() - { - $errors = array(); - foreach (libxml_get_errors() as $error) - { - $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', - LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', - $error->code, - trim($error->message), - $error->file ? $error->file : 'n/a', - $error->line, - $error->column - ); - } - - libxml_clear_errors(); - libxml_use_internal_errors(false); - - return $errors; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/XmlFilesLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/XmlFilesLoader.php index c641635558..6d8f59d2bf 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/XmlFilesLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/XmlFilesLoader.php @@ -9,11 +9,11 @@ namespace Symfony\Components\Validator\Mapping\Loader; */ class XmlFilesLoader extends FilesLoader { - /** - * {@inheritDoc} - */ - public function getFileLoaderInstance($file) - { - return new XmlFileLoader($file); - } + /** + * {@inheritDoc} + */ + public function getFileLoaderInstance($file) + { + return new XmlFileLoader($file); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/YamlFileLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/YamlFileLoader.php index 16cdf95545..dd632b963d 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/YamlFileLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/YamlFileLoader.php @@ -8,99 +8,83 @@ use Symfony\Components\Yaml\Yaml; class YamlFileLoader extends FileLoader { - /** - * An array of YAML class descriptions - * @val array - */ - protected $classes = null; + /** + * An array of YAML class descriptions + * @val array + */ + protected $classes = null; - /** - * {@inheritDoc} - */ - public function loadClassMetadata(ClassMetadata $metadata) - { - if (is_null($this->classes)) + /** + * {@inheritDoc} + */ + public function loadClassMetadata(ClassMetadata $metadata) { - $this->classes = Yaml::load($this->file); + if (is_null($this->classes)) { + $this->classes = Yaml::load($this->file); + } + + // TODO validation + + if (isset($this->classes[$metadata->getClassName()])) { + $yaml = $this->classes[$metadata->getClassName()]; + + if (isset($yaml['constraints'])) { + foreach ($this->parseNodes($yaml['constraints']) as $constraint) { + $metadata->addConstraint($constraint); + } + } + + if (isset($yaml['properties'])) { + foreach ($yaml['properties'] as $property => $constraints) { + foreach ($this->parseNodes($constraints) as $constraint) { + $metadata->addPropertyConstraint($property, $constraint); + } + } + } + + if (isset($yaml['getters'])) { + foreach ($yaml['getters'] as $getter => $constraints) { + foreach ($this->parseNodes($constraints) as $constraint) { + $metadata->addGetterConstraint($getter, $constraint); + } + } + } + + return true; + } + + return false; } - // TODO validation - - if (isset($this->classes[$metadata->getClassName()])) + /** + * Parses a collection of YAML nodes + * + * @param array $nodes The YAML nodes + * @return array An array of values or Constraint instances + */ + protected function parseNodes(array $nodes) { - $yaml = $this->classes[$metadata->getClassName()]; + $values = array(); - if (isset($yaml['constraints'])) - { - foreach ($this->parseNodes($yaml['constraints']) as $constraint) - { - $metadata->addConstraint($constraint); + foreach ($nodes as $name => $childNodes) { + if (is_numeric($name) && is_array($childNodes) && count($childNodes) == 1) { + $className = 'Symfony\\Components\\Validator\\Constraints\\'.key($childNodes); + $options = current($childNodes); + + if (is_array($options)) { + $options = $this->parseNodes($options); + } + + $values[] = new $className($options); + } else { + if (is_array($childNodes)) { + $childNodes = $this->parseNodes($childNodes); + } + + $values[$name] = $childNodes; + } } - } - if (isset($yaml['properties'])) - { - foreach ($yaml['properties'] as $property => $constraints) - { - foreach ($this->parseNodes($constraints) as $constraint) - { - $metadata->addPropertyConstraint($property, $constraint); - } - } - } - - if (isset($yaml['getters'])) - { - foreach ($yaml['getters'] as $getter => $constraints) - { - foreach ($this->parseNodes($constraints) as $constraint) - { - $metadata->addGetterConstraint($getter, $constraint); - } - } - } - - return true; + return $values; } - - return false; - } - - /** - * Parses a collection of YAML nodes - * - * @param array $nodes The YAML nodes - * @return array An array of values or Constraint instances - */ - protected function parseNodes(array $nodes) - { - $values = array(); - - foreach ($nodes as $name => $childNodes) - { - if (is_numeric($name) && is_array($childNodes) && count($childNodes) == 1) - { - $className = 'Symfony\\Components\\Validator\\Constraints\\'.key($childNodes); - $options = current($childNodes); - - if (is_array($options)) - { - $options = $this->parseNodes($options); - } - - $values[] = new $className($options); - } - else - { - if (is_array($childNodes)) - { - $childNodes = $this->parseNodes($childNodes); - } - - $values[$name] = $childNodes; - } - } - - return $values; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/Loader/YamlFilesLoader.php b/src/Symfony/Components/Validator/Mapping/Loader/YamlFilesLoader.php index 2571fea773..e45177fe41 100644 --- a/src/Symfony/Components/Validator/Mapping/Loader/YamlFilesLoader.php +++ b/src/Symfony/Components/Validator/Mapping/Loader/YamlFilesLoader.php @@ -9,11 +9,11 @@ namespace Symfony\Components\Validator\Mapping\Loader; */ class YamlFilesLoader extends FilesLoader { - /** - * {@inheritDoc} - */ - public function getFileLoaderInstance($file) - { - return new YamlFileLoader($file); - } + /** + * {@inheritDoc} + */ + public function getFileLoaderInstance($file) + { + return new YamlFileLoader($file); + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/MemberMetadata.php b/src/Symfony/Components/Validator/Mapping/MemberMetadata.php index fe88308850..472469b3ce 100644 --- a/src/Symfony/Components/Validator/Mapping/MemberMetadata.php +++ b/src/Symfony/Components/Validator/Mapping/MemberMetadata.php @@ -6,112 +6,111 @@ use Symfony\Components\Validator\Exception\ValidatorException; abstract class MemberMetadata extends ElementMetadata { - private $class; - private $name; - private $property; - private $reflMember; + private $class; + private $name; + private $property; + private $reflMember; - /** - * Constructor. - * - * @param string $class The name of the class this member is defined on - * @param string $name The name of the member - * @param string $property The property the member belongs to - */ - public function __construct($class, $name, $property) - { - $this->class = $class; - $this->name = $name; - $this->property = $property; - } - - /** - * Returns the name of the member - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Returns the class this member is defined on - * - * @return string - */ - public function getClassName() - { - return $this->class; - } - - /** - * Returns the name of the property this member belongs to - * - * @return string The property name - */ - public function getPropertyName() - { - return $this->property; - } - - /** - * Returns whether this member is public - * - * @return boolean - */ - public function isPublic() - { - return $this->getReflectionMember()->isPublic(); - } - - /** - * Returns whether this member is protected - * - * @return boolean - */ - public function isProtected() - { - return $this->getReflectionMember()->isProtected(); - } - - /** - * Returns whether this member is private - * - * @return boolean - */ - public function isPrivate() - { - return $this->getReflectionMember()->isPrivate(); - } - - /** - * Returns the value of this property in the given object - * - * @param object $object The object - * @return mixed The property value - */ - abstract public function getValue($object); - - /** - * Returns the Reflection instance of the member - * - * @return object - */ - public function getReflectionMember() - { - if (!$this->reflMember) + /** + * Constructor. + * + * @param string $class The name of the class this member is defined on + * @param string $name The name of the member + * @param string $property The property the member belongs to + */ + public function __construct($class, $name, $property) { - $this->reflMember = $this->newReflectionMember(); + $this->class = $class; + $this->name = $name; + $this->property = $property; } - return $this->reflMember; - } + /** + * Returns the name of the member + * + * @return string + */ + public function getName() + { + return $this->name; + } - /** - * Creates a new Reflection instance for the member - * - * @return object - */ - abstract protected function newReflectionMember(); + /** + * Returns the class this member is defined on + * + * @return string + */ + public function getClassName() + { + return $this->class; + } + + /** + * Returns the name of the property this member belongs to + * + * @return string The property name + */ + public function getPropertyName() + { + return $this->property; + } + + /** + * Returns whether this member is public + * + * @return boolean + */ + public function isPublic() + { + return $this->getReflectionMember()->isPublic(); + } + + /** + * Returns whether this member is protected + * + * @return boolean + */ + public function isProtected() + { + return $this->getReflectionMember()->isProtected(); + } + + /** + * Returns whether this member is private + * + * @return boolean + */ + public function isPrivate() + { + return $this->getReflectionMember()->isPrivate(); + } + + /** + * Returns the value of this property in the given object + * + * @param object $object The object + * @return mixed The property value + */ + abstract public function getValue($object); + + /** + * Returns the Reflection instance of the member + * + * @return object + */ + public function getReflectionMember() + { + if (!$this->reflMember) { + $this->reflMember = $this->newReflectionMember(); + } + + return $this->reflMember; + } + + /** + * Creates a new Reflection instance for the member + * + * @return object + */ + abstract protected function newReflectionMember(); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Mapping/PropertyMetadata.php b/src/Symfony/Components/Validator/Mapping/PropertyMetadata.php index e3bd83f43a..a83afc94d5 100644 --- a/src/Symfony/Components/Validator/Mapping/PropertyMetadata.php +++ b/src/Symfony/Components/Validator/Mapping/PropertyMetadata.php @@ -6,38 +6,37 @@ use Symfony\Components\Validator\Exception\ValidatorException; class PropertyMetadata extends MemberMetadata { - /** - * Constructor. - * - * @param string $class The class this property is defined on - * @param string $name The name of this property - */ - public function __construct($class, $name) - { - if (!property_exists($class, $name)) + /** + * Constructor. + * + * @param string $class The class this property is defined on + * @param string $name The name of this property + */ + public function __construct($class, $name) { - throw new ValidatorException(sprintf('Property %s does not exists in class %s', $name, $class)); + if (!property_exists($class, $name)) { + throw new ValidatorException(sprintf('Property %s does not exists in class %s', $name, $class)); + } + + parent::__construct($class, $name, $name); } - parent::__construct($class, $name, $name); - } + /** + * {@inheritDoc} + */ + public function getValue($object) + { + return $this->getReflectionMember()->getValue($object); + } - /** - * {@inheritDoc} - */ - public function getValue($object) - { - return $this->getReflectionMember()->getValue($object); - } + /** + * {@inheritDoc} + */ + protected function newReflectionMember() + { + $member = new \ReflectionProperty($this->getClassName(), $this->getName()); + $member->setAccessible(true); - /** - * {@inheritDoc} - */ - protected function newReflectionMember() - { - $member = new \ReflectionProperty($this->getClassName(), $this->getName()); - $member->setAccessible(true); - - return $member; - } + return $member; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/MessageInterpolator/MessageInterpolatorInterface.php b/src/Symfony/Components/Validator/MessageInterpolator/MessageInterpolatorInterface.php index 94025a563e..c19d947574 100644 --- a/src/Symfony/Components/Validator/MessageInterpolator/MessageInterpolatorInterface.php +++ b/src/Symfony/Components/Validator/MessageInterpolator/MessageInterpolatorInterface.php @@ -4,12 +4,12 @@ namespace Symfony\Components\Validator\MessageInterpolator; interface MessageInterpolatorInterface { - /** - * Interpolates a text and inserts the given parameters - * - * @param string $text The text to interpolate - * @param array $parameters The parameters to insert into the text - * @return string The interpolated text - */ - function interpolate($text, array $parameters = array()); + /** + * Interpolates a text and inserts the given parameters + * + * @param string $text The text to interpolate + * @param array $parameters The parameters to insert into the text + * @return string The interpolated text + */ + function interpolate($text, array $parameters = array()); } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/MessageInterpolator/XliffMessageInterpolator.php b/src/Symfony/Components/Validator/MessageInterpolator/XliffMessageInterpolator.php index e01f8ecfd1..716a507376 100644 --- a/src/Symfony/Components/Validator/MessageInterpolator/XliffMessageInterpolator.php +++ b/src/Symfony/Components/Validator/MessageInterpolator/XliffMessageInterpolator.php @@ -4,99 +4,92 @@ namespace Symfony\Components\Validator\MessageInterpolator; class XliffMessageInterpolator implements MessageInterpolatorInterface { - protected $translations = array(); + protected $translations = array(); - /** - * Constructs an interpolator from the given XLIFF file - * - * @param string|array $file One or more paths to existing XLIFF files - */ - public function __construct($file) - { - $files = (array)$file; - - foreach ($files as $file) + /** + * Constructs an interpolator from the given XLIFF file + * + * @param string|array $file One or more paths to existing XLIFF files + */ + public function __construct($file) { - $xml = $this->parseFile($file); - $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2'); + $files = (array)$file; - foreach ($xml->xpath('//xliff:trans-unit') as $translation) - { - $this->translations[(string)$translation->source] = (string)$translation->target; - } - } - } + foreach ($files as $file) { + $xml = $this->parseFile($file); + $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2'); - /** - * {@inheritDoc} - */ - public function interpolate($text, array $parameters = array()) - { - if (isset($this->translations[$text])) - { - $text = $this->translations[$text]; + foreach ($xml->xpath('//xliff:trans-unit') as $translation) { + $this->translations[(string)$translation->source] = (string)$translation->target; + } + } } - $sources = array(); - $targets = array(); - - foreach ($parameters as $key => $value) + /** + * {@inheritDoc} + */ + public function interpolate($text, array $parameters = array()) { - $sources[] = '%'.$key.'%'; - $targets[] = (string)$value; + if (isset($this->translations[$text])) { + $text = $this->translations[$text]; + } + + $sources = array(); + $targets = array(); + + foreach ($parameters as $key => $value) { + $sources[] = '%'.$key.'%'; + $targets[] = (string)$value; + } + + return str_replace($sources, $targets, $text); } - return str_replace($sources, $targets, $text); - } - - /** - * Validates and parses the given file into a SimpleXMLElement - * - * @param string $file - * @return SimpleXMLElement - */ - protected function parseFile($file) - { - $dom = new \DOMDocument(); - libxml_use_internal_errors(true); - if (!$dom->load($file, LIBXML_COMPACT)) + /** + * Validates and parses the given file into a SimpleXMLElement + * + * @param string $file + * @return SimpleXMLElement + */ + protected function parseFile($file) { - throw new \Exception(implode("\n", $this->getXmlErrors())); - } - if (!$dom->schemaValidate(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd')) - { - throw new \Exception(implode("\n", $this->getXmlErrors())); - } - $dom->validateOnParse = true; - $dom->normalizeDocument(); - libxml_use_internal_errors(false); + $dom = new \DOMDocument(); + libxml_use_internal_errors(true); + if (!$dom->load($file, LIBXML_COMPACT)) { + throw new \Exception(implode("\n", $this->getXmlErrors())); + } + if (!$dom->schemaValidate(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd')) { + throw new \Exception(implode("\n", $this->getXmlErrors())); + } + $dom->validateOnParse = true; + $dom->normalizeDocument(); + libxml_use_internal_errors(false); - return simplexml_import_dom($dom); - } - - /** - * Returns the XML errors of the internal XML parser - * - * @return array An array of errors - */ - protected function getXmlErrors() - { - $errors = array(); - foreach (libxml_get_errors() as $error) - { - $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', - LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', - $error->code, - trim($error->message), - $error->file ? $error->file : 'n/a', - $error->line, - $error->column - ); + return simplexml_import_dom($dom); } - libxml_clear_errors(); - libxml_use_internal_errors(false); + /** + * Returns the XML errors of the internal XML parser + * + * @return array An array of errors + */ + protected function getXmlErrors() + { + $errors = array(); + foreach (libxml_get_errors() as $error) { + $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', + LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', + $error->code, + trim($error->message), + $error->file ? $error->file : 'n/a', + $error->line, + $error->column + ); + } - return $errors; - } + libxml_clear_errors(); + libxml_use_internal_errors(false); + + return $errors; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ValidationContext.php b/src/Symfony/Components/Validator/ValidationContext.php index 259ca17687..1805f739da 100644 --- a/src/Symfony/Components/Validator/ValidationContext.php +++ b/src/Symfony/Components/Validator/ValidationContext.php @@ -7,102 +7,102 @@ use Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface; class ValidationContext { - protected $root; - protected $propertyPath; - protected $class; - protected $property; - protected $group; - protected $violations; - protected $graphWalker; - protected $metadataFactory; - protected $messageInterpolator; + protected $root; + protected $propertyPath; + protected $class; + protected $property; + protected $group; + protected $violations; + protected $graphWalker; + protected $metadataFactory; + protected $messageInterpolator; - public function __construct( - $root, - GraphWalker $graphWalker, - ClassMetadataFactoryInterface $metadataFactory, - MessageInterpolatorInterface $messageInterpolator - ) - { - $this->root = $root; - $this->graphWalker = $graphWalker; - $this->messageInterpolator = $messageInterpolator; - $this->metadataFactory = $metadataFactory; - $this->violations = new ConstraintViolationList(); - } + public function __construct( + $root, + GraphWalker $graphWalker, + ClassMetadataFactoryInterface $metadataFactory, + MessageInterpolatorInterface $messageInterpolator + ) + { + $this->root = $root; + $this->graphWalker = $graphWalker; + $this->messageInterpolator = $messageInterpolator; + $this->metadataFactory = $metadataFactory; + $this->violations = new ConstraintViolationList(); + } - public function __clone() - { - $this->violations = clone $this->violations; - } + public function __clone() + { + $this->violations = clone $this->violations; + } - public function addViolation($message, array $params, $invalidValue) - { - $this->violations->add(new ConstraintViolation( - $this->messageInterpolator->interpolate($message, $params), - $this->root, - $this->propertyPath, - $invalidValue - )); - } + public function addViolation($message, array $params, $invalidValue) + { + $this->violations->add(new ConstraintViolation( + $this->messageInterpolator->interpolate($message, $params), + $this->root, + $this->propertyPath, + $invalidValue + )); + } - public function getViolations() - { - return $this->violations; - } + public function getViolations() + { + return $this->violations; + } - public function getRoot() - { - return $this->root; - } + public function getRoot() + { + return $this->root; + } - public function setPropertyPath($propertyPath) - { - $this->propertyPath = $propertyPath; - } + public function setPropertyPath($propertyPath) + { + $this->propertyPath = $propertyPath; + } - public function getPropertyPath() - { - return $this->propertyPath; - } + public function getPropertyPath() + { + return $this->propertyPath; + } - public function setCurrentClass($class) - { - $this->class = $class; - } + public function setCurrentClass($class) + { + $this->class = $class; + } - public function getCurrentClass() - { - return $this->class; - } + public function getCurrentClass() + { + return $this->class; + } - public function setCurrentProperty($property) - { - $this->property = $property; - } + public function setCurrentProperty($property) + { + $this->property = $property; + } - public function getCurrentProperty() - { - return $this->property; - } + public function getCurrentProperty() + { + return $this->property; + } - public function setGroup($group) - { - $this->group = $group; - } + public function setGroup($group) + { + $this->group = $group; + } - public function getGroup() - { - return $this->group; - } + public function getGroup() + { + return $this->group; + } - public function getGraphWalker() - { - return $this->graphWalker; - } + public function getGraphWalker() + { + return $this->graphWalker; + } - public function getClassMetadataFactory() - { - return $this->metadataFactory; - } + public function getClassMetadataFactory() + { + return $this->metadataFactory; + } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/Validator.php b/src/Symfony/Components/Validator/Validator.php index ac6acffab1..7bd3d0a3af 100644 --- a/src/Symfony/Components/Validator/Validator.php +++ b/src/Symfony/Components/Validator/Validator.php @@ -9,141 +9,126 @@ use Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterfac class Validator implements ValidatorInterface { - protected $metadataFactory; - protected $validatorFactory; - protected $messageInterpolator; + protected $metadataFactory; + protected $validatorFactory; + protected $messageInterpolator; - public function __construct( - ClassMetadataFactoryInterface $metadataFactory, - ConstraintValidatorFactoryInterface $validatorFactory, - MessageInterpolatorInterface $messageInterpolator - ) - { - $this->metadataFactory = $metadataFactory; - $this->validatorFactory = $validatorFactory; - $this->messageInterpolator = $messageInterpolator; - } - - public function validate($object, $groups = null) - { - $metadata = $this->metadataFactory->getClassMetadata(get_class($object)); - $groupChain = $this->buildGroupChain($metadata, $groups); - - $closure = function(GraphWalker $walker, $group) use ($metadata, $object) { - return $walker->walkClass($metadata, $object, $group, ''); - }; - - return $this->validateGraph($object, $closure, $groupChain); - } - - public function validateProperty($object, $property, $groups = null) - { - $metadata = $this->metadataFactory->getClassMetadata(get_class($object)); - $groupChain = $this->buildGroupChain($metadata, $groups); - - $closure = function(GraphWalker $walker, $group) use ($metadata, $property, $object) { - return $walker->walkProperty($metadata, $property, $object, $group, ''); - }; - - return $this->validateGraph($object, $closure, $groupChain); - } - - public function validatePropertyValue($class, $property, $value, $groups = null) - { - $metadata = $this->metadataFactory->getClassMetadata($class); - $groupChain = $this->buildGroupChain($metadata, $groups); - - $closure = function(GraphWalker $walker, $group) use ($metadata, $property, $value) { - return $walker->walkPropertyValue($metadata, $property, $value, $group, ''); - }; - - return $this->validateGraph($object, $closure, $groupChain); - } - - public function validateValue($value, Constraint $constraint, $groups = null) - { - $groupChain = $this->buildSimpleGroupChain($groups); - - $closure = function(GraphWalker $walker, $group) use ($constraint, $value) { - return $walker->walkConstraint($constraint, $value, $group, ''); - }; - - return $this->validateGraph($value, $closure, $groupChain); - } - - protected function validateGraph($root, \Closure $closure, GroupChain $groupChain) - { - $walker = new GraphWalker($root, $this->metadataFactory, $this->validatorFactory, $this->messageInterpolator); - - foreach ($groupChain->getGroups() as $group) + public function __construct( + ClassMetadataFactoryInterface $metadataFactory, + ConstraintValidatorFactoryInterface $validatorFactory, + MessageInterpolatorInterface $messageInterpolator + ) { - $closure($walker, $group); + $this->metadataFactory = $metadataFactory; + $this->validatorFactory = $validatorFactory; + $this->messageInterpolator = $messageInterpolator; } - foreach ($groupChain->getGroupSequences() as $sequence) + public function validate($object, $groups = null) { - $violationCount = count($walker->getViolations()); + $metadata = $this->metadataFactory->getClassMetadata(get_class($object)); + $groupChain = $this->buildGroupChain($metadata, $groups); - foreach ($sequence as $group) - { - $closure($walker, $group); + $closure = function(GraphWalker $walker, $group) use ($metadata, $object) { + return $walker->walkClass($metadata, $object, $group, ''); + }; - if (count($walker->getViolations()) > $violationCount) - { - break; + return $this->validateGraph($object, $closure, $groupChain); + } + + public function validateProperty($object, $property, $groups = null) + { + $metadata = $this->metadataFactory->getClassMetadata(get_class($object)); + $groupChain = $this->buildGroupChain($metadata, $groups); + + $closure = function(GraphWalker $walker, $group) use ($metadata, $property, $object) { + return $walker->walkProperty($metadata, $property, $object, $group, ''); + }; + + return $this->validateGraph($object, $closure, $groupChain); + } + + public function validatePropertyValue($class, $property, $value, $groups = null) + { + $metadata = $this->metadataFactory->getClassMetadata($class); + $groupChain = $this->buildGroupChain($metadata, $groups); + + $closure = function(GraphWalker $walker, $group) use ($metadata, $property, $value) { + return $walker->walkPropertyValue($metadata, $property, $value, $group, ''); + }; + + return $this->validateGraph($object, $closure, $groupChain); + } + + public function validateValue($value, Constraint $constraint, $groups = null) + { + $groupChain = $this->buildSimpleGroupChain($groups); + + $closure = function(GraphWalker $walker, $group) use ($constraint, $value) { + return $walker->walkConstraint($constraint, $value, $group, ''); + }; + + return $this->validateGraph($value, $closure, $groupChain); + } + + protected function validateGraph($root, \Closure $closure, GroupChain $groupChain) + { + $walker = new GraphWalker($root, $this->metadataFactory, $this->validatorFactory, $this->messageInterpolator); + + foreach ($groupChain->getGroups() as $group) { + $closure($walker, $group); } - } + + foreach ($groupChain->getGroupSequences() as $sequence) { + $violationCount = count($walker->getViolations()); + + foreach ($sequence as $group) { + $closure($walker, $group); + + if (count($walker->getViolations()) > $violationCount) { + break; + } + } + } + + return $walker->getViolations(); } - return $walker->getViolations(); - } - - protected function buildSimpleGroupChain($groups) - { - if (is_null($groups)) + protected function buildSimpleGroupChain($groups) { - $groups = array(Constraint::DEFAULT_GROUP); + if (is_null($groups)) { + $groups = array(Constraint::DEFAULT_GROUP); + } else { + $groups = (array)$groups; + } + + $chain = new GroupChain(); + + foreach ($groups as $group) { + $chain->addGroup($group); + } + + return $chain; } - else + + protected function buildGroupChain(ClassMetadata $metadata, $groups) { - $groups = (array)$groups; + if (is_null($groups)) { + $groups = array(Constraint::DEFAULT_GROUP); + } else { + $groups = (array)$groups; + } + + $chain = new GroupChain(); + + foreach ($groups as $group) { + if ($group == Constraint::DEFAULT_GROUP && $metadata->hasGroupSequence()) { + $chain->addGroupSequence($metadata->getGroupSequence()); + } else { + $chain->addGroup($group); + } + } + + return $chain; } - - $chain = new GroupChain(); - - foreach ($groups as $group) - { - $chain->addGroup($group); - } - - return $chain; - } - - protected function buildGroupChain(ClassMetadata $metadata, $groups) - { - if (is_null($groups)) - { - $groups = array(Constraint::DEFAULT_GROUP); - } - else - { - $groups = (array)$groups; - } - - $chain = new GroupChain(); - - foreach ($groups as $group) - { - if ($group == Constraint::DEFAULT_GROUP && $metadata->hasGroupSequence()) - { - $chain->addGroupSequence($metadata->getGroupSequence()); - } - else - { - $chain->addGroup($group); - } - } - - return $chain; - } } \ No newline at end of file diff --git a/src/Symfony/Components/Validator/ValidatorInterface.php b/src/Symfony/Components/Validator/ValidatorInterface.php index ef256274e8..8e9278b70a 100644 --- a/src/Symfony/Components/Validator/ValidatorInterface.php +++ b/src/Symfony/Components/Validator/ValidatorInterface.php @@ -12,11 +12,11 @@ use Symfony\Components\Validator\Constraint; */ interface ValidatorInterface { - public function validate($object, $groups = null); + public function validate($object, $groups = null); - public function validateProperty($object, $property, $groups = null); + public function validateProperty($object, $property, $groups = null); - public function validatePropertyValue($class, $property, $value, $groups = null); + public function validatePropertyValue($class, $property, $value, $groups = null); - public function validateValue($value, Constraint $constraint, $groups = null); + public function validateValue($value, Constraint $constraint, $groups = null); } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/File/FileTest.php b/tests/Symfony/Tests/Components/File/FileTest.php index 6e1d989349..58f1aa67fd 100644 --- a/tests/Symfony/Tests/Components/File/FileTest.php +++ b/tests/Symfony/Tests/Components/File/FileTest.php @@ -10,65 +10,65 @@ use Symfony\Components\File\MimeType\MimeTypeGuesser; class FileTest extends \PHPUnit_Framework_TestCase { - protected $file; + protected $file; - public function setUp() - { - $this->file = new File(__DIR__.'/Fixtures/test.gif'); - } + public function setUp() + { + $this->file = new File(__DIR__.'/Fixtures/test.gif'); + } - public function testGetPathReturnsAbsolutePath() - { - $this->assertEquals(__DIR__.'/Fixtures/test.gif', $this->file->getPath()); - } + public function testGetPathReturnsAbsolutePath() + { + $this->assertEquals(__DIR__.'/Fixtures/test.gif', $this->file->getPath()); + } - public function testGetNameReturnsNameWithExtension() - { - $this->assertEquals('test.gif', $this->file->getName()); - } + public function testGetNameReturnsNameWithExtension() + { + $this->assertEquals('test.gif', $this->file->getName()); + } - public function testGetExtensionReturnsExtensionWithDot() - { - $this->assertEquals('.gif', $this->file->getExtension()); - } + public function testGetExtensionReturnsExtensionWithDot() + { + $this->assertEquals('.gif', $this->file->getExtension()); + } - public function testGetDirectoryReturnsDirectoryName() - { - $this->assertEquals(__DIR__.'/Fixtures', $this->file->getDirectory()); - } + public function testGetDirectoryReturnsDirectoryName() + { + $this->assertEquals(__DIR__.'/Fixtures', $this->file->getDirectory()); + } - public function testGetMimeTypeUsesMimeTypeGuessers() - { - $guesser = $this->createMockGuesser($this->file->getPath(), 'image/gif'); + public function testGetMimeTypeUsesMimeTypeGuessers() + { + $guesser = $this->createMockGuesser($this->file->getPath(), 'image/gif'); - MimeTypeGuesser::getInstance()->register($guesser); + MimeTypeGuesser::getInstance()->register($guesser); - $this->assertEquals('image/gif', $this->file->getMimeType()); - } + $this->assertEquals('image/gif', $this->file->getMimeType()); + } - public function testGetDefaultExtensionIsBasedOnMimeType() - { - $file = new File(__DIR__.'/Fixtures/test'); - $guesser = $this->createMockGuesser($file->getPath(), 'image/gif'); + public function testGetDefaultExtensionIsBasedOnMimeType() + { + $file = new File(__DIR__.'/Fixtures/test'); + $guesser = $this->createMockGuesser($file->getPath(), 'image/gif'); - MimeTypeGuesser::getInstance()->register($guesser); + MimeTypeGuesser::getInstance()->register($guesser); - $this->assertEquals('.gif', $file->getDefaultExtension()); - } + $this->assertEquals('.gif', $file->getDefaultExtension()); + } - public function testSizeReturnsFileSize() - { - $this->assertEquals(filesize($this->file->getPath()), $this->file->size()); - } + public function testSizeReturnsFileSize() + { + $this->assertEquals(filesize($this->file->getPath()), $this->file->size()); + } - protected function createMockGuesser($path, $mimeType) - { - $guesser = $this->getMock('Symfony\Components\File\MimeType\MimeTypeGuesserInterface'); - $guesser->expects($this->once()) - ->method('guess') - ->with($this->equalTo($path)) - ->will($this->returnValue($mimeType)); + protected function createMockGuesser($path, $mimeType) + { + $guesser = $this->getMock('Symfony\Components\File\MimeType\MimeTypeGuesserInterface'); + $guesser->expects($this->once()) + ->method('guess') + ->with($this->equalTo($path)) + ->will($this->returnValue($mimeType)); - return $guesser; - } + return $guesser; + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/File/UploadedFileTest.php b/tests/Symfony/Tests/Components/File/UploadedFileTest.php index f94eb465de..28f968792e 100644 --- a/tests/Symfony/Tests/Components/File/UploadedFileTest.php +++ b/tests/Symfony/Tests/Components/File/UploadedFileTest.php @@ -9,37 +9,35 @@ use Symfony\Components\File\UploadedFile; class UploadedFileTest extends \PHPUnit_Framework_TestCase { - public function testFileUploadsMustBeEnabled() - { - // we can't change this setting without modifying php.ini :( - if (!ini_get('file_uploads')) + public function testFileUploadsMustBeEnabled() { - $this->setExpectedException('Symfony\Components\File\Exception\FileException'); + // we can't change this setting without modifying php.ini :( + if (!ini_get('file_uploads')) { + $this->setExpectedException('Symfony\Components\File\Exception\FileException'); - new UploadedFile( - __DIR__.'/Fixtures/test.gif', - 'original.gif', - 'image/gif', - filesize(__DIR__.'/Fixtures/test.gif'), - UPLOAD_ERR_OK - ); + new UploadedFile( + __DIR__.'/Fixtures/test.gif', + 'original.gif', + 'image/gif', + filesize(__DIR__.'/Fixtures/test.gif'), + UPLOAD_ERR_OK + ); + } } - } - public function testErrorIsOkByDefault() - { - // we can't change this setting without modifying php.ini :( - if (ini_get('file_uploads')) + public function testErrorIsOkByDefault() { - $file = new UploadedFile( - __DIR__.'/Fixtures/test.gif', - 'original.gif', - 'image/gif', - filesize(__DIR__.'/Fixtures/test.gif'), - null - ); + // we can't change this setting without modifying php.ini :( + if (ini_get('file_uploads')) { + $file = new UploadedFile( + __DIR__.'/Fixtures/test.gif', + 'original.gif', + 'image/gif', + filesize(__DIR__.'/Fixtures/test.gif'), + null + ); - $this->assertEquals(UPLOAD_ERR_OK, $file->getError()); + $this->assertEquals(UPLOAD_ERR_OK, $file->getError()); + } } - } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/CheckboxFieldTest.php b/tests/Symfony/Tests/Components/Form/CheckboxFieldTest.php index 4245c1220f..b9230c0fb6 100644 --- a/tests/Symfony/Tests/Components/Form/CheckboxFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/CheckboxFieldTest.php @@ -8,15 +8,15 @@ use Symfony\Components\Form\CheckboxField; class CheckboxFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new CheckboxField('name'); - $field->setData(true); + public function testRender() + { + $field = new CheckboxField('name'); + $field->setData(true); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/ChoiceFieldTest.php b/tests/Symfony/Tests/Components/Form/ChoiceFieldTest.php index 064bc193d8..94dbd0599a 100644 --- a/tests/Symfony/Tests/Components/Form/ChoiceFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/ChoiceFieldTest.php @@ -8,53 +8,53 @@ use Symfony\Components\Form\ChoiceField; class ChoiceFieldTest extends \PHPUnit_Framework_TestCase { - protected $choices = array( - 'a' => 'Bernhard', - 'b' => 'Fabien', - 'c' => 'Kris', - 'd' => 'Jon', - 'e' => 'Roman', - ); + protected $choices = array( + 'a' => 'Bernhard', + 'b' => 'Fabien', + 'c' => 'Kris', + 'd' => 'Jon', + 'e' => 'Roman', + ); - protected $preferredChoices = array('d', 'e'); + protected $preferredChoices = array('d', 'e'); - protected $groupedChoices = array( - 'Symfony' => array( - 'a' => 'Bernhard', - 'b' => 'Fabien', - 'c' => 'Kris', - ), - 'Doctrine' => array( - 'd' => 'Jon', - 'e' => 'Roman', - ) - ); + protected $groupedChoices = array( + 'Symfony' => array( + 'a' => 'Bernhard', + 'b' => 'Fabien', + 'c' => 'Kris', + ), + 'Doctrine' => array( + 'd' => 'Jon', + 'e' => 'Roman', + ) + ); - public function testBindSingleNonExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->choices, - )); + public function testBindSingleNonExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->choices, + )); - $field->bind('b'); + $field->bind('b'); - $this->assertEquals('b', $field->getData()); - $this->assertEquals('b', $field->getDisplayedData()); - } + $this->assertEquals('b', $field->getData()); + $this->assertEquals('b', $field->getDisplayedData()); + } - public function testRenderSingleNonExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->choices, - )); + public function testRenderSingleNonExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->choices, + )); - $field->setData('b'); + $field->setData('b'); - $html = << @@ -64,31 +64,31 @@ class ChoiceFieldTest extends \PHPUnit_Framework_TestCase EOF; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - public function testRenderSingleNonExpanded_translateChoices() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - $translator->expects($this->any()) - ->method('translate') - ->will($this->returnCallback(function($text) { - return 'translated['.$text.']'; - })); + public function testRenderSingleNonExpanded_translateChoices() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + $translator->expects($this->any()) + ->method('translate') + ->will($this->returnCallback(function($text) { + return 'translated['.$text.']'; + })); - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->choices, - 'translate_choices' => true, - )); + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->choices, + 'translate_choices' => true, + )); - $field->setTranslator($translator); - $field->setData('b'); + $field->setTranslator($translator); + $field->setData('b'); - $html = << @@ -98,22 +98,22 @@ EOF; EOF; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - public function testRenderSingleNonExpanded_disabled() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->choices, - 'disabled' => true, - )); + public function testRenderSingleNonExpanded_disabled() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->choices, + 'disabled' => true, + )); - $html = << @@ -123,22 +123,22 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderSingleNonExpandedWithPreferred() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->choices, - 'preferred_choices' => $this->preferredChoices, - 'separator' => '---', - )); + public function testRenderSingleNonExpandedWithPreferred() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->choices, + 'preferred_choices' => $this->preferredChoices, + 'separator' => '---', + )); - $field->setData('d'); + $field->setData('d'); - $html = << @@ -149,18 +149,18 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderSingleNonExpandedWithGroups() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->groupedChoices, - )); + public function testRenderSingleNonExpandedWithGroups() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->groupedChoices, + )); - $html = << @@ -174,22 +174,22 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderSingleNonExpandedNonRequired() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => false, - 'choices' => $this->choices, - 'empty_value' => 'empty', - )); + public function testRenderSingleNonExpandedNonRequired() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => false, + 'choices' => $this->choices, + 'empty_value' => 'empty', + )); - $field->setData(null); - $field->setRequired(false); + $field->setData(null); + $field->setRequired(false); - $html = << @@ -200,34 +200,34 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testBindMultipleNonExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => true, - 'expanded' => false, - 'choices' => $this->choices, - )); + public function testBindMultipleNonExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => true, + 'expanded' => false, + 'choices' => $this->choices, + )); - $field->bind(array('a', 'b')); + $field->bind(array('a', 'b')); - $this->assertEquals(array('a', 'b'), $field->getData()); - $this->assertEquals(array('a', 'b'), $field->getDisplayedData()); - } + $this->assertEquals(array('a', 'b'), $field->getData()); + $this->assertEquals(array('a', 'b'), $field->getDisplayedData()); + } - public function testRenderMultipleNonExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => true, - 'expanded' => false, - 'choices' => $this->choices, - )); + public function testRenderMultipleNonExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => true, + 'expanded' => false, + 'choices' => $this->choices, + )); - $field->setData(array('a', 'b')); + $field->setData(array('a', 'b')); - $html = << @@ -237,34 +237,34 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testBindSingleExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => true, - 'expanded' => false, - 'choices' => $this->choices, - )); + public function testBindSingleExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => true, + 'expanded' => false, + 'choices' => $this->choices, + )); - $field->bind('b'); + $field->bind('b'); - $this->assertEquals('b', $field->getData()); - $this->assertEquals('b', $field->getDisplayedData()); - } + $this->assertEquals('b', $field->getData()); + $this->assertEquals('b', $field->getDisplayedData()); + } - public function testRenderSingleExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => true, - 'choices' => $this->choices, - )); + public function testRenderSingleExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => true, + 'choices' => $this->choices, + )); - $field->setData('b'); + $field->setData('b'); - $html = << @@ -273,29 +273,29 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderSingleExpanded_translateChoices() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - $translator->expects($this->any()) - ->method('translate') - ->will($this->returnCallback(function($text) { - return 'translated['.$text.']'; - })); + public function testRenderSingleExpanded_translateChoices() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + $translator->expects($this->any()) + ->method('translate') + ->will($this->returnCallback(function($text) { + return 'translated['.$text.']'; + })); - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => true, - 'choices' => $this->choices, - 'translate_choices' => true, - )); + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => true, + 'choices' => $this->choices, + 'translate_choices' => true, + )); - $field->setTranslator($translator); - $field->setData('b'); + $field->setTranslator($translator); + $field->setData('b'); - $html = << @@ -304,19 +304,19 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderSingleExpandedWithPreferred() - { - $field = new ChoiceField('name', array( - 'multiple' => false, - 'expanded' => true, - 'choices' => $this->choices, - 'preferred_choices' => $this->preferredChoices, - )); + public function testRenderSingleExpandedWithPreferred() + { + $field = new ChoiceField('name', array( + 'multiple' => false, + 'expanded' => true, + 'choices' => $this->choices, + 'preferred_choices' => $this->preferredChoices, + )); - $html = << @@ -325,44 +325,44 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testBindMultipleExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => true, - 'expanded' => true, - 'choices' => $this->choices, - )); + public function testBindMultipleExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => true, + 'expanded' => true, + 'choices' => $this->choices, + )); - $field->bind(array('a' => 'a', 'b' => 'b')); + $field->bind(array('a' => 'a', 'b' => 'b')); - $this->assertSame(array('a', 'b'), $field->getData()); - $this->assertSame(true, $field['a']->getData()); - $this->assertSame(true, $field['b']->getData()); - $this->assertSame(null, $field['c']->getData()); - $this->assertSame(null, $field['d']->getData()); - $this->assertSame(null, $field['e']->getData()); - $this->assertSame('1', $field['a']->getDisplayedData()); - $this->assertSame('1', $field['b']->getDisplayedData()); - $this->assertSame('', $field['c']->getDisplayedData()); - $this->assertSame('', $field['d']->getDisplayedData()); - $this->assertSame('', $field['e']->getDisplayedData()); - $this->assertSame(array('a' => '1', 'b' => '1', 'c' => '', 'd' => '', 'e' => ''), $field->getDisplayedData()); - } + $this->assertSame(array('a', 'b'), $field->getData()); + $this->assertSame(true, $field['a']->getData()); + $this->assertSame(true, $field['b']->getData()); + $this->assertSame(null, $field['c']->getData()); + $this->assertSame(null, $field['d']->getData()); + $this->assertSame(null, $field['e']->getData()); + $this->assertSame('1', $field['a']->getDisplayedData()); + $this->assertSame('1', $field['b']->getDisplayedData()); + $this->assertSame('', $field['c']->getDisplayedData()); + $this->assertSame('', $field['d']->getDisplayedData()); + $this->assertSame('', $field['e']->getDisplayedData()); + $this->assertSame(array('a' => '1', 'b' => '1', 'c' => '', 'd' => '', 'e' => ''), $field->getDisplayedData()); + } - public function testRenderMultipleExpanded() - { - $field = new ChoiceField('name', array( - 'multiple' => true, - 'expanded' => true, - 'choices' => $this->choices, - )); + public function testRenderMultipleExpanded() + { + $field = new ChoiceField('name', array( + 'multiple' => true, + 'expanded' => true, + 'choices' => $this->choices, + )); - $field->setData(array('a', 'b')); + $field->setData(array('a', 'b')); - $html = << @@ -371,6 +371,6 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/CollectionFieldTest.php b/tests/Symfony/Tests/Components/Form/CollectionFieldTest.php index 48e06b6183..a8a394cd1a 100644 --- a/tests/Symfony/Tests/Components/Form/CollectionFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/CollectionFieldTest.php @@ -11,90 +11,90 @@ use Symfony\Tests\Components\Form\Fixtures\TestField; class CollectionFieldTest extends \PHPUnit_Framework_TestCase { - public function testContainsNoFieldsByDefault() - { - $field = new CollectionField(new TestField('emails')); - $this->assertEquals(0, count($field)); - } + public function testContainsNoFieldsByDefault() + { + $field = new CollectionField(new TestField('emails')); + $this->assertEquals(0, count($field)); + } - public function testSetDataAdjustsSize() - { - $field = new CollectionField(new TestField('emails')); - $field->setData(array('foo@foo.com', 'foo@bar.com')); + public function testSetDataAdjustsSize() + { + $field = new CollectionField(new TestField('emails')); + $field->setData(array('foo@foo.com', 'foo@bar.com')); - $this->assertTrue($field[0] instanceof TestField); - $this->assertTrue($field[1] instanceof TestField); - $this->assertEquals(2, count($field)); - $this->assertEquals('foo@foo.com', $field[0]->getData()); - $this->assertEquals('foo@bar.com', $field[1]->getData()); - } + $this->assertTrue($field[0] instanceof TestField); + $this->assertTrue($field[1] instanceof TestField); + $this->assertEquals(2, count($field)); + $this->assertEquals('foo@foo.com', $field[0]->getData()); + $this->assertEquals('foo@bar.com', $field[1]->getData()); + } - public function testThrowsExceptionIfObjectIsNotTraversable() - { - $field = new CollectionField(new TestField('emails')); - $this->setExpectedException('Symfony\Components\Form\Exception\UnexpectedTypeException'); - $field->setData(new \stdClass()); - } + public function testThrowsExceptionIfObjectIsNotTraversable() + { + $field = new CollectionField(new TestField('emails')); + $this->setExpectedException('Symfony\Components\Form\Exception\UnexpectedTypeException'); + $field->setData(new \stdClass()); + } - public function testModifiableCollectionsContainExtraField() - { - $field = new CollectionField(new TestField('emails'), array( - 'modifiable' => true, - )); - $field->setData(array('foo@bar.com')); + public function testModifiableCollectionsContainExtraField() + { + $field = new CollectionField(new TestField('emails'), array( + 'modifiable' => true, + )); + $field->setData(array('foo@bar.com')); - $this->assertTrue($field['0'] instanceof TestField); - $this->assertTrue($field['$$key$$'] instanceof TestField); - $this->assertEquals(2, count($field)); - } + $this->assertTrue($field['0'] instanceof TestField); + $this->assertTrue($field['$$key$$'] instanceof TestField); + $this->assertEquals(2, count($field)); + } - public function testNotResizedIfBoundWithMissingData() - { - $field = new CollectionField(new TestField('emails')); - $field->setData(array('foo@foo.com', 'bar@bar.com')); - $field->bind(array('foo@bar.com')); + public function testNotResizedIfBoundWithMissingData() + { + $field = new CollectionField(new TestField('emails')); + $field->setData(array('foo@foo.com', 'bar@bar.com')); + $field->bind(array('foo@bar.com')); - $this->assertTrue($field->has('0')); - $this->assertTrue($field->has('1')); - $this->assertEquals('foo@bar.com', $field[0]->getData()); - $this->assertEquals(null, $field[1]->getData()); - } + $this->assertTrue($field->has('0')); + $this->assertTrue($field->has('1')); + $this->assertEquals('foo@bar.com', $field[0]->getData()); + $this->assertEquals(null, $field[1]->getData()); + } - public function testResizedIfBoundWithMissingDataAndModifiable() - { - $field = new CollectionField(new TestField('emails'), array( - 'modifiable' => true, - )); - $field->setData(array('foo@foo.com', 'bar@bar.com')); - $field->bind(array('foo@bar.com')); + public function testResizedIfBoundWithMissingDataAndModifiable() + { + $field = new CollectionField(new TestField('emails'), array( + 'modifiable' => true, + )); + $field->setData(array('foo@foo.com', 'bar@bar.com')); + $field->bind(array('foo@bar.com')); - $this->assertTrue($field->has('0')); - $this->assertFalse($field->has('1')); - $this->assertEquals('foo@bar.com', $field[0]->getData()); - } + $this->assertTrue($field->has('0')); + $this->assertFalse($field->has('1')); + $this->assertEquals('foo@bar.com', $field[0]->getData()); + } - public function testNotResizedIfBoundWithExtraData() - { - $field = new CollectionField(new TestField('emails')); - $field->setData(array('foo@bar.com')); - $field->bind(array('foo@foo.com', 'bar@bar.com')); + public function testNotResizedIfBoundWithExtraData() + { + $field = new CollectionField(new TestField('emails')); + $field->setData(array('foo@bar.com')); + $field->bind(array('foo@foo.com', 'bar@bar.com')); - $this->assertTrue($field->has('0')); - $this->assertFalse($field->has('1')); - $this->assertEquals('foo@foo.com', $field[0]->getData()); - } + $this->assertTrue($field->has('0')); + $this->assertFalse($field->has('1')); + $this->assertEquals('foo@foo.com', $field[0]->getData()); + } - public function testResizedIfBoundWithExtraDataAndModifiable() - { - $field = new CollectionField(new TestField('emails'), array( - 'modifiable' => true, - )); - $field->setData(array('foo@bar.com')); - $field->bind(array('foo@foo.com', 'bar@bar.com')); + public function testResizedIfBoundWithExtraDataAndModifiable() + { + $field = new CollectionField(new TestField('emails'), array( + 'modifiable' => true, + )); + $field->setData(array('foo@bar.com')); + $field->bind(array('foo@foo.com', 'bar@bar.com')); - $this->assertTrue($field->has('0')); - $this->assertTrue($field->has('1')); - $this->assertEquals('foo@foo.com', $field[0]->getData()); - $this->assertEquals('bar@bar.com', $field[1]->getData()); - } + $this->assertTrue($field->has('0')); + $this->assertTrue($field->has('1')); + $this->assertEquals('foo@foo.com', $field[0]->getData()); + $this->assertEquals('bar@bar.com', $field[1]->getData()); + } } diff --git a/tests/Symfony/Tests/Components/Form/DateFieldTest.php b/tests/Symfony/Tests/Components/Form/DateFieldTest.php index 1300c4d12e..35672a2747 100644 --- a/tests/Symfony/Tests/Components/Form/DateFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/DateFieldTest.php @@ -9,137 +9,137 @@ use Symfony\Components\Form\DateField; class DateFieldTest extends DateTimeTestCase { - public function testBind_fromInput_dateTime() - { - $field = new DateField('name', array('widget' => 'input', 'type' => DateField::DATETIME)); + public function testBind_fromInput_dateTime() + { + $field = new DateField('name', array('widget' => 'input', 'type' => DateField::DATETIME)); - $field->setLocale('de_AT'); - $field->bind('2.6.2010'); + $field->setLocale('de_AT'); + $field->bind('2.6.2010'); - $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $field->getData()); - $this->assertEquals('02.06.2010', $field->getDisplayedData()); - } + $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $field->getData()); + $this->assertEquals('02.06.2010', $field->getDisplayedData()); + } - public function testBind_fromInput_string() - { - $field = new DateField('name', array('widget' => 'input', 'type' => DateField::STRING)); + public function testBind_fromInput_string() + { + $field = new DateField('name', array('widget' => 'input', 'type' => DateField::STRING)); - $field->setLocale('de_AT'); - $field->bind('2.6.2010'); + $field->setLocale('de_AT'); + $field->bind('2.6.2010'); - $this->assertEquals('2010-06-02', $field->getData()); - $this->assertEquals('02.06.2010', $field->getDisplayedData()); - } + $this->assertEquals('2010-06-02', $field->getData()); + $this->assertEquals('02.06.2010', $field->getDisplayedData()); + } - public function testBind_fromInput_timestamp() - { - $field = new DateField('name', array('widget' => 'input', 'type' => DateField::TIMESTAMP)); + public function testBind_fromInput_timestamp() + { + $field = new DateField('name', array('widget' => 'input', 'type' => DateField::TIMESTAMP)); - $field->setLocale('de_AT'); - $field->bind('2.6.2010'); + $field->setLocale('de_AT'); + $field->bind('2.6.2010'); - $dateTime = new \DateTime('2010-06-02 UTC'); + $dateTime = new \DateTime('2010-06-02 UTC'); - $this->assertEquals($dateTime->format('U'), $field->getData()); - $this->assertEquals('02.06.2010', $field->getDisplayedData()); - } + $this->assertEquals($dateTime->format('U'), $field->getData()); + $this->assertEquals('02.06.2010', $field->getDisplayedData()); + } - public function testBind_fromInput_raw() - { - $field = new DateField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'widget' => 'input', - 'type' => DateField::RAW, - )); + public function testBind_fromInput_raw() + { + $field = new DateField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'widget' => 'input', + 'type' => DateField::RAW, + )); - $field->setLocale('de_AT'); - $field->bind('2.6.2010'); + $field->setLocale('de_AT'); + $field->bind('2.6.2010'); - $output = array( - 'day' => '2', - 'month' => '6', - 'year' => '2010', - ); + $output = array( + 'day' => '2', + 'month' => '6', + 'year' => '2010', + ); - $this->assertEquals($output, $field->getData()); - $this->assertEquals('02.06.2010', $field->getDisplayedData()); - } + $this->assertEquals($output, $field->getData()); + $this->assertEquals('02.06.2010', $field->getDisplayedData()); + } - public function testBind_fromChoice() - { - $field = new DateField('name', array('widget' => DateField::CHOICE)); + public function testBind_fromChoice() + { + $field = new DateField('name', array('widget' => DateField::CHOICE)); - $input = array( - 'day' => '2', - 'month' => '6', - 'year' => '2010', - ); + $input = array( + 'day' => '2', + 'month' => '6', + 'year' => '2010', + ); - $field->setLocale('de_AT'); - $field->bind($input); + $field->setLocale('de_AT'); + $field->bind($input); - $dateTime = new \DateTime('2010-06-02 UTC'); + $dateTime = new \DateTime('2010-06-02 UTC'); - $this->assertDateTimeEquals($dateTime, $field->getData()); - $this->assertEquals($input, $field->getDisplayedData()); - } + $this->assertDateTimeEquals($dateTime, $field->getData()); + $this->assertEquals($input, $field->getDisplayedData()); + } - public function testSetData_differentTimezones() - { - $field = new DateField('name', array( - 'data_timezone' => 'America/New_York', - 'user_timezone' => 'Pacific/Tahiti', - // don't do this test with DateTime, because it leads to wrong results! - 'type' => DateField::STRING, - 'widget' => 'input', - )); + public function testSetData_differentTimezones() + { + $field = new DateField('name', array( + 'data_timezone' => 'America/New_York', + 'user_timezone' => 'Pacific/Tahiti', + // don't do this test with DateTime, because it leads to wrong results! + 'type' => DateField::STRING, + 'widget' => 'input', + )); - $field->setLocale('de_AT'); - $field->setData('2010-06-02'); + $field->setLocale('de_AT'); + $field->setData('2010-06-02'); - $this->assertEquals('01.06.2010', $field->getDisplayedData()); - } + $this->assertEquals('01.06.2010', $field->getDisplayedData()); + } - public function testRenderAsInput() - { - $field = new DateField('name', array('widget' => 'input')); + public function testRenderAsInput() + { + $field = new DateField('name', array('widget' => 'input')); - $field->setLocale('de_AT'); - $field->setData(new \DateTime('2010-06-02 UTC')); + $field->setLocale('de_AT'); + $field->setData(new \DateTime('2010-06-02 UTC')); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - public function testRenderAsInputWithFormat() - { - $field = new DateField('name', array('widget' => 'input', 'format' => 'short')); + public function testRenderAsInputWithFormat() + { + $field = new DateField('name', array('widget' => 'input', 'format' => 'short')); - $field->setLocale('de_AT'); - $field->setData(new \DateTime('2010-06-02 UTC')); + $field->setLocale('de_AT'); + $field->setData(new \DateTime('2010-06-02 UTC')); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderAsChoice() - { - $field = new DateField('name', array( - 'years' => array(2010, 2011), - 'months' => array(6, 7), - 'days' => array(1, 2), - 'widget' => DateField::CHOICE, - )); + public function testRenderAsChoice() + { + $field = new DateField('name', array( + 'years' => array(2010, 2011), + 'months' => array(6, 7), + 'days' => array(1, 2), + 'widget' => DateField::CHOICE, + )); - $field->setLocale('de_AT'); - $field->setData(new \DateTime('2010-06-02 UTC')); + $field->setLocale('de_AT'); + $field->setData(new \DateTime('2010-06-02 UTC')); - $html = << @@ -152,24 +152,24 @@ class DateFieldTest extends DateTimeTestCase EOF; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - public function testRenderAsChoiceNonRequired() - { - $field = new DateField('name', array( - 'years' => array(2010, 2011), - 'months' => array(6, 7), - 'days' => array(1, 2), - 'widget' => DateField::CHOICE, - )); + public function testRenderAsChoiceNonRequired() + { + $field = new DateField('name', array( + 'years' => array(2010, 2011), + 'months' => array(6, 7), + 'days' => array(1, 2), + 'widget' => DateField::CHOICE, + )); - $field->setLocale('de_AT'); - $field->setRequired(false); + $field->setLocale('de_AT'); + $field->setRequired(false); - $html = << @@ -185,20 +185,20 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderAsChoiceWithPattern() - { - $field = new DateField('name', array( - 'years' => array(2010, 2011), - 'months' => array(6, 7), - 'days' => array(1, 2), - 'widget' => DateField::CHOICE, - 'pattern' => '%day%---%month%---%year%', - )); + public function testRenderAsChoiceWithPattern() + { + $field = new DateField('name', array( + 'years' => array(2010, 2011), + 'months' => array(6, 7), + 'days' => array(1, 2), + 'widget' => DateField::CHOICE, + 'pattern' => '%day%---%month%---%year%', + )); - $html = << @@ -211,6 +211,6 @@ EOF; EOF; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/DateTimeFieldTest.php b/tests/Symfony/Tests/Components/Form/DateTimeFieldTest.php index 5131b3cb24..3f2bbb592b 100644 --- a/tests/Symfony/Tests/Components/Form/DateTimeFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/DateTimeFieldTest.php @@ -11,168 +11,168 @@ use Symfony\Components\Form\TimeField; class DateTimeFieldTest extends DateTimeTestCase { - public function testBind_dateTime() - { - $field = new DateTimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'date_widget' => DateField::CHOICE, - 'time_widget' => TimeField::CHOICE, - 'type' => DateTimeField::DATETIME, - )); + public function testBind_dateTime() + { + $field = new DateTimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'date_widget' => DateField::CHOICE, + 'time_widget' => TimeField::CHOICE, + 'type' => DateTimeField::DATETIME, + )); - $field->bind(array( - 'date' => array( - 'day' => '2', - 'month' => '6', - 'year' => '2010', - ), - 'time' => array( - 'hour' => '3', - 'minute' => '4', - ), - )); + $field->bind(array( + 'date' => array( + 'day' => '2', + 'month' => '6', + 'year' => '2010', + ), + 'time' => array( + 'hour' => '3', + 'minute' => '4', + ), + )); - $dateTime = new \DateTime('2010-06-02 03:04:00 UTC'); + $dateTime = new \DateTime('2010-06-02 03:04:00 UTC'); - $this->assertDateTimeEquals($dateTime, $field->getData()); - } + $this->assertDateTimeEquals($dateTime, $field->getData()); + } - public function testBind_string() - { - $field = new DateTimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => DateTimeField::STRING, - 'date_widget' => DateField::CHOICE, - 'time_widget' => TimeField::CHOICE, - )); + public function testBind_string() + { + $field = new DateTimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => DateTimeField::STRING, + 'date_widget' => DateField::CHOICE, + 'time_widget' => TimeField::CHOICE, + )); - $field->bind(array( - 'date' => array( - 'day' => '2', - 'month' => '6', - 'year' => '2010', - ), - 'time' => array( - 'hour' => '3', - 'minute' => '4', - ), - )); + $field->bind(array( + 'date' => array( + 'day' => '2', + 'month' => '6', + 'year' => '2010', + ), + 'time' => array( + 'hour' => '3', + 'minute' => '4', + ), + )); - $this->assertEquals('2010-06-02 03:04:00', $field->getData()); - } + $this->assertEquals('2010-06-02 03:04:00', $field->getData()); + } - public function testBind_timestamp() - { - $field = new DateTimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => DateTimeField::TIMESTAMP, - 'date_widget' => DateField::CHOICE, - 'time_widget' => TimeField::CHOICE, - )); + public function testBind_timestamp() + { + $field = new DateTimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => DateTimeField::TIMESTAMP, + 'date_widget' => DateField::CHOICE, + 'time_widget' => TimeField::CHOICE, + )); - $field->bind(array( - 'date' => array( - 'day' => '2', - 'month' => '6', - 'year' => '2010', - ), - 'time' => array( - 'hour' => '3', - 'minute' => '4', - ), - )); + $field->bind(array( + 'date' => array( + 'day' => '2', + 'month' => '6', + 'year' => '2010', + ), + 'time' => array( + 'hour' => '3', + 'minute' => '4', + ), + )); - $dateTime = new \DateTime('2010-06-02 03:04:00 UTC'); + $dateTime = new \DateTime('2010-06-02 03:04:00 UTC'); - $this->assertEquals($dateTime->format('U'), $field->getData()); - } + $this->assertEquals($dateTime->format('U'), $field->getData()); + } - public function testBind_withSeconds() - { - $field = new DateTimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'date_widget' => DateField::CHOICE, - 'time_widget' => TimeField::CHOICE, - 'type' => DateTimeField::DATETIME, - 'with_seconds' => true, - )); + public function testBind_withSeconds() + { + $field = new DateTimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'date_widget' => DateField::CHOICE, + 'time_widget' => TimeField::CHOICE, + 'type' => DateTimeField::DATETIME, + 'with_seconds' => true, + )); - $field->setData(new \DateTime('2010-06-02 03:04:05 UTC')); + $field->setData(new \DateTime('2010-06-02 03:04:05 UTC')); - $input = array( - 'date' => array( - 'day' => '2', - 'month' => '6', - 'year' => '2010', - ), - 'time' => array( - 'hour' => '3', - 'minute' => '4', - 'second' => '5', - ), - ); + $input = array( + 'date' => array( + 'day' => '2', + 'month' => '6', + 'year' => '2010', + ), + 'time' => array( + 'hour' => '3', + 'minute' => '4', + 'second' => '5', + ), + ); - $field->bind($input); + $field->bind($input); - $this->assertDateTimeEquals(new \DateTime('2010-06-02 03:04:05 UTC'), $field->getData()); - } + $this->assertDateTimeEquals(new \DateTime('2010-06-02 03:04:05 UTC'), $field->getData()); + } - public function testBind_differentTimezones() - { - $field = new DateTimeField('name', array( - 'data_timezone' => 'America/New_York', - 'user_timezone' => 'Pacific/Tahiti', - 'date_widget' => DateField::CHOICE, - 'time_widget' => TimeField::CHOICE, - // don't do this test with DateTime, because it leads to wrong results! - 'type' => DateTimeField::STRING, - 'with_seconds' => true, - )); + public function testBind_differentTimezones() + { + $field = new DateTimeField('name', array( + 'data_timezone' => 'America/New_York', + 'user_timezone' => 'Pacific/Tahiti', + 'date_widget' => DateField::CHOICE, + 'time_widget' => TimeField::CHOICE, + // don't do this test with DateTime, because it leads to wrong results! + 'type' => DateTimeField::STRING, + 'with_seconds' => true, + )); - $dateTime = new \DateTime('2010-06-02 03:04:05 Pacific/Tahiti'); + $dateTime = new \DateTime('2010-06-02 03:04:05 Pacific/Tahiti'); - $field->bind(array( - 'date' => array( - 'day' => (int)$dateTime->format('d'), - 'month' => (int)$dateTime->format('m'), - 'year' => (int)$dateTime->format('Y'), - ), - 'time' => array( - 'hour' => (int)$dateTime->format('H'), - 'minute' => (int)$dateTime->format('i'), - 'second' => (int)$dateTime->format('s'), - ), - )); + $field->bind(array( + 'date' => array( + 'day' => (int)$dateTime->format('d'), + 'month' => (int)$dateTime->format('m'), + 'year' => (int)$dateTime->format('Y'), + ), + 'time' => array( + 'hour' => (int)$dateTime->format('H'), + 'minute' => (int)$dateTime->format('i'), + 'second' => (int)$dateTime->format('s'), + ), + )); - $dateTime->setTimezone(new \DateTimeZone('America/New_York')); + $dateTime->setTimezone(new \DateTimeZone('America/New_York')); - $this->assertEquals($dateTime->format('Y-m-d H:i:s'), $field->getData()); - } + $this->assertEquals($dateTime->format('Y-m-d H:i:s'), $field->getData()); + } - public function testRender() - { - $field = new DateTimeField('name', array( - 'years' => array(2010, 2011), - 'months' => array(6, 7), - 'days' => array(1, 2), - 'hours' => array(3, 4), - 'minutes' => array(5, 6), - 'seconds' => array(7, 8), - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'date_widget' => DateField::CHOICE, - 'time_widget' => TimeField::CHOICE, - 'type' => DateTimeField::DATETIME, - 'with_seconds' => true, - )); + public function testRender() + { + $field = new DateTimeField('name', array( + 'years' => array(2010, 2011), + 'months' => array(6, 7), + 'days' => array(1, 2), + 'hours' => array(3, 4), + 'minutes' => array(5, 6), + 'seconds' => array(7, 8), + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'date_widget' => DateField::CHOICE, + 'time_widget' => TimeField::CHOICE, + 'type' => DateTimeField::DATETIME, + 'with_seconds' => true, + )); - $field->setData(new \DateTime('2010-06-02 03:04:05 UTC')); + $field->setData(new \DateTime('2010-06-02 03:04:05 UTC')); - $html = << @@ -196,5 +196,5 @@ class DateTimeFieldTest extends DateTimeTestCase EOF; $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/DateTimeTestCase.php b/tests/Symfony/Tests/Components/Form/DateTimeTestCase.php index f53932aa27..29f3602449 100644 --- a/tests/Symfony/Tests/Components/Form/DateTimeTestCase.php +++ b/tests/Symfony/Tests/Components/Form/DateTimeTestCase.php @@ -4,8 +4,8 @@ namespace Symfony\Tests\Components\Form; class DateTimeTestCase extends \PHPUnit_Framework_TestCase { - public static function assertDateTimeEquals(\DateTime $expected, \DateTime $actual) - { - self::assertEquals($expected->format('c'), $actual->format('c')); - } + public static function assertDateTimeEquals(\DateTime $expected, \DateTime $actual) + { + self::assertEquals($expected->format('c'), $actual->format('c')); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/FieldGroupTest.php b/tests/Symfony/Tests/Components/Form/FieldGroupTest.php index a7633a78b9..a5e8bdc19d 100644 --- a/tests/Symfony/Tests/Components/Form/FieldGroupTest.php +++ b/tests/Symfony/Tests/Components/Form/FieldGroupTest.php @@ -16,611 +16,611 @@ use Symfony\Tests\Components\Form\Fixtures\TestField; abstract class FieldGroupTest_Field implements FieldInterface { - public $locales = array(); + public $locales = array(); - public function setLocale($locale) - { - $this->locales[] = $locale; - } + public function setLocale($locale) + { + $this->locales[] = $locale; + } } class FieldGroupTest extends \PHPUnit_Framework_TestCase { - public function testSupportsArrayAccess() - { - $group = new FieldGroup('author'); - $group->add($this->createMockField('firstName')); - $this->assertEquals($group->get('firstName'), $group['firstName']); - $this->assertTrue(isset($group['firstName'])); - } - - public function testSupportsUnset() - { - $group = new FieldGroup('author'); - $group->add($this->createMockField('firstName')); - unset($group['firstName']); - $this->assertFalse(isset($group['firstName'])); - } - - public function testDoesNotSupportAddingFields() - { - $group = new FieldGroup('author'); - $this->setExpectedException('LogicException'); - $group[] = $this->createMockField('lastName'); - } - - public function testSupportsCountable() - { - $group = new FieldGroup('group'); - $group->add($this->createMockField('firstName')); - $group->add($this->createMockField('lastName')); - $this->assertEquals(2, count($group)); - - $group->add($this->createMockField('australian')); - $this->assertEquals(3, count($group)); - } - - public function testSupportsIterable() - { - $group = new FieldGroup('group'); - $group->add($field1 = $this->createMockField('field1')); - $group->add($field2 = $this->createMockField('field2')); - $group->add($field3 = $this->createMockField('field3')); - - $expected = array( - 'field1' => $field1, - 'field2' => $field2, - 'field3' => $field3, - ); - - $this->assertEquals($expected, iterator_to_array($group)); - } - - public function testIsBound() - { - $group = new FieldGroup('author'); - $this->assertFalse($group->isBound()); - $group->bind(array('firstName' => 'Bernhard')); - $this->assertTrue($group->isBound()); - } - - public function testValidIfAllFieldsAreValid() - { - $group = new FieldGroup('author'); - $group->add($this->createValidMockField('firstName')); - $group->add($this->createValidMockField('lastName')); - - $group->bind(array('firstName' => 'Bernhard', 'lastName' => 'Potencier')); - - $this->assertTrue($group->isValid()); - } - - public function testInvalidIfFieldIsInvalid() - { - $group = new FieldGroup('author'); - $group->add($this->createInvalidMockField('firstName')); - $group->add($this->createValidMockField('lastName')); - - $group->bind(array('firstName' => 'Bernhard', 'lastName' => 'Potencier')); - - $this->assertFalse($group->isValid()); - } - - public function testInvalidIfBoundWithExtraFields() - { - $group = new FieldGroup('author'); - $group->add($this->createValidMockField('firstName')); - $group->add($this->createValidMockField('lastName')); - - $group->bind(array('foo' => 'bar', 'firstName' => 'Bernhard', 'lastName' => 'Potencier')); - - $this->assertTrue($group->isBoundWithExtraFields()); - } - - public function testBindForwardsBoundValues() - { - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('bind') - ->with($this->equalTo('Bernhard')); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->bind(array('firstName' => 'Bernhard')); - } - - public function testBindForwardsNullIfValueIsMissing() - { - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('bind') - ->with($this->equalTo(null)); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->bind(array()); - } - - public function testAddErrorMapsFieldValidationErrorsOntoFields() - { - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('addError') - ->with($this->equalTo('Message')); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('fields[firstName].data'), FieldGroup::FIELD_ERROR); - } - - public function testAddErrorKeepsFieldValidationErrorsIfFieldNotFound() - { - $field = $this->createMockField('foo'); - $field->expects($this->never()) - ->method('addError'); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('fields[bar].data'), FieldGroup::FIELD_ERROR); - - $this->assertEquals(array('Message'), $group->getErrors()); - } - - public function testAddErrorKeepsFieldValidationErrorsIfFieldIsHidden() - { - $field = $this->createMockField('firstName'); - $field->expects($this->any()) - ->method('isHidden') - ->will($this->returnValue(true)); - $field->expects($this->never()) - ->method('addError'); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('fields[firstName].data'), FieldGroup::FIELD_ERROR); - - $this->assertEquals(array('Message'), $group->getErrors()); - } - - public function testAddErrorMapsDataValidationErrorsOntoFields() - { - // path is expected to point at "firstName" - $expectedPath = new PropertyPath('firstName'); - - $field = $this->createMockField('firstName'); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(new PropertyPath('firstName'))); - $field->expects($this->once()) - ->method('addError') - ->with($this->equalTo('Message'), $this->equalTo($expectedPath), $this->equalTo(FieldGroup::DATA_ERROR)); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('firstName'), FieldGroup::DATA_ERROR); - } - - public function testAddErrorKeepsDataValidationErrorsIfFieldNotFound() - { - $field = $this->createMockField('foo'); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(new PropertyPath('foo'))); - $field->expects($this->never()) - ->method('addError'); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('bar'), FieldGroup::DATA_ERROR); - } - - public function testAddErrorKeepsDataValidationErrorsIfFieldIsHidden() - { - $field = $this->createMockField('firstName'); - $field->expects($this->any()) - ->method('isHidden') - ->will($this->returnValue(true)); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(new PropertyPath('firstName'))); - $field->expects($this->never()) - ->method('addError'); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('firstName'), FieldGroup::DATA_ERROR); - } - - public function testAddErrorMapsDataValidationErrorsOntoNestedFields() - { - // path is expected to point at "street" - $expectedPath = new PropertyPath('address.street'); - $expectedPath->next(); - - $field = $this->createMockField('address'); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(new PropertyPath('address'))); - $field->expects($this->once()) - ->method('addError') - ->with($this->equalTo('Message'), $this->equalTo($expectedPath), $this->equalTo(FieldGroup::DATA_ERROR)); - - $group = new FieldGroup('author'); - $group->add($field); - - $group->addError('Message', new PropertyPath('address.street'), FieldGroup::DATA_ERROR); - } - - public function testAddErrorMapsErrorsOntoFieldsInAnonymousGroups() - { - // path is expected to point at "address" - $expectedPath = new PropertyPath('address'); - - $field = $this->createMockField('address'); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(new PropertyPath('address'))); - $field->expects($this->once()) - ->method('addError') - ->with($this->equalTo('Message'), $this->equalTo($expectedPath), $this->equalTo(FieldGroup::DATA_ERROR)); - - $group = new FieldGroup('author'); - $group2 = new FieldGroup('anonymous', array('property_path' => null)); - $group2->add($field); - $group->add($group2); - - $group->addError('Message', new PropertyPath('address'), FieldGroup::DATA_ERROR); - } - - public function testAddThrowsExceptionIfAlreadyBound() - { - $group = new FieldGroup('author'); - $group->add($this->createMockField('firstName')); - $group->bind(array('firstName' => 'Bernhard')); - - $this->setExpectedException('Symfony\Components\Form\Exception\AlreadyBoundException'); - $group->add($this->createMockField('lastName')); - } - - public function testAddSetsFieldParent() - { - $group = new FieldGroup('author'); - - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('setParent'); - // PHPUnit fails to compare infinitely recursive objects - //->with($this->equalTo($group)); - - $group->add($field); - } - - public function testRemoveUnsetsFieldParent() - { - $group = new FieldGroup('author'); - - $field = $this->createMockField('firstName'); - $field->expects($this->exactly(2)) - ->method('setParent'); - // PHPUnit fails to compare subsequent method calls with different arguments - - $group->add($field); - $group->remove('firstName'); - } - - public function testMergeAddsFieldsFromAnotherGroup() - { - $group1 = new FieldGroup('author'); - $group1->add($field1 = new TestField('firstName')); - - $group2 = new FieldGroup('publisher'); - $group2->add($field2 = new TestField('lastName')); - - $group1->merge($group2); - - $this->assertTrue($group1->has('lastName')); - $this->assertEquals(new PropertyPath('publisher.lastName'), $group1->get('lastName')->getPropertyPath()); - } - - public function testMergeThrowsExceptionIfOtherGroupAlreadyBound() - { - $group1 = new FieldGroup('author'); - $group2 = new FieldGroup('publisher'); - $group2->add($this->createMockField('firstName')); - - $group2->bind(array('firstName' => 'Bernhard')); - - $this->setExpectedException('Symfony\Components\Form\Exception\AlreadyBoundException'); - $group1->merge($group2); - } - - public function testAddUpdatesFieldFromTransformedData() - { - $originalAuthor = new Author(); - $transformedAuthor = new Author(); - // the authors should differ to make sure the test works - $transformedAuthor->firstName = 'Foo'; - - $group = new FieldGroup('author'); - - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('transform') - ->with($this->equalTo($originalAuthor)) - ->will($this->returnValue($transformedAuthor)); - - $group->setValueTransformer($transformer); - $group->setData($originalAuthor); - - $field = $this->createMockField('firstName'); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(new PropertyPath('firstName'))); - $field->expects($this->once()) - ->method('updateFromObject') - ->with($this->equalTo($transformedAuthor)); - - $group->add($field); - } - - public function testAddDoesNotUpdateFieldsWithEmptyPropertyPath() - { - $group = new FieldGroup('author'); - $group->setData(new Author()); + public function testSupportsArrayAccess() + { + $group = new FieldGroup('author'); + $group->add($this->createMockField('firstName')); + $this->assertEquals($group->get('firstName'), $group['firstName']); + $this->assertTrue(isset($group['firstName'])); + } + + public function testSupportsUnset() + { + $group = new FieldGroup('author'); + $group->add($this->createMockField('firstName')); + unset($group['firstName']); + $this->assertFalse(isset($group['firstName'])); + } + + public function testDoesNotSupportAddingFields() + { + $group = new FieldGroup('author'); + $this->setExpectedException('LogicException'); + $group[] = $this->createMockField('lastName'); + } + + public function testSupportsCountable() + { + $group = new FieldGroup('group'); + $group->add($this->createMockField('firstName')); + $group->add($this->createMockField('lastName')); + $this->assertEquals(2, count($group)); + + $group->add($this->createMockField('australian')); + $this->assertEquals(3, count($group)); + } + + public function testSupportsIterable() + { + $group = new FieldGroup('group'); + $group->add($field1 = $this->createMockField('field1')); + $group->add($field2 = $this->createMockField('field2')); + $group->add($field3 = $this->createMockField('field3')); + + $expected = array( + 'field1' => $field1, + 'field2' => $field2, + 'field3' => $field3, + ); + + $this->assertEquals($expected, iterator_to_array($group)); + } + + public function testIsBound() + { + $group = new FieldGroup('author'); + $this->assertFalse($group->isBound()); + $group->bind(array('firstName' => 'Bernhard')); + $this->assertTrue($group->isBound()); + } + + public function testValidIfAllFieldsAreValid() + { + $group = new FieldGroup('author'); + $group->add($this->createValidMockField('firstName')); + $group->add($this->createValidMockField('lastName')); + + $group->bind(array('firstName' => 'Bernhard', 'lastName' => 'Potencier')); + + $this->assertTrue($group->isValid()); + } + + public function testInvalidIfFieldIsInvalid() + { + $group = new FieldGroup('author'); + $group->add($this->createInvalidMockField('firstName')); + $group->add($this->createValidMockField('lastName')); + + $group->bind(array('firstName' => 'Bernhard', 'lastName' => 'Potencier')); + + $this->assertFalse($group->isValid()); + } + + public function testInvalidIfBoundWithExtraFields() + { + $group = new FieldGroup('author'); + $group->add($this->createValidMockField('firstName')); + $group->add($this->createValidMockField('lastName')); + + $group->bind(array('foo' => 'bar', 'firstName' => 'Bernhard', 'lastName' => 'Potencier')); + + $this->assertTrue($group->isBoundWithExtraFields()); + } + + public function testBindForwardsBoundValues() + { + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('bind') + ->with($this->equalTo('Bernhard')); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->bind(array('firstName' => 'Bernhard')); + } + + public function testBindForwardsNullIfValueIsMissing() + { + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('bind') + ->with($this->equalTo(null)); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->bind(array()); + } + + public function testAddErrorMapsFieldValidationErrorsOntoFields() + { + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('addError') + ->with($this->equalTo('Message')); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('fields[firstName].data'), FieldGroup::FIELD_ERROR); + } + + public function testAddErrorKeepsFieldValidationErrorsIfFieldNotFound() + { + $field = $this->createMockField('foo'); + $field->expects($this->never()) + ->method('addError'); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('fields[bar].data'), FieldGroup::FIELD_ERROR); + + $this->assertEquals(array('Message'), $group->getErrors()); + } + + public function testAddErrorKeepsFieldValidationErrorsIfFieldIsHidden() + { + $field = $this->createMockField('firstName'); + $field->expects($this->any()) + ->method('isHidden') + ->will($this->returnValue(true)); + $field->expects($this->never()) + ->method('addError'); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('fields[firstName].data'), FieldGroup::FIELD_ERROR); + + $this->assertEquals(array('Message'), $group->getErrors()); + } + + public function testAddErrorMapsDataValidationErrorsOntoFields() + { + // path is expected to point at "firstName" + $expectedPath = new PropertyPath('firstName'); + + $field = $this->createMockField('firstName'); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(new PropertyPath('firstName'))); + $field->expects($this->once()) + ->method('addError') + ->with($this->equalTo('Message'), $this->equalTo($expectedPath), $this->equalTo(FieldGroup::DATA_ERROR)); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('firstName'), FieldGroup::DATA_ERROR); + } + + public function testAddErrorKeepsDataValidationErrorsIfFieldNotFound() + { + $field = $this->createMockField('foo'); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(new PropertyPath('foo'))); + $field->expects($this->never()) + ->method('addError'); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('bar'), FieldGroup::DATA_ERROR); + } + + public function testAddErrorKeepsDataValidationErrorsIfFieldIsHidden() + { + $field = $this->createMockField('firstName'); + $field->expects($this->any()) + ->method('isHidden') + ->will($this->returnValue(true)); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(new PropertyPath('firstName'))); + $field->expects($this->never()) + ->method('addError'); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('firstName'), FieldGroup::DATA_ERROR); + } + + public function testAddErrorMapsDataValidationErrorsOntoNestedFields() + { + // path is expected to point at "street" + $expectedPath = new PropertyPath('address.street'); + $expectedPath->next(); + + $field = $this->createMockField('address'); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(new PropertyPath('address'))); + $field->expects($this->once()) + ->method('addError') + ->with($this->equalTo('Message'), $this->equalTo($expectedPath), $this->equalTo(FieldGroup::DATA_ERROR)); + + $group = new FieldGroup('author'); + $group->add($field); + + $group->addError('Message', new PropertyPath('address.street'), FieldGroup::DATA_ERROR); + } + + public function testAddErrorMapsErrorsOntoFieldsInAnonymousGroups() + { + // path is expected to point at "address" + $expectedPath = new PropertyPath('address'); + + $field = $this->createMockField('address'); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(new PropertyPath('address'))); + $field->expects($this->once()) + ->method('addError') + ->with($this->equalTo('Message'), $this->equalTo($expectedPath), $this->equalTo(FieldGroup::DATA_ERROR)); + + $group = new FieldGroup('author'); + $group2 = new FieldGroup('anonymous', array('property_path' => null)); + $group2->add($field); + $group->add($group2); + + $group->addError('Message', new PropertyPath('address'), FieldGroup::DATA_ERROR); + } + + public function testAddThrowsExceptionIfAlreadyBound() + { + $group = new FieldGroup('author'); + $group->add($this->createMockField('firstName')); + $group->bind(array('firstName' => 'Bernhard')); + + $this->setExpectedException('Symfony\Components\Form\Exception\AlreadyBoundException'); + $group->add($this->createMockField('lastName')); + } + + public function testAddSetsFieldParent() + { + $group = new FieldGroup('author'); + + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('setParent'); + // PHPUnit fails to compare infinitely recursive objects + //->with($this->equalTo($group)); + + $group->add($field); + } + + public function testRemoveUnsetsFieldParent() + { + $group = new FieldGroup('author'); + + $field = $this->createMockField('firstName'); + $field->expects($this->exactly(2)) + ->method('setParent'); + // PHPUnit fails to compare subsequent method calls with different arguments + + $group->add($field); + $group->remove('firstName'); + } + + public function testMergeAddsFieldsFromAnotherGroup() + { + $group1 = new FieldGroup('author'); + $group1->add($field1 = new TestField('firstName')); + + $group2 = new FieldGroup('publisher'); + $group2->add($field2 = new TestField('lastName')); + + $group1->merge($group2); + + $this->assertTrue($group1->has('lastName')); + $this->assertEquals(new PropertyPath('publisher.lastName'), $group1->get('lastName')->getPropertyPath()); + } + + public function testMergeThrowsExceptionIfOtherGroupAlreadyBound() + { + $group1 = new FieldGroup('author'); + $group2 = new FieldGroup('publisher'); + $group2->add($this->createMockField('firstName')); + + $group2->bind(array('firstName' => 'Bernhard')); + + $this->setExpectedException('Symfony\Components\Form\Exception\AlreadyBoundException'); + $group1->merge($group2); + } + + public function testAddUpdatesFieldFromTransformedData() + { + $originalAuthor = new Author(); + $transformedAuthor = new Author(); + // the authors should differ to make sure the test works + $transformedAuthor->firstName = 'Foo'; + + $group = new FieldGroup('author'); + + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('transform') + ->with($this->equalTo($originalAuthor)) + ->will($this->returnValue($transformedAuthor)); + + $group->setValueTransformer($transformer); + $group->setData($originalAuthor); + + $field = $this->createMockField('firstName'); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(new PropertyPath('firstName'))); + $field->expects($this->once()) + ->method('updateFromObject') + ->with($this->equalTo($transformedAuthor)); + + $group->add($field); + } + + public function testAddDoesNotUpdateFieldsWithEmptyPropertyPath() + { + $group = new FieldGroup('author'); + $group->setData(new Author()); - $field = $this->createMockField('firstName'); - $field->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue(null)); - $field->expects($this->never()) - ->method('updateFromObject'); + $field = $this->createMockField('firstName'); + $field->expects($this->any()) + ->method('getPropertyPath') + ->will($this->returnValue(null)); + $field->expects($this->never()) + ->method('updateFromObject'); - $group->add($field); - } + $group->add($field); + } - public function testAddDoesNotUpdateFieldIfTransformedDataIsEmpty() - { - $originalAuthor = new Author(); + public function testAddDoesNotUpdateFieldIfTransformedDataIsEmpty() + { + $originalAuthor = new Author(); - $group = new FieldGroup('author'); - - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('transform') - ->with($this->equalTo($originalAuthor)) - ->will($this->returnValue('')); - - $group->setValueTransformer($transformer); - $group->setData($originalAuthor); - - $field = $this->createMockField('firstName'); - $field->expects($this->never()) - ->method('updateFromObject'); - - $group->add($field); - } - - public function testSetDataUpdatesAllFieldsFromTransformedData() - { - $originalAuthor = new Author(); - $transformedAuthor = new Author(); - // the authors should differ to make sure the test works - $transformedAuthor->firstName = 'Foo'; - - $group = new FieldGroup('author'); - - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('transform') - ->with($this->equalTo($originalAuthor)) - ->will($this->returnValue($transformedAuthor)); - - $group->setValueTransformer($transformer); - - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('updateFromObject') - ->with($this->equalTo($transformedAuthor)); - - $group->add($field); - - $field = $this->createMockField('lastName'); - $field->expects($this->once()) - ->method('updateFromObject') - ->with($this->equalTo($transformedAuthor)); - - $group->add($field); - - $group->setData($originalAuthor); - } - - public function testSetDataThrowsAnExceptionIfArgumentIsNotObjectOrArray() - { - $group = new FieldGroup('author'); - - $this->setExpectedException('InvalidArgumentException'); + $group = new FieldGroup('author'); + + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('transform') + ->with($this->equalTo($originalAuthor)) + ->will($this->returnValue('')); + + $group->setValueTransformer($transformer); + $group->setData($originalAuthor); + + $field = $this->createMockField('firstName'); + $field->expects($this->never()) + ->method('updateFromObject'); + + $group->add($field); + } + + public function testSetDataUpdatesAllFieldsFromTransformedData() + { + $originalAuthor = new Author(); + $transformedAuthor = new Author(); + // the authors should differ to make sure the test works + $transformedAuthor->firstName = 'Foo'; + + $group = new FieldGroup('author'); + + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('transform') + ->with($this->equalTo($originalAuthor)) + ->will($this->returnValue($transformedAuthor)); + + $group->setValueTransformer($transformer); + + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('updateFromObject') + ->with($this->equalTo($transformedAuthor)); + + $group->add($field); + + $field = $this->createMockField('lastName'); + $field->expects($this->once()) + ->method('updateFromObject') + ->with($this->equalTo($transformedAuthor)); + + $group->add($field); + + $group->setData($originalAuthor); + } + + public function testSetDataThrowsAnExceptionIfArgumentIsNotObjectOrArray() + { + $group = new FieldGroup('author'); + + $this->setExpectedException('InvalidArgumentException'); - $group->setData('foobar'); - } - - public function testBindUpdatesTransformedDataFromAllFields() - { - $originalAuthor = new Author(); - $transformedAuthor = new Author(); - // the authors should differ to make sure the test works - $transformedAuthor->firstName = 'Foo'; + $group->setData('foobar'); + } + + public function testBindUpdatesTransformedDataFromAllFields() + { + $originalAuthor = new Author(); + $transformedAuthor = new Author(); + // the authors should differ to make sure the test works + $transformedAuthor->firstName = 'Foo'; - $group = new FieldGroup('author'); + $group = new FieldGroup('author'); - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('transform') - ->with($this->equalTo($originalAuthor)) - ->will($this->returnValue($transformedAuthor)); + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('transform') + ->with($this->equalTo($originalAuthor)) + ->will($this->returnValue($transformedAuthor)); - $group->setValueTransformer($transformer); - $group->setData($originalAuthor); + $group->setValueTransformer($transformer); + $group->setData($originalAuthor); - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('updateObject') - ->with($this->equalTo($transformedAuthor)); + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('updateObject') + ->with($this->equalTo($transformedAuthor)); - $group->add($field); + $group->add($field); - $field = $this->createMockField('lastName'); - $field->expects($this->once()) - ->method('updateObject') - ->with($this->equalTo($transformedAuthor)); - - $group->add($field); + $field = $this->createMockField('lastName'); + $field->expects($this->once()) + ->method('updateObject') + ->with($this->equalTo($transformedAuthor)); + + $group->add($field); - $group->bind(array()); // irrelevant - } - - public function testGetDataReturnsObject() - { - $group = new FieldGroup('author'); - $object = new \stdClass(); - $group->setData($object); - $this->assertEquals($object, $group->getData()); - } - - public function testGetDisplayedDataForwardsCall() - { - $field = $this->createValidMockField('firstName'); - $field->expects($this->atLeastOnce()) - ->method('getDisplayedData') - ->will($this->returnValue('Bernhard')); - - $group = new FieldGroup('author'); - $group->add($field); - - $this->assertEquals(array('firstName' => 'Bernhard'), $group->getDisplayedData()); - } - - public function testIsMultipartIfAnyFieldIsMultipart() - { - $group = new FieldGroup('author'); - $group->add($this->createMultipartMockField('firstName')); - $group->add($this->createNonMultipartMockField('lastName')); - - $this->assertTrue($group->isMultipart()); - } - - public function testIsNotMultipartIfNoFieldIsMultipart() - { - $group = new FieldGroup('author'); - $group->add($this->createNonMultipartMockField('firstName')); - $group->add($this->createNonMultipartMockField('lastName')); - - $this->assertFalse($group->isMultipart()); - } - - public function testRenderForwardsToRenderer() - { - $group = new FieldGroup('author'); - - $renderer = $this->createMockRenderer(); - $renderer->expects($this->once()) - ->method('render') - ->with($this->equalTo($group), $this->equalTo(array('foo' => 'bar'))) - ->will($this->returnValue('HTML')); - - $group->setRenderer($renderer); - - // test - $output = $group->render(array('foo' => 'bar')); - - $this->assertEquals('HTML', $output); - } - - public function testRenderErrorsForwardsToRenderer() - { - $group = new FieldGroup('author'); - - $renderer = $this->createMockRenderer(); - $renderer->expects($this->once()) - ->method('renderErrors') - ->with($this->equalTo($group)) - ->will($this->returnValue('HTML')); - - $group->setRenderer($renderer); - - // test - $output = $group->renderErrors(); - - $this->assertEquals('HTML', $output); - } - - public function testLocaleIsPassedToRenderer() - { - $renderer = $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); - $renderer->expects($this->once()) - ->method('setLocale') - ->with($this->equalTo('de_DE')); - - $group = new FieldGroup('author'); - $group->setRenderer($renderer); - $group->setLocale('de_DE'); - $group->render(); - } - - public function testTranslatorIsPassedToRenderer() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - $renderer = $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); - $renderer->expects($this->once()) - ->method('setTranslator') - ->with($this->equalTo($translator)); - - $group = new FieldGroup('author'); - $group->setRenderer($renderer); - $group->setTranslator($translator); - $group->render(); - } - - public function testTranslatorIsNotPassedToRendererIfNotSet() - { - $renderer = $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); - $renderer->expects($this->never()) - ->method('setTranslator'); - - $group = new FieldGroup('author'); - $group->setRenderer($renderer); - $group->render(); - } - - public function testLocaleIsPassedToField_SetBeforeAddingTheField() - { - $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); - $field->expects($this->once()) - ->method('setLocale') - ->with($this->equalTo('de_DE')); - - $group = new FieldGroup('author'); - $group->setLocale('de_DE'); - $group->add($field); - } - - public function testLocaleIsPassedToField_SetAfterAddingTheField() - { - $field = $this->getMockForAbstractClass(__NAMESPACE__ . '\FieldGroupTest_Field', array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); + $group->bind(array()); // irrelevant + } + + public function testGetDataReturnsObject() + { + $group = new FieldGroup('author'); + $object = new \stdClass(); + $group->setData($object); + $this->assertEquals($object, $group->getData()); + } + + public function testGetDisplayedDataForwardsCall() + { + $field = $this->createValidMockField('firstName'); + $field->expects($this->atLeastOnce()) + ->method('getDisplayedData') + ->will($this->returnValue('Bernhard')); + + $group = new FieldGroup('author'); + $group->add($field); + + $this->assertEquals(array('firstName' => 'Bernhard'), $group->getDisplayedData()); + } + + public function testIsMultipartIfAnyFieldIsMultipart() + { + $group = new FieldGroup('author'); + $group->add($this->createMultipartMockField('firstName')); + $group->add($this->createNonMultipartMockField('lastName')); + + $this->assertTrue($group->isMultipart()); + } + + public function testIsNotMultipartIfNoFieldIsMultipart() + { + $group = new FieldGroup('author'); + $group->add($this->createNonMultipartMockField('firstName')); + $group->add($this->createNonMultipartMockField('lastName')); + + $this->assertFalse($group->isMultipart()); + } + + public function testRenderForwardsToRenderer() + { + $group = new FieldGroup('author'); + + $renderer = $this->createMockRenderer(); + $renderer->expects($this->once()) + ->method('render') + ->with($this->equalTo($group), $this->equalTo(array('foo' => 'bar'))) + ->will($this->returnValue('HTML')); + + $group->setRenderer($renderer); + + // test + $output = $group->render(array('foo' => 'bar')); + + $this->assertEquals('HTML', $output); + } + + public function testRenderErrorsForwardsToRenderer() + { + $group = new FieldGroup('author'); + + $renderer = $this->createMockRenderer(); + $renderer->expects($this->once()) + ->method('renderErrors') + ->with($this->equalTo($group)) + ->will($this->returnValue('HTML')); + + $group->setRenderer($renderer); + + // test + $output = $group->renderErrors(); + + $this->assertEquals('HTML', $output); + } + + public function testLocaleIsPassedToRenderer() + { + $renderer = $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); + $renderer->expects($this->once()) + ->method('setLocale') + ->with($this->equalTo('de_DE')); + + $group = new FieldGroup('author'); + $group->setRenderer($renderer); + $group->setLocale('de_DE'); + $group->render(); + } + + public function testTranslatorIsPassedToRenderer() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + $renderer = $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); + $renderer->expects($this->once()) + ->method('setTranslator') + ->with($this->equalTo($translator)); + + $group = new FieldGroup('author'); + $group->setRenderer($renderer); + $group->setTranslator($translator); + $group->render(); + } + + public function testTranslatorIsNotPassedToRendererIfNotSet() + { + $renderer = $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); + $renderer->expects($this->never()) + ->method('setTranslator'); + + $group = new FieldGroup('author'); + $group->setRenderer($renderer); + $group->render(); + } + + public function testLocaleIsPassedToField_SetBeforeAddingTheField() + { + $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); + $field->expects($this->once()) + ->method('setLocale') + ->with($this->equalTo('de_DE')); + + $group = new FieldGroup('author'); + $group->setLocale('de_DE'); + $group->add($field); + } + + public function testLocaleIsPassedToField_SetAfterAddingTheField() + { + $field = $this->getMockForAbstractClass(__NAMESPACE__ . '\FieldGroupTest_Field', array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); // DOESN'T WORK! // $field = $this->getMock(__NAMESPACE__ . '\Fixtures\Field', array(), array(), '', false, false); // $field->expects($this->once()) @@ -630,176 +630,176 @@ class FieldGroupTest extends \PHPUnit_Framework_TestCase // ->method('setLocale') // ->with($this->equalTo('de_DE')); - $group = new FieldGroup('author'); - $group->add($field); - $group->setLocale('de_DE'); + $group = new FieldGroup('author'); + $group->add($field); + $group->setLocale('de_DE'); - $this->assertEquals(array(\Locale::getDefault(), 'de_DE'), $field->locales); - } + $this->assertEquals(array(\Locale::getDefault(), 'de_DE'), $field->locales); + } - public function testTranslatorIsPassedToField_SetBeforeAddingTheField() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); - $field->expects($this->once()) - ->method('setTranslator') - ->with($this->equalTo($translator)); + public function testTranslatorIsPassedToField_SetBeforeAddingTheField() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); + $field->expects($this->once()) + ->method('setTranslator') + ->with($this->equalTo($translator)); - $group = new FieldGroup('author'); - $group->setTranslator($translator); - $group->add($field); - } + $group = new FieldGroup('author'); + $group->setTranslator($translator); + $group->add($field); + } - public function testTranslatorIsPassedToField_SetAfterAddingTheField() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); - $field->expects($this->once()) - ->method('setTranslator') - ->with($this->equalTo($translator)); + public function testTranslatorIsPassedToField_SetAfterAddingTheField() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); + $field->expects($this->once()) + ->method('setTranslator') + ->with($this->equalTo($translator)); - $group = new FieldGroup('author'); - $group->add($field); - $group->setTranslator($translator); - } + $group = new FieldGroup('author'); + $group->add($field); + $group->setTranslator($translator); + } - public function testTranslatorIsNotPassedToFieldIfNotSet() - { - $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); - $field->expects($this->never()) - ->method('setTranslator'); + public function testTranslatorIsNotPassedToFieldIfNotSet() + { + $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); + $field->expects($this->never()) + ->method('setTranslator'); - $group = new FieldGroup('author'); - $group->add($field); - } + $group = new FieldGroup('author'); + $group->add($field); + } - public function testSupportsClone() - { - $group = new FieldGroup('author'); - $group->add($this->createMockField('firstName')); + public function testSupportsClone() + { + $group = new FieldGroup('author'); + $group->add($this->createMockField('firstName')); - $clone = clone $group; + $clone = clone $group; - $this->assertNotSame($clone['firstName'], $group['firstName']); - } + $this->assertNotSame($clone['firstName'], $group['firstName']); + } - public function testBindWithoutPriorSetData() - { - return; // TODO - $field = $this->createMockField('firstName'); - $field->expects($this->any()) - ->method('getData') - ->will($this->returnValue('Bernhard')); + public function testBindWithoutPriorSetData() + { + return; // TODO + $field = $this->createMockField('firstName'); + $field->expects($this->any()) + ->method('getData') + ->will($this->returnValue('Bernhard')); - $group = new FieldGroup('author'); - $group->add($field); + $group = new FieldGroup('author'); + $group->add($field); - $group->bind(array('firstName' => 'Bernhard')); + $group->bind(array('firstName' => 'Bernhard')); - $this->assertEquals(array('firstName' => 'Bernhard'), $group->getData()); - } + $this->assertEquals(array('firstName' => 'Bernhard'), $group->getData()); + } - public function testSetGenerator_calledBeforeAdding() - { - $generator = $this->getMock('Symfony\Components\Form\HtmlGeneratorInterface'); + public function testSetGenerator_calledBeforeAdding() + { + $generator = $this->getMock('Symfony\Components\Form\HtmlGeneratorInterface'); - $field = $this->createMockField('firstName'); - $field->expects($this->once()) - ->method('setGenerator') - ->with($this->equalTo($generator)); + $field = $this->createMockField('firstName'); + $field->expects($this->once()) + ->method('setGenerator') + ->with($this->equalTo($generator)); - $group = new FieldGroup('author'); - $group->setGenerator($generator); - $group->add($field); - } + $group = new FieldGroup('author'); + $group->setGenerator($generator); + $group->add($field); + } - public function testSetGenerator_calledAfterAdding() - { - $generator = $this->getMock('Symfony\Components\Form\HtmlGeneratorInterface'); + public function testSetGenerator_calledAfterAdding() + { + $generator = $this->getMock('Symfony\Components\Form\HtmlGeneratorInterface'); - $field = $this->createMockField('firstName'); - $field->expects($this->exactly(2)) // cannot test different arguments :( - ->method('setGenerator'); + $field = $this->createMockField('firstName'); + $field->expects($this->exactly(2)) // cannot test different arguments :( + ->method('setGenerator'); - $group = new FieldGroup('author'); - $group->add($field); - $group->setGenerator($generator); - } + $group = new FieldGroup('author'); + $group->add($field); + $group->setGenerator($generator); + } - protected function createMockField($key) - { - $field = $this->getMock( - 'Symfony\Components\Form\FieldInterface', - array(), - array(), - '', - false, // don't use constructor - false // don't call parent::__clone - ); + protected function createMockField($key) + { + $field = $this->getMock( + 'Symfony\Components\Form\FieldInterface', + array(), + array(), + '', + false, // don't use constructor + false // don't call parent::__clone + ); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue($key)); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue($key)); - return $field; - } + return $field; + } - protected function createInvalidMockField($key) - { - $field = $this->createMockField($key); - $field->expects($this->any()) - ->method('isValid') - ->will($this->returnValue(false)); + protected function createInvalidMockField($key) + { + $field = $this->createMockField($key); + $field->expects($this->any()) + ->method('isValid') + ->will($this->returnValue(false)); - return $field; - } + return $field; + } - protected function createValidMockField($key) - { - $field = $this->createMockField($key); - $field->expects($this->any()) - ->method('isValid') - ->will($this->returnValue(true)); + protected function createValidMockField($key) + { + $field = $this->createMockField($key); + $field->expects($this->any()) + ->method('isValid') + ->will($this->returnValue(true)); - return $field; - } + return $field; + } - protected function createNonMultipartMockField($key) - { - $field = $this->createMockField($key); - $field->expects($this->any()) - ->method('isMultipart') - ->will($this->returnValue(false)); + protected function createNonMultipartMockField($key) + { + $field = $this->createMockField($key); + $field->expects($this->any()) + ->method('isMultipart') + ->will($this->returnValue(false)); - return $field; - } + return $field; + } - protected function createMultipartMockField($key) - { - $field = $this->createMockField($key); - $field->expects($this->any()) - ->method('isMultipart') - ->will($this->returnValue(true)); + protected function createMultipartMockField($key) + { + $field = $this->createMockField($key); + $field->expects($this->any()) + ->method('isMultipart') + ->will($this->returnValue(true)); - return $field; - } + return $field; + } - protected function createMockRenderer() - { - return $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); - } + protected function createMockRenderer() + { + return $this->getMock('Symfony\Components\Form\Renderer\RendererInterface'); + } - protected function createMockTransformer() - { - return $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false); - } + protected function createMockTransformer() + { + return $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false); + } } diff --git a/tests/Symfony/Tests/Components/Form/FieldTest.php b/tests/Symfony/Tests/Components/Form/FieldTest.php index 618d98961c..796f907609 100644 --- a/tests/Symfony/Tests/Components/Form/FieldTest.php +++ b/tests/Symfony/Tests/Components/Form/FieldTest.php @@ -16,651 +16,651 @@ use Symfony\Tests\Components\Form\Fixtures\RequiredOptionsField; class FieldTest extends \PHPUnit_Framework_TestCase { - protected $field; + protected $field; - protected function setUp() - { - $this->field = new TestField('title'); - } + protected function setUp() + { + $this->field = new TestField('title'); + } - public function testPassRequiredAsOption() - { - $field = new TestField('title', array('required' => false)); + public function testPassRequiredAsOption() + { + $field = new TestField('title', array('required' => false)); - $this->assertFalse($field->isRequired()); + $this->assertFalse($field->isRequired()); - $field = new TestField('title', array('required' => true)); + $field = new TestField('title', array('required' => true)); - $this->assertTrue($field->isRequired()); - } + $this->assertTrue($field->isRequired()); + } - public function testPassDisabledAsOption() - { - $field = new TestField('title', array('disabled' => false)); + public function testPassDisabledAsOption() + { + $field = new TestField('title', array('disabled' => false)); - $this->assertFalse($field->isDisabled()); + $this->assertFalse($field->isDisabled()); - $field = new TestField('title', array('disabled' => true)); + $field = new TestField('title', array('disabled' => true)); - $this->assertTrue($field->isDisabled()); - } + $this->assertTrue($field->isDisabled()); + } - public function testFieldIsDisabledIfParentIsDisabled() - { - $field = new TestField('title', array('disabled' => false)); - $field->setParent(new TestField('title', array('disabled' => true))); + public function testFieldIsDisabledIfParentIsDisabled() + { + $field = new TestField('title', array('disabled' => false)); + $field->setParent(new TestField('title', array('disabled' => true))); - $this->assertTrue($field->isDisabled()); - } + $this->assertTrue($field->isDisabled()); + } - public function testFieldWithNoErrorsIsValid() - { - $this->field->bind('data'); + public function testFieldWithNoErrorsIsValid() + { + $this->field->bind('data'); - $this->assertTrue($this->field->isValid()); - } + $this->assertTrue($this->field->isValid()); + } - public function testFieldWithErrorsIsInvalid() - { - $this->field->bind('data'); - $this->field->addError('Some error'); + public function testFieldWithErrorsIsInvalid() + { + $this->field->bind('data'); + $this->field->addError('Some error'); - $this->assertFalse($this->field->isValid()); - } + $this->assertFalse($this->field->isValid()); + } - public function testBindResetsErrors() - { - $this->field->addError('Some error'); - $this->field->bind('data'); + public function testBindResetsErrors() + { + $this->field->addError('Some error'); + $this->field->bind('data'); - $this->assertTrue($this->field->isValid()); - } + $this->assertTrue($this->field->isValid()); + } - public function testUnboundFieldIsInvalid() - { - $this->assertFalse($this->field->isValid()); - } + public function testUnboundFieldIsInvalid() + { + $this->assertFalse($this->field->isValid()); + } - public function testGetNameReturnsKey() - { - $this->assertEquals('title', $this->field->getName()); - } + public function testGetNameReturnsKey() + { + $this->assertEquals('title', $this->field->getName()); + } - public function testGetNameIncludesParent() - { - $this->field->setParent($this->createMockGroupWithName('news[article]')); + public function testGetNameIncludesParent() + { + $this->field->setParent($this->createMockGroupWithName('news[article]')); - $this->assertEquals('news[article][title]', $this->field->getName()); - } + $this->assertEquals('news[article][title]', $this->field->getName()); + } - public function testGetIdReturnsKey() - { - $this->assertEquals('title', $this->field->getId()); - } + public function testGetIdReturnsKey() + { + $this->assertEquals('title', $this->field->getId()); + } - public function testGetIdIncludesParent() - { - $this->field->setParent($this->createMockGroupWithId('news_article')); + public function testGetIdIncludesParent() + { + $this->field->setParent($this->createMockGroupWithId('news_article')); - $this->assertEquals('news_article_title', $this->field->getId()); - } + $this->assertEquals('news_article_title', $this->field->getId()); + } - public function testLocaleIsPassedToLocalizableValueTransformer_setLocaleCalledBefore() - { - $transformer = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer->expects($this->once()) - ->method('setLocale') - ->with($this->equalTo('de_DE')); + public function testLocaleIsPassedToLocalizableValueTransformer_setLocaleCalledBefore() + { + $transformer = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer->expects($this->once()) + ->method('setLocale') + ->with($this->equalTo('de_DE')); - $this->field->setLocale('de_DE'); - $this->field->setValueTransformer($transformer); - } + $this->field->setLocale('de_DE'); + $this->field->setValueTransformer($transformer); + } - public function testLocaleIsPassedToValueTransformer_setLocaleCalledAfter() - { - $transformer = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer->expects($this->exactly(2)) - ->method('setLocale'); // we can't test the params cause they differ :( - - $this->field->setValueTransformer($transformer); - $this->field->setLocale('de_DE'); - } - - public function testIsRequiredReturnsOwnValueIfNoParent() - { - $this->field->setRequired(true); - $this->assertTrue($this->field->isRequired()); - - $this->field->setRequired(false); - $this->assertFalse($this->field->isRequired()); - } - - public function testIsRequiredReturnsOwnValueIfParentIsRequired() - { - $group = $this->createMockGroup(); - $group->expects($this->any()) - ->method('isRequired') - ->will($this->returnValue(true)); - - $this->field->setParent($group); - - $this->field->setRequired(true); - $this->assertTrue($this->field->isRequired()); - - $this->field->setRequired(false); - $this->assertFalse($this->field->isRequired()); - } - - public function testIsRequiredReturnsFalseIfParentIsNotRequired() - { - $group = $this->createMockGroup(); - $group->expects($this->any()) - ->method('isRequired') - ->will($this->returnValue(false)); - - $this->field->setParent($group); - $this->field->setRequired(true); - - $this->assertFalse($this->field->isRequired()); - } - - public function testExceptionIfUnknownOption() - { - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidOptionsException'); - - new RequiredOptionsField('name', array('bar' => 'baz', 'moo' => 'maa')); - } - - public function testExceptionIfMissingOption() - { - $this->setExpectedException('Symfony\Components\Form\Exception\MissingOptionsException'); - - new RequiredOptionsField('name'); - } - - public function testIsBound() - { - $this->assertFalse($this->field->isBound()); - $this->field->bind('symfony'); - $this->assertTrue($this->field->isBound()); - } - - public function testDefaultValuesAreTransformedCorrectly() - { - $field = new TestField('name'); - - $this->assertEquals(null, $this->field->getData()); - $this->assertEquals('', $this->field->getDisplayedData()); - } - - public function testValuesAreTransformedCorrectlyIfNull() - { - // The value is converted to an empty string and NOT passed to the - // value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->never()) - ->method('transform'); - - $this->field->setValueTransformer($transformer); - $this->field->setData(null); - - $this->assertSame(null, $this->field->getData()); - $this->assertSame('', $this->field->getDisplayedData()); - } - - public function testValuesAreTransformedCorrectlyIfNull_noValueTransformer() - { - $this->field->setData(null); - - $this->assertSame(null, $this->field->getData()); - $this->assertSame('', $this->field->getDisplayedData()); - } - - public function testBoundValuesAreTransformedCorrectly() - { - $field = $this->getMock( - 'Symfony\Tests\Components\Form\Fixtures\TestField', - array('processData'), // only mock processData() - array('title') - ); - - // 1. The value is converted to a string and passed to the value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo('0')) - ->will($this->returnValue('reverse[0]')); - - $field->setValueTransformer($transformer); - - // 2. The output of the reverse transformation is passed to processData() - $field->expects($this->once()) - ->method('processData') - ->with($this->equalTo('reverse[0]')) - ->will($this->returnValue('processed[reverse[0]]')); - - // 3. The processed data is transformed again (for displayed data) - $transformer->expects($this->once()) - ->method('transform') - ->with($this->equalTo('processed[reverse[0]]')) - ->will($this->returnValue('transform[processed[reverse[0]]]')); - - $field->bind(0); - - $this->assertEquals('processed[reverse[0]]', $field->getData()); - $this->assertEquals('transform[processed[reverse[0]]]', $field->getDisplayedData()); - } - - public function testBoundValuesAreTransformedCorrectlyIfEmpty_processDataReturnsValue() - { - $field = $this->getMock( - 'Symfony\Tests\Components\Form\Fixtures\TestField', - array('processData'), // only mock processData() - array('title') - ); - - // 1. Empty values are always converted to NULL. They are never passed to - // the value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->never()) - ->method('reverseTransform'); - - $field->setValueTransformer($transformer); - - // 2. NULL is passed to processData() - $field->expects($this->once()) - ->method('processData') - ->with($this->identicalTo(null)) - ->will($this->returnValue('processed')); - - // 3. The processed data is transformed (for displayed data) - $transformer->expects($this->once()) - ->method('transform') - ->with($this->equalTo('processed')) - ->will($this->returnValue('transform[processed]')); - - $field->bind(''); - - $this->assertSame('processed', $field->getData()); - $this->assertEquals('transform[processed]', $field->getDisplayedData()); - } - - public function testBoundValuesAreTransformedCorrectlyIfEmpty_processDataReturnsNull() - { - // 1. Empty values are always converted to NULL. They are never passed to - // the value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->never()) - ->method('reverseTransform'); - - $this->field->setValueTransformer($transformer); - - // 2. The processed data is NULL and therefore transformed to an empty - // string. It is NOT passed to the value transformer - $transformer->expects($this->never()) - ->method('transform'); - - $this->field->bind(''); - - $this->assertSame(null, $this->field->getData()); - $this->assertEquals('', $this->field->getDisplayedData()); - } - - public function testBoundValuesAreTransformedCorrectlyIfEmpty_processDataReturnsNull_noValueTransformer() - { - $this->field->bind(''); - - $this->assertSame(null, $this->field->getData()); - $this->assertEquals('', $this->field->getDisplayedData()); - } - - public function testValuesAreTransformedCorrectly() - { - // The value is passed to the value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('transform') - ->with($this->identicalTo(0)) - ->will($this->returnValue('transform[0]')); - - $this->field->setValueTransformer($transformer); - $this->field->setData(0); - - $this->assertEquals(0, $this->field->getData()); - $this->assertEquals('transform[0]', $this->field->getDisplayedData()); - } - - public function testBoundValuesAreTrimmedBeforeTransforming() - { - // The value is passed to the value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo('a')) - ->will($this->returnValue('reverse[a]')); - - $transformer->expects($this->once()) - ->method('transform') - ->with($this->identicalTo('reverse[a]')) - ->will($this->returnValue('a')); - - $this->field->setValueTransformer($transformer); - $this->field->bind(' a '); - - $this->assertEquals('a', $this->field->getDisplayedData()); - $this->assertEquals('reverse[a]', $this->field->getData()); - } - - public function testBoundValuesAreNotTrimmedBeforeTransformingIfDisabled() - { - // The value is passed to the value transformer - $transformer = $this->createMockTransformer(); - $transformer->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo(' a ')) - ->will($this->returnValue('reverse[ a ]')); - - $transformer->expects($this->once()) - ->method('transform') - ->with($this->identicalTo('reverse[ a ]')) - ->will($this->returnValue(' a ')); - - $field = new TestField('title', array('trim' => false)); - $field->setValueTransformer($transformer); - $field->bind(' a '); - - $this->assertEquals(' a ', $field->getDisplayedData()); - $this->assertEquals('reverse[ a ]', $field->getData()); - } - - public function testUpdateFromObjectReadsArray() - { - $array = array('firstName' => 'Bernhard'); - - $field = new TestField('firstName'); - $field->updateFromObject($array); - - $this->assertEquals('Bernhard', $field->getData()); - } - - public function testUpdateFromObjectReadsArrayWithCustomPropertyPath() - { - $array = array('child' => array('index' => array('firstName' => 'Bernhard'))); - - $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); - $field->updateFromObject($array); - - $this->assertEquals('Bernhard', $field->getData()); - } - - public function testUpdateFromObjectReadsProperty() - { - $object = new Author(); - $object->firstName = 'Bernhard'; - - $field = new TestField('firstName'); - $field->updateFromObject($object); - - $this->assertEquals('Bernhard', $field->getData()); - } - - public function testUpdateFromObjectReadsPropertyWithCustomPropertyPath() - { - $object = new Author(); - $object->child = array(); - $object->child['index'] = new Author(); - $object->child['index']->firstName = 'Bernhard'; - - $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); - $field->updateFromObject($object); - - $this->assertEquals('Bernhard', $field->getData()); - } - - public function testUpdateFromObjectReadsArrayAccess() - { - $object = new \ArrayObject(); - $object['firstName'] = 'Bernhard'; - - $field = new TestField('firstName', array('property_path' => '[firstName]')); - $field->updateFromObject($object); - - $this->assertEquals('Bernhard', $field->getData()); - } - - public function testUpdateFromObjectThrowsExceptionIfArrayAccessExpected() - { - $field = new TestField('firstName', array('property_path' => '[firstName]')); - - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyException'); - $field->updateFromObject(new Author()); - } - - /* - * The use case of this test is a field group with an empty property path. - * Even if the field group itself is not associated to a specific property, - * nested fields might be. - */ - public function testUpdateFromObjectPassesObjectThroughIfPropertyPathIsEmpty() - { - $object = new Author(); - $object->firstName = 'Bernhard'; - - $field = new TestField('firstName', array('property_path' => null)); - $field->updateFromObject($object); - - $this->assertEquals($object, $field->getData()); - } - - public function testUpdateFromObjectThrowsExceptionIfPropertyIsNotPublic() - { - $field = new TestField('privateProperty'); + public function testLocaleIsPassedToValueTransformer_setLocaleCalledAfter() + { + $transformer = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer->expects($this->exactly(2)) + ->method('setLocale'); // we can't test the params cause they differ :( + + $this->field->setValueTransformer($transformer); + $this->field->setLocale('de_DE'); + } + + public function testIsRequiredReturnsOwnValueIfNoParent() + { + $this->field->setRequired(true); + $this->assertTrue($this->field->isRequired()); + + $this->field->setRequired(false); + $this->assertFalse($this->field->isRequired()); + } + + public function testIsRequiredReturnsOwnValueIfParentIsRequired() + { + $group = $this->createMockGroup(); + $group->expects($this->any()) + ->method('isRequired') + ->will($this->returnValue(true)); + + $this->field->setParent($group); + + $this->field->setRequired(true); + $this->assertTrue($this->field->isRequired()); + + $this->field->setRequired(false); + $this->assertFalse($this->field->isRequired()); + } + + public function testIsRequiredReturnsFalseIfParentIsNotRequired() + { + $group = $this->createMockGroup(); + $group->expects($this->any()) + ->method('isRequired') + ->will($this->returnValue(false)); + + $this->field->setParent($group); + $this->field->setRequired(true); + + $this->assertFalse($this->field->isRequired()); + } + + public function testExceptionIfUnknownOption() + { + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidOptionsException'); + + new RequiredOptionsField('name', array('bar' => 'baz', 'moo' => 'maa')); + } + + public function testExceptionIfMissingOption() + { + $this->setExpectedException('Symfony\Components\Form\Exception\MissingOptionsException'); + + new RequiredOptionsField('name'); + } + + public function testIsBound() + { + $this->assertFalse($this->field->isBound()); + $this->field->bind('symfony'); + $this->assertTrue($this->field->isBound()); + } + + public function testDefaultValuesAreTransformedCorrectly() + { + $field = new TestField('name'); + + $this->assertEquals(null, $this->field->getData()); + $this->assertEquals('', $this->field->getDisplayedData()); + } + + public function testValuesAreTransformedCorrectlyIfNull() + { + // The value is converted to an empty string and NOT passed to the + // value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->never()) + ->method('transform'); + + $this->field->setValueTransformer($transformer); + $this->field->setData(null); + + $this->assertSame(null, $this->field->getData()); + $this->assertSame('', $this->field->getDisplayedData()); + } + + public function testValuesAreTransformedCorrectlyIfNull_noValueTransformer() + { + $this->field->setData(null); + + $this->assertSame(null, $this->field->getData()); + $this->assertSame('', $this->field->getDisplayedData()); + } + + public function testBoundValuesAreTransformedCorrectly() + { + $field = $this->getMock( + 'Symfony\Tests\Components\Form\Fixtures\TestField', + array('processData'), // only mock processData() + array('title') + ); + + // 1. The value is converted to a string and passed to the value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('reverseTransform') + ->with($this->identicalTo('0')) + ->will($this->returnValue('reverse[0]')); + + $field->setValueTransformer($transformer); + + // 2. The output of the reverse transformation is passed to processData() + $field->expects($this->once()) + ->method('processData') + ->with($this->equalTo('reverse[0]')) + ->will($this->returnValue('processed[reverse[0]]')); + + // 3. The processed data is transformed again (for displayed data) + $transformer->expects($this->once()) + ->method('transform') + ->with($this->equalTo('processed[reverse[0]]')) + ->will($this->returnValue('transform[processed[reverse[0]]]')); + + $field->bind(0); + + $this->assertEquals('processed[reverse[0]]', $field->getData()); + $this->assertEquals('transform[processed[reverse[0]]]', $field->getDisplayedData()); + } + + public function testBoundValuesAreTransformedCorrectlyIfEmpty_processDataReturnsValue() + { + $field = $this->getMock( + 'Symfony\Tests\Components\Form\Fixtures\TestField', + array('processData'), // only mock processData() + array('title') + ); + + // 1. Empty values are always converted to NULL. They are never passed to + // the value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->never()) + ->method('reverseTransform'); + + $field->setValueTransformer($transformer); + + // 2. NULL is passed to processData() + $field->expects($this->once()) + ->method('processData') + ->with($this->identicalTo(null)) + ->will($this->returnValue('processed')); + + // 3. The processed data is transformed (for displayed data) + $transformer->expects($this->once()) + ->method('transform') + ->with($this->equalTo('processed')) + ->will($this->returnValue('transform[processed]')); + + $field->bind(''); + + $this->assertSame('processed', $field->getData()); + $this->assertEquals('transform[processed]', $field->getDisplayedData()); + } + + public function testBoundValuesAreTransformedCorrectlyIfEmpty_processDataReturnsNull() + { + // 1. Empty values are always converted to NULL. They are never passed to + // the value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->never()) + ->method('reverseTransform'); + + $this->field->setValueTransformer($transformer); + + // 2. The processed data is NULL and therefore transformed to an empty + // string. It is NOT passed to the value transformer + $transformer->expects($this->never()) + ->method('transform'); + + $this->field->bind(''); + + $this->assertSame(null, $this->field->getData()); + $this->assertEquals('', $this->field->getDisplayedData()); + } + + public function testBoundValuesAreTransformedCorrectlyIfEmpty_processDataReturnsNull_noValueTransformer() + { + $this->field->bind(''); + + $this->assertSame(null, $this->field->getData()); + $this->assertEquals('', $this->field->getDisplayedData()); + } + + public function testValuesAreTransformedCorrectly() + { + // The value is passed to the value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('transform') + ->with($this->identicalTo(0)) + ->will($this->returnValue('transform[0]')); + + $this->field->setValueTransformer($transformer); + $this->field->setData(0); + + $this->assertEquals(0, $this->field->getData()); + $this->assertEquals('transform[0]', $this->field->getDisplayedData()); + } + + public function testBoundValuesAreTrimmedBeforeTransforming() + { + // The value is passed to the value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('reverseTransform') + ->with($this->identicalTo('a')) + ->will($this->returnValue('reverse[a]')); + + $transformer->expects($this->once()) + ->method('transform') + ->with($this->identicalTo('reverse[a]')) + ->will($this->returnValue('a')); + + $this->field->setValueTransformer($transformer); + $this->field->bind(' a '); + + $this->assertEquals('a', $this->field->getDisplayedData()); + $this->assertEquals('reverse[a]', $this->field->getData()); + } + + public function testBoundValuesAreNotTrimmedBeforeTransformingIfDisabled() + { + // The value is passed to the value transformer + $transformer = $this->createMockTransformer(); + $transformer->expects($this->once()) + ->method('reverseTransform') + ->with($this->identicalTo(' a ')) + ->will($this->returnValue('reverse[ a ]')); + + $transformer->expects($this->once()) + ->method('transform') + ->with($this->identicalTo('reverse[ a ]')) + ->will($this->returnValue(' a ')); + + $field = new TestField('title', array('trim' => false)); + $field->setValueTransformer($transformer); + $field->bind(' a '); + + $this->assertEquals(' a ', $field->getDisplayedData()); + $this->assertEquals('reverse[ a ]', $field->getData()); + } + + public function testUpdateFromObjectReadsArray() + { + $array = array('firstName' => 'Bernhard'); + + $field = new TestField('firstName'); + $field->updateFromObject($array); + + $this->assertEquals('Bernhard', $field->getData()); + } + + public function testUpdateFromObjectReadsArrayWithCustomPropertyPath() + { + $array = array('child' => array('index' => array('firstName' => 'Bernhard'))); + + $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); + $field->updateFromObject($array); + + $this->assertEquals('Bernhard', $field->getData()); + } + + public function testUpdateFromObjectReadsProperty() + { + $object = new Author(); + $object->firstName = 'Bernhard'; + + $field = new TestField('firstName'); + $field->updateFromObject($object); + + $this->assertEquals('Bernhard', $field->getData()); + } + + public function testUpdateFromObjectReadsPropertyWithCustomPropertyPath() + { + $object = new Author(); + $object->child = array(); + $object->child['index'] = new Author(); + $object->child['index']->firstName = 'Bernhard'; + + $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); + $field->updateFromObject($object); + + $this->assertEquals('Bernhard', $field->getData()); + } + + public function testUpdateFromObjectReadsArrayAccess() + { + $object = new \ArrayObject(); + $object['firstName'] = 'Bernhard'; + + $field = new TestField('firstName', array('property_path' => '[firstName]')); + $field->updateFromObject($object); + + $this->assertEquals('Bernhard', $field->getData()); + } + + public function testUpdateFromObjectThrowsExceptionIfArrayAccessExpected() + { + $field = new TestField('firstName', array('property_path' => '[firstName]')); + + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyException'); + $field->updateFromObject(new Author()); + } + + /* + * The use case of this test is a field group with an empty property path. + * Even if the field group itself is not associated to a specific property, + * nested fields might be. + */ + public function testUpdateFromObjectPassesObjectThroughIfPropertyPathIsEmpty() + { + $object = new Author(); + $object->firstName = 'Bernhard'; + + $field = new TestField('firstName', array('property_path' => null)); + $field->updateFromObject($object); + + $this->assertEquals($object, $field->getData()); + } + + public function testUpdateFromObjectThrowsExceptionIfPropertyIsNotPublic() + { + $field = new TestField('privateProperty'); - $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); - $field->updateFromObject(new Author()); - } + $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); + $field->updateFromObject(new Author()); + } - public function testUpdateFromObjectReadsGetters() - { - $object = new Author(); - $object->setLastName('Schussek'); + public function testUpdateFromObjectReadsGetters() + { + $object = new Author(); + $object->setLastName('Schussek'); - $field = new TestField('lastName'); - $field->updateFromObject($object); + $field = new TestField('lastName'); + $field->updateFromObject($object); - $this->assertEquals('Schussek', $field->getData()); - } + $this->assertEquals('Schussek', $field->getData()); + } - public function testUpdateFromObjectThrowsExceptionIfGetterIsNotPublic() - { - $field = new TestField('privateGetter'); + public function testUpdateFromObjectThrowsExceptionIfGetterIsNotPublic() + { + $field = new TestField('privateGetter'); - $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); - $field->updateFromObject(new Author()); - } + $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); + $field->updateFromObject(new Author()); + } - public function testUpdateFromObjectReadsIssers() - { - $object = new Author(); - $object->setAustralian(false); + public function testUpdateFromObjectReadsIssers() + { + $object = new Author(); + $object->setAustralian(false); - $field = new TestField('australian'); - $field->updateFromObject($object); + $field = new TestField('australian'); + $field->updateFromObject($object); - $this->assertSame(false, $field->getData()); - } + $this->assertSame(false, $field->getData()); + } - public function testUpdateFromObjectThrowsExceptionIfIsserIsNotPublic() - { - $field = new TestField('privateIsser'); - - $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); - $field->updateFromObject(new Author()); - } + public function testUpdateFromObjectThrowsExceptionIfIsserIsNotPublic() + { + $field = new TestField('privateIsser'); + + $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); + $field->updateFromObject(new Author()); + } - public function testUpdateFromObjectThrowsExceptionIfPropertyDoesNotExist() - { - $field = new TestField('foobar'); + public function testUpdateFromObjectThrowsExceptionIfPropertyDoesNotExist() + { + $field = new TestField('foobar'); - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyException'); - $field->updateFromObject(new Author()); - } + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyException'); + $field->updateFromObject(new Author()); + } - public function testUpdateObjectUpdatesArrays() - { - $array = array(); + public function testUpdateObjectUpdatesArrays() + { + $array = array(); - $field = new TestField('firstName'); - $field->bind('Bernhard'); - $field->updateObject($array); + $field = new TestField('firstName'); + $field->bind('Bernhard'); + $field->updateObject($array); - $this->assertEquals(array('firstName' => 'Bernhard'), $array); - } + $this->assertEquals(array('firstName' => 'Bernhard'), $array); + } - public function testUpdateObjectUpdatesArraysWithCustomPropertyPath() - { - $array = array(); + public function testUpdateObjectUpdatesArraysWithCustomPropertyPath() + { + $array = array(); - $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); - $field->bind('Bernhard'); - $field->updateObject($array); + $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); + $field->bind('Bernhard'); + $field->updateObject($array); - $this->assertEquals(array('child' => array('index' => array('firstName' => 'Bernhard'))), $array); - } - - /* - * This is important so that bind() can work even if setData() was not called - * before - */ - public function testUpdateObjectTreatsEmptyValuesAsArrays() - { - $array = null; - - $field = new TestField('firstName'); - $field->bind('Bernhard'); - $field->updateObject($array); - - $this->assertEquals(array('firstName' => 'Bernhard'), $array); - } - - public function testUpdateObjectUpdatesProperties() - { - $object = new Author(); - - $field = new TestField('firstName'); - $field->bind('Bernhard'); - $field->updateObject($object); - - $this->assertEquals('Bernhard', $object->firstName); - } - - public function testUpdateObjectUpdatesPropertiesWithCustomPropertyPath() - { - $object = new Author(); - $object->child = array(); - $object->child['index'] = new Author(); - - $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); - $field->bind('Bernhard'); - $field->updateObject($object); - - $this->assertEquals('Bernhard', $object->child['index']->firstName); - } - - public function testUpdateObjectUpdatesArrayAccess() - { - $object = new \ArrayObject(); - - $field = new TestField('firstName', array('property_path' => '[firstName]')); - $field->bind('Bernhard'); - $field->updateObject($object); - - $this->assertEquals('Bernhard', $object['firstName']); - } - - public function testUpdateObjectThrowsExceptionIfArrayAccessExpected() - { - $field = new TestField('firstName', array('property_path' => '[firstName]')); - $field->bind('Bernhard'); - - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyException'); - $field->updateObject(new Author()); - } - - public function testUpdateObjectDoesNotUpdatePropertyIfPropertyPathIsEmpty() - { - $object = new Author(); - - $field = new TestField('firstName', array('property_path' => null)); - $field->bind('Bernhard'); - $field->updateObject($object); - - $this->assertEquals(null, $object->firstName); - } - - public function testUpdateObjectUpdatesSetters() - { - $object = new Author(); - - $field = new TestField('lastName'); - $field->bind('Schussek'); - $field->updateObject($object); - - $this->assertEquals('Schussek', $object->getLastName()); - } - - public function testUpdateObjectThrowsExceptionIfGetterIsNotPublic() - { - $field = new TestField('privateSetter'); - $field->bind('foobar'); - - $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); - $field->updateObject(new Author()); - } - - protected function createMockTransformer() - { - return $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false); - } - - protected function createMockTransformerTransformingTo($value) - { - $transformer = $this->createMockTransformer(); - $transformer->expects($this->any()) - ->method('reverseTransform') - ->will($this->returnValue($value)); - - return $transformer; - } - - protected function createMockGroup() - { - return $this->getMock( - 'Symfony\Components\Form\FieldGroup', - array(), - array(), - '', - false // don't call constructor - ); - } - - protected function createMockGroupWithName($name) - { - $group = $this->createMockGroup(); - $group->expects($this->any()) - ->method('getName') - ->will($this->returnValue($name)); - - return $group; - } - - protected function createMockGroupWithId($id) - { - $group = $this->createMockGroup(); - $group->expects($this->any()) - ->method('getId') - ->will($this->returnValue($id)); - - return $group; - } + $this->assertEquals(array('child' => array('index' => array('firstName' => 'Bernhard'))), $array); + } + + /* + * This is important so that bind() can work even if setData() was not called + * before + */ + public function testUpdateObjectTreatsEmptyValuesAsArrays() + { + $array = null; + + $field = new TestField('firstName'); + $field->bind('Bernhard'); + $field->updateObject($array); + + $this->assertEquals(array('firstName' => 'Bernhard'), $array); + } + + public function testUpdateObjectUpdatesProperties() + { + $object = new Author(); + + $field = new TestField('firstName'); + $field->bind('Bernhard'); + $field->updateObject($object); + + $this->assertEquals('Bernhard', $object->firstName); + } + + public function testUpdateObjectUpdatesPropertiesWithCustomPropertyPath() + { + $object = new Author(); + $object->child = array(); + $object->child['index'] = new Author(); + + $field = new TestField('firstName', array('property_path' => 'child[index].firstName')); + $field->bind('Bernhard'); + $field->updateObject($object); + + $this->assertEquals('Bernhard', $object->child['index']->firstName); + } + + public function testUpdateObjectUpdatesArrayAccess() + { + $object = new \ArrayObject(); + + $field = new TestField('firstName', array('property_path' => '[firstName]')); + $field->bind('Bernhard'); + $field->updateObject($object); + + $this->assertEquals('Bernhard', $object['firstName']); + } + + public function testUpdateObjectThrowsExceptionIfArrayAccessExpected() + { + $field = new TestField('firstName', array('property_path' => '[firstName]')); + $field->bind('Bernhard'); + + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyException'); + $field->updateObject(new Author()); + } + + public function testUpdateObjectDoesNotUpdatePropertyIfPropertyPathIsEmpty() + { + $object = new Author(); + + $field = new TestField('firstName', array('property_path' => null)); + $field->bind('Bernhard'); + $field->updateObject($object); + + $this->assertEquals(null, $object->firstName); + } + + public function testUpdateObjectUpdatesSetters() + { + $object = new Author(); + + $field = new TestField('lastName'); + $field->bind('Schussek'); + $field->updateObject($object); + + $this->assertEquals('Schussek', $object->getLastName()); + } + + public function testUpdateObjectThrowsExceptionIfGetterIsNotPublic() + { + $field = new TestField('privateSetter'); + $field->bind('foobar'); + + $this->setExpectedException('Symfony\Components\Form\Exception\PropertyAccessDeniedException'); + $field->updateObject(new Author()); + } + + protected function createMockTransformer() + { + return $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface', array(), array(), '', false, false); + } + + protected function createMockTransformerTransformingTo($value) + { + $transformer = $this->createMockTransformer(); + $transformer->expects($this->any()) + ->method('reverseTransform') + ->will($this->returnValue($value)); + + return $transformer; + } + + protected function createMockGroup() + { + return $this->getMock( + 'Symfony\Components\Form\FieldGroup', + array(), + array(), + '', + false // don't call constructor + ); + } + + protected function createMockGroupWithName($name) + { + $group = $this->createMockGroup(); + $group->expects($this->any()) + ->method('getName') + ->will($this->returnValue($name)); + + return $group; + } + + protected function createMockGroupWithId($id) + { + $group = $this->createMockGroup(); + $group->expects($this->any()) + ->method('getId') + ->will($this->returnValue($id)); + + return $group; + } } diff --git a/tests/Symfony/Tests/Components/Form/Fixtures/Author.php b/tests/Symfony/Tests/Components/Form/Fixtures/Author.php index 63e0601251..d35ebec7a2 100644 --- a/tests/Symfony/Tests/Components/Form/Fixtures/Author.php +++ b/tests/Symfony/Tests/Components/Form/Fixtures/Author.php @@ -4,48 +4,48 @@ namespace Symfony\Tests\Components\Form\Fixtures; class Author { - public $firstName; - private $lastName; - private $australian; - public $child; + public $firstName; + private $lastName; + private $australian; + public $child; - private $privateProperty; + private $privateProperty; - public function setLastName($lastName) - { - $this->lastName = $lastName; - } + public function setLastName($lastName) + { + $this->lastName = $lastName; + } - public function getLastName() - { - return $this->lastName; - } + public function getLastName() + { + return $this->lastName; + } - private function getPrivateGetter() - { - return 'foobar'; - } + private function getPrivateGetter() + { + return 'foobar'; + } - public function setAustralian($australian) - { - $this->australian = $australian; - } + public function setAustralian($australian) + { + $this->australian = $australian; + } - public function isAustralian() - { - return $this->australian; - } + public function isAustralian() + { + return $this->australian; + } - private function isPrivateIsser() - { - return true; - } + private function isPrivateIsser() + { + return true; + } - public function getPrivateSetter() - { - } + public function getPrivateSetter() + { + } - private function setPrivateSetter($data) - { - } + private function setPrivateSetter($data) + { + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/Fixtures/InvalidField.php b/tests/Symfony/Tests/Components/Form/Fixtures/InvalidField.php index aba4b0a2a5..2f35c3f8b6 100644 --- a/tests/Symfony/Tests/Components/Form/Fixtures/InvalidField.php +++ b/tests/Symfony/Tests/Components/Form/Fixtures/InvalidField.php @@ -6,12 +6,12 @@ use Symfony\Components\Form\Field; class InvalidField extends Field { - public function isValid() - { - return false; - } + public function isValid() + { + return false; + } - public function render(array $attributes = array()) - { - } + public function render(array $attributes = array()) + { + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/Fixtures/RequiredOptionsField.php b/tests/Symfony/Tests/Components/Form/Fixtures/RequiredOptionsField.php index e7a07812d4..5b9b145db5 100644 --- a/tests/Symfony/Tests/Components/Form/Fixtures/RequiredOptionsField.php +++ b/tests/Symfony/Tests/Components/Form/Fixtures/RequiredOptionsField.php @@ -6,13 +6,13 @@ use Symfony\Components\Form\Field; class RequiredOptionsField extends Field { - protected function configure() - { - $this->addOption('foo'); - $this->addRequiredOption('bar'); - } + protected function configure() + { + $this->addOption('foo'); + $this->addRequiredOption('bar'); + } - public function render(array $attributes = array()) - { - } + public function render(array $attributes = array()) + { + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/Fixtures/TestField.php b/tests/Symfony/Tests/Components/Form/Fixtures/TestField.php index dc247a5f40..ba8bae8696 100644 --- a/tests/Symfony/Tests/Components/Form/Fixtures/TestField.php +++ b/tests/Symfony/Tests/Components/Form/Fixtures/TestField.php @@ -6,7 +6,7 @@ use Symfony\Components\Form\Field; class TestField extends Field { - public function render(array $attributes = array()) - { - } + public function render(array $attributes = array()) + { + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/FormTest.php b/tests/Symfony/Tests/Components/Form/FormTest.php index eb676a84b8..4f7ce21b5f 100644 --- a/tests/Symfony/Tests/Components/Form/FormTest.php +++ b/tests/Symfony/Tests/Components/Form/FormTest.php @@ -20,375 +20,375 @@ use Symfony\Tests\Components\Form\Fixtures\TestField; class FormTest_PreconfiguredForm extends Form { - protected function configure() - { - $this->add(new Field('firstName')); - } + protected function configure() + { + $this->add(new Field('firstName')); + } } class FormTest extends \PHPUnit_Framework_TestCase { - protected $validator; - protected $form; + protected $validator; + protected $form; - protected function setUp() - { - Form::disableDefaultCsrfProtection(); - Form::setDefaultCsrfSecret(null); - $this->validator = $this->createMockValidator(); - $this->form = new Form('author', new Author(), $this->validator); - } + protected function setUp() + { + Form::disableDefaultCsrfProtection(); + Form::setDefaultCsrfSecret(null); + $this->validator = $this->createMockValidator(); + $this->form = new Form('author', new Author(), $this->validator); + } - public function testConstructInitializesObject() - { - $this->assertEquals(new Author(), $this->form->getData()); - } + public function testConstructInitializesObject() + { + $this->assertEquals(new Author(), $this->form->getData()); + } - public function testIsCsrfProtected() - { - $this->assertFalse($this->form->isCsrfProtected()); + public function testIsCsrfProtected() + { + $this->assertFalse($this->form->isCsrfProtected()); - $this->form->enableCsrfProtection(); + $this->form->enableCsrfProtection(); - $this->assertTrue($this->form->isCsrfProtected()); + $this->assertTrue($this->form->isCsrfProtected()); - $this->form->disableCsrfProtection(); + $this->form->disableCsrfProtection(); - $this->assertFalse($this->form->isCsrfProtected()); - } + $this->assertFalse($this->form->isCsrfProtected()); + } - public function testNoCsrfProtectionByDefault() - { - $form = new Form('author', new Author(), $this->validator); + public function testNoCsrfProtectionByDefault() + { + $form = new Form('author', new Author(), $this->validator); - $this->assertFalse($form->isCsrfProtected()); - } + $this->assertFalse($form->isCsrfProtected()); + } - public function testDefaultCsrfProtectionCanBeEnabled() - { - Form::enableDefaultCsrfProtection(); - $form = new Form('author', new Author(), $this->validator); + public function testDefaultCsrfProtectionCanBeEnabled() + { + Form::enableDefaultCsrfProtection(); + $form = new Form('author', new Author(), $this->validator); - $this->assertTrue($form->isCsrfProtected()); - } + $this->assertTrue($form->isCsrfProtected()); + } - public function testGeneratedCsrfSecretByDefault() - { - $form = new Form('author', new Author(), $this->validator); + public function testGeneratedCsrfSecretByDefault() + { + $form = new Form('author', new Author(), $this->validator); - $this->assertTrue(strlen($form->getCsrfSecret()) >= 32); - } + $this->assertTrue(strlen($form->getCsrfSecret()) >= 32); + } - public function testDefaultCsrfSecretCanBeSet() - { - Form::setDefaultCsrfSecret('foobar'); - $form = new Form('author', new Author(), $this->validator); + public function testDefaultCsrfSecretCanBeSet() + { + Form::setDefaultCsrfSecret('foobar'); + $form = new Form('author', new Author(), $this->validator); - $this->assertEquals('foobar', $form->getCsrfSecret()); - } + $this->assertEquals('foobar', $form->getCsrfSecret()); + } - public function testDefaultCsrfFieldNameCanBeSet() - { - Form::setDefaultCsrfFieldName('foobar'); - $form = new Form('author', new Author(), $this->validator); + public function testDefaultCsrfFieldNameCanBeSet() + { + Form::setDefaultCsrfFieldName('foobar'); + $form = new Form('author', new Author(), $this->validator); - $this->assertEquals('foobar', $form->getCsrfFieldName()); - } + $this->assertEquals('foobar', $form->getCsrfFieldName()); + } - public function testCsrfProtectedFormsHaveExtraField() - { - $this->form->enableCsrfProtection(); + public function testCsrfProtectedFormsHaveExtraField() + { + $this->form->enableCsrfProtection(); - $this->assertTrue($this->form->has($this->form->getCsrfFieldName())); + $this->assertTrue($this->form->has($this->form->getCsrfFieldName())); - $field = $this->form->get($this->form->getCsrfFieldName()); + $field = $this->form->get($this->form->getCsrfFieldName()); - $this->assertTrue($field instanceof HiddenField); - $this->assertGreaterThanOrEqual(32, strlen($field->getDisplayedData())); - } + $this->assertTrue($field instanceof HiddenField); + $this->assertGreaterThanOrEqual(32, strlen($field->getDisplayedData())); + } - public function testIsCsrfTokenValidPassesIfCsrfProtectionIsDisabled() - { - $this->form->bind(array()); + public function testIsCsrfTokenValidPassesIfCsrfProtectionIsDisabled() + { + $this->form->bind(array()); - $this->assertTrue($this->form->isCsrfTokenValid()); - } + $this->assertTrue($this->form->isCsrfTokenValid()); + } - public function testIsCsrfTokenValidPasses() - { - $this->form->enableCsrfProtection(); - - $field = $this->form->getCsrfFieldName(); - $token = $this->form->get($field)->getDisplayedData(); - - $this->form->bind(array($field => $token)); - - $this->assertTrue($this->form->isCsrfTokenValid()); - } - - public function testIsCsrfTokenValidFails() - { - $this->form->enableCsrfProtection(); - - $field = $this->form->getCsrfFieldName(); - - $this->form->bind(array($field => 'foobar')); - - $this->assertFalse($this->form->isCsrfTokenValid()); - } - - public function testDefaultLocaleCanBeSet() - { - Form::setDefaultLocale('de-DE-1996'); - $form = new Form('author', new Author(), $this->validator); - - $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); - $field->expects($this->once()) - ->method('setLocale') - ->with($this->equalTo('de-DE-1996')); - - $form->add($field); - } - - public function testDefaultTranslatorCanBeSet() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - Form::setDefaultTranslator($translator); - $form = new Form('author', new Author(), $this->validator); - - $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('firstName')); - $field->expects($this->once()) - ->method('setTranslator') - ->with($this->equalTo($translator)); - - $form->add($field); - } - - public function testValidationGroupsCanBeSet() - { - $form = new Form('author', new Author(), $this->validator); - - $this->assertNull($form->getValidationGroups()); - $form->setValidationGroups('group'); - $this->assertEquals(array('group'), $form->getValidationGroups()); - $form->setValidationGroups(array('group1', 'group2')); - $this->assertEquals(array('group1', 'group2'), $form->getValidationGroups()); - $form->setValidationGroups(null); - $this->assertNull($form->getValidationGroups()); - } - - public function testBindUsesValidationGroups() - { - $field = $this->createMockField('firstName'); - $form = new Form('author', new Author(), $this->validator); - $form->add($field); - $form->setValidationGroups('group'); - - $this->validator->expects($this->once()) - ->method('validate') - ->with($this->equalTo($form), $this->equalTo(array('group'))); - - $form->bind(array()); // irrelevant - } - - public function testBindConvertsUploadedFiles() - { - $tmpFile = $this->createTempFile(); - $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - - $field = $this->createMockField('file'); - $field->expects($this->once()) - ->method('bind') - ->with($this->equalTo($file)); - - $form = new Form('author', new Author(), $this->validator); - $form->add($field); - - // test - $form->bind(array(), array('file' => array( - 'name' => basename($tmpFile), - 'type' => 'text/plain', - 'tmp_name' => $tmpFile, - 'error' => 0, - 'size' => 100 - ))); - } - - public function testBindConvertsUploadedFilesWithPhpBug() - { - $tmpFile = $this->createTempFile(); - $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - - $field = $this->createMockField('file'); - $field->expects($this->once()) - ->method('bind') - ->with($this->equalTo($file)); - - $form = new Form('author', new Author(), $this->validator); - $form->add($field); - - // test - $form->bind(array(), array( - 'name' => array( - 'file' => basename($tmpFile), - ), - 'type' => array( - 'file' => 'text/plain', - ), - 'tmp_name' => array( - 'file' => $tmpFile, - ), - 'error' => array( - 'file' => 0, - ), - 'size' => array( - 'file' => 100, - ), - )); - } - - public function testBindConvertsNestedUploadedFilesWithPhpBug() - { - $tmpFile = $this->createTempFile(); - $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - - $group = $this->getMock( - 'Symfony\Components\Form\FieldGroup', - array('bind'), - array('child', array('property_path' => null)) - ); - $group->expects($this->once()) - ->method('bind') - ->with($this->equalTo(array('file' => $file))); - - $form = new Form('author', new Author(), $this->validator); - $form->add($group); - - // test - $form->bind(array(), array( - 'name' => array( - 'child' => array('file' => basename($tmpFile)), - ), - 'type' => array( - 'child' => array('file' => 'text/plain'), - ), - 'tmp_name' => array( - 'child' => array('file' => $tmpFile), - ), - 'error' => array( - 'child' => array('file' => 0), - ), - 'size' => array( - 'child' => array('file' => 100), - ), - )); - } - - public function testMultipartFormsWithoutParentsRequireFiles() - { - $form = new Form('author', new Author(), $this->validator); - $form->add($this->createMultipartMockField('file')); - - $this->setExpectedException('InvalidArgumentException'); - - // should be given in second argument - $form->bind(array('file' => 'test.txt')); - } - - public function testMultipartFormsWithParentsRequireNoFiles() - { - $form = new Form('author', new Author(), $this->validator); - $form->add($this->createMultipartMockField('file')); - - $form->setParent($this->createMockField('group')); - - // files are expected to be converted by the parent - $form->bind(array('file' => 'test.txt')); - } - - public function testRenderFormTagProducesValidXhtml() - { - $form = new Form('author', new Author(), $this->validator); - - $this->assertEquals('
', $form->renderFormTag('url')); - } - - public function testSetCharsetAdjustsGenerator() - { - $form = $this->getMock( - 'Symfony\Components\Form\Form', - array('setGenerator'), - array(), - '', - false // don't call original constructor - ); - - $form->expects($this->once()) - ->method('setGenerator') - ->with($this->equalTo(new HtmlGenerator('iso-8859-1'))); - - $form->setCharset('iso-8859-1'); - } - - protected function createMockField($key) - { - $field = $this->getMock( - 'Symfony\Components\Form\FieldInterface', - array(), - array(), - '', - false, // don't use constructor - false // don't call parent::__clone - ); - - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue($key)); - - return $field; - } - - protected function createMockFieldGroup($key) - { - $field = $this->getMock( - 'Symfony\Components\Form\FieldGroup', - array(), - array(), - '', - false, // don't use constructor - false // don't call parent::__clone - ); - - $field->expects($this->any()) - ->method('getKey') - ->will($this->returnValue($key)); - - return $field; - } - - protected function createMultipartMockField($key) - { - $field = $this->createMockField($key); - $field->expects($this->any()) - ->method('isMultipart') - ->will($this->returnValue(true)); - - return $field; - } - - protected function createTempFile() - { - return tempnam(sys_get_temp_dir(), 'FormTest'); - } - - protected function createMockValidator() - { - return $this->getMock('Symfony\Components\Validator\ValidatorInterface'); - } + public function testIsCsrfTokenValidPasses() + { + $this->form->enableCsrfProtection(); + + $field = $this->form->getCsrfFieldName(); + $token = $this->form->get($field)->getDisplayedData(); + + $this->form->bind(array($field => $token)); + + $this->assertTrue($this->form->isCsrfTokenValid()); + } + + public function testIsCsrfTokenValidFails() + { + $this->form->enableCsrfProtection(); + + $field = $this->form->getCsrfFieldName(); + + $this->form->bind(array($field => 'foobar')); + + $this->assertFalse($this->form->isCsrfTokenValid()); + } + + public function testDefaultLocaleCanBeSet() + { + Form::setDefaultLocale('de-DE-1996'); + $form = new Form('author', new Author(), $this->validator); + + $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); + $field->expects($this->once()) + ->method('setLocale') + ->with($this->equalTo('de-DE-1996')); + + $form->add($field); + } + + public function testDefaultTranslatorCanBeSet() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + Form::setDefaultTranslator($translator); + $form = new Form('author', new Author(), $this->validator); + + $field = $this->getMock('Symfony\Components\Form\Field', array(), array(), '', false, false); + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('firstName')); + $field->expects($this->once()) + ->method('setTranslator') + ->with($this->equalTo($translator)); + + $form->add($field); + } + + public function testValidationGroupsCanBeSet() + { + $form = new Form('author', new Author(), $this->validator); + + $this->assertNull($form->getValidationGroups()); + $form->setValidationGroups('group'); + $this->assertEquals(array('group'), $form->getValidationGroups()); + $form->setValidationGroups(array('group1', 'group2')); + $this->assertEquals(array('group1', 'group2'), $form->getValidationGroups()); + $form->setValidationGroups(null); + $this->assertNull($form->getValidationGroups()); + } + + public function testBindUsesValidationGroups() + { + $field = $this->createMockField('firstName'); + $form = new Form('author', new Author(), $this->validator); + $form->add($field); + $form->setValidationGroups('group'); + + $this->validator->expects($this->once()) + ->method('validate') + ->with($this->equalTo($form), $this->equalTo(array('group'))); + + $form->bind(array()); // irrelevant + } + + public function testBindConvertsUploadedFiles() + { + $tmpFile = $this->createTempFile(); + $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); + + $field = $this->createMockField('file'); + $field->expects($this->once()) + ->method('bind') + ->with($this->equalTo($file)); + + $form = new Form('author', new Author(), $this->validator); + $form->add($field); + + // test + $form->bind(array(), array('file' => array( + 'name' => basename($tmpFile), + 'type' => 'text/plain', + 'tmp_name' => $tmpFile, + 'error' => 0, + 'size' => 100 + ))); + } + + public function testBindConvertsUploadedFilesWithPhpBug() + { + $tmpFile = $this->createTempFile(); + $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); + + $field = $this->createMockField('file'); + $field->expects($this->once()) + ->method('bind') + ->with($this->equalTo($file)); + + $form = new Form('author', new Author(), $this->validator); + $form->add($field); + + // test + $form->bind(array(), array( + 'name' => array( + 'file' => basename($tmpFile), + ), + 'type' => array( + 'file' => 'text/plain', + ), + 'tmp_name' => array( + 'file' => $tmpFile, + ), + 'error' => array( + 'file' => 0, + ), + 'size' => array( + 'file' => 100, + ), + )); + } + + public function testBindConvertsNestedUploadedFilesWithPhpBug() + { + $tmpFile = $this->createTempFile(); + $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); + + $group = $this->getMock( + 'Symfony\Components\Form\FieldGroup', + array('bind'), + array('child', array('property_path' => null)) + ); + $group->expects($this->once()) + ->method('bind') + ->with($this->equalTo(array('file' => $file))); + + $form = new Form('author', new Author(), $this->validator); + $form->add($group); + + // test + $form->bind(array(), array( + 'name' => array( + 'child' => array('file' => basename($tmpFile)), + ), + 'type' => array( + 'child' => array('file' => 'text/plain'), + ), + 'tmp_name' => array( + 'child' => array('file' => $tmpFile), + ), + 'error' => array( + 'child' => array('file' => 0), + ), + 'size' => array( + 'child' => array('file' => 100), + ), + )); + } + + public function testMultipartFormsWithoutParentsRequireFiles() + { + $form = new Form('author', new Author(), $this->validator); + $form->add($this->createMultipartMockField('file')); + + $this->setExpectedException('InvalidArgumentException'); + + // should be given in second argument + $form->bind(array('file' => 'test.txt')); + } + + public function testMultipartFormsWithParentsRequireNoFiles() + { + $form = new Form('author', new Author(), $this->validator); + $form->add($this->createMultipartMockField('file')); + + $form->setParent($this->createMockField('group')); + + // files are expected to be converted by the parent + $form->bind(array('file' => 'test.txt')); + } + + public function testRenderFormTagProducesValidXhtml() + { + $form = new Form('author', new Author(), $this->validator); + + $this->assertEquals('', $form->renderFormTag('url')); + } + + public function testSetCharsetAdjustsGenerator() + { + $form = $this->getMock( + 'Symfony\Components\Form\Form', + array('setGenerator'), + array(), + '', + false // don't call original constructor + ); + + $form->expects($this->once()) + ->method('setGenerator') + ->with($this->equalTo(new HtmlGenerator('iso-8859-1'))); + + $form->setCharset('iso-8859-1'); + } + + protected function createMockField($key) + { + $field = $this->getMock( + 'Symfony\Components\Form\FieldInterface', + array(), + array(), + '', + false, // don't use constructor + false // don't call parent::__clone + ); + + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue($key)); + + return $field; + } + + protected function createMockFieldGroup($key) + { + $field = $this->getMock( + 'Symfony\Components\Form\FieldGroup', + array(), + array(), + '', + false, // don't use constructor + false // don't call parent::__clone + ); + + $field->expects($this->any()) + ->method('getKey') + ->will($this->returnValue($key)); + + return $field; + } + + protected function createMultipartMockField($key) + { + $field = $this->createMockField($key); + $field->expects($this->any()) + ->method('isMultipart') + ->will($this->returnValue(true)); + + return $field; + } + + protected function createTempFile() + { + return tempnam(sys_get_temp_dir(), 'FormTest'); + } + + protected function createMockValidator() + { + return $this->getMock('Symfony\Components\Validator\ValidatorInterface'); + } } diff --git a/tests/Symfony/Tests/Components/Form/HiddenFieldTest.php b/tests/Symfony/Tests/Components/Form/HiddenFieldTest.php index 1b9650ede0..54e389005e 100644 --- a/tests/Symfony/Tests/Components/Form/HiddenFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/HiddenFieldTest.php @@ -8,26 +8,26 @@ use Symfony\Components\Form\HiddenField; class HiddenFieldTest extends \PHPUnit_Framework_TestCase { - protected $field; + protected $field; - public function setUp() - { - $this->field = new HiddenField('name'); - } + public function setUp() + { + $this->field = new HiddenField('name'); + } - public function testRender() - { - $this->field->setData('foobar'); + public function testRender() + { + $this->field->setData('foobar'); - $html = ''; + $html = ''; - $this->assertEquals($html, $this->field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $this->field->render(array( + 'class' => 'foobar', + ))); + } - public function testIsHidden() - { - $this->assertTrue($this->field->isHidden()); - } + public function testIsHidden() + { + $this->assertTrue($this->field->isHidden()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/HtmlGeneratorTest.php b/tests/Symfony/Tests/Components/Form/HtmlGeneratorTest.php index 31ad7c257c..c91ae9dc9b 100644 --- a/tests/Symfony/Tests/Components/Form/HtmlGeneratorTest.php +++ b/tests/Symfony/Tests/Components/Form/HtmlGeneratorTest.php @@ -8,86 +8,86 @@ use Symfony\Components\Form\HtmlGenerator; class HtmlGeneratorTest extends \PHPUnit_Framework_TestCase { - protected $generator; + protected $generator; - public function setUp() - { - HtmlGenerator::setXhtml(true); - $this->generator = new HtmlGenerator(); - } + public function setUp() + { + HtmlGenerator::setXhtml(true); + $this->generator = new HtmlGenerator(); + } - public function testEscape() - { - $this->assertEquals('<&abcd', $this->generator->escape('<&abcd')); - } + public function testEscape() + { + $this->assertEquals('<&abcd', $this->generator->escape('<&abcd')); + } - public function testEscapeOnlyOnce() - { - $this->assertEquals('<&abcd', $this->generator->escape('<&abcd')); - } + public function testEscapeOnlyOnce() + { + $this->assertEquals('<&abcd', $this->generator->escape('<&abcd')); + } - public function testAttribute() - { - $this->assertEquals('foo="bar"', $this->generator->attribute('foo', 'bar')); - } + public function testAttribute() + { + $this->assertEquals('foo="bar"', $this->generator->attribute('foo', 'bar')); + } - public function testEscapeAttribute() - { - $this->assertEquals('foo="<>"', $this->generator->attribute('foo', '<>')); - } + public function testEscapeAttribute() + { + $this->assertEquals('foo="<>"', $this->generator->attribute('foo', '<>')); + } - public function testXhtmlAttribute() - { - HtmlGenerator::setXhtml(true); - $this->assertEquals('foo="foo"', $this->generator->attribute('foo', true)); - } + public function testXhtmlAttribute() + { + HtmlGenerator::setXhtml(true); + $this->assertEquals('foo="foo"', $this->generator->attribute('foo', true)); + } - public function testNonXhtmlAttribute() - { - HtmlGenerator::setXhtml(false); - $this->assertEquals('foo', $this->generator->attribute('foo', true)); - } + public function testNonXhtmlAttribute() + { + HtmlGenerator::setXhtml(false); + $this->assertEquals('foo', $this->generator->attribute('foo', true)); + } - public function testAttributes() - { - $html = $this->generator->attributes(array( - 'foo' => 'bar', - 'bar' => 'baz', - )); - $this->assertEquals(' foo="bar" bar="baz"', $html); - } + public function testAttributes() + { + $html = $this->generator->attributes(array( + 'foo' => 'bar', + 'bar' => 'baz', + )); + $this->assertEquals(' foo="bar" bar="baz"', $html); + } - public function testXhtmlTag() - { - HtmlGenerator::setXhtml(true); - $html = $this->generator->tag('input', array( - 'type' => 'text', - )); - $this->assertEquals('', $html); - } + public function testXhtmlTag() + { + HtmlGenerator::setXhtml(true); + $html = $this->generator->tag('input', array( + 'type' => 'text', + )); + $this->assertEquals('', $html); + } - public function testNonXhtmlTag() - { - HtmlGenerator::setXhtml(false); - $html = $this->generator->tag('input', array( - 'type' => 'text', - )); - $this->assertEquals('', $html); - } + public function testNonXhtmlTag() + { + HtmlGenerator::setXhtml(false); + $html = $this->generator->tag('input', array( + 'type' => 'text', + )); + $this->assertEquals('', $html); + } - public function testContentTag() - { - $html = $this->generator->contentTag('p', 'asdf', array( - 'class' => 'foo', - )); - $this->assertEquals('

asdf

', $html); - } + public function testContentTag() + { + $html = $this->generator->contentTag('p', 'asdf', array( + 'class' => 'foo', + )); + $this->assertEquals('

asdf

', $html); + } - // it should be possible to pass the output of the tag() method as body - // of the content tag - public function testDontEscapeContentTag() - { - $this->assertEquals('

<&

', $this->generator->contentTag('p', '<&')); - } + // it should be possible to pass the output of the tag() method as body + // of the content tag + public function testDontEscapeContentTag() + { + $this->assertEquals('

<&

', $this->generator->contentTag('p', '<&')); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/InputFieldTest.php b/tests/Symfony/Tests/Components/Form/InputFieldTest.php index 1c45b571ee..310506387e 100644 --- a/tests/Symfony/Tests/Components/Form/InputFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/InputFieldTest.php @@ -10,25 +10,25 @@ use Symfony\Tests\Components\Form\Fixtures\TestInputField; class InputFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new TestInputField('name'); - $field->setData('foobar'); + public function testRender() + { + $field = new TestInputField('name'); + $field->setData('foobar'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - public function testRender_disabled() - { - $field = new TestInputField('name', array('disabled' => true)); - $field->setData('foobar'); + public function testRender_disabled() + { + $field = new TestInputField('name', array('disabled' => true)); + $field->setData('foobar'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/IntegerFieldTest.php b/tests/Symfony/Tests/Components/Form/IntegerFieldTest.php index 20c7e35fd7..d35b6e8ee2 100644 --- a/tests/Symfony/Tests/Components/Form/IntegerFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/IntegerFieldTest.php @@ -8,13 +8,13 @@ use Symfony\Components\Form\IntegerField; class IntegerFieldTest extends \PHPUnit_Framework_TestCase { - public function testBindCastsToInteger() - { - $field = new IntegerField('name'); + public function testBindCastsToInteger() + { + $field = new IntegerField('name'); - $field->bind('1.678'); + $field->bind('1.678'); - $this->assertSame(1, $field->getData()); - $this->assertSame('1', $field->getDisplayedData()); - } + $this->assertSame(1, $field->getData()); + $this->assertSame('1', $field->getDisplayedData()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/MoneyFieldTest.php b/tests/Symfony/Tests/Components/Form/MoneyFieldTest.php index 3401dabbeb..86c51b3788 100644 --- a/tests/Symfony/Tests/Components/Form/MoneyFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/MoneyFieldTest.php @@ -8,39 +8,39 @@ use Symfony\Components\Form\MoneyField; class MoneyFieldTest extends \PHPUnit_Framework_TestCase { - public function testRenderWithoutCurrency() - { - $field = new MoneyField('name'); + public function testRenderWithoutCurrency() + { + $field = new MoneyField('name'); - $field->setLocale('de_AT'); - $field->setData(1234); + $field->setLocale('de_AT'); + $field->setData(1234); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - public function testRenderWithCurrency_afterWidget() - { - $field = new MoneyField('name', array('currency' => 'EUR')); + public function testRenderWithCurrency_afterWidget() + { + $field = new MoneyField('name', array('currency' => 'EUR')); - $field->setLocale('de_DE'); - $field->setData(1234); + $field->setLocale('de_DE'); + $field->setData(1234); - $html = ' €'; + $html = ' €'; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderWithCurrency_beforeWidget() - { - $field = new MoneyField('name', array('currency' => 'EUR')); + public function testRenderWithCurrency_beforeWidget() + { + $field = new MoneyField('name', array('currency' => 'EUR')); - $field->setLocale('en_US'); - $field->setData(1234); + $field->setLocale('en_US'); + $field->setData(1234); - $html = '€ '; + $html = '€ '; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/NumberFieldTest.php b/tests/Symfony/Tests/Components/Form/NumberFieldTest.php index 6e4aa77357..dc2934b34a 100644 --- a/tests/Symfony/Tests/Components/Form/NumberFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/NumberFieldTest.php @@ -8,39 +8,39 @@ use Symfony\Components\Form\NumberField; class NumberFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new NumberField('name'); + public function testRender() + { + $field = new NumberField('name'); - $field->setLocale('de_AT'); - $field->setData(1234.5678); + $field->setLocale('de_AT'); + $field->setData(1234.5678); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - public function testRenderWithPrecision() - { - $field = new NumberField('name', array('precision' => 4)); + public function testRenderWithPrecision() + { + $field = new NumberField('name', array('precision' => 4)); - $field->setLocale('de_AT'); - $field->setData(1234.5678); + $field->setLocale('de_AT'); + $field->setData(1234.5678); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderWithGrouping() - { - $field = new NumberField('name', array('grouping' => true)); + public function testRenderWithGrouping() + { + $field = new NumberField('name', array('grouping' => true)); - $field->setLocale('de_AT'); - $field->setData(1234.5678); + $field->setLocale('de_AT'); + $field->setData(1234.5678); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/PasswordFieldTest.php b/tests/Symfony/Tests/Components/Form/PasswordFieldTest.php index e7444b6f24..3a5b65019b 100644 --- a/tests/Symfony/Tests/Components/Form/PasswordFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/PasswordFieldTest.php @@ -8,44 +8,44 @@ use Symfony\Components\Form\PasswordField; class PasswordFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new PasswordField('name'); - $field->setData('asdf'); + public function testRender() + { + $field = new PasswordField('name'); + $field->setData('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - // when the user made an error in the form, display the value in the field - public function testRenderAfterBinding() - { - $field = new PasswordField('name'); - $field->bind('asdf'); + // when the user made an error in the form, display the value in the field + public function testRenderAfterBinding() + { + $field = new PasswordField('name'); + $field->bind('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderNotAlwaysEmpty() - { - $field = new PasswordField('name', array('always_empty' => false)); - $field->setData('asdf'); + public function testRenderNotAlwaysEmpty() + { + $field = new PasswordField('name', array('always_empty' => false)); + $field->setData('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderNotAlwaysEmptyAfterBinding() - { - $field = new PasswordField('name', array('always_empty' => false)); - $field->bind('asdf'); + public function testRenderNotAlwaysEmptyAfterBinding() + { + $field = new PasswordField('name', array('always_empty' => false)); + $field->bind('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/PercentFieldTest.php b/tests/Symfony/Tests/Components/Form/PercentFieldTest.php index f32c9642d9..531041bd15 100644 --- a/tests/Symfony/Tests/Components/Form/PercentFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/PercentFieldTest.php @@ -8,39 +8,39 @@ use Symfony\Components\Form\PercentField; class PercentFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new PercentField('name'); + public function testRender() + { + $field = new PercentField('name'); - $field->setLocale('de_DE'); - $field->setData(0.12); + $field->setLocale('de_DE'); + $field->setData(0.12); - $html = ' %'; + $html = ' %'; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderWithPrecision() - { - $field = new PercentField('name', array('precision' => 2)); + public function testRenderWithPrecision() + { + $field = new PercentField('name', array('precision' => 2)); - $field->setLocale('de_DE'); - $field->setData(0.1234); + $field->setLocale('de_DE'); + $field->setData(0.1234); - $html = ' %'; + $html = ' %'; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRenderWithInteger() - { - $field = new PercentField('name', array('type' => 'integer')); + public function testRenderWithInteger() + { + $field = new PercentField('name', array('type' => 'integer')); - $field->setLocale('de_DE'); - $field->setData(123); + $field->setLocale('de_DE'); + $field->setData(123); - $html = ' %'; + $html = ' %'; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/PropertyPathTest.php b/tests/Symfony/Tests/Components/Form/PropertyPathTest.php index 3ee2a0695a..5832872f8b 100644 --- a/tests/Symfony/Tests/Components/Form/PropertyPathTest.php +++ b/tests/Symfony/Tests/Components/Form/PropertyPathTest.php @@ -8,78 +8,78 @@ use Symfony\Components\Form\PropertyPath; class PropertyPathTest extends \PHPUnit_Framework_TestCase { - public function testValidPropertyPath() - { - $path = new PropertyPath('reference.traversable[index].property'); + public function testValidPropertyPath() + { + $path = new PropertyPath('reference.traversable[index].property'); - $this->assertEquals('reference', $path->getCurrent()); - $this->assertTrue($path->hasNext()); - $this->assertTrue($path->isProperty()); - $this->assertFalse($path->isIndex()); + $this->assertEquals('reference', $path->getCurrent()); + $this->assertTrue($path->hasNext()); + $this->assertTrue($path->isProperty()); + $this->assertFalse($path->isIndex()); - $path->next(); + $path->next(); - $this->assertEquals('traversable', $path->getCurrent()); - $this->assertTrue($path->hasNext()); - $this->assertTrue($path->isProperty()); - $this->assertFalse($path->isIndex()); + $this->assertEquals('traversable', $path->getCurrent()); + $this->assertTrue($path->hasNext()); + $this->assertTrue($path->isProperty()); + $this->assertFalse($path->isIndex()); - $path->next(); + $path->next(); - $this->assertEquals('index', $path->getCurrent()); - $this->assertTrue($path->hasNext()); - $this->assertFalse($path->isProperty()); - $this->assertTrue($path->isIndex()); + $this->assertEquals('index', $path->getCurrent()); + $this->assertTrue($path->hasNext()); + $this->assertFalse($path->isProperty()); + $this->assertTrue($path->isIndex()); - $path->next(); + $path->next(); - $this->assertEquals('property', $path->getCurrent()); - $this->assertFalse($path->hasNext()); - $this->assertTrue($path->isProperty()); - $this->assertFalse($path->isIndex()); - } + $this->assertEquals('property', $path->getCurrent()); + $this->assertFalse($path->hasNext()); + $this->assertTrue($path->isProperty()); + $this->assertFalse($path->isIndex()); + } - public function testToString() - { - $path = new PropertyPath('reference.traversable[index].property'); + public function testToString() + { + $path = new PropertyPath('reference.traversable[index].property'); - $this->assertEquals('reference.traversable[index].property', $path->__toString()); - } + $this->assertEquals('reference.traversable[index].property', $path->__toString()); + } - public function testInvalidPropertyPath_noDotBeforeProperty() - { - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); + public function testInvalidPropertyPath_noDotBeforeProperty() + { + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); - new PropertyPath('[index]property'); - } + new PropertyPath('[index]property'); + } - public function testInvalidPropertyPath_dotAtTheBeginning() - { - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); + public function testInvalidPropertyPath_dotAtTheBeginning() + { + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); - new PropertyPath('.property'); - } + new PropertyPath('.property'); + } - public function testInvalidPropertyPath_unexpectedCharacters() - { - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); + public function testInvalidPropertyPath_unexpectedCharacters() + { + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); - new PropertyPath('property.$field'); - } + new PropertyPath('property.$field'); + } - public function testInvalidPropertyPath_empty() - { - $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); + public function testInvalidPropertyPath_empty() + { + $this->setExpectedException('Symfony\Components\Form\Exception\InvalidPropertyPathException'); - new PropertyPath(''); - } + new PropertyPath(''); + } - public function testNextThrowsExceptionIfNoNextElement() - { - $path = new PropertyPath('property'); + public function testNextThrowsExceptionIfNoNextElement() + { + $path = new PropertyPath('property'); - $this->setExpectedException('OutOfBoundsException'); + $this->setExpectedException('OutOfBoundsException'); - $path->next(); - } + $path->next(); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/RadioFieldTest.php b/tests/Symfony/Tests/Components/Form/RadioFieldTest.php index c769afc9da..c7e0a2a959 100644 --- a/tests/Symfony/Tests/Components/Form/RadioFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/RadioFieldTest.php @@ -9,27 +9,27 @@ use Symfony\Components\Form\FieldGroup; class RadioFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new RadioField('name'); - $field->setData(true); + public function testRender() + { + $field = new RadioField('name'); + $field->setData(true); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - // when a radio button is in a field group, all radio buttons in that group - // should have the same name - public function testRenderParentName() - { - $field = new RadioField('name'); - $field->setParent(new FieldGroup('parent')); + // when a radio button is in a field group, all radio buttons in that group + // should have the same name + public function testRenderParentName() + { + $field = new RadioField('name'); + $field->setParent(new FieldGroup('parent')); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/Renderer/RendererTestCase.php b/tests/Symfony/Tests/Components/Form/Renderer/RendererTestCase.php index 30a757195c..114a2b0ff6 100644 --- a/tests/Symfony/Tests/Components/Form/Renderer/RendererTestCase.php +++ b/tests/Symfony/Tests/Components/Form/Renderer/RendererTestCase.php @@ -4,20 +4,20 @@ namespace Symfony\Tests\Components\Form\Renderer; abstract class RendererTestCase extends \PHPUnit_Framework_TestCase { - protected function createFieldMock($name, $id, $displayedData) - { - $field = $this->getMock('Symfony\Components\Form\FieldInterface'); + protected function createFieldMock($name, $id, $displayedData) + { + $field = $this->getMock('Symfony\Components\Form\FieldInterface'); - $field->expects($this->any()) - ->method('getDisplayedData') - ->will($this->returnValue($displayedData)); - $field->expects($this->any()) - ->method('getName') - ->will($this->returnValue($name)); - $field->expects($this->any()) - ->method('getId') - ->will($this->returnValue($id)); + $field->expects($this->any()) + ->method('getDisplayedData') + ->will($this->returnValue($displayedData)); + $field->expects($this->any()) + ->method('getName') + ->will($this->returnValue($name)); + $field->expects($this->any()) + ->method('getId') + ->will($this->returnValue($id)); - return $field; - } + return $field; + } } diff --git a/tests/Symfony/Tests/Components/Form/RepeatedFieldTest.php b/tests/Symfony/Tests/Components/Form/RepeatedFieldTest.php index 9df4e6c6f9..3a8dd7ff42 100644 --- a/tests/Symfony/Tests/Components/Form/RepeatedFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/RepeatedFieldTest.php @@ -10,44 +10,44 @@ use Symfony\Tests\Components\Form\Fixtures\TestField; class RepeatedFieldTest extends \PHPUnit_Framework_TestCase { - protected $field; + protected $field; - public function setUp() - { - $this->field = new RepeatedField(new TestField('name')); - } + public function setUp() + { + $this->field = new RepeatedField(new TestField('name')); + } - public function testSetData() - { - $this->field->setData('foobar'); + public function testSetData() + { + $this->field->setData('foobar'); - $this->assertEquals('foobar', $this->field['first']->getData()); - $this->assertEquals('foobar', $this->field['second']->getData()); - } + $this->assertEquals('foobar', $this->field['first']->getData()); + $this->assertEquals('foobar', $this->field['second']->getData()); + } - public function testBindUnequal() - { - $input = array('first' => 'foo', 'second' => 'bar'); + public function testBindUnequal() + { + $input = array('first' => 'foo', 'second' => 'bar'); - $this->field->bind($input); + $this->field->bind($input); - $this->assertEquals('foo', $this->field['first']->getDisplayedData()); - $this->assertEquals('bar', $this->field['second']->getDisplayedData()); - $this->assertFalse($this->field->isFirstEqualToSecond()); - $this->assertEquals($input, $this->field->getDisplayedData()); - $this->assertEquals(null, $this->field->getData()); - } + $this->assertEquals('foo', $this->field['first']->getDisplayedData()); + $this->assertEquals('bar', $this->field['second']->getDisplayedData()); + $this->assertFalse($this->field->isFirstEqualToSecond()); + $this->assertEquals($input, $this->field->getDisplayedData()); + $this->assertEquals(null, $this->field->getData()); + } - public function testBindEqual() - { - $input = array('first' => 'foo', 'second' => 'foo'); + public function testBindEqual() + { + $input = array('first' => 'foo', 'second' => 'foo'); - $this->field->bind($input); + $this->field->bind($input); - $this->assertEquals('foo', $this->field['first']->getDisplayedData()); - $this->assertEquals('foo', $this->field['second']->getDisplayedData()); - $this->assertTrue($this->field->isFirstEqualToSecond()); - $this->assertEquals($input, $this->field->getDisplayedData()); - $this->assertEquals('foo', $this->field->getData()); - } + $this->assertEquals('foo', $this->field['first']->getDisplayedData()); + $this->assertEquals('foo', $this->field['second']->getDisplayedData()); + $this->assertTrue($this->field->isFirstEqualToSecond()); + $this->assertEquals($input, $this->field->getDisplayedData()); + $this->assertEquals('foo', $this->field->getData()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/TextFieldTest.php b/tests/Symfony/Tests/Components/Form/TextFieldTest.php index d14d04b607..40248e04f6 100644 --- a/tests/Symfony/Tests/Components/Form/TextFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/TextFieldTest.php @@ -8,23 +8,23 @@ use Symfony\Components\Form\TextField; class TextFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new TextField('name'); - $field->setData('asdf'); + public function testRender() + { + $field = new TextField('name'); + $field->setData('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - public function testRenderWithMaxLength() - { - $field = new TextField('name', array('max_length' => 10)); - $field->setData('asdf'); + public function testRenderWithMaxLength() + { + $field = new TextField('name', array('max_length' => 10)); + $field->setData('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/TextareaFieldTest.php b/tests/Symfony/Tests/Components/Form/TextareaFieldTest.php index 679c65c578..88c8e90dfb 100644 --- a/tests/Symfony/Tests/Components/Form/TextareaFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/TextareaFieldTest.php @@ -8,23 +8,23 @@ use Symfony\Components\Form\TextareaField; class TextareaFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender() - { - $field = new TextareaField('name'); - $field->setData('asdf'); + public function testRender() + { + $field = new TextareaField('name'); + $field->setData('asdf'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - public function testRenderEscapesValue() - { - $field = new TextareaField('name'); - $field->setData('<&&'); + public function testRenderEscapesValue() + { + $field = new TextareaField('name'); + $field->setData('<&&'); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/TimeFieldTest.php b/tests/Symfony/Tests/Components/Form/TimeFieldTest.php index d7b4da8207..1253ddd175 100644 --- a/tests/Symfony/Tests/Components/Form/TimeFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/TimeFieldTest.php @@ -9,163 +9,163 @@ use Symfony\Components\Form\TimeField; class TimeFieldTest extends DateTimeTestCase { - public function testBind_dateTime() - { - $field = new TimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => TimeField::DATETIME, - )); + public function testBind_dateTime() + { + $field = new TimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => TimeField::DATETIME, + )); - $input = array( - 'hour' => '3', - 'minute' => '4', - ); + $input = array( + 'hour' => '3', + 'minute' => '4', + ); - $field->bind($input); + $field->bind($input); - $dateTime = new \DateTime('1970-01-01 03:04:00 UTC'); + $dateTime = new \DateTime('1970-01-01 03:04:00 UTC'); - $this->assertEquals($dateTime, $field->getData()); - $this->assertEquals($input, $field->getDisplayedData()); - } + $this->assertEquals($dateTime, $field->getData()); + $this->assertEquals($input, $field->getDisplayedData()); + } - public function testBind_string() - { - $field = new TimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => TimeField::STRING, - )); + public function testBind_string() + { + $field = new TimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => TimeField::STRING, + )); - $input = array( - 'hour' => '3', - 'minute' => '4', - ); + $input = array( + 'hour' => '3', + 'minute' => '4', + ); - $field->bind($input); + $field->bind($input); - $this->assertEquals('03:04:00', $field->getData()); - $this->assertEquals($input, $field->getDisplayedData()); - } + $this->assertEquals('03:04:00', $field->getData()); + $this->assertEquals($input, $field->getDisplayedData()); + } - public function testBind_timestamp() - { - $field = new TimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => TimeField::TIMESTAMP, - )); + public function testBind_timestamp() + { + $field = new TimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => TimeField::TIMESTAMP, + )); - $input = array( - 'hour' => '3', - 'minute' => '4', - ); + $input = array( + 'hour' => '3', + 'minute' => '4', + ); - $field->bind($input); + $field->bind($input); - $dateTime = new \DateTime('1970-01-01 03:04:00 UTC'); + $dateTime = new \DateTime('1970-01-01 03:04:00 UTC'); - $this->assertEquals($dateTime->format('U'), $field->getData()); - $this->assertEquals($input, $field->getDisplayedData()); - } + $this->assertEquals($dateTime->format('U'), $field->getData()); + $this->assertEquals($input, $field->getDisplayedData()); + } - public function testBind_raw() - { - $field = new TimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => TimeField::RAW, - )); + public function testBind_raw() + { + $field = new TimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => TimeField::RAW, + )); - $input = array( - 'hour' => '3', - 'minute' => '4', - ); + $input = array( + 'hour' => '3', + 'minute' => '4', + ); - $data = array( - 'hour' => '3', - 'minute' => '4', - 'second' => '0', - ); + $data = array( + 'hour' => '3', + 'minute' => '4', + 'second' => '0', + ); - $field->bind($input); + $field->bind($input); - $this->assertEquals($data, $field->getData()); - $this->assertEquals($input, $field->getDisplayedData()); - } + $this->assertEquals($data, $field->getData()); + $this->assertEquals($input, $field->getDisplayedData()); + } - public function testSetData_withSeconds() - { - $field = new TimeField('name', array( - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'type' => TimeField::DATETIME, - 'with_seconds' => true, - )); + public function testSetData_withSeconds() + { + $field = new TimeField('name', array( + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'type' => TimeField::DATETIME, + 'with_seconds' => true, + )); - $field->setData(new \DateTime('03:04:05 UTC')); + $field->setData(new \DateTime('03:04:05 UTC')); - $this->assertEquals(array('hour' => 3, 'minute' => 4, 'second' => 5), $field->getDisplayedData()); - } + $this->assertEquals(array('hour' => 3, 'minute' => 4, 'second' => 5), $field->getDisplayedData()); + } - public function testSetData_differentTimezones() - { - $field = new TimeField('name', array( - 'data_timezone' => 'America/New_York', - 'user_timezone' => 'Pacific/Tahiti', - // don't do this test with DateTime, because it leads to wrong results! - 'type' => TimeField::STRING, - 'with_seconds' => true, - )); + public function testSetData_differentTimezones() + { + $field = new TimeField('name', array( + 'data_timezone' => 'America/New_York', + 'user_timezone' => 'Pacific/Tahiti', + // don't do this test with DateTime, because it leads to wrong results! + 'type' => TimeField::STRING, + 'with_seconds' => true, + )); - $dateTime = new \DateTime('03:04:05 America/New_York'); + $dateTime = new \DateTime('03:04:05 America/New_York'); - $field->setData($dateTime->format('H:i:s')); + $field->setData($dateTime->format('H:i:s')); - $dateTime = clone $dateTime; - $dateTime->setTimezone(new \DateTimeZone('Pacific/Tahiti')); + $dateTime = clone $dateTime; + $dateTime->setTimezone(new \DateTimeZone('Pacific/Tahiti')); - $displayedData = array( - 'hour' => (int)$dateTime->format('H'), - 'minute' => (int)$dateTime->format('i'), - 'second' => (int)$dateTime->format('s') - ); + $displayedData = array( + 'hour' => (int)$dateTime->format('H'), + 'minute' => (int)$dateTime->format('i'), + 'second' => (int)$dateTime->format('s') + ); - $this->assertEquals($displayedData, $field->getDisplayedData()); - } + $this->assertEquals($displayedData, $field->getDisplayedData()); + } - public function testRenderAsInputs() - { - $field = new TimeField('name', array( - 'widget' => TimeField::INPUT, - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - )); + public function testRenderAsInputs() + { + $field = new TimeField('name', array( + 'widget' => TimeField::INPUT, + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + )); - $field->setData(new \DateTime('04:05 UTC')); + $field->setData(new \DateTime('04:05 UTC')); - $html = << : EOF; - $this->assertEquals(str_replace("\n", '', $html), $field->render(array('class' => 'foobar'))); - } + $this->assertEquals(str_replace("\n", '', $html), $field->render(array('class' => 'foobar'))); + } - public function testRenderAsInputs_withSeconds() - { - $field = new TimeField('name', array( - 'widget' => TimeField::INPUT, - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'with_seconds' => true, - )); + public function testRenderAsInputs_withSeconds() + { + $field = new TimeField('name', array( + 'widget' => TimeField::INPUT, + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'with_seconds' => true, + )); - $field->setData(new \DateTime('04:05:06 UTC')); + $field->setData(new \DateTime('04:05:06 UTC')); - $html = << : @@ -173,22 +173,22 @@ EOF; EOF; - $this->assertEquals(str_replace("\n", '', $html), $field->render(array('class' => 'foobar'))); - } + $this->assertEquals(str_replace("\n", '', $html), $field->render(array('class' => 'foobar'))); + } - public function testRenderAsChoices() - { - $field = new TimeField('name', array( - 'hours' => array(3, 4), - 'minutes' => array(5, 6), - 'widget' => TimeField::CHOICE, - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - )); + public function testRenderAsChoices() + { + $field = new TimeField('name', array( + 'hours' => array(3, 4), + 'minutes' => array(5, 6), + 'widget' => TimeField::CHOICE, + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + )); - $field->setData(new \DateTime('04:05 UTC')); + $field->setData(new \DateTime('04:05 UTC')); - $html = << @@ -198,24 +198,24 @@ EOF; EOF; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - public function testRenderAsChoices_withSeconds() - { - $field = new TimeField('name', array( - 'hours' => array(3, 4), - 'minutes' => array(5, 6), - 'seconds' => array(7, 8), - 'widget' => TimeField::CHOICE, - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - 'with_seconds' => true, - )); + public function testRenderAsChoices_withSeconds() + { + $field = new TimeField('name', array( + 'hours' => array(3, 4), + 'minutes' => array(5, 6), + 'seconds' => array(7, 8), + 'widget' => TimeField::CHOICE, + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + 'with_seconds' => true, + )); - $field->setData(new \DateTime('04:05:07 UTC')); + $field->setData(new \DateTime('04:05:07 UTC')); - $html = << @@ -228,23 +228,23 @@ EOF; EOF; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } - public function testRenderAsChoices_nonRequired() - { - $field = new TimeField('name', array( - 'hours' => array(3, 4), - 'minutes' => array(5, 6), - 'widget' => TimeField::CHOICE, - 'data_timezone' => 'UTC', - 'user_timezone' => 'UTC', - )); + public function testRenderAsChoices_nonRequired() + { + $field = new TimeField('name', array( + 'hours' => array(3, 4), + 'minutes' => array(5, 6), + 'widget' => TimeField::CHOICE, + 'data_timezone' => 'UTC', + 'user_timezone' => 'UTC', + )); - $field->setRequired(false); - $field->setData(new \DateTime('04:05 UTC')); + $field->setRequired(false); + $field->setData(new \DateTime('04:05 UTC')); - $html = << @@ -256,6 +256,6 @@ EOF; EOF; - $this->assertEquals($html, $field->render(array('class' => 'foobar'))); - } + $this->assertEquals($html, $field->render(array('class' => 'foobar'))); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/ToggleFieldTest.php b/tests/Symfony/Tests/Components/Form/ToggleFieldTest.php index c366b0ea79..a6cefa618f 100644 --- a/tests/Symfony/Tests/Components/Form/ToggleFieldTest.php +++ b/tests/Symfony/Tests/Components/Form/ToggleFieldTest.php @@ -9,60 +9,60 @@ use Symfony\Tests\Components\Form\Fixtures\TestToggleField; class ToggleFieldTest extends \PHPUnit_Framework_TestCase { - public function testRender_selected() - { - $field = new TestToggleField('name'); - $field->setData(true); + public function testRender_selected() + { + $field = new TestToggleField('name'); + $field->setData(true); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render(array( - 'class' => 'foobar', - ))); - } + $this->assertEquals($html, $field->render(array( + 'class' => 'foobar', + ))); + } - public function testRender_deselected() - { - $field = new TestToggleField('name'); - $field->setData(false); + public function testRender_deselected() + { + $field = new TestToggleField('name'); + $field->setData(false); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRender_withValue() - { - $field = new TestToggleField('name', array('value' => 'foobar')); + public function testRender_withValue() + { + $field = new TestToggleField('name', array('value' => 'foobar')); - $html = ''; + $html = ''; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRender_withLabel() - { - $field = new TestToggleField('name', array('label' => 'foobar')); + public function testRender_withLabel() + { + $field = new TestToggleField('name', array('label' => 'foobar')); - $html = ' '; + $html = ' '; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } - public function testRender_withTranslatedLabel() - { - $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); - $translator->expects($this->any()) - ->method('translate') - ->will($this->returnCallback(function($text) { - return 'translated['.$text.']'; - })); + public function testRender_withTranslatedLabel() + { + $translator = $this->getMock('Symfony\Components\I18N\TranslatorInterface'); + $translator->expects($this->any()) + ->method('translate') + ->will($this->returnCallback(function($text) { + return 'translated['.$text.']'; + })); - $field = new TestToggleField('name', array('label' => 'foobar', 'translate_label' => true)); - $field->setTranslator($translator); + $field = new TestToggleField('name', array('label' => 'foobar', 'translate_label' => true)); + $field->setTranslator($translator); - $html = ' '; + $html = ' '; - $this->assertEquals($html, $field->render()); - } + $this->assertEquals($html, $field->render()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/BooleanToStringTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/BooleanToStringTransformerTest.php index 1a63193660..b3d5ce89c7 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/BooleanToStringTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/BooleanToStringTransformerTest.php @@ -9,37 +9,37 @@ use Symfony\Components\Form\ValueTransformer\BooleanToStringTransformer; class BooleanToStringTransformerTest extends \PHPUnit_Framework_TestCase { - protected $transformer; + protected $transformer; - public function setUp() - { - $this->transformer = new BooleanToStringTransformer(); - } + public function setUp() + { + $this->transformer = new BooleanToStringTransformer(); + } - public function testTransform() - { - $this->assertEquals('1', $this->transformer->transform(true)); - $this->assertEquals('', $this->transformer->transform(false)); - } + public function testTransform() + { + $this->assertEquals('1', $this->transformer->transform(true)); + $this->assertEquals('', $this->transformer->transform(false)); + } - public function testTransformExpectsBoolean() - { - $this->setExpectedException('\InvalidArgumentException'); + public function testTransformExpectsBoolean() + { + $this->setExpectedException('\InvalidArgumentException'); - $this->transformer->transform('1'); - } + $this->transformer->transform('1'); + } - public function testReverseTransformExpectsString() - { - $this->setExpectedException('\InvalidArgumentException'); + public function testReverseTransformExpectsString() + { + $this->setExpectedException('\InvalidArgumentException'); - $this->transformer->reverseTransform(1); - } + $this->transformer->reverseTransform(1); + } - public function testReverseTransform() - { - $this->assertEquals(true, $this->transformer->reverseTransform('1')); - $this->assertEquals(true, $this->transformer->reverseTransform('0')); - $this->assertEquals(false, $this->transformer->reverseTransform('')); - } + public function testReverseTransform() + { + $this->assertEquals(true, $this->transformer->reverseTransform('1')); + $this->assertEquals(true, $this->transformer->reverseTransform('0')); + $this->assertEquals(false, $this->transformer->reverseTransform('')); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToArrayTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToArrayTransformerTest.php index 96276cda32..95ca6043dd 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToArrayTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToArrayTransformerTest.php @@ -10,172 +10,172 @@ use Symfony\Tests\Components\Form\DateTimeTestCase; class DateTimeToArrayTransformerTest extends DateTimeTestCase { - public function testTransform() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); + public function testTransform() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); - $input = new \DateTime('2010-02-03 04:05:06 UTC'); + $input = new \DateTime('2010-02-03 04:05:06 UTC'); - $output = array( - 'year' => 2010, - 'month' => 2, - 'day' => 3, - 'hour' => 4, - 'minute' => 5, - 'second' => 6, - ); + $output = array( + 'year' => 2010, + 'month' => 2, + 'day' => 3, + 'hour' => 4, + 'minute' => 5, + 'second' => 6, + ); - $this->assertSame($output, $transformer->transform($input)); - } + $this->assertSame($output, $transformer->transform($input)); + } - public function testTransform_withFields() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'fields' => array('year', 'month', 'minute', 'second'), - )); + public function testTransform_withFields() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'fields' => array('year', 'month', 'minute', 'second'), + )); - $input = new \DateTime('2010-02-03 04:05:06 UTC'); + $input = new \DateTime('2010-02-03 04:05:06 UTC'); - $output = array( - 'year' => 2010, - 'month' => 2, - 'minute' => 5, - 'second' => 6, - ); + $output = array( + 'year' => 2010, + 'month' => 2, + 'minute' => 5, + 'second' => 6, + ); - $this->assertSame($output, $transformer->transform($input)); - } + $this->assertSame($output, $transformer->transform($input)); + } - public function testTransform_withPadding() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'pad' => true, - )); + public function testTransform_withPadding() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'pad' => true, + )); - $input = new \DateTime('2010-02-03 04:05:06 UTC'); + $input = new \DateTime('2010-02-03 04:05:06 UTC'); - $output = array( - 'year' => '2010', - 'month' => '02', - 'day' => '03', - 'hour' => '04', - 'minute' => '05', - 'second' => '06', - ); + $output = array( + 'year' => '2010', + 'month' => '02', + 'day' => '03', + 'hour' => '04', + 'minute' => '05', + 'second' => '06', + ); - $this->assertSame($output, $transformer->transform($input)); - } + $this->assertSame($output, $transformer->transform($input)); + } - public function testTransform_differentTimezones() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'America/New_York', - 'output_timezone' => 'Asia/Hong_Kong', - )); + public function testTransform_differentTimezones() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'America/New_York', + 'output_timezone' => 'Asia/Hong_Kong', + )); - $input = new \DateTime('2010-02-03 04:05:06 America/New_York'); + $input = new \DateTime('2010-02-03 04:05:06 America/New_York'); - $dateTime = new \DateTime('2010-02-03 04:05:06 America/New_York'); - $dateTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong')); - $output = array( - 'year' => (int)$dateTime->format('Y'), - 'month' => (int)$dateTime->format('m'), - 'day' => (int)$dateTime->format('d'), - 'hour' => (int)$dateTime->format('H'), - 'minute' => (int)$dateTime->format('i'), - 'second' => (int)$dateTime->format('s'), - ); + $dateTime = new \DateTime('2010-02-03 04:05:06 America/New_York'); + $dateTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong')); + $output = array( + 'year' => (int)$dateTime->format('Y'), + 'month' => (int)$dateTime->format('m'), + 'day' => (int)$dateTime->format('d'), + 'hour' => (int)$dateTime->format('H'), + 'minute' => (int)$dateTime->format('i'), + 'second' => (int)$dateTime->format('s'), + ); - $this->assertSame($output, $transformer->transform($input)); - } + $this->assertSame($output, $transformer->transform($input)); + } - public function testTransformRequiresDateTime() - { - $transformer = new DateTimeToArrayTransformer(); + public function testTransformRequiresDateTime() + { + $transformer = new DateTimeToArrayTransformer(); - $this->setExpectedException('\InvalidArgumentException'); + $this->setExpectedException('\InvalidArgumentException'); - $transformer->reverseTransform('12345'); - } + $transformer->reverseTransform('12345'); + } - public function testReverseTransform() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); + public function testReverseTransform() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); - $input = array( - 'year' => 2010, - 'month' => 2, - 'day' => 3, - 'hour' => 4, - 'minute' => 5, - 'second' => 6, - ); + $input = array( + 'year' => 2010, + 'month' => 2, + 'day' => 3, + 'hour' => 4, + 'minute' => 5, + 'second' => 6, + ); - $output = new \DateTime('2010-02-03 04:05:06 UTC'); + $output = new \DateTime('2010-02-03 04:05:06 UTC'); - $this->assertDateTimeEquals($output, $transformer->reverseTransform($input)); - } + $this->assertDateTimeEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransform_differentTimezones() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'America/New_York', - 'output_timezone' => 'Asia/Hong_Kong', - )); + public function testReverseTransform_differentTimezones() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'America/New_York', + 'output_timezone' => 'Asia/Hong_Kong', + )); - $input = array( - 'year' => 2010, - 'month' => 2, - 'day' => 3, - 'hour' => 4, - 'minute' => 5, - 'second' => 6, - ); + $input = array( + 'year' => 2010, + 'month' => 2, + 'day' => 3, + 'hour' => 4, + 'minute' => 5, + 'second' => 6, + ); - $output = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); - $output->setTimezone(new \DateTimeZone('America/New_York')); + $output = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); + $output->setTimezone(new \DateTimeZone('America/New_York')); - $this->assertDateTimeEquals($output, $transformer->reverseTransform($input)); - } + $this->assertDateTimeEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransformToDifferentTimezone() - { - $transformer = new DateTimeToArrayTransformer(array( - 'input_timezone' => 'Asia/Hong_Kong', - 'output_timezone' => 'UTC', - )); + public function testReverseTransformToDifferentTimezone() + { + $transformer = new DateTimeToArrayTransformer(array( + 'input_timezone' => 'Asia/Hong_Kong', + 'output_timezone' => 'UTC', + )); - $input = array( - 'year' => 2010, - 'month' => 2, - 'day' => 3, - 'hour' => 4, - 'minute' => 5, - 'second' => 6, - ); + $input = array( + 'year' => 2010, + 'month' => 2, + 'day' => 3, + 'hour' => 4, + 'minute' => 5, + 'second' => 6, + ); - $output = new \DateTime('2010-02-03 04:05:06 UTC'); - $output->setTimezone(new \DateTimeZone('Asia/Hong_Kong')); + $output = new \DateTime('2010-02-03 04:05:06 UTC'); + $output->setTimezone(new \DateTimeZone('Asia/Hong_Kong')); - $this->assertDateTimeEquals($output, $transformer->reverseTransform($input)); - } + $this->assertDateTimeEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransformRequiresArray() - { - $transformer = new DateTimeToArrayTransformer(); + public function testReverseTransformRequiresArray() + { + $transformer = new DateTimeToArrayTransformer(); - $this->setExpectedException('\InvalidArgumentException'); + $this->setExpectedException('\InvalidArgumentException'); - $transformer->reverseTransform('12345'); - } + $transformer->reverseTransform('12345'); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformerTest.php index 8ec4a4ff73..dda3da248a 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -10,301 +10,300 @@ use Symfony\Tests\Components\Form\DateTimeTestCase; class DateTimeToLocalizedStringTransformerTest extends DateTimeTestCase { - protected $dateTime; - protected $dateTimeWithoutSeconds; + protected $dateTime; + protected $dateTimeWithoutSeconds; - public function setUp() - { - $this->dateTime = new \DateTime('2010-02-03 04:05:06 UTC'); - $this->dateTimeWithoutSeconds = new \DateTime('2010-02-03 04:05:00 UTC'); - } - - public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) - { - if ($expected instanceof \DateTime && $actual instanceof \DateTime) + public function setUp() { - $expected = $expected->format('c'); - $actual = $actual->format('c'); + $this->dateTime = new \DateTime('2010-02-03 04:05:06 UTC'); + $this->dateTimeWithoutSeconds = new \DateTime('2010-02-03 04:05:00 UTC'); } - parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); - } + public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) + { + if ($expected instanceof \DateTime && $actual instanceof \DateTime) { + $expected = $expected->format('c'); + $actual = $actual->format('c'); + } - public function testTransformShortDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'short', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03.02.10 04:05', $transformer->transform($this->dateTime)); - } + parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); + } - public function testTransformMediumDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'medium', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03.02.2010 04:05', $transformer->transform($this->dateTime)); - } + public function testTransformShortDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'short', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03.02.10 04:05', $transformer->transform($this->dateTime)); + } - public function testTransformLongDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'long', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03. Februar 2010 04:05', $transformer->transform($this->dateTime)); - } + public function testTransformMediumDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'medium', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03.02.2010 04:05', $transformer->transform($this->dateTime)); + } - public function testTransformFullDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'full', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('Mittwoch, 03. Februar 2010 04:05', $transformer->transform($this->dateTime)); - } + public function testTransformLongDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'long', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03. Februar 2010 04:05', $transformer->transform($this->dateTime)); + } - public function testTransformShortTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'short', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03.02.2010 04:05', $transformer->transform($this->dateTime)); - } + public function testTransformFullDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'full', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('Mittwoch, 03. Februar 2010 04:05', $transformer->transform($this->dateTime)); + } - public function testTransformMediumTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'medium', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03.02.2010 04:05:06', $transformer->transform($this->dateTime)); - } + public function testTransformShortTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'short', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03.02.2010 04:05', $transformer->transform($this->dateTime)); + } - public function testTransformLongTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'long', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03.02.2010 04:05:06 GMT+00:00', $transformer->transform($this->dateTime)); - } + public function testTransformMediumTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'medium', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03.02.2010 04:05:06', $transformer->transform($this->dateTime)); + } - public function testTransformFullTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'full', - )); - $transformer->setLocale('de_AT'); - $this->assertEquals('03.02.2010 04:05:06 GMT+00:00', $transformer->transform($this->dateTime)); - } + public function testTransformLongTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'long', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03.02.2010 04:05:06 GMT+00:00', $transformer->transform($this->dateTime)); + } - public function testTransformToDifferentLocale() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); - $transformer->setLocale('en_US'); - $this->assertEquals('Feb 3, 2010 4:05 AM', $transformer->transform($this->dateTime)); - } + public function testTransformFullTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'full', + )); + $transformer->setLocale('de_AT'); + $this->assertEquals('03.02.2010 04:05:06 GMT+00:00', $transformer->transform($this->dateTime)); + } - public function testTransform_differentTimezones() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'America/New_York', - 'output_timezone' => 'Asia/Hong_Kong', - )); - $transformer->setLocale('de_AT'); + public function testTransformToDifferentLocale() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); + $transformer->setLocale('en_US'); + $this->assertEquals('Feb 3, 2010 4:05 AM', $transformer->transform($this->dateTime)); + } - $input = new \DateTime('2010-02-03 04:05:06 America/New_York'); + public function testTransform_differentTimezones() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'America/New_York', + 'output_timezone' => 'Asia/Hong_Kong', + )); + $transformer->setLocale('de_AT'); - $dateTime = clone $input; - $dateTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong')); + $input = new \DateTime('2010-02-03 04:05:06 America/New_York'); - $this->assertEquals($dateTime->format('d.m.Y H:i'), $transformer->transform($input)); - } + $dateTime = clone $input; + $dateTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong')); - public function testTransformRequiresValidDateTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(); + $this->assertEquals($dateTime->format('d.m.Y H:i'), $transformer->transform($input)); + } - $this->setExpectedException('\InvalidArgumentException'); + public function testTransformRequiresValidDateTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(); - $transformer->transform('2010-01-01'); - } + $this->setExpectedException('\InvalidArgumentException'); - public function testTransformWrapsIntlErrors() - { - $transformer = new DateTimeToLocalizedStringTransformer(); + $transformer->transform('2010-01-01'); + } - // HOW TO REPRODUCE? + public function testTransformWrapsIntlErrors() + { + $transformer = new DateTimeToLocalizedStringTransformer(); - //$this->setExpectedException('Symfony\Components\Form\ValueTransformer\Transdate_formationFailedException'); + // HOW TO REPRODUCE? - //$transformer->transform(1.5); - } + //$this->setExpectedException('Symfony\Components\Form\ValueTransformer\Transdate_formationFailedException'); - public function testReverseTransformShortDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'short', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03.02.10 04:05')); - } + //$transformer->transform(1.5); + } - public function testReverseTransformMediumDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'medium', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03.02.2010 04:05')); - } + public function testReverseTransformShortDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'short', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03.02.10 04:05')); + } - public function testReverseTransformLongDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'long', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03. Februar 2010 04:05')); - } + public function testReverseTransformMediumDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'medium', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03.02.2010 04:05')); + } - public function testReverseTransformFullDate() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'date_format' => 'full', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('Mittwoch, 03. Februar 2010 04:05')); - } + public function testReverseTransformLongDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'long', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03. Februar 2010 04:05')); + } - public function testReverseTransformShortTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'short', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03.02.2010 04:05')); - } + public function testReverseTransformFullDate() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'date_format' => 'full', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('Mittwoch, 03. Februar 2010 04:05')); + } - public function testReverseTransformMediumTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'medium', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06')); - } + public function testReverseTransformShortTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'short', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('03.02.2010 04:05')); + } - public function testReverseTransformLongTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'long', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06 GMT+00:00')); - } + public function testReverseTransformMediumTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'medium', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06')); + } - public function testReverseTransformFullTime() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - 'time_format' => 'full', - )); - $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06 GMT+00:00')); - } + public function testReverseTransformLongTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'long', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06 GMT+00:00')); + } - public function testReverseTransformFromDifferentLocale() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); - $transformer->setLocale('en_US'); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('Feb 3, 2010 04:05 AM')); - } + public function testReverseTransformFullTime() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + 'time_format' => 'full', + )); + $transformer->setLocale('de_AT'); + $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06 GMT+00:00')); + } - public function testReverseTransform_differentTimezones() - { - $transformer = new DateTimeToLocalizedStringTransformer(array( - 'input_timezone' => 'America/New_York', - 'output_timezone' => 'Asia/Hong_Kong', - )); - $transformer->setLocale('de_AT'); + public function testReverseTransformFromDifferentLocale() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); + $transformer->setLocale('en_US'); + $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('Feb 3, 2010 04:05 AM')); + } - $dateTime = new \DateTime('2010-02-03 04:05:00 Asia/Hong_Kong'); - $dateTime->setTimezone(new \DateTimeZone('America/New_York')); + public function testReverseTransform_differentTimezones() + { + $transformer = new DateTimeToLocalizedStringTransformer(array( + 'input_timezone' => 'America/New_York', + 'output_timezone' => 'Asia/Hong_Kong', + )); + $transformer->setLocale('de_AT'); - $this->assertDateTimeEquals($dateTime, $transformer->reverseTransform('03.02.2010 04:05')); - } + $dateTime = new \DateTime('2010-02-03 04:05:00 Asia/Hong_Kong'); + $dateTime->setTimezone(new \DateTimeZone('America/New_York')); - public function testReverseTransformRequiresString() - { - $transformer = new DateTimeToLocalizedStringTransformer(); + $this->assertDateTimeEquals($dateTime, $transformer->reverseTransform('03.02.2010 04:05')); + } - $this->setExpectedException('\InvalidArgumentException'); + public function testReverseTransformRequiresString() + { + $transformer = new DateTimeToLocalizedStringTransformer(); - $transformer->reverseTransform(12345); - } + $this->setExpectedException('\InvalidArgumentException'); - public function testReverseTransformWrapsIntlErrors() - { - $transformer = new DateTimeToLocalizedStringTransformer(); + $transformer->reverseTransform(12345); + } - $this->setExpectedException('Symfony\Components\Form\ValueTransformer\TransformationFailedException'); + public function testReverseTransformWrapsIntlErrors() + { + $transformer = new DateTimeToLocalizedStringTransformer(); - $transformer->reverseTransform('12345'); - } + $this->setExpectedException('Symfony\Components\Form\ValueTransformer\TransformationFailedException'); - public function testValidateDateFormatOption() - { - $this->setExpectedException('\InvalidArgumentException'); + $transformer->reverseTransform('12345'); + } - new DateTimeToLocalizedStringTransformer(array('date_format' => 'foobar')); - } + public function testValidateDateFormatOption() + { + $this->setExpectedException('\InvalidArgumentException'); - public function testValidateTimeFormatOption() - { - $this->setExpectedException('\InvalidArgumentException'); + new DateTimeToLocalizedStringTransformer(array('date_format' => 'foobar')); + } - new DateTimeToLocalizedStringTransformer(array('time_format' => 'foobar')); - } + public function testValidateTimeFormatOption() + { + $this->setExpectedException('\InvalidArgumentException'); + + new DateTimeToLocalizedStringTransformer(array('time_format' => 'foobar')); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/NumberToLocalizedStringTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/NumberToLocalizedStringTransformerTest.php index 34ae20e9b9..52012e2f31 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/NumberToLocalizedStringTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/NumberToLocalizedStringTransformerTest.php @@ -9,78 +9,78 @@ use Symfony\Components\Form\ValueTransformer\NumberToLocalizedStringTransformer; class NumberToLocalizedStringTransformerTest extends \PHPUnit_Framework_TestCase { - public function testTransform() - { - $transformer = new NumberToLocalizedStringTransformer(); - $transformer->setLocale('de_AT'); + public function testTransform() + { + $transformer = new NumberToLocalizedStringTransformer(); + $transformer->setLocale('de_AT'); - $this->assertEquals('1', $transformer->transform(1)); - $this->assertEquals('1,5', $transformer->transform(1.5)); - $this->assertEquals('1234,5', $transformer->transform(1234.5)); - $this->assertEquals('12345,912', $transformer->transform(12345.9123)); - } + $this->assertEquals('1', $transformer->transform(1)); + $this->assertEquals('1,5', $transformer->transform(1.5)); + $this->assertEquals('1234,5', $transformer->transform(1234.5)); + $this->assertEquals('12345,912', $transformer->transform(12345.9123)); + } - public function testTransformWithGrouping() - { - $transformer = new NumberToLocalizedStringTransformer(array( - 'grouping' => true, - )); - $transformer->setLocale('de_AT'); + public function testTransformWithGrouping() + { + $transformer = new NumberToLocalizedStringTransformer(array( + 'grouping' => true, + )); + $transformer->setLocale('de_AT'); - $this->assertEquals('1.234,5', $transformer->transform(1234.5)); - $this->assertEquals('12.345,912', $transformer->transform(12345.9123)); - } + $this->assertEquals('1.234,5', $transformer->transform(1234.5)); + $this->assertEquals('12.345,912', $transformer->transform(12345.9123)); + } - public function testTransformWithPrecision() - { - $transformer = new NumberToLocalizedStringTransformer(array( - 'precision' => 2, - )); - $transformer->setLocale('de_AT'); + public function testTransformWithPrecision() + { + $transformer = new NumberToLocalizedStringTransformer(array( + 'precision' => 2, + )); + $transformer->setLocale('de_AT'); - $this->assertEquals('1234,50', $transformer->transform(1234.5)); - $this->assertEquals('678,92', $transformer->transform(678.916)); - } + $this->assertEquals('1234,50', $transformer->transform(1234.5)); + $this->assertEquals('678,92', $transformer->transform(678.916)); + } - public function testReverseTransform() - { - $transformer = new NumberToLocalizedStringTransformer(); - $transformer->setLocale('de_AT'); + public function testReverseTransform() + { + $transformer = new NumberToLocalizedStringTransformer(); + $transformer->setLocale('de_AT'); - $this->assertEquals(1, $transformer->reverseTransform('1')); - $this->assertEquals(1.5, $transformer->reverseTransform('1,5')); - $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5')); - $this->assertEquals(12345.912, $transformer->reverseTransform('12345,912')); - } + $this->assertEquals(1, $transformer->reverseTransform('1')); + $this->assertEquals(1.5, $transformer->reverseTransform('1,5')); + $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5')); + $this->assertEquals(12345.912, $transformer->reverseTransform('12345,912')); + } - public function testReverseTransformWithGrouping() - { - $transformer = new NumberToLocalizedStringTransformer(array( - 'grouping' => true, - )); - $transformer->setLocale('de_AT'); + public function testReverseTransformWithGrouping() + { + $transformer = new NumberToLocalizedStringTransformer(array( + 'grouping' => true, + )); + $transformer->setLocale('de_AT'); - $this->assertEquals(1234.5, $transformer->reverseTransform('1.234,5')); - $this->assertEquals(12345.912, $transformer->reverseTransform('12.345,912')); - $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5')); - $this->assertEquals(12345.912, $transformer->reverseTransform('12345,912')); - } + $this->assertEquals(1234.5, $transformer->reverseTransform('1.234,5')); + $this->assertEquals(12345.912, $transformer->reverseTransform('12.345,912')); + $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5')); + $this->assertEquals(12345.912, $transformer->reverseTransform('12345,912')); + } - public function testTransformExpectsNumeric() - { - $transformer = new NumberToLocalizedStringTransformer(); + public function testTransformExpectsNumeric() + { + $transformer = new NumberToLocalizedStringTransformer(); - $this->setExpectedException('\InvalidArgumentException'); + $this->setExpectedException('\InvalidArgumentException'); - $transformer->transform('foo'); - } + $transformer->transform('foo'); + } - public function testReverseTransformExpectsString() - { - $transformer = new NumberToLocalizedStringTransformer(); + public function testReverseTransformExpectsString() + { + $transformer = new NumberToLocalizedStringTransformer(); - $this->setExpectedException('\InvalidArgumentException'); + $this->setExpectedException('\InvalidArgumentException'); - $transformer->reverseTransform(1); - } + $transformer->reverseTransform(1); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/PercentToLocalizedStringTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/PercentToLocalizedStringTransformerTest.php index ec1c8c2dd9..a4e1663408 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/PercentToLocalizedStringTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/PercentToLocalizedStringTransformerTest.php @@ -9,89 +9,89 @@ use Symfony\Components\Form\ValueTransformer\PercentToLocalizedStringTransformer class PercentToLocalizedStringTransformerTest extends \PHPUnit_Framework_TestCase { - public function testTransform() - { - $transformer = new PercentToLocalizedStringTransformer(); - $transformer->setLocale('de_AT'); + public function testTransform() + { + $transformer = new PercentToLocalizedStringTransformer(); + $transformer->setLocale('de_AT'); - $this->assertEquals('10', $transformer->transform(0.1)); - $this->assertEquals('15', $transformer->transform(0.15)); - $this->assertEquals('12', $transformer->transform(0.1234)); - $this->assertEquals('200', $transformer->transform(2)); - } + $this->assertEquals('10', $transformer->transform(0.1)); + $this->assertEquals('15', $transformer->transform(0.15)); + $this->assertEquals('12', $transformer->transform(0.1234)); + $this->assertEquals('200', $transformer->transform(2)); + } - public function testTransformWithInteger() - { - $transformer = new PercentToLocalizedStringTransformer(array( - 'type' => 'integer', - )); - $transformer->setLocale('de_AT'); + public function testTransformWithInteger() + { + $transformer = new PercentToLocalizedStringTransformer(array( + 'type' => 'integer', + )); + $transformer->setLocale('de_AT'); - $this->assertEquals('0', $transformer->transform(0.1)); - $this->assertEquals('1', $transformer->transform(1)); - $this->assertEquals('15', $transformer->transform(15)); - $this->assertEquals('16', $transformer->transform(15.9)); - } + $this->assertEquals('0', $transformer->transform(0.1)); + $this->assertEquals('1', $transformer->transform(1)); + $this->assertEquals('15', $transformer->transform(15)); + $this->assertEquals('16', $transformer->transform(15.9)); + } - public function testTransformWithPrecision() - { - $transformer = new PercentToLocalizedStringTransformer(array( - 'precision' => 2, - )); - $transformer->setLocale('de_AT'); + public function testTransformWithPrecision() + { + $transformer = new PercentToLocalizedStringTransformer(array( + 'precision' => 2, + )); + $transformer->setLocale('de_AT'); - $this->assertEquals('12,34', $transformer->transform(0.1234)); - } + $this->assertEquals('12,34', $transformer->transform(0.1234)); + } - public function testReverseTransform() - { - $transformer = new PercentToLocalizedStringTransformer(); - $transformer->setLocale('de_AT'); + public function testReverseTransform() + { + $transformer = new PercentToLocalizedStringTransformer(); + $transformer->setLocale('de_AT'); - $this->assertEquals(0.1, $transformer->reverseTransform('10')); - $this->assertEquals(0.15, $transformer->reverseTransform('15')); - $this->assertEquals(0.12, $transformer->reverseTransform('12')); - $this->assertEquals(2, $transformer->reverseTransform('200')); - } + $this->assertEquals(0.1, $transformer->reverseTransform('10')); + $this->assertEquals(0.15, $transformer->reverseTransform('15')); + $this->assertEquals(0.12, $transformer->reverseTransform('12')); + $this->assertEquals(2, $transformer->reverseTransform('200')); + } - public function testReverseTransformWithInteger() - { - $transformer = new PercentToLocalizedStringTransformer(array( - 'type' => 'integer', - )); - $transformer->setLocale('de_AT'); + public function testReverseTransformWithInteger() + { + $transformer = new PercentToLocalizedStringTransformer(array( + 'type' => 'integer', + )); + $transformer->setLocale('de_AT'); - $this->assertEquals(10, $transformer->reverseTransform('10')); - $this->assertEquals(15, $transformer->reverseTransform('15')); - $this->assertEquals(12, $transformer->reverseTransform('12')); - $this->assertEquals(200, $transformer->reverseTransform('200')); - } + $this->assertEquals(10, $transformer->reverseTransform('10')); + $this->assertEquals(15, $transformer->reverseTransform('15')); + $this->assertEquals(12, $transformer->reverseTransform('12')); + $this->assertEquals(200, $transformer->reverseTransform('200')); + } - public function testReverseTransformWithPrecision() - { - $transformer = new PercentToLocalizedStringTransformer(array( - 'precision' => 2, - )); - $transformer->setLocale('de_AT'); + public function testReverseTransformWithPrecision() + { + $transformer = new PercentToLocalizedStringTransformer(array( + 'precision' => 2, + )); + $transformer->setLocale('de_AT'); - $this->assertEquals(0.1234, $transformer->reverseTransform('12,34')); - } + $this->assertEquals(0.1234, $transformer->reverseTransform('12,34')); + } - public function testTransformExpectsNumeric() - { - $transformer = new PercentToLocalizedStringTransformer(); + public function testTransformExpectsNumeric() + { + $transformer = new PercentToLocalizedStringTransformer(); - $this->setExpectedException('\InvalidArgumentException'); + $this->setExpectedException('\InvalidArgumentException'); - $transformer->transform('foo'); - } + $transformer->transform('foo'); + } - public function testReverseTransformExpectsString() - { - $transformer = new PercentToLocalizedStringTransformer(); + public function testReverseTransformExpectsString() + { + $transformer = new PercentToLocalizedStringTransformer(); - $this->setExpectedException('\InvalidArgumentException'); + $this->setExpectedException('\InvalidArgumentException'); - $transformer->reverseTransform(1); - } + $transformer->reverseTransform(1); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/StringToDateTimeTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/StringToDateTimeTransformerTest.php index 3a5b7d8961..2ccfc84dfa 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/StringToDateTimeTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/StringToDateTimeTransformerTest.php @@ -10,75 +10,75 @@ use Symfony\Tests\Components\Form\DateTimeTestCase; class StringToDateTimeTransformerTest extends DateTimeTestCase { - public function testTransform() - { - $transformer = new StringToDateTimeTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); + public function testTransform() + { + $transformer = new StringToDateTimeTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); - $output = new \DateTime('2010-02-03 04:05:06 UTC'); - $input = $output->format('Y-m-d H:i:s'); + $output = new \DateTime('2010-02-03 04:05:06 UTC'); + $input = $output->format('Y-m-d H:i:s'); - $this->assertDateTimeEquals($output, $transformer->transform($input)); - } + $this->assertDateTimeEquals($output, $transformer->transform($input)); + } - public function testTransform_differentTimezones() - { - $transformer = new StringToDateTimeTransformer(array( - 'input_timezone' => 'America/New_York', - 'output_timezone' => 'Asia/Hong_Kong', - )); + public function testTransform_differentTimezones() + { + $transformer = new StringToDateTimeTransformer(array( + 'input_timezone' => 'America/New_York', + 'output_timezone' => 'Asia/Hong_Kong', + )); - $output = new \DateTime('2010-02-03 04:05:06 America/New_York'); - $input = $output->format('Y-m-d H:i:s'); - $output->setTimeZone(new \DateTimeZone('Asia/Hong_Kong')); + $output = new \DateTime('2010-02-03 04:05:06 America/New_York'); + $input = $output->format('Y-m-d H:i:s'); + $output->setTimeZone(new \DateTimeZone('Asia/Hong_Kong')); - $this->assertDateTimeEquals($output, $transformer->transform($input)); - } + $this->assertDateTimeEquals($output, $transformer->transform($input)); + } - public function testTransformExpectsValidString() - { - $transformer = new StringToDateTimeTransformer(); + public function testTransformExpectsValidString() + { + $transformer = new StringToDateTimeTransformer(); - $this->setExpectedException('\InvalidArgumentException'); - $transformer->transform('2010-2010-2010'); - } + $this->setExpectedException('\InvalidArgumentException'); + $transformer->transform('2010-2010-2010'); + } - public function testReverseTransform() - { - $transformer = new StringToDateTimeTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); + public function testReverseTransform() + { + $transformer = new StringToDateTimeTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); - $input = new \DateTime('2010-02-03 04:05:06 UTC'); - $output = clone $input; - $output->setTimezone(new \DateTimeZone('UTC')); - $output = $output->format('Y-m-d H:i:s'); + $input = new \DateTime('2010-02-03 04:05:06 UTC'); + $output = clone $input; + $output->setTimezone(new \DateTimeZone('UTC')); + $output = $output->format('Y-m-d H:i:s'); - $this->assertEquals($output, $transformer->reverseTransform($input)); - } + $this->assertEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransform_differentTimezones() - { - $transformer = new StringToDateTimeTransformer(array( - 'input_timezone' => 'Asia/Hong_Kong', - 'output_timezone' => 'America/New_York', - )); + public function testReverseTransform_differentTimezones() + { + $transformer = new StringToDateTimeTransformer(array( + 'input_timezone' => 'Asia/Hong_Kong', + 'output_timezone' => 'America/New_York', + )); - $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); - $output = $input->format('Y-m-d H:i:s'); - $input->setTimezone(new \DateTimeZone('America/New_York')); + $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); + $output = $input->format('Y-m-d H:i:s'); + $input->setTimezone(new \DateTimeZone('America/New_York')); - $this->assertEquals($output, $transformer->reverseTransform($input)); - } + $this->assertEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransformExpectsDateTime() - { - $transformer = new StringToDateTimeTransformer(); + public function testReverseTransformExpectsDateTime() + { + $transformer = new StringToDateTimeTransformer(); - $this->setExpectedException('\InvalidArgumentException'); - $transformer->reverseTransform('1234'); - } + $this->setExpectedException('\InvalidArgumentException'); + $transformer->reverseTransform('1234'); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/TimestampToDateTimeTransformerTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/TimestampToDateTimeTransformerTest.php index 3d29cf1b60..19bc01ea61 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/TimestampToDateTimeTransformerTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/TimestampToDateTimeTransformerTest.php @@ -10,89 +10,89 @@ use Symfony\Tests\Components\Form\DateTimeTestCase; class TimestampToDateTimeTransformerTest extends DateTimeTestCase { - public function testTransform() - { - $transformer = new TimestampToDateTimeTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); + public function testTransform() + { + $transformer = new TimestampToDateTimeTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); - $output = new \DateTime('2010-02-03 04:05:06 UTC'); - $input = $output->format('U'); + $output = new \DateTime('2010-02-03 04:05:06 UTC'); + $input = $output->format('U'); - $this->assertDateTimeEquals($output, $transformer->transform($input)); - } + $this->assertDateTimeEquals($output, $transformer->transform($input)); + } - public function testTransform_differentTimezones() - { - $transformer = new TimestampToDateTimeTransformer(array( - 'input_timezone' => 'Asia/Hong_Kong', - 'output_timezone' => 'America/New_York', - )); + public function testTransform_differentTimezones() + { + $transformer = new TimestampToDateTimeTransformer(array( + 'input_timezone' => 'Asia/Hong_Kong', + 'output_timezone' => 'America/New_York', + )); - $output = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); - $input = $output->format('U'); - $output->setTimezone(new \DateTimeZone('America/New_York')); + $output = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); + $input = $output->format('U'); + $output->setTimezone(new \DateTimeZone('America/New_York')); - $this->assertDateTimeEquals($output, $transformer->transform($input)); - } + $this->assertDateTimeEquals($output, $transformer->transform($input)); + } - public function testReverseTransformExpectsValidTimestamp() - { - $transformer = new TimestampToDateTimeTransformer(); + public function testReverseTransformExpectsValidTimestamp() + { + $transformer = new TimestampToDateTimeTransformer(); - $this->setExpectedException('\InvalidArgumentException'); - $transformer->transform('2010-2010-2010'); - } + $this->setExpectedException('\InvalidArgumentException'); + $transformer->transform('2010-2010-2010'); + } - public function testReverseTransform() - { - $transformer = new TimestampToDateTimeTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'UTC', - )); + public function testReverseTransform() + { + $transformer = new TimestampToDateTimeTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'UTC', + )); - $input = new \DateTime('2010-02-03 04:05:06 UTC'); - $output = $input->format('U'); + $input = new \DateTime('2010-02-03 04:05:06 UTC'); + $output = $input->format('U'); - $this->assertEquals($output, $transformer->reverseTransform($input)); - } + $this->assertEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransform_differentTimezones() - { - $transformer = new TimestampToDateTimeTransformer(array( - 'input_timezone' => 'Asia/Hong_Kong', - 'output_timezone' => 'America/New_York', - )); + public function testReverseTransform_differentTimezones() + { + $transformer = new TimestampToDateTimeTransformer(array( + 'input_timezone' => 'Asia/Hong_Kong', + 'output_timezone' => 'America/New_York', + )); - $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); - $output = $input->format('U'); - $input->setTimezone(new \DateTimeZone('America/New_York')); + $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); + $output = $input->format('U'); + $input->setTimezone(new \DateTimeZone('America/New_York')); - $this->assertEquals($output, $transformer->reverseTransform($input)); - } + $this->assertEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransformFromDifferentTimezone() - { - $transformer = new TimestampToDateTimeTransformer(array( - 'input_timezone' => 'UTC', - 'output_timezone' => 'Asia/Hong_Kong', - )); + public function testReverseTransformFromDifferentTimezone() + { + $transformer = new TimestampToDateTimeTransformer(array( + 'input_timezone' => 'UTC', + 'output_timezone' => 'Asia/Hong_Kong', + )); - $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); + $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong'); - $dateTime = clone $input; - $dateTime->setTimezone(new \DateTimeZone('UTC')); - $output = $dateTime->format('U'); + $dateTime = clone $input; + $dateTime->setTimezone(new \DateTimeZone('UTC')); + $output = $dateTime->format('U'); - $this->assertEquals($output, $transformer->reverseTransform($input)); - } + $this->assertEquals($output, $transformer->reverseTransform($input)); + } - public function testReverseTransformExpectsDateTime() - { - $transformer = new TimestampToDateTimeTransformer(); + public function testReverseTransformExpectsDateTime() + { + $transformer = new TimestampToDateTimeTransformer(); - $this->setExpectedException('\InvalidArgumentException'); - $transformer->reverseTransform('1234'); - } + $this->setExpectedException('\InvalidArgumentException'); + $transformer->reverseTransform('1234'); + } } diff --git a/tests/Symfony/Tests/Components/Form/ValueTransformer/ValueTransformerChainTest.php b/tests/Symfony/Tests/Components/Form/ValueTransformer/ValueTransformerChainTest.php index cdafe334da..92d68108de 100644 --- a/tests/Symfony/Tests/Components/Form/ValueTransformer/ValueTransformerChainTest.php +++ b/tests/Symfony/Tests/Components/Form/ValueTransformer/ValueTransformerChainTest.php @@ -9,55 +9,55 @@ use Symfony\Components\Form\ValueTransformer\ValueTransformerChain; class ValueTransformerChainTest extends \PHPUnit_Framework_TestCase { - public function testTransform() - { - $transformer1 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer1->expects($this->once()) - ->method('transform') - ->with($this->identicalTo('foo')) - ->will($this->returnValue('bar')); - $transformer2 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer2->expects($this->once()) - ->method('transform') - ->with($this->identicalTo('bar')) - ->will($this->returnValue('baz')); + public function testTransform() + { + $transformer1 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer1->expects($this->once()) + ->method('transform') + ->with($this->identicalTo('foo')) + ->will($this->returnValue('bar')); + $transformer2 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer2->expects($this->once()) + ->method('transform') + ->with($this->identicalTo('bar')) + ->will($this->returnValue('baz')); - $chain = new ValueTransformerChain(array($transformer1, $transformer2)); + $chain = new ValueTransformerChain(array($transformer1, $transformer2)); - $this->assertEquals('baz', $chain->transform('foo')); - } + $this->assertEquals('baz', $chain->transform('foo')); + } - public function testReverseTransform() - { - $transformer2 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer2->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo('foo')) - ->will($this->returnValue('bar')); - $transformer1 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer1->expects($this->once()) - ->method('reverseTransform') - ->with($this->identicalTo('bar')) - ->will($this->returnValue('baz')); + public function testReverseTransform() + { + $transformer2 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer2->expects($this->once()) + ->method('reverseTransform') + ->with($this->identicalTo('foo')) + ->will($this->returnValue('bar')); + $transformer1 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer1->expects($this->once()) + ->method('reverseTransform') + ->with($this->identicalTo('bar')) + ->will($this->returnValue('baz')); - $chain = new ValueTransformerChain(array($transformer1, $transformer2)); + $chain = new ValueTransformerChain(array($transformer1, $transformer2)); - $this->assertEquals('baz', $chain->reverseTransform('foo')); - } + $this->assertEquals('baz', $chain->reverseTransform('foo')); + } - public function testSetLocale() - { - $transformer1 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer1->expects($this->once()) - ->method('setLocale') - ->with($this->identicalTo('de_DE')); - $transformer2 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); - $transformer2->expects($this->once()) - ->method('setLocale') - ->with($this->identicalTo('de_DE')); + public function testSetLocale() + { + $transformer1 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer1->expects($this->once()) + ->method('setLocale') + ->with($this->identicalTo('de_DE')); + $transformer2 = $this->getMock('Symfony\Components\Form\ValueTransformer\ValueTransformerInterface'); + $transformer2->expects($this->once()) + ->method('setLocale') + ->with($this->identicalTo('de_DE')); - $chain = new ValueTransformerChain(array($transformer1, $transformer2)); + $chain = new ValueTransformerChain(array($transformer1, $transformer2)); - $chain->setLocale('de_DE'); - } + $chain->setLocale('de_DE'); + } } diff --git a/tests/Symfony/Tests/Components/Validator/ConstraintTest.php b/tests/Symfony/Tests/Components/Validator/ConstraintTest.php index 385a154ec7..e34c5e7e80 100644 --- a/tests/Symfony/Tests/Components/Validator/ConstraintTest.php +++ b/tests/Symfony/Tests/Components/Validator/ConstraintTest.php @@ -13,74 +13,74 @@ use Symfony\Tests\Components\Validator\Fixtures\ConstraintC; class ConstraintTest extends \PHPUnit_Framework_TestCase { - public function testSetProperties() - { - $constraint = new ConstraintA(array( - 'property1' => 'foo', - 'property2' => 'bar', - )); + public function testSetProperties() + { + $constraint = new ConstraintA(array( + 'property1' => 'foo', + 'property2' => 'bar', + )); - $this->assertEquals('foo', $constraint->property1); - $this->assertEquals('bar', $constraint->property2); - } + $this->assertEquals('foo', $constraint->property1); + $this->assertEquals('bar', $constraint->property2); + } - public function testSetNotExistingPropertyThrowsException() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\InvalidOptionsException'); + public function testSetNotExistingPropertyThrowsException() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\InvalidOptionsException'); - new ConstraintA(array( - 'foo' => 'bar', - )); - } + new ConstraintA(array( + 'foo' => 'bar', + )); + } - public function testMagicPropertiesAreNotAllowed() - { - $constraint = new ConstraintA(); + public function testMagicPropertiesAreNotAllowed() + { + $constraint = new ConstraintA(); - $this->setExpectedException('Symfony\Components\Validator\Exception\InvalidOptionsException'); + $this->setExpectedException('Symfony\Components\Validator\Exception\InvalidOptionsException'); - $constraint->foo = 'bar'; - } + $constraint->foo = 'bar'; + } - public function testSetDefaultProperty() - { - $constraint = new ConstraintA('foo'); + public function testSetDefaultProperty() + { + $constraint = new ConstraintA('foo'); - $this->assertEquals('foo', $constraint->property2); - } + $this->assertEquals('foo', $constraint->property2); + } - public function testSetDefaultPropertyDoctrineStyle() - { - $constraint = new ConstraintA(array('value' => 'foo')); + public function testSetDefaultPropertyDoctrineStyle() + { + $constraint = new ConstraintA(array('value' => 'foo')); - $this->assertEquals('foo', $constraint->property2); - } + $this->assertEquals('foo', $constraint->property2); + } - public function testSetUndefinedDefaultProperty() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); + public function testSetUndefinedDefaultProperty() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); - new ConstraintB('foo'); - } + new ConstraintB('foo'); + } - public function testRequiredOptionsMustBeDefined() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\MissingOptionsException'); + public function testRequiredOptionsMustBeDefined() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\MissingOptionsException'); - new ConstraintC(); - } + new ConstraintC(); + } - public function testGroupsAreConvertedToArray() - { - $constraint = new ConstraintA(array('groups' => 'Foo')); + public function testGroupsAreConvertedToArray() + { + $constraint = new ConstraintA(array('groups' => 'Foo')); - $this->assertEquals(array('Foo'), $constraint->groups); - } + $this->assertEquals(array('Foo'), $constraint->groups); + } - public function testAddDefaultGroupAddsGroup() - { - $constraint = new ConstraintA(array('groups' => 'Default')); - $constraint->addImplicitGroupName('Foo'); - $this->assertEquals(array('Default', 'Foo'), $constraint->groups); - } + public function testAddDefaultGroupAddsGroup() + { + $constraint = new ConstraintA(array('groups' => 'Default')); + $constraint->addImplicitGroupName('Foo'); + $this->assertEquals(array('Default', 'Foo'), $constraint->groups); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/AllValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/AllValidatorTest.php index a39756553b..cefcdb994e 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/AllValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/AllValidatorTest.php @@ -11,84 +11,82 @@ use Symfony\Components\Validator\Constraints\AllValidator; class AllValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; - protected $walker; - protected $context; + protected $validator; + protected $walker; + protected $context; - public function setUp() - { - $this->walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); - $metadataFactory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); - $messageInterpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); - - $this->context = new ValidationContext('Root', $this->walker, $metadataFactory, $messageInterpolator); - - $this->validator = new AllValidator(); - $this->validator->initialize($this->context); - } - - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new All(new Min(4)))); - } - - public function testThrowsExceptionIfNotTraversable() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - - $this->validator->isValid('foobar', new All(new Min(4))); - } - - /** - * @dataProvider getValidArguments - */ - public function testWalkSingleConstraint($array) - { - $this->context->setGroup('MyGroup'); - $this->context->setPropertyPath('foo'); - - $constraint = new Min(4); - - foreach ($array as $key => $value) + public function setUp() { - $this->walker->expects($this->once()) - ->method('walkConstraint') - ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + $this->walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); + $metadataFactory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); + $messageInterpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); + + $this->context = new ValidationContext('Root', $this->walker, $metadataFactory, $messageInterpolator); + + $this->validator = new AllValidator(); + $this->validator->initialize($this->context); } - $this->assertTrue($this->validator->isValid($array, new All($constraint))); - } - - /** - * @dataProvider getValidArguments - */ - public function testWalkMultipleConstraints($array) - { - $this->context->setGroup('MyGroup'); - $this->context->setPropertyPath('foo'); - - $constraint = new Min(4); - // can only test for twice the same constraint because PHPUnits mocking - // can't test method calls with different arguments - $constraints = array($constraint, $constraint); - - foreach ($array as $key => $value) + public function testNullIsValid() { - $this->walker->expects($this->exactly(2)) - ->method('walkConstraint') - ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + $this->assertTrue($this->validator->isValid(null, new All(new Min(4)))); } - $this->assertTrue($this->validator->isValid($array, new All($constraints))); - } + public function testThrowsExceptionIfNotTraversable() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - public function getValidArguments() - { - return array( - // can only test for one entry, because PHPUnits mocking does not allow - // to expect multiple method calls with different arguments - array(array(1)), - array(new \ArrayObject(array(1))), - ); - } + $this->validator->isValid('foobar', new All(new Min(4))); + } + + /** + * @dataProvider getValidArguments + */ + public function testWalkSingleConstraint($array) + { + $this->context->setGroup('MyGroup'); + $this->context->setPropertyPath('foo'); + + $constraint = new Min(4); + + foreach ($array as $key => $value) { + $this->walker->expects($this->once()) + ->method('walkConstraint') + ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + } + + $this->assertTrue($this->validator->isValid($array, new All($constraint))); + } + + /** + * @dataProvider getValidArguments + */ + public function testWalkMultipleConstraints($array) + { + $this->context->setGroup('MyGroup'); + $this->context->setPropertyPath('foo'); + + $constraint = new Min(4); + // can only test for twice the same constraint because PHPUnits mocking + // can't test method calls with different arguments + $constraints = array($constraint, $constraint); + + foreach ($array as $key => $value) { + $this->walker->expects($this->exactly(2)) + ->method('walkConstraint') + ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + } + + $this->assertTrue($this->validator->isValid($array, new All($constraints))); + } + + public function getValidArguments() + { + return array( + // can only test for one entry, because PHPUnits mocking does not allow + // to expect multiple method calls with different arguments + array(array(1)), + array(new \ArrayObject(array(1))), + ); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/AssertFalseValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/AssertFalseValidatorTest.php index c0250e857c..bbadce0034 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/AssertFalseValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/AssertFalseValidatorTest.php @@ -9,31 +9,31 @@ use Symfony\Components\Validator\Constraints\AssertFalseValidator; class AssertFalseValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new AssertFalseValidator(); - } + public function setUp() + { + $this->validator = new AssertFalseValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new AssertFalse())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new AssertFalse())); + } - public function testFalseIsValid() - { - $this->assertTrue($this->validator->isValid(false, new AssertFalse())); - } + public function testFalseIsValid() + { + $this->assertTrue($this->validator->isValid(false, new AssertFalse())); + } - public function testTrueIsInvalid() - { - $constraint = new AssertFalse(array( - 'message' => 'myMessage' - )); + public function testTrueIsInvalid() + { + $constraint = new AssertFalse(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid(true, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array()); - } + $this->assertFalse($this->validator->isValid(true, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/AssertTrueValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/AssertTrueValidatorTest.php index 06261e72ed..ffaf68aad8 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/AssertTrueValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/AssertTrueValidatorTest.php @@ -9,31 +9,31 @@ use Symfony\Components\Validator\Constraints\AssertTrueValidator; class AssertTrueValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new AssertTrueValidator(); - } + public function setUp() + { + $this->validator = new AssertTrueValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new AssertTrue())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new AssertTrue())); + } - public function testTrueIsValid() - { - $this->assertTrue($this->validator->isValid(true, new AssertTrue())); - } + public function testTrueIsValid() + { + $this->assertTrue($this->validator->isValid(true, new AssertTrue())); + } - public function testFalseIsInvalid() - { - $constraint = new AssertTrue(array( - 'message' => 'myMessage' - )); + public function testFalseIsInvalid() + { + $constraint = new AssertTrue(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid(false, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array()); - } + $this->assertFalse($this->validator->isValid(false, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/AssertTypeValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/AssertTypeValidatorTest.php index ad6c71d3e2..ef9e190726 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/AssertTypeValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/AssertTypeValidatorTest.php @@ -9,120 +9,118 @@ use Symfony\Components\Validator\Constraints\AssertTypeValidator; class AssertTypeValidatorTest extends \PHPUnit_Framework_TestCase { - protected static $file; + protected static $file; - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new AssertTypeValidator(); - } - - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new AssertType(array('type' => 'integer')))); - } - - /** - * @dataProvider getValidValues - */ - public function testValidValues($value, $type) - { - $constraint = new AssertType(array('type' => $type)); - - $this->assertTrue($this->validator->isValid($value, $constraint)); - } - - public function getValidValues() - { - $object = new \stdClass(); - $file = $this->createFile(); - - return array( - array(true, 'boolean'), - array(false, 'boolean'), - array(true, 'bool'), - array(false, 'bool'), - array(0, 'numeric'), - array('0', 'numeric'), - array(1.5, 'numeric'), - array('1.5', 'numeric'), - array(0, 'integer'), - array(1.5, 'float'), - array('12345', 'string'), - array(array(), 'array'), - array($object, 'object'), - array($object, 'stdClass'), - array($file, 'resource'), - ); - } - - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value, $type) - { - $constraint = new AssertType(array('type' => $type)); - - $this->assertFalse($this->validator->isValid($value, $constraint)); - } - - public function getInvalidValues() - { - $object = new \stdClass(); - $file = $this->createFile(); - - return array( - array('foobar', 'numeric'), - array('foobar', 'boolean'), - array('0', 'integer'), - array('1.5', 'float'), - array(12345, 'string'), - array($object, 'boolean'), - array($object, 'numeric'), - array($object, 'integer'), - array($object, 'float'), - array($object, 'string'), - array($object, 'resource'), - array($file, 'boolean'), - array($file, 'numeric'), - array($file, 'integer'), - array($file, 'float'), - array($file, 'string'), - array($file, 'object'), - ); - } - - public function testMessageIsSet() - { - $constraint = new AssertType(array( - 'type' => 'numeric', - 'message' => 'myMessage' - )); - - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - 'type' => 'numeric', - )); - } - - protected function createFile() - { - if (!self::$file) + public function setUp() { - self::$file = fopen(__FILE__, 'r'); + $this->validator = new AssertTypeValidator(); } - return self::$file; - } - - public static function tearDownAfterClass() - { - if (self::$file) + public function testNullIsValid() { - fclose(self::$file); + $this->assertTrue($this->validator->isValid(null, new AssertType(array('type' => 'integer')))); + } + + /** + * @dataProvider getValidValues + */ + public function testValidValues($value, $type) + { + $constraint = new AssertType(array('type' => $type)); + + $this->assertTrue($this->validator->isValid($value, $constraint)); + } + + public function getValidValues() + { + $object = new \stdClass(); + $file = $this->createFile(); + + return array( + array(true, 'boolean'), + array(false, 'boolean'), + array(true, 'bool'), + array(false, 'bool'), + array(0, 'numeric'), + array('0', 'numeric'), + array(1.5, 'numeric'), + array('1.5', 'numeric'), + array(0, 'integer'), + array(1.5, 'float'), + array('12345', 'string'), + array(array(), 'array'), + array($object, 'object'), + array($object, 'stdClass'), + array($file, 'resource'), + ); + } + + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value, $type) + { + $constraint = new AssertType(array('type' => $type)); + + $this->assertFalse($this->validator->isValid($value, $constraint)); + } + + public function getInvalidValues() + { + $object = new \stdClass(); + $file = $this->createFile(); + + return array( + array('foobar', 'numeric'), + array('foobar', 'boolean'), + array('0', 'integer'), + array('1.5', 'float'), + array(12345, 'string'), + array($object, 'boolean'), + array($object, 'numeric'), + array($object, 'integer'), + array($object, 'float'), + array($object, 'string'), + array($object, 'resource'), + array($file, 'boolean'), + array($file, 'numeric'), + array($file, 'integer'), + array($file, 'float'), + array($file, 'string'), + array($file, 'object'), + ); + } + + public function testMessageIsSet() + { + $constraint = new AssertType(array( + 'type' => 'numeric', + 'message' => 'myMessage' + )); + + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + 'type' => 'numeric', + )); + } + + protected function createFile() + { + if (!self::$file) { + self::$file = fopen(__FILE__, 'r'); + } + + return self::$file; + } + + public static function tearDownAfterClass() + { + if (self::$file) { + fclose(self::$file); + } } - } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/BlankValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/BlankValidatorTest.php index 05279d2109..859bc7ac70 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/BlankValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/BlankValidatorTest.php @@ -9,51 +9,51 @@ use Symfony\Components\Validator\Constraints\BlankValidator; class BlankValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new BlankValidator(); - } + public function setUp() + { + $this->validator = new BlankValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Blank())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Blank())); + } - public function testBlankIsValid() - { - $this->assertTrue($this->validator->isValid('', new Blank())); - } + public function testBlankIsValid() + { + $this->assertTrue($this->validator->isValid('', new Blank())); + } - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($date) - { - $this->assertFalse($this->validator->isValid($date, new Blank())); - } + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($date) + { + $this->assertFalse($this->validator->isValid($date, new Blank())); + } - public function getInvalidValues() - { - return array( - array('foobar'), - array(0), - array(false), - array(1234), - ); - } + public function getInvalidValues() + { + return array( + array('foobar'), + array(0), + array(false), + array(1234), + ); + } - public function testMessageIsSet() - { - $constraint = new Blank(array( - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Blank(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/ChoiceValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/ChoiceValidatorTest.php index c7fa670451..ff76e643d1 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/ChoiceValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/ChoiceValidatorTest.php @@ -10,165 +10,165 @@ use Symfony\Components\Validator\Constraints\ChoiceValidator; function choice_callback() { - return array('foo', 'bar'); + return array('foo', 'bar'); } class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public static function staticCallback() - { - return array('foo', 'bar'); - } + public static function staticCallback() + { + return array('foo', 'bar'); + } - public function setUp() - { - $interpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); - $walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); - $factory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); - $context = new ValidationContext('root', $walker, $factory, $interpolator); - $context->setCurrentClass(__CLASS__); - $this->validator = new ChoiceValidator(); - $this->validator->initialize($context); - } + public function setUp() + { + $interpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); + $walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); + $factory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); + $context = new ValidationContext('root', $walker, $factory, $interpolator); + $context->setCurrentClass(__CLASS__); + $this->validator = new ChoiceValidator(); + $this->validator->initialize($context); + } - public function testExpectArrayIfMultipleIsTrue() - { - $constraint = new Choice(array( - 'choices' => array('foo', 'bar'), - 'multiple' => true, - )); + public function testExpectArrayIfMultipleIsTrue() + { + $constraint = new Choice(array( + 'choices' => array('foo', 'bar'), + 'multiple' => true, + )); - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid('asdf', $constraint); - } + $this->validator->isValid('asdf', $constraint); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Choice(array('choices' => array('foo', 'bar'))))); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Choice(array('choices' => array('foo', 'bar'))))); + } - public function testChoicesOrCallbackExpected() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); + public function testChoicesOrCallbackExpected() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); - $this->validator->isValid('foobar', new Choice()); - } + $this->validator->isValid('foobar', new Choice()); + } - public function testValidCallbackExpected() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); + public function testValidCallbackExpected() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); - $this->validator->isValid('foobar', new Choice(array('callback' => 'abcd'))); - } + $this->validator->isValid('foobar', new Choice(array('callback' => 'abcd'))); + } - public function testValidChoiceArray() - { - $constraint = new Choice(array('choices' => array('foo', 'bar'))); + public function testValidChoiceArray() + { + $constraint = new Choice(array('choices' => array('foo', 'bar'))); - $this->assertTrue($this->validator->isValid('bar', $constraint)); - } + $this->assertTrue($this->validator->isValid('bar', $constraint)); + } - public function testValidChoiceCallbackFunction() - { - $constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback')); + public function testValidChoiceCallbackFunction() + { + $constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback')); - $this->assertTrue($this->validator->isValid('bar', $constraint)); - } + $this->assertTrue($this->validator->isValid('bar', $constraint)); + } - public function testValidChoiceCallbackClosure() - { - $constraint = new Choice(array('callback' => function() { - return array('foo', 'bar'); - })); + public function testValidChoiceCallbackClosure() + { + $constraint = new Choice(array('callback' => function() { + return array('foo', 'bar'); + })); - $this->assertTrue($this->validator->isValid('bar', $constraint)); - } + $this->assertTrue($this->validator->isValid('bar', $constraint)); + } - public function testValidChoiceCallbackStaticMethod() - { - $constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback'))); + public function testValidChoiceCallbackStaticMethod() + { + $constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback'))); - $this->assertTrue($this->validator->isValid('bar', $constraint)); - } + $this->assertTrue($this->validator->isValid('bar', $constraint)); + } - public function testValidChoiceCallbackContextMethod() - { - $constraint = new Choice(array('callback' => 'staticCallback')); + public function testValidChoiceCallbackContextMethod() + { + $constraint = new Choice(array('callback' => 'staticCallback')); - $this->assertTrue($this->validator->isValid('bar', $constraint)); - } + $this->assertTrue($this->validator->isValid('bar', $constraint)); + } - public function testMultipleChoices() - { - $constraint = new Choice(array( - 'choices' => array('foo', 'bar', 'baz'), - 'multiple' => true, - )); + public function testMultipleChoices() + { + $constraint = new Choice(array( + 'choices' => array('foo', 'bar', 'baz'), + 'multiple' => true, + )); - $this->assertTrue($this->validator->isValid(array('baz', 'bar'), $constraint)); - } + $this->assertTrue($this->validator->isValid(array('baz', 'bar'), $constraint)); + } - public function testInvalidChoice() - { - $constraint = new Choice(array( - 'choices' => array('foo', 'bar'), - 'message' => 'myMessage', - )); + public function testInvalidChoice() + { + $constraint = new Choice(array( + 'choices' => array('foo', 'bar'), + 'message' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid('baz', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'baz', - )); - } + $this->assertFalse($this->validator->isValid('baz', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'baz', + )); + } - public function testInvalidChoiceMultiple() - { - $constraint = new Choice(array( - 'choices' => array('foo', 'bar'), - 'message' => 'myMessage', - 'multiple' => true, - )); + public function testInvalidChoiceMultiple() + { + $constraint = new Choice(array( + 'choices' => array('foo', 'bar'), + 'message' => 'myMessage', + 'multiple' => true, + )); - $this->assertFalse($this->validator->isValid(array('foo', 'baz'), $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'baz', - )); - } + $this->assertFalse($this->validator->isValid(array('foo', 'baz'), $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'baz', + )); + } - public function testTooFewChoices() - { - $constraint = new Choice(array( - 'choices' => array('foo', 'bar', 'moo', 'maa'), - 'multiple' => true, - 'min' => 2, - 'minMessage' => 'myMessage', - )); + public function testTooFewChoices() + { + $constraint = new Choice(array( + 'choices' => array('foo', 'bar', 'moo', 'maa'), + 'multiple' => true, + 'min' => 2, + 'minMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid(array('foo'), $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'limit' => 2, - )); - } + $this->assertFalse($this->validator->isValid(array('foo'), $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'limit' => 2, + )); + } - public function testTooManyChoices() - { - $constraint = new Choice(array( - 'choices' => array('foo', 'bar', 'moo', 'maa'), - 'multiple' => true, - 'max' => 2, - 'maxMessage' => 'myMessage', - )); + public function testTooManyChoices() + { + $constraint = new Choice(array( + 'choices' => array('foo', 'bar', 'moo', 'maa'), + 'multiple' => true, + 'max' => 2, + 'maxMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid(array('foo', 'bar', 'moo'), $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'limit' => 2, - )); - } + $this->assertFalse($this->validator->isValid(array('foo', 'bar', 'moo'), $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'limit' => 2, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/CollectionValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/CollectionValidatorTest.php index 33f2c0aff6..777098945e 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/CollectionValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/CollectionValidatorTest.php @@ -11,174 +11,172 @@ use Symfony\Components\Validator\Constraints\CollectionValidator; class CollectionValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; - protected $walker; - protected $context; + protected $validator; + protected $walker; + protected $context; - public function setUp() - { - $this->walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); - $metadataFactory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); - $messageInterpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); - - $this->context = new ValidationContext('Root', $this->walker, $metadataFactory, $messageInterpolator); - - $this->validator = new CollectionValidator(); - $this->validator->initialize($this->context); - } - - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Collection(array('fields' => array( - 'foo' => new Min(4), - ))))); - } - - public function testThrowsExceptionIfNotTraversable() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - - $this->validator->isValid('foobar', new Collection(array('fields' => array( - 'foo' => new Min(4), - )))); - } - - /** - * @dataProvider getValidArguments - */ - public function testWalkSingleConstraint($array) - { - $this->context->setGroup('MyGroup'); - $this->context->setPropertyPath('foo'); - - $constraint = new Min(4); - - foreach ($array as $key => $value) + public function setUp() { - $this->walker->expects($this->once()) - ->method('walkConstraint') - ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + $this->walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); + $metadataFactory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); + $messageInterpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); + + $this->context = new ValidationContext('Root', $this->walker, $metadataFactory, $messageInterpolator); + + $this->validator = new CollectionValidator(); + $this->validator->initialize($this->context); } - $this->assertTrue($this->validator->isValid($array, new Collection(array( - 'fields' => array( - 'foo' => $constraint, - ), - )))); - } - - /** - * @dataProvider getValidArguments - */ - public function testWalkMultipleConstraints($array) - { - $this->context->setGroup('MyGroup'); - $this->context->setPropertyPath('foo'); - - $constraint = new Min(4); - // can only test for twice the same constraint because PHPUnits mocking - // can't test method calls with different arguments - $constraints = array($constraint, $constraint); - - foreach ($array as $key => $value) + public function testNullIsValid() { - $this->walker->expects($this->exactly(2)) - ->method('walkConstraint') - ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + $this->assertTrue($this->validator->isValid(null, new Collection(array('fields' => array( + 'foo' => new Min(4), + ))))); } - $this->assertTrue($this->validator->isValid($array, new Collection(array( - 'fields' => array( - 'foo' => $constraints, - ) - )))); - } + public function testThrowsExceptionIfNotTraversable() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - public function testExtraFieldsDisallowed() - { - $array = array( - 'foo' => 5, - 'bar' => 6, - ); + $this->validator->isValid('foobar', new Collection(array('fields' => array( + 'foo' => new Min(4), + )))); + } - $this->assertFalse($this->validator->isValid($array, new Collection(array( - 'fields' => array( - 'foo' => new Min(4), - ), - )))); - } + /** + * @dataProvider getValidArguments + */ + public function testWalkSingleConstraint($array) + { + $this->context->setGroup('MyGroup'); + $this->context->setPropertyPath('foo'); - // bug fix - public function testNullNotConsideredExtraField() - { - $array = array( - 'foo' => null, - ); + $constraint = new Min(4); - $this->assertTrue($this->validator->isValid($array, new Collection(array( - 'fields' => array( - 'foo' => new Min(4), - ), - )))); - } + foreach ($array as $key => $value) { + $this->walker->expects($this->once()) + ->method('walkConstraint') + ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + } - public function testExtraFieldsAllowed() - { - $array = array( - 'foo' => 5, - 'bar' => 6, - ); + $this->assertTrue($this->validator->isValid($array, new Collection(array( + 'fields' => array( + 'foo' => $constraint, + ), + )))); + } - $this->assertTrue($this->validator->isValid($array, new Collection(array( - 'fields' => array( - 'foo' => new Min(4), - ), - 'allowExtraFields' => true, - )))); - } + /** + * @dataProvider getValidArguments + */ + public function testWalkMultipleConstraints($array) + { + $this->context->setGroup('MyGroup'); + $this->context->setPropertyPath('foo'); - public function testMissingFieldsDisallowed() - { - $this->assertFalse($this->validator->isValid(array(), new Collection(array( - 'fields' => array( - 'foo' => new Min(4), - ), - )))); - } + $constraint = new Min(4); + // can only test for twice the same constraint because PHPUnits mocking + // can't test method calls with different arguments + $constraints = array($constraint, $constraint); - public function testMissingFieldsAllowed() - { - $this->assertTrue($this->validator->isValid(array(), new Collection(array( - 'fields' => array( - 'foo' => new Min(4), - ), - 'allowMissingFields' => true, - )))); - } + foreach ($array as $key => $value) { + $this->walker->expects($this->exactly(2)) + ->method('walkConstraint') + ->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); + } - public function getValidArguments() - { - return array( - // can only test for one entry, because PHPUnits mocking does not allow - // to expect multiple method calls with different arguments - array(array('foo' => 3)), - array(new \ArrayObject(array('foo' => 3))), - ); - } + $this->assertTrue($this->validator->isValid($array, new Collection(array( + 'fields' => array( + 'foo' => $constraints, + ) + )))); + } - public function testObjectShouldBeLeftUnchanged() - { - $value = new \ArrayObject(array( - 'foo' => 3 - )); - $this->validator->isValid($value, new Collection(array( - 'fields' => array( - 'foo' => new Min(2), - ) - ))); + public function testExtraFieldsDisallowed() + { + $array = array( + 'foo' => 5, + 'bar' => 6, + ); - $this->assertEquals(array( - 'foo' => 3 - ), (array) $value); - } + $this->assertFalse($this->validator->isValid($array, new Collection(array( + 'fields' => array( + 'foo' => new Min(4), + ), + )))); + } + + // bug fix + public function testNullNotConsideredExtraField() + { + $array = array( + 'foo' => null, + ); + + $this->assertTrue($this->validator->isValid($array, new Collection(array( + 'fields' => array( + 'foo' => new Min(4), + ), + )))); + } + + public function testExtraFieldsAllowed() + { + $array = array( + 'foo' => 5, + 'bar' => 6, + ); + + $this->assertTrue($this->validator->isValid($array, new Collection(array( + 'fields' => array( + 'foo' => new Min(4), + ), + 'allowExtraFields' => true, + )))); + } + + public function testMissingFieldsDisallowed() + { + $this->assertFalse($this->validator->isValid(array(), new Collection(array( + 'fields' => array( + 'foo' => new Min(4), + ), + )))); + } + + public function testMissingFieldsAllowed() + { + $this->assertTrue($this->validator->isValid(array(), new Collection(array( + 'fields' => array( + 'foo' => new Min(4), + ), + 'allowMissingFields' => true, + )))); + } + + public function getValidArguments() + { + return array( + // can only test for one entry, because PHPUnits mocking does not allow + // to expect multiple method calls with different arguments + array(array('foo' => 3)), + array(new \ArrayObject(array('foo' => 3))), + ); + } + + public function testObjectShouldBeLeftUnchanged() + { + $value = new \ArrayObject(array( + 'foo' => 3 + )); + $this->validator->isValid($value, new Collection(array( + 'fields' => array( + 'foo' => new Min(2), + ) + ))); + + $this->assertEquals(array( + 'foo' => 3 + ), (array) $value); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/DateTimeValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/DateTimeValidatorTest.php index b242b3265c..2457eaabf6 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/DateTimeValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/DateTimeValidatorTest.php @@ -9,76 +9,76 @@ use Symfony\Components\Validator\Constraints\DateTimeValidator; class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new DateTimeValidator(); - } + public function setUp() + { + $this->validator = new DateTimeValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new DateTime())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new DateTime())); + } - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new DateTime()); - } + $this->validator->isValid(new \stdClass(), new DateTime()); + } - /** - * @dataProvider getValidDateTimes - */ - public function testValidDateTimes($date) - { - $this->assertTrue($this->validator->isValid($date, new DateTime())); - } + /** + * @dataProvider getValidDateTimes + */ + public function testValidDateTimes($date) + { + $this->assertTrue($this->validator->isValid($date, new DateTime())); + } - public function getValidDateTimes() - { - return array( - array('2010-01-01 01:02:03'), - array('1955-12-12 00:00:00'), - array('2030-05-31 23:59:59'), - ); - } + public function getValidDateTimes() + { + return array( + array('2010-01-01 01:02:03'), + array('1955-12-12 00:00:00'), + array('2030-05-31 23:59:59'), + ); + } - /** - * @dataProvider getInvalidDateTimes - */ - public function testInvalidDateTimes($date) - { - $this->assertFalse($this->validator->isValid($date, new DateTime())); - } + /** + * @dataProvider getInvalidDateTimes + */ + public function testInvalidDateTimes($date) + { + $this->assertFalse($this->validator->isValid($date, new DateTime())); + } - public function getInvalidDateTimes() - { - return array( - array('foobar'), - array('2010-01-01'), - array('00:00:00'), - array('2010-01-01 00:00'), - array('2010-13-01 00:00:00'), - array('2010-04-32 00:00:00'), - array('2010-02-29 00:00:00'), - array('2010-01-01 24:00:00'), - array('2010-01-01 00:60:00'), - array('2010-01-01 00:00:60'), - ); - } + public function getInvalidDateTimes() + { + return array( + array('foobar'), + array('2010-01-01'), + array('00:00:00'), + array('2010-01-01 00:00'), + array('2010-13-01 00:00:00'), + array('2010-04-32 00:00:00'), + array('2010-02-29 00:00:00'), + array('2010-01-01 24:00:00'), + array('2010-01-01 00:60:00'), + array('2010-01-01 00:00:60'), + ); + } - public function testMessageIsSet() - { - $constraint = new DateTime(array( - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new DateTime(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/DateValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/DateValidatorTest.php index 2ff9730f61..c011df936a 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/DateValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/DateValidatorTest.php @@ -9,70 +9,70 @@ use Symfony\Components\Validator\Constraints\DateValidator; class DateValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new DateValidator(); - } + public function setUp() + { + $this->validator = new DateValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Date())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Date())); + } - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Date()); - } + $this->validator->isValid(new \stdClass(), new Date()); + } - /** - * @dataProvider getValidDates - */ - public function testValidDates($date) - { - $this->assertTrue($this->validator->isValid($date, new Date())); - } + /** + * @dataProvider getValidDates + */ + public function testValidDates($date) + { + $this->assertTrue($this->validator->isValid($date, new Date())); + } - public function getValidDates() - { - return array( - array('2010-01-01'), - array('1955-12-12'), - array('2030-05-31'), - ); - } + public function getValidDates() + { + return array( + array('2010-01-01'), + array('1955-12-12'), + array('2030-05-31'), + ); + } - /** - * @dataProvider getInvalidDates - */ - public function testInvalidDates($date) - { - $this->assertFalse($this->validator->isValid($date, new Date())); - } + /** + * @dataProvider getInvalidDates + */ + public function testInvalidDates($date) + { + $this->assertFalse($this->validator->isValid($date, new Date())); + } - public function getInvalidDates() - { - return array( - array('foobar'), - array('2010-13-01'), - array('2010-04-32'), - array('2010-02-29'), - ); - } + public function getInvalidDates() + { + return array( + array('foobar'), + array('2010-13-01'), + array('2010-04-32'), + array('2010-02-29'), + ); + } - public function testMessageIsSet() - { - $constraint = new Date(array( - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Date(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/EmailValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/EmailValidatorTest.php index a6f4b63f8a..32773d9e57 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/EmailValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/EmailValidatorTest.php @@ -9,70 +9,70 @@ use Symfony\Components\Validator\Constraints\EmailValidator; class EmailValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new EmailValidator(); - } + public function setUp() + { + $this->validator = new EmailValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Email())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Email())); + } - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Email()); - } + $this->validator->isValid(new \stdClass(), new Email()); + } - /** - * @dataProvider getValidEmails - */ - public function testValidEmails($email) - { - $this->assertTrue($this->validator->isValid($email, new Email())); - } + /** + * @dataProvider getValidEmails + */ + public function testValidEmails($email) + { + $this->assertTrue($this->validator->isValid($email, new Email())); + } - public function getValidEmails() - { - return array( - array('fabien.potencier@symfony-project.com'), - array('example@example.co.uk'), - array('fabien_potencier@example.fr'), - ); - } + public function getValidEmails() + { + return array( + array('fabien.potencier@symfony-project.com'), + array('example@example.co.uk'), + array('fabien_potencier@example.fr'), + ); + } - /** - * @dataProvider getInvalidEmails - */ - public function testInvalidEmails($email) - { - $this->assertFalse($this->validator->isValid($email, new Email())); - } + /** + * @dataProvider getInvalidEmails + */ + public function testInvalidEmails($email) + { + $this->assertFalse($this->validator->isValid($email, new Email())); + } - public function getInvalidEmails() - { - return array( - array('example'), - array('example@'), - array('example@localhost'), - array('example@example.com@example.com'), - ); - } + public function getInvalidEmails() + { + return array( + array('example'), + array('example@'), + array('example@localhost'), + array('example@example.com@example.com'), + ); + } - public function testMessageIsSet() - { - $constraint = new Email(array( - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Email(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/FileValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/FileValidatorTest.php index b376a04227..6da9737085 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/FileValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/FileValidatorTest.php @@ -9,155 +9,155 @@ use Symfony\Components\Validator\Constraints\FileValidator; class FileValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; - protected $path; - protected $file; + protected $validator; + protected $path; + protected $file; - public function setUp() - { - $this->validator = new FileValidator(); - $this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'FileValidatorTest'; - $this->file = fopen($this->path, 'w'); - } + public function setUp() + { + $this->validator = new FileValidator(); + $this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'FileValidatorTest'; + $this->file = fopen($this->path, 'w'); + } - public function tearDown() - { - fclose($this->file); - } + public function tearDown() + { + fclose($this->file); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new File())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new File())); + } - public function testExpectsStringCompatibleTypeOrFile() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleTypeOrFile() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new File()); - } + $this->validator->isValid(new \stdClass(), new File()); + } - public function testValidFile() - { - $this->assertTrue($this->validator->isValid($this->path, new File())); - } + public function testValidFile() + { + $this->assertTrue($this->validator->isValid($this->path, new File())); + } - public function testTooLargeBytes() - { - fwrite($this->file, str_repeat('0', 11)); + public function testTooLargeBytes() + { + fwrite($this->file, str_repeat('0', 11)); - $constraint = new File(array( - 'maxSize' => 10, - 'maxSizeMessage' => 'myMessage', - )); + $constraint = new File(array( + 'maxSize' => 10, + 'maxSizeMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid($this->path, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'limit' => '10 bytes', - 'size' => '11 bytes', - 'file' => $this->path, - )); - } + $this->assertFalse($this->validator->isValid($this->path, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'limit' => '10 bytes', + 'size' => '11 bytes', + 'file' => $this->path, + )); + } - public function testTooLargeKiloBytes() - { - fwrite($this->file, str_repeat('0', 1400)); + public function testTooLargeKiloBytes() + { + fwrite($this->file, str_repeat('0', 1400)); - $constraint = new File(array( - 'maxSize' => '1k', - 'maxSizeMessage' => 'myMessage', - )); + $constraint = new File(array( + 'maxSize' => '1k', + 'maxSizeMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid($this->path, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'limit' => '1 kB', - 'size' => '1.4 kB', - 'file' => $this->path, - )); - } + $this->assertFalse($this->validator->isValid($this->path, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'limit' => '1 kB', + 'size' => '1.4 kB', + 'file' => $this->path, + )); + } - public function testTooLargeMegaBytes() - { - fwrite($this->file, str_repeat('0', 1400000)); + public function testTooLargeMegaBytes() + { + fwrite($this->file, str_repeat('0', 1400000)); - $constraint = new File(array( - 'maxSize' => '1M', - 'maxSizeMessage' => 'myMessage', - )); + $constraint = new File(array( + 'maxSize' => '1M', + 'maxSizeMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid($this->path, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'limit' => '1 MB', - 'size' => '1.4 MB', - 'file' => $this->path, - )); - } + $this->assertFalse($this->validator->isValid($this->path, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'limit' => '1 MB', + 'size' => '1.4 MB', + 'file' => $this->path, + )); + } - public function testInvalidMaxSize() - { - $constraint = new File(array( - 'maxSize' => '1abc', - )); + public function testInvalidMaxSize() + { + $constraint = new File(array( + 'maxSize' => '1abc', + )); - $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); + $this->setExpectedException('Symfony\Components\Validator\Exception\ConstraintDefinitionException'); - $this->validator->isValid($this->path, $constraint); - } + $this->validator->isValid($this->path, $constraint); + } - public function testFileNotFound() - { - $constraint = new File(array( - 'notFoundMessage' => 'myMessage', - )); + public function testFileNotFound() + { + $constraint = new File(array( + 'notFoundMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'file' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'file' => 'foobar', + )); + } - public function testValidMimeType() - { - $file = $this->getMock('Symfony\Components\File\File', array(), array(), '', false); - $file->expects($this->any()) - ->method('getPath') - ->will($this->returnValue($this->path)); - $file->expects($this->any()) - ->method('getMimeType') - ->will($this->returnValue('image/jpg')); + public function testValidMimeType() + { + $file = $this->getMock('Symfony\Components\File\File', array(), array(), '', false); + $file->expects($this->any()) + ->method('getPath') + ->will($this->returnValue($this->path)); + $file->expects($this->any()) + ->method('getMimeType') + ->will($this->returnValue('image/jpg')); - $constraint = new File(array( - 'mimeTypes' => array('image/png', 'image/jpg'), - )); + $constraint = new File(array( + 'mimeTypes' => array('image/png', 'image/jpg'), + )); - $this->assertTrue($this->validator->isValid($file, $constraint)); - } + $this->assertTrue($this->validator->isValid($file, $constraint)); + } - public function testInvalidMimeType() - { - $file = $this->getMock('Symfony\Components\File\File', array(), array(), '', false); - $file->expects($this->any()) - ->method('getPath') - ->will($this->returnValue($this->path)); - $file->expects($this->any()) - ->method('getMimeType') - ->will($this->returnValue('application/pdf')); + public function testInvalidMimeType() + { + $file = $this->getMock('Symfony\Components\File\File', array(), array(), '', false); + $file->expects($this->any()) + ->method('getPath') + ->will($this->returnValue($this->path)); + $file->expects($this->any()) + ->method('getMimeType') + ->will($this->returnValue('application/pdf')); - $constraint = new File(array( - 'mimeTypes' => array('image/png', 'image/jpg'), - 'mimeTypesMessage' => 'myMessage', - )); + $constraint = new File(array( + 'mimeTypes' => array('image/png', 'image/jpg'), + 'mimeTypesMessage' => 'myMessage', + )); - $this->assertFalse($this->validator->isValid($file, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'type' => '"application/pdf"', - 'types' => '"image/png", "image/jpg"', - 'file' => $this->path, - )); - } + $this->assertFalse($this->validator->isValid($file, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'type' => '"application/pdf"', + 'types' => '"image/png", "image/jpg"', + 'file' => $this->path, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/MaxLengthValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/MaxLengthValidatorTest.php index dc5b8f9224..ee7f00f51e 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/MaxLengthValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/MaxLengthValidatorTest.php @@ -9,81 +9,79 @@ use Symfony\Components\Validator\Constraints\MaxLengthValidator; class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new MaxLengthValidator(); - } - - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new MaxLength(array('limit' => 5)))); - } - - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - - $this->validator->isValid(new \stdClass(), new MaxLength(array('limit' => 5))); - } - - /** - * @dataProvider getValidValues - */ - public function testValidValues($value, $skip = false) - { - if (!$skip) + public function setUp() { - $constraint = new MaxLength(array('limit' => 5)); - $this->assertTrue($this->validator->isValid($value, $constraint)); + $this->validator = new MaxLengthValidator(); } - } - public function getValidValues() - { - return array( - array(12345), - array('12345'), - array('üüüüü', !function_exists('mb_strlen')), - array('ééééé', !function_exists('mb_strlen')), - ); - } - - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value, $skip = false) - { - if (!$skip) + public function testNullIsValid() { - $constraint = new MaxLength(array('limit' => 5)); - $this->assertFalse($this->validator->isValid($value, $constraint)); + $this->assertTrue($this->validator->isValid(null, new MaxLength(array('limit' => 5)))); } - } - public function getInvalidValues() - { - return array( - array(123456), - array('123456'), - array('üüüüüü', !function_exists('mb_strlen')), - array('éééééé', !function_exists('mb_strlen')), - ); - } + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - public function testMessageIsSet() - { - $constraint = new MaxLength(array( - 'limit' => 5, - 'message' => 'myMessage' - )); + $this->validator->isValid(new \stdClass(), new MaxLength(array('limit' => 5))); + } - $this->assertFalse($this->validator->isValid('123456', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => '123456', - 'limit' => 5, - )); - } + /** + * @dataProvider getValidValues + */ + public function testValidValues($value, $skip = false) + { + if (!$skip) { + $constraint = new MaxLength(array('limit' => 5)); + $this->assertTrue($this->validator->isValid($value, $constraint)); + } + } + + public function getValidValues() + { + return array( + array(12345), + array('12345'), + array('üüüüü', !function_exists('mb_strlen')), + array('ééééé', !function_exists('mb_strlen')), + ); + } + + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value, $skip = false) + { + if (!$skip) { + $constraint = new MaxLength(array('limit' => 5)); + $this->assertFalse($this->validator->isValid($value, $constraint)); + } + } + + public function getInvalidValues() + { + return array( + array(123456), + array('123456'), + array('üüüüüü', !function_exists('mb_strlen')), + array('éééééé', !function_exists('mb_strlen')), + ); + } + + public function testMessageIsSet() + { + $constraint = new MaxLength(array( + 'limit' => 5, + 'message' => 'myMessage' + )); + + $this->assertFalse($this->validator->isValid('123456', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => '123456', + 'limit' => 5, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/MaxValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/MaxValidatorTest.php index c0e5ce5496..a692e3086d 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/MaxValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/MaxValidatorTest.php @@ -9,73 +9,73 @@ use Symfony\Components\Validator\Constraints\MaxValidator; class MaxValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new MaxValidator(); - } + public function setUp() + { + $this->validator = new MaxValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Max(array('limit' => 10)))); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Max(array('limit' => 10)))); + } - public function testExpectsNumericType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsNumericType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Max(array('limit' => 10))); - } + $this->validator->isValid(new \stdClass(), new Max(array('limit' => 10))); + } - /** - * @dataProvider getValidValues - */ - public function testValidValues($value) - { - $constraint = new Max(array('limit' => 10)); - $this->assertTrue($this->validator->isValid($value, $constraint)); - } + /** + * @dataProvider getValidValues + */ + public function testValidValues($value) + { + $constraint = new Max(array('limit' => 10)); + $this->assertTrue($this->validator->isValid($value, $constraint)); + } - public function getValidValues() - { - return array( - array(9.999999), - array(10), - array(10.0), - array('10'), - ); - } + public function getValidValues() + { + return array( + array(9.999999), + array(10), + array(10.0), + array('10'), + ); + } - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value) - { - $constraint = new Max(array('limit' => 10)); - $this->assertFalse($this->validator->isValid($value, $constraint)); - } + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value) + { + $constraint = new Max(array('limit' => 10)); + $this->assertFalse($this->validator->isValid($value, $constraint)); + } - public function getInvalidValues() - { - return array( - array(10.00001), - array('10.00001'), - ); - } + public function getInvalidValues() + { + return array( + array(10.00001), + array('10.00001'), + ); + } - public function testMessageIsSet() - { - $constraint = new Max(array( - 'limit' => 10, - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Max(array( + 'limit' => 10, + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid(11, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 11, - 'limit' => 10, - )); - } + $this->assertFalse($this->validator->isValid(11, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 11, + 'limit' => 10, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/MinLengthValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/MinLengthValidatorTest.php index dd883a63f0..bfdd2e7ed1 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/MinLengthValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/MinLengthValidatorTest.php @@ -9,81 +9,79 @@ use Symfony\Components\Validator\Constraints\MinLengthValidator; class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new MinLengthValidator(); - } - - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new MinLength(array('limit' => 6)))); - } - - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - - $this->validator->isValid(new \stdClass(), new MinLength(array('limit' => 5))); - } - - /** - * @dataProvider getValidValues - */ - public function testValidValues($value, $skip = false) - { - if (!$skip) + public function setUp() { - $constraint = new MinLength(array('limit' => 6)); - $this->assertTrue($this->validator->isValid($value, $constraint)); + $this->validator = new MinLengthValidator(); } - } - public function getValidValues() - { - return array( - array(123456), - array('123456'), - array('üüüüüü', !function_exists('mb_strlen')), - array('éééééé', !function_exists('mb_strlen')), - ); - } - - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value, $skip = false) - { - if (!$skip) + public function testNullIsValid() { - $constraint = new MinLength(array('limit' => 6)); - $this->assertFalse($this->validator->isValid($value, $constraint)); + $this->assertTrue($this->validator->isValid(null, new MinLength(array('limit' => 6)))); } - } - public function getInvalidValues() - { - return array( - array(12345), - array('12345'), - array('üüüüü', !function_exists('mb_strlen')), - array('ééééé', !function_exists('mb_strlen')), - ); - } + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - public function testMessageIsSet() - { - $constraint = new MinLength(array( - 'limit' => 5, - 'message' => 'myMessage' - )); + $this->validator->isValid(new \stdClass(), new MinLength(array('limit' => 5))); + } - $this->assertFalse($this->validator->isValid('1234', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => '1234', - 'limit' => 5, - )); - } + /** + * @dataProvider getValidValues + */ + public function testValidValues($value, $skip = false) + { + if (!$skip) { + $constraint = new MinLength(array('limit' => 6)); + $this->assertTrue($this->validator->isValid($value, $constraint)); + } + } + + public function getValidValues() + { + return array( + array(123456), + array('123456'), + array('üüüüüü', !function_exists('mb_strlen')), + array('éééééé', !function_exists('mb_strlen')), + ); + } + + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value, $skip = false) + { + if (!$skip) { + $constraint = new MinLength(array('limit' => 6)); + $this->assertFalse($this->validator->isValid($value, $constraint)); + } + } + + public function getInvalidValues() + { + return array( + array(12345), + array('12345'), + array('üüüüü', !function_exists('mb_strlen')), + array('ééééé', !function_exists('mb_strlen')), + ); + } + + public function testMessageIsSet() + { + $constraint = new MinLength(array( + 'limit' => 5, + 'message' => 'myMessage' + )); + + $this->assertFalse($this->validator->isValid('1234', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => '1234', + 'limit' => 5, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/MinValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/MinValidatorTest.php index cd2d20905b..147f764e3f 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/MinValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/MinValidatorTest.php @@ -9,73 +9,73 @@ use Symfony\Components\Validator\Constraints\MinValidator; class MinValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new MinValidator(); - } + public function setUp() + { + $this->validator = new MinValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Min(array('limit' => 10)))); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Min(array('limit' => 10)))); + } - public function testExpectsNumericType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsNumericType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Min(array('limit' => 10))); - } + $this->validator->isValid(new \stdClass(), new Min(array('limit' => 10))); + } - /** - * @dataProvider getValidValues - */ - public function testValidValues($value) - { - $constraint = new Min(array('limit' => 10)); - $this->assertTrue($this->validator->isValid($value, $constraint)); - } + /** + * @dataProvider getValidValues + */ + public function testValidValues($value) + { + $constraint = new Min(array('limit' => 10)); + $this->assertTrue($this->validator->isValid($value, $constraint)); + } - public function getValidValues() - { - return array( - array(10.00001), - array('10.00001'), - array(10), - array(10.0), - ); - } + public function getValidValues() + { + return array( + array(10.00001), + array('10.00001'), + array(10), + array(10.0), + ); + } - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value) - { - $constraint = new Min(array('limit' => 10)); - $this->assertFalse($this->validator->isValid($value, $constraint)); - } + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value) + { + $constraint = new Min(array('limit' => 10)); + $this->assertFalse($this->validator->isValid($value, $constraint)); + } - public function getInvalidValues() - { - return array( - array(9.999999), - array('9.999999'), - ); - } + public function getInvalidValues() + { + return array( + array(9.999999), + array('9.999999'), + ); + } - public function testMessageIsSet() - { - $constraint = new Min(array( - 'limit' => 10, - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Min(array( + 'limit' => 10, + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid(9, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 9, - 'limit' => 10, - )); - } + $this->assertFalse($this->validator->isValid(9, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 9, + 'limit' => 10, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/NotBlankValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/NotBlankValidatorTest.php index 63ec4a816d..bc5ea505ab 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/NotBlankValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/NotBlankValidatorTest.php @@ -9,49 +9,49 @@ use Symfony\Components\Validator\Constraints\NotBlankValidator; class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new NotBlankValidator(); - } + public function setUp() + { + $this->validator = new NotBlankValidator(); + } - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($date) - { - $this->assertTrue($this->validator->isValid($date, new NotBlank())); - } + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($date) + { + $this->assertTrue($this->validator->isValid($date, new NotBlank())); + } - public function getInvalidValues() - { - return array( - array('foobar'), - array(0), - array(false), - array(1234), - ); - } + public function getInvalidValues() + { + return array( + array('foobar'), + array(0), + array(false), + array(1234), + ); + } - public function testNullIsInvalid() - { - $this->assertFalse($this->validator->isValid(null, new NotBlank())); - } + public function testNullIsInvalid() + { + $this->assertFalse($this->validator->isValid(null, new NotBlank())); + } - public function testBlankIsInvalid() - { - $this->assertFalse($this->validator->isValid('', new NotBlank())); - } + public function testBlankIsInvalid() + { + $this->assertFalse($this->validator->isValid('', new NotBlank())); + } - public function testSetMessage() - { - $constraint = new NotBlank(array( - 'message' => 'myMessage' - )); + public function testSetMessage() + { + $constraint = new NotBlank(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array()); - } + $this->assertFalse($this->validator->isValid('', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/NotNullValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/NotNullValidatorTest.php index dc14692596..69eb0117d1 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/NotNullValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/NotNullValidatorTest.php @@ -9,39 +9,39 @@ use Symfony\Components\Validator\Constraints\NotNullValidator; class NotNullValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new NotNullValidator(); - } + public function setUp() + { + $this->validator = new NotNullValidator(); + } - /** - * @dataProvider getValidValues - */ - public function testValidValues($value) - { - $this->assertTrue($this->validator->isValid($value, new NotNull())); - } + /** + * @dataProvider getValidValues + */ + public function testValidValues($value) + { + $this->assertTrue($this->validator->isValid($value, new NotNull())); + } - public function getValidValues() - { - return array( - array(0), - array(false), - array(true), - array(''), - ); - } + public function getValidValues() + { + return array( + array(0), + array(false), + array(true), + array(''), + ); + } - public function testNullIsInvalid() - { - $constraint = new NotNull(array( - 'message' => 'myMessage' - )); + public function testNullIsInvalid() + { + $constraint = new NotNull(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid(null, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array()); - } + $this->assertFalse($this->validator->isValid(null, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array()); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/NullValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/NullValidatorTest.php index 93e0fdf01a..2041c98a01 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/NullValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/NullValidatorTest.php @@ -9,46 +9,46 @@ use Symfony\Components\Validator\Constraints\NullValidator; class NullValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new NullValidator(); - } + public function setUp() + { + $this->validator = new NullValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Null())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Null())); + } - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value) - { - $this->assertFalse($this->validator->isValid($value, new Null())); - } + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value) + { + $this->assertFalse($this->validator->isValid($value, new Null())); + } - public function getInvalidValues() - { - return array( - array(0), - array(false), - array(true), - array(''), - ); - } + public function getInvalidValues() + { + return array( + array(0), + array(false), + array(true), + array(''), + ); + } - public function testSetMessage() - { - $constraint = new Null(array( - 'message' => 'myMessage' - )); + public function testSetMessage() + { + $constraint = new Null(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid(1, $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 1, - )); - } + $this->assertFalse($this->validator->isValid(1, $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 1, + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/RegexValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/RegexValidatorTest.php index 477910c3a2..31ba831428 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/RegexValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/RegexValidatorTest.php @@ -9,72 +9,72 @@ use Symfony\Components\Validator\Constraints\RegexValidator; class RegexValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new RegexValidator(); - } + public function setUp() + { + $this->validator = new RegexValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Regex(array('pattern' => '/^[0-9]+$/')))); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Regex(array('pattern' => '/^[0-9]+$/')))); + } - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/'))); - } + $this->validator->isValid(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/'))); + } - /** - * @dataProvider getValidValues - */ - public function testValidValues($value) - { - $constraint = new Regex(array('pattern' => '/^[0-9]+$/')); - $this->assertTrue($this->validator->isValid($value, $constraint)); - } + /** + * @dataProvider getValidValues + */ + public function testValidValues($value) + { + $constraint = new Regex(array('pattern' => '/^[0-9]+$/')); + $this->assertTrue($this->validator->isValid($value, $constraint)); + } - public function getValidValues() - { - return array( - array(0), - array('0'), - array('090909'), - array(90909), - ); - } + public function getValidValues() + { + return array( + array(0), + array('0'), + array('090909'), + array(90909), + ); + } - /** - * @dataProvider getInvalidValues - */ - public function testInvalidValues($value) - { - $constraint = new Regex(array('pattern' => '/^[0-9]+$/')); - $this->assertFalse($this->validator->isValid($value, $constraint)); - } + /** + * @dataProvider getInvalidValues + */ + public function testInvalidValues($value) + { + $constraint = new Regex(array('pattern' => '/^[0-9]+$/')); + $this->assertFalse($this->validator->isValid($value, $constraint)); + } - public function getInvalidValues() - { - return array( - array('abcd'), - array('090foo'), - ); - } + public function getInvalidValues() + { + return array( + array('abcd'), + array('090foo'), + ); + } - public function testMessageIsSet() - { - $constraint = new Regex(array( - 'pattern' => '/^[0-9]+$/', - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Regex(array( + 'pattern' => '/^[0-9]+$/', + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/TimeValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/TimeValidatorTest.php index 9da89d4fc9..92a1303444 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/TimeValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/TimeValidatorTest.php @@ -9,71 +9,71 @@ use Symfony\Components\Validator\Constraints\TimeValidator; class TimeValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new TimeValidator(); - } + public function setUp() + { + $this->validator = new TimeValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Time())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Time())); + } - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Time()); - } + $this->validator->isValid(new \stdClass(), new Time()); + } - /** - * @dataProvider getValidTimes - */ - public function testValidTimes($time) - { - $this->assertTrue($this->validator->isValid($time, new Time())); - } + /** + * @dataProvider getValidTimes + */ + public function testValidTimes($time) + { + $this->assertTrue($this->validator->isValid($time, new Time())); + } - public function getValidTimes() - { - return array( - array('01:02:03'), - array('00:00:00'), - array('23:59:59'), - ); - } + public function getValidTimes() + { + return array( + array('01:02:03'), + array('00:00:00'), + array('23:59:59'), + ); + } - /** - * @dataProvider getInvalidTimes - */ - public function testInvalidTimes($time) - { - $this->assertFalse($this->validator->isValid($time, new Time())); - } + /** + * @dataProvider getInvalidTimes + */ + public function testInvalidTimes($time) + { + $this->assertFalse($this->validator->isValid($time, new Time())); + } - public function getInvalidTimes() - { - return array( - array('foobar'), - array('00:00'), - array('24:00:00'), - array('00:60:00'), - array('00:00:60'), - ); - } + public function getInvalidTimes() + { + return array( + array('foobar'), + array('00:00'), + array('24:00:00'), + array('00:60:00'), + array('00:00:60'), + ); + } - public function testMessageIsSet() - { - $constraint = new Time(array( - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Time(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/UrlValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/UrlValidatorTest.php index 879ba0569b..b62f15c99e 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/UrlValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/UrlValidatorTest.php @@ -9,74 +9,74 @@ use Symfony\Components\Validator\Constraints\UrlValidator; class UrlValidatorTest extends \PHPUnit_Framework_TestCase { - protected $validator; + protected $validator; - public function setUp() - { - $this->validator = new UrlValidator(); - } + public function setUp() + { + $this->validator = new UrlValidator(); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Url())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Url())); + } - public function testExpectsStringCompatibleType() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testExpectsStringCompatibleType() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid(new \stdClass(), new Url()); - } + $this->validator->isValid(new \stdClass(), new Url()); + } - /** - * @dataProvider getValidUrls - */ - public function testValidUrls($url) - { - $this->assertTrue($this->validator->isValid($url, new Url())); - } + /** + * @dataProvider getValidUrls + */ + public function testValidUrls($url) + { + $this->assertTrue($this->validator->isValid($url, new Url())); + } - public function getValidUrls() - { - return array( - array('http://www.google.com'), - array('https://google.com/'), - array('https://google.com:80/'), - array('http://www.symfony-project.com/'), - array('http://127.0.0.1/'), - array('http://127.0.0.1:80/'), - array('ftp://google.com/foo.tgz'), - array('ftps://google.com/foo.tgz'), - ); - } + public function getValidUrls() + { + return array( + array('http://www.google.com'), + array('https://google.com/'), + array('https://google.com:80/'), + array('http://www.symfony-project.com/'), + array('http://127.0.0.1/'), + array('http://127.0.0.1:80/'), + array('ftp://google.com/foo.tgz'), + array('ftps://google.com/foo.tgz'), + ); + } - /** - * @dataProvider getInvalidUrls - */ - public function testInvalidUrls($url) - { - $this->assertFalse($this->validator->isValid($url, new Url())); - } + /** + * @dataProvider getInvalidUrls + */ + public function testInvalidUrls($url) + { + $this->assertFalse($this->validator->isValid($url, new Url())); + } - public function getInvalidUrls() - { - return array( - array('google.com'), - array('http:/google.com'), - array('http://google.com::aa'), - ); - } + public function getInvalidUrls() + { + return array( + array('google.com'), + array('http:/google.com'), + array('http://google.com::aa'), + ); + } - public function testMessageIsSet() - { - $constraint = new Url(array( - 'message' => 'myMessage' - )); + public function testMessageIsSet() + { + $constraint = new Url(array( + 'message' => 'myMessage' + )); - $this->assertFalse($this->validator->isValid('foobar', $constraint)); - $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); - $this->assertEquals($this->validator->getMessageParameters(), array( - 'value' => 'foobar', - )); - } + $this->assertFalse($this->validator->isValid('foobar', $constraint)); + $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); + $this->assertEquals($this->validator->getMessageParameters(), array( + 'value' => 'foobar', + )); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Constraints/ValidValidatorTest.php b/tests/Symfony/Tests/Components/Validator/Constraints/ValidValidatorTest.php index d0fdbf3d2a..6e1879c422 100644 --- a/tests/Symfony/Tests/Components/Validator/Constraints/ValidValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/Constraints/ValidValidatorTest.php @@ -12,96 +12,96 @@ use Symfony\Tests\Components\Validator\Fixtures\Entity; class ValidValidatorTest extends \PHPUnit_Framework_TestCase { - const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; + const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; - protected $validator; - protected $factory; - protected $walker; - protected $context; + protected $validator; + protected $factory; + protected $walker; + protected $context; - public function setUp() - { - $this->walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); - $this->factory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); - $messageInterpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); + public function setUp() + { + $this->walker = $this->getMock('Symfony\Components\Validator\GraphWalker', array(), array(), '', false); + $this->factory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); + $messageInterpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); - $this->context = new ValidationContext('Root', $this->walker, $this->factory, $messageInterpolator); + $this->context = new ValidationContext('Root', $this->walker, $this->factory, $messageInterpolator); - $this->validator = new ValidValidator(); - $this->validator->initialize($this->context); - } + $this->validator = new ValidValidator(); + $this->validator->initialize($this->context); + } - public function testNullIsValid() - { - $this->assertTrue($this->validator->isValid(null, new Valid())); - } + public function testNullIsValid() + { + $this->assertTrue($this->validator->isValid(null, new Valid())); + } - public function testThrowsExceptionIfNotObjectOrArray() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); + public function testThrowsExceptionIfNotObjectOrArray() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\UnexpectedTypeException'); - $this->validator->isValid('foobar', new Valid()); - } + $this->validator->isValid('foobar', new Valid()); + } - public function testWalkObject() - { - $this->context->setGroup('MyGroup'); - $this->context->setPropertyPath('foo'); + public function testWalkObject() + { + $this->context->setGroup('MyGroup'); + $this->context->setPropertyPath('foo'); - $metadata = $this->createClassMetadata(); - $entity = new Entity(); + $metadata = $this->createClassMetadata(); + $entity = new Entity(); - $this->factory->expects($this->once()) - ->method('getClassMetadata') - ->with($this->equalTo(self::CLASSNAME)) - ->will($this->returnValue($metadata)); + $this->factory->expects($this->once()) + ->method('getClassMetadata') + ->with($this->equalTo(self::CLASSNAME)) + ->will($this->returnValue($metadata)); - $this->walker->expects($this->once()) - ->method('walkClass') - ->with($this->equalTo($metadata), $this->equalTo($entity), 'MyGroup', 'foo'); + $this->walker->expects($this->once()) + ->method('walkClass') + ->with($this->equalTo($metadata), $this->equalTo($entity), 'MyGroup', 'foo'); - $this->assertTrue($this->validator->isValid($entity, new Valid())); - } + $this->assertTrue($this->validator->isValid($entity, new Valid())); + } - public function testWalkArray() - { - $this->context->setGroup('MyGroup'); - $this->context->setPropertyPath('foo'); + public function testWalkArray() + { + $this->context->setGroup('MyGroup'); + $this->context->setPropertyPath('foo'); - $constraint = new Valid(); - $entity = new Entity(); - // can only test for one object due to PHPUnit's mocking limitations - $array = array('key' => $entity); + $constraint = new Valid(); + $entity = new Entity(); + // can only test for one object due to PHPUnit's mocking limitations + $array = array('key' => $entity); - $this->walker->expects($this->once()) - ->method('walkConstraint') - ->with($this->equalTo($constraint), $this->equalTo($entity), 'MyGroup', 'foo[key]'); + $this->walker->expects($this->once()) + ->method('walkConstraint') + ->with($this->equalTo($constraint), $this->equalTo($entity), 'MyGroup', 'foo[key]'); - $this->assertTrue($this->validator->isValid($array, $constraint)); - } + $this->assertTrue($this->validator->isValid($array, $constraint)); + } - public function testValidateClass_Succeeds() - { - $metadata = $this->createClassMetadata(); - $entity = new Entity(); + public function testValidateClass_Succeeds() + { + $metadata = $this->createClassMetadata(); + $entity = new Entity(); - $this->factory->expects($this->any()) - ->method('getClassMetadata') - ->with($this->equalTo(self::CLASSNAME)) - ->will($this->returnValue($metadata)); + $this->factory->expects($this->any()) + ->method('getClassMetadata') + ->with($this->equalTo(self::CLASSNAME)) + ->will($this->returnValue($metadata)); - $this->assertTrue($this->validator->isValid($entity, new Valid(array('class' => self::CLASSNAME)))); - } + $this->assertTrue($this->validator->isValid($entity, new Valid(array('class' => self::CLASSNAME)))); + } - public function testValidateClass_Fails() - { - $entity = new \stdClass(); + public function testValidateClass_Fails() + { + $entity = new \stdClass(); - $this->assertFalse($this->validator->isValid($entity, new Valid(array('class' => self::CLASSNAME)))); - } + $this->assertFalse($this->validator->isValid($entity, new Valid(array('class' => self::CLASSNAME)))); + } - protected function createClassMetadata() - { - return $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadata', array(), array(), '', false); - } + protected function createClassMetadata() + { + return $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadata', array(), array(), '', false); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/DependencyInjectionValidatorFactoryTest.php b/tests/Symfony/Tests/Components/Validator/DependencyInjectionValidatorFactoryTest.php index ea277c68c4..59bb3a6437 100644 --- a/tests/Symfony/Tests/Components/Validator/DependencyInjectionValidatorFactoryTest.php +++ b/tests/Symfony/Tests/Components/Validator/DependencyInjectionValidatorFactoryTest.php @@ -14,46 +14,46 @@ use Symfony\Tests\Components\Validator\Fixtures\InvalidConstraint; class DependencyInjectionValidatorFactoryTest extends \PHPUnit_Framework_TestCase { - protected $container; - protected $factory; + protected $container; + protected $factory; - public function setUp() - { - $this->container = new Container(); - $this->factory = new DependencyInjectionValidatorFactory($this->container); - } + public function setUp() + { + $this->container = new Container(); + $this->factory = new DependencyInjectionValidatorFactory($this->container); + } - public function tearDown() - { - unset ($this->factory); - unset ($this->container); - } + public function tearDown() + { + unset ($this->factory); + unset ($this->container); + } - public function testGetInstanceRetunsCorrectValidatorInstance() - { - $constraint = new Valid(); - $validator = $this->factory->getInstance($constraint); - $this->assertTrue($validator instanceof ValidValidator); - } + public function testGetInstanceRetunsCorrectValidatorInstance() + { + $constraint = new Valid(); + $validator = $this->factory->getInstance($constraint); + $this->assertTrue($validator instanceof ValidValidator); + } - public function testGetInstanceAddsValidatorServiceToContainer() - { - $constraint = new Valid(); - $validator = $this->factory->getInstance($constraint); - $this->assertServiceExists('Symfony.Components.Validator.Constraints.ValidValidator'); - } + public function testGetInstanceAddsValidatorServiceToContainer() + { + $constraint = new Valid(); + $validator = $this->factory->getInstance($constraint); + $this->assertServiceExists('Symfony.Components.Validator.Constraints.ValidValidator'); + } - public function assertServiceExists($id) - { - $this->assertTrue($this->container->hasService($id), 'Service ' . $id . ' doesn\'t exist on container'); - } + public function assertServiceExists($id) + { + $this->assertTrue($this->container->hasService($id), 'Service ' . $id . ' doesn\'t exist on container'); + } - /** - * @expectedException LogicException - */ - public function testGetInstanceThrowsLogicExceptionIfValidatorNotInstanceOfValidatorInterface() - { - $constraint = new InvalidConstraint(); - $validator = $this->factory->getInstance($constraint); - } + /** + * @expectedException LogicException + */ + public function testGetInstanceThrowsLogicExceptionIfValidatorNotInstanceOfValidatorInterface() + { + $constraint = new InvalidConstraint(); + $validator = $this->factory->getInstance($constraint); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Extension/DependencyInjectionValidatorFactoryTest.php b/tests/Symfony/Tests/Components/Validator/Extension/DependencyInjectionValidatorFactoryTest.php index 587e0d233b..c900e02127 100644 --- a/tests/Symfony/Tests/Components/Validator/Extension/DependencyInjectionValidatorFactoryTest.php +++ b/tests/Symfony/Tests/Components/Validator/Extension/DependencyInjectionValidatorFactoryTest.php @@ -14,46 +14,46 @@ use Symfony\Tests\Components\Validator\Fixtures\InvalidConstraint; class DependencyInjectionValidatorFactoryTest extends \PHPUnit_Framework_TestCase { - protected $container; - protected $factory; + protected $container; + protected $factory; - public function setUp() - { - $this->container = new Container(); - $this->factory = new DependencyInjectionValidatorFactory($this->container); - } + public function setUp() + { + $this->container = new Container(); + $this->factory = new DependencyInjectionValidatorFactory($this->container); + } - public function tearDown() - { - unset($this->factory); - unset($this->container); - } + public function tearDown() + { + unset($this->factory); + unset($this->container); + } - public function testGetInstanceRetunsCorrectValidatorInstance() - { - $constraint = new Valid(); - $validator = $this->factory->getInstance($constraint); - $this->assertTrue($validator instanceof ValidValidator); - } + public function testGetInstanceRetunsCorrectValidatorInstance() + { + $constraint = new Valid(); + $validator = $this->factory->getInstance($constraint); + $this->assertTrue($validator instanceof ValidValidator); + } - public function testGetInstanceAddsValidatorServiceToContainer() - { - $constraint = new Valid(); - $validator = $this->factory->getInstance($constraint); - $this->assertServiceExists('Symfony.Components.Validator.Constraints.ValidValidator'); - } + public function testGetInstanceAddsValidatorServiceToContainer() + { + $constraint = new Valid(); + $validator = $this->factory->getInstance($constraint); + $this->assertServiceExists('Symfony.Components.Validator.Constraints.ValidValidator'); + } - private function assertServiceExists($id) - { - $this->assertTrue($this->container->hasService($id), 'Service ' . $id . ' doesn\'t exist on container'); - } + private function assertServiceExists($id) + { + $this->assertTrue($this->container->hasService($id), 'Service ' . $id . ' doesn\'t exist on container'); + } - /** - * @expectedException LogicException - */ - public function testGetInstanceThrowsLogicExceptionIfValidatorNotInstanceOfValidatorInterface() - { - $constraint = new InvalidConstraint(); - $validator = $this->factory->getInstance($constraint); - } + /** + * @expectedException LogicException + */ + public function testGetInstanceThrowsLogicExceptionIfValidatorNotInstanceOfValidatorInterface() + { + $constraint = new InvalidConstraint(); + $validator = $this->factory->getInstance($constraint); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintA.php b/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintA.php index ebd4685312..b361889e80 100644 --- a/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintA.php +++ b/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintA.php @@ -6,11 +6,11 @@ use Symfony\Components\Validator\Constraint; class ConstraintA extends Constraint { - public $property1; - public $property2; + public $property1; + public $property2; - public function defaultOption() - { - return 'property2'; - } + public function defaultOption() + { + return 'property2'; + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintAValidator.php b/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintAValidator.php index b511eb61d5..5464ec556a 100644 --- a/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintAValidator.php +++ b/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintAValidator.php @@ -7,14 +7,13 @@ use Symfony\Components\Validator\ConstraintValidator; class ConstraintAValidator extends ConstraintValidator { - public function isValid($value, Constraint $constraint) - { - if ($value != 'VALID') + public function isValid($value, Constraint $constraint) { - $this->setMessage('message', array('param' => 'value')); - return false; - } + if ($value != 'VALID') { + $this->setMessage('message', array('param' => 'value')); + return false; + } - return true; - } + return true; + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintC.php b/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintC.php index 1f30ce41aa..98fac93c5c 100644 --- a/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintC.php +++ b/tests/Symfony/Tests/Components/Validator/Fixtures/ConstraintC.php @@ -6,10 +6,10 @@ use Symfony\Components\Validator\Constraint; class ConstraintC extends Constraint { - public $option1; + public $option1; - public function requiredOptions() - { - return array('option1'); - } + public function requiredOptions() + { + return array('option1'); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Fixtures/Entity.php b/tests/Symfony/Tests/Components/Validator/Fixtures/Entity.php index a73dec1604..bd0fef7d0b 100644 --- a/tests/Symfony/Tests/Components/Validator/Fixtures/Entity.php +++ b/tests/Symfony/Tests/Components/Validator/Fixtures/Entity.php @@ -20,34 +20,34 @@ require_once __DIR__.'/EntityInterface.php'; */ class Entity extends EntityParent implements EntityInterface { - /** - * @Validation({ - * @Choice(choices={"A", "B"}, message="Must be one of %choices%") - * }) - */ - protected $firstName; + /** + * @Validation({ + * @Choice(choices={"A", "B"}, message="Must be one of %choices%") + * }) + */ + protected $firstName; - protected $lastName; + protected $lastName; - private $internal; + private $internal; - public function __construct($internal = null) - { - $this->internal = $internal; - } + public function __construct($internal = null) + { + $this->internal = $internal; + } - public function getInternal() - { - return $this->internal . ' from getter'; - } + public function getInternal() + { + return $this->internal . ' from getter'; + } - /** - * @Validation({ - * @NotNull - * }) - */ - public function getLastName() - { - return $this->lastName; - } + /** + * @Validation({ + * @NotNull + * }) + */ + public function getLastName() + { + return $this->lastName; + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Fixtures/EntityParent.php b/tests/Symfony/Tests/Components/Validator/Fixtures/EntityParent.php index 7fa1afcf2d..0a19110473 100644 --- a/tests/Symfony/Tests/Components/Validator/Fixtures/EntityParent.php +++ b/tests/Symfony/Tests/Components/Validator/Fixtures/EntityParent.php @@ -4,6 +4,6 @@ namespace Symfony\Tests\Components\Validator\Fixtures; class EntityParent { - protected $firstName; - private $internal; + protected $firstName; + private $internal; } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Fixtures/FilesLoader.php b/tests/Symfony/Tests/Components/Validator/Fixtures/FilesLoader.php index 4648234158..4c86fb0c42 100644 --- a/tests/Symfony/Tests/Components/Validator/Fixtures/FilesLoader.php +++ b/tests/Symfony/Tests/Components/Validator/Fixtures/FilesLoader.php @@ -7,23 +7,23 @@ use Symfony\Components\Validator\Mapping\Loader\LoaderInterface; abstract class FilesLoader extends BaseFilesLoader { - protected $timesCalled = 0; - protected $loader; + protected $timesCalled = 0; + protected $loader; - public function __construct(array $paths, LoaderInterface $loader) - { - $this->loader = $loader; - parent::__construct($paths); - } + public function __construct(array $paths, LoaderInterface $loader) + { + $this->loader = $loader; + parent::__construct($paths); + } - protected function getFileLoaderInstance($file) - { - $this->timesCalled++; - return $this->loader; - } + protected function getFileLoaderInstance($file) + { + $this->timesCalled++; + return $this->loader; + } - public function getTimesCalled() - { - return $this->timesCalled; - } + public function getTimesCalled() + { + return $this->timesCalled; + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/GraphWalkerTest.php b/tests/Symfony/Tests/Components/Validator/GraphWalkerTest.php index ae54dab744..cac6cefad1 100644 --- a/tests/Symfony/Tests/Components/Validator/GraphWalkerTest.php +++ b/tests/Symfony/Tests/Components/Validator/GraphWalkerTest.php @@ -21,84 +21,84 @@ use Symfony\Components\Validator\Constraints\Valid; class GraphWalkerTest extends \PHPUnit_Framework_TestCase { - const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; + const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; - protected $interpolator; - protected $factory; - protected $metadata; + protected $interpolator; + protected $factory; + protected $metadata; - public function setUp() - { - $this->interpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); - $this->factory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); - $this->walker = new GraphWalker('Root', $this->factory, new ConstraintValidatorFactory(), $this->interpolator); - $this->metadata = new ClassMetadata(self::CLASSNAME); - } + public function setUp() + { + $this->interpolator = $this->getMock('Symfony\Components\Validator\MessageInterpolator\MessageInterpolatorInterface'); + $this->factory = $this->getMock('Symfony\Components\Validator\Mapping\ClassMetadataFactoryInterface'); + $this->walker = new GraphWalker('Root', $this->factory, new ConstraintValidatorFactory(), $this->interpolator); + $this->metadata = new ClassMetadata(self::CLASSNAME); + } - public function testWalkClassValidatesConstraints() - { - $this->metadata->addConstraint(new ConstraintA()); + public function testWalkClassValidatesConstraints() + { + $this->metadata->addConstraint(new ConstraintA()); - $this->walker->walkClass($this->metadata, new Entity(), 'Default', ''); + $this->walker->walkClass($this->metadata, new Entity(), 'Default', ''); - $this->assertEquals(1, count($this->walker->getViolations())); - } + $this->assertEquals(1, count($this->walker->getViolations())); + } - public function testWalkClassValidatesPropertyConstraints() - { - $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); + public function testWalkClassValidatesPropertyConstraints() + { + $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); - $this->walker->walkClass($this->metadata, new Entity(), 'Default', ''); + $this->walker->walkClass($this->metadata, new Entity(), 'Default', ''); - $this->assertEquals(1, count($this->walker->getViolations())); - } + $this->assertEquals(1, count($this->walker->getViolations())); + } - public function testWalkClassValidatesGetterConstraints() - { - $this->metadata->addGetterConstraint('lastName', new ConstraintA()); + public function testWalkClassValidatesGetterConstraints() + { + $this->metadata->addGetterConstraint('lastName', new ConstraintA()); - $this->walker->walkClass($this->metadata, new Entity(), 'Default', ''); + $this->walker->walkClass($this->metadata, new Entity(), 'Default', ''); - $this->assertEquals(1, count($this->walker->getViolations())); - } + $this->assertEquals(1, count($this->walker->getViolations())); + } - public function testWalkPropertyValueValidatesConstraints() - { - $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); + public function testWalkPropertyValueValidatesConstraints() + { + $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); - $this->walker->walkPropertyValue($this->metadata, 'firstName', 'value', 'Default', ''); + $this->walker->walkPropertyValue($this->metadata, 'firstName', 'value', 'Default', ''); - $this->assertEquals(1, count($this->walker->getViolations())); - } + $this->assertEquals(1, count($this->walker->getViolations())); + } - public function testWalkConstraintBuildsAViolationIfFailed() - { - $constraint = new ConstraintA(); + public function testWalkConstraintBuildsAViolationIfFailed() + { + $constraint = new ConstraintA(); - $this->interpolator->expects($this->once()) - ->method('interpolate') - ->with($this->equalTo('message'), $this->equalTo(array('param' => 'value'))) - ->will($this->returnValue('interpolated text')); + $this->interpolator->expects($this->once()) + ->method('interpolate') + ->with($this->equalTo('message'), $this->equalTo(array('param' => 'value'))) + ->will($this->returnValue('interpolated text')); - $this->walker->walkConstraint($constraint, 'foobar', 'Default', 'firstName.path'); + $this->walker->walkConstraint($constraint, 'foobar', 'Default', 'firstName.path'); - $violations = new ConstraintViolationList(); - $violations->add(new ConstraintViolation( - 'interpolated text', - 'Root', - 'firstName.path', - 'foobar' - )); + $violations = new ConstraintViolationList(); + $violations->add(new ConstraintViolation( + 'interpolated text', + 'Root', + 'firstName.path', + 'foobar' + )); - $this->assertEquals($violations, $this->walker->getViolations()); - } + $this->assertEquals($violations, $this->walker->getViolations()); + } - public function testWalkConstraintBuildsNoViolationIfSuccessful() - { - $constraint = new ConstraintA(); + public function testWalkConstraintBuildsNoViolationIfSuccessful() + { + $constraint = new ConstraintA(); - $this->walker->walkConstraint($constraint, 'VALID', 'Default', 'firstName.path'); + $this->walker->walkConstraint($constraint, 'VALID', 'Default', 'firstName.path'); - $this->assertEquals(0, count($this->walker->getViolations())); - } + $this->assertEquals(0, count($this->walker->getViolations())); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataFactoryTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataFactoryTest.php index 8c45be133c..0bb0e47b13 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataFactoryTest.php @@ -17,51 +17,51 @@ use Symfony\Components\Validator\Mapping\Loader\LoaderInterface; class ClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase { - const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; - const PARENTCLASS = 'Symfony\Tests\Components\Validator\Fixtures\EntityParent'; + const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; + const PARENTCLASS = 'Symfony\Tests\Components\Validator\Fixtures\EntityParent'; - public function testLoadClassMetadata() - { - $factory = new ClassMetadataFactory(new TestLoader()); - $metadata = $factory->getClassMetadata(self::PARENTCLASS); + public function testLoadClassMetadata() + { + $factory = new ClassMetadataFactory(new TestLoader()); + $metadata = $factory->getClassMetadata(self::PARENTCLASS); - $constraints = array( - new ConstraintA(array('groups' => array('Default', 'EntityParent'))), - ); + $constraints = array( + new ConstraintA(array('groups' => array('Default', 'EntityParent'))), + ); - $this->assertEquals($constraints, $metadata->getConstraints()); - } + $this->assertEquals($constraints, $metadata->getConstraints()); + } - public function testMergeParentConstraints() - { - $factory = new ClassMetadataFactory(new TestLoader()); - $metadata = $factory->getClassMetadata(self::CLASSNAME); + public function testMergeParentConstraints() + { + $factory = new ClassMetadataFactory(new TestLoader()); + $metadata = $factory->getClassMetadata(self::CLASSNAME); - $constraints = array( - new ConstraintA(array('groups' => array( - 'Default', - 'EntityParent', - 'Entity', - ))), - new ConstraintA(array('groups' => array( - 'Default', - 'EntityInterface', - 'Entity', - ))), - new ConstraintA(array('groups' => array( - 'Default', - 'Entity', - ))), - ); + $constraints = array( + new ConstraintA(array('groups' => array( + 'Default', + 'EntityParent', + 'Entity', + ))), + new ConstraintA(array('groups' => array( + 'Default', + 'EntityInterface', + 'Entity', + ))), + new ConstraintA(array('groups' => array( + 'Default', + 'Entity', + ))), + ); - $this->assertEquals($constraints, $metadata->getConstraints()); - } + $this->assertEquals($constraints, $metadata->getConstraints()); + } } class TestLoader implements LoaderInterface { - public function loadClassMetadata(ClassMetadata $metadata) - { - $metadata->addConstraint(new ConstraintA()); - } + public function loadClassMetadata(ClassMetadata $metadata) + { + $metadata->addConstraint(new ConstraintA()); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataTest.php index 24e9b0bf57..4c819a0fd7 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/ClassMetadataTest.php @@ -15,110 +15,110 @@ use Symfony\Components\Validator\Mapping\PropertyMetadata; class ClassMetadataTest extends \PHPUnit_Framework_TestCase { - const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; - const PARENTCLASS = 'Symfony\Tests\Components\Validator\Fixtures\EntityParent'; + const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; + const PARENTCLASS = 'Symfony\Tests\Components\Validator\Fixtures\EntityParent'; - protected $metadata; + protected $metadata; - public function setUp() - { - $this->metadata = new ClassMetadata(self::CLASSNAME); - } + public function setUp() + { + $this->metadata = new ClassMetadata(self::CLASSNAME); + } - public function testAddPropertyConstraints() - { - $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); - $this->metadata->addPropertyConstraint('lastName', new ConstraintB()); + public function testAddPropertyConstraints() + { + $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); + $this->metadata->addPropertyConstraint('lastName', new ConstraintB()); - $this->assertEquals(array('firstName', 'lastName'), $this->metadata->getConstrainedProperties()); - } + $this->assertEquals(array('firstName', 'lastName'), $this->metadata->getConstrainedProperties()); + } - public function testMergeConstraintsMergesClassConstraints() - { - $parent = new ClassMetadata(self::PARENTCLASS); - $parent->addConstraint(new ConstraintA()); + public function testMergeConstraintsMergesClassConstraints() + { + $parent = new ClassMetadata(self::PARENTCLASS); + $parent->addConstraint(new ConstraintA()); - $this->metadata->mergeConstraints($parent); - $this->metadata->addConstraint(new ConstraintA()); + $this->metadata->mergeConstraints($parent); + $this->metadata->addConstraint(new ConstraintA()); - $constraints = array( - new ConstraintA(array('groups' => array( - 'Default', - 'EntityParent', - 'Entity', - ))), - new ConstraintA(array('groups' => array( - 'Default', - 'Entity', - ))), - ); + $constraints = array( + new ConstraintA(array('groups' => array( + 'Default', + 'EntityParent', + 'Entity', + ))), + new ConstraintA(array('groups' => array( + 'Default', + 'Entity', + ))), + ); - $this->assertEquals($constraints, $this->metadata->getConstraints()); - } + $this->assertEquals($constraints, $this->metadata->getConstraints()); + } - public function testMergeConstraintsMergesMemberConstraints() - { - $parent = new ClassMetadata(self::PARENTCLASS); - $parent->addPropertyConstraint('firstName', new ConstraintA()); + public function testMergeConstraintsMergesMemberConstraints() + { + $parent = new ClassMetadata(self::PARENTCLASS); + $parent->addPropertyConstraint('firstName', new ConstraintA()); - $this->metadata->mergeConstraints($parent); - $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); + $this->metadata->mergeConstraints($parent); + $this->metadata->addPropertyConstraint('firstName', new ConstraintA()); - $constraints = array( - new ConstraintA(array('groups' => array( - 'Default', - 'EntityParent', - 'Entity', - ))), - new ConstraintA(array('groups' => array( - 'Default', - 'Entity', - ))), - ); + $constraints = array( + new ConstraintA(array('groups' => array( + 'Default', + 'EntityParent', + 'Entity', + ))), + new ConstraintA(array('groups' => array( + 'Default', + 'Entity', + ))), + ); - $members = $this->metadata->getMemberMetadatas('firstName'); + $members = $this->metadata->getMemberMetadatas('firstName'); - $this->assertEquals(1, count($members)); - $this->assertEquals(self::PARENTCLASS, $members[0]->getClassName()); - $this->assertEquals($constraints, $members[0]->getConstraints()); - } + $this->assertEquals(1, count($members)); + $this->assertEquals(self::PARENTCLASS, $members[0]->getClassName()); + $this->assertEquals($constraints, $members[0]->getConstraints()); + } - public function testMergeConstraintsKeepsPrivateMembersSeperate() - { - $parent = new ClassMetadata(self::PARENTCLASS); - $parent->addPropertyConstraint('internal', new ConstraintA()); + public function testMergeConstraintsKeepsPrivateMembersSeperate() + { + $parent = new ClassMetadata(self::PARENTCLASS); + $parent->addPropertyConstraint('internal', new ConstraintA()); - $this->metadata->mergeConstraints($parent); - $this->metadata->addPropertyConstraint('internal', new ConstraintA()); + $this->metadata->mergeConstraints($parent); + $this->metadata->addPropertyConstraint('internal', new ConstraintA()); - $parentConstraints = array( - new ConstraintA(array('groups' => array( - 'Default', - 'EntityParent', - 'Entity', - ))), - ); - $constraints = array( - new ConstraintA(array('groups' => array( - 'Default', - 'Entity', - ))), - ); + $parentConstraints = array( + new ConstraintA(array('groups' => array( + 'Default', + 'EntityParent', + 'Entity', + ))), + ); + $constraints = array( + new ConstraintA(array('groups' => array( + 'Default', + 'Entity', + ))), + ); - $members = $this->metadata->getMemberMetadatas('internal'); + $members = $this->metadata->getMemberMetadatas('internal'); - $this->assertEquals(2, count($members)); - $this->assertEquals(self::PARENTCLASS, $members[0]->getClassName()); - $this->assertEquals($parentConstraints, $members[0]->getConstraints()); - $this->assertEquals(self::CLASSNAME, $members[1]->getClassName()); - $this->assertEquals($constraints, $members[1]->getConstraints()); - } + $this->assertEquals(2, count($members)); + $this->assertEquals(self::PARENTCLASS, $members[0]->getClassName()); + $this->assertEquals($parentConstraints, $members[0]->getConstraints()); + $this->assertEquals(self::CLASSNAME, $members[1]->getClassName()); + $this->assertEquals($constraints, $members[1]->getConstraints()); + } - public function testGetReflectionClass() - { - $reflClass = new \ReflectionClass(self::CLASSNAME); + public function testGetReflectionClass() + { + $reflClass = new \ReflectionClass(self::CLASSNAME); - $this->assertEquals($reflClass, $this->metadata->getReflectionClass()); - } + $this->assertEquals($reflClass, $this->metadata->getReflectionClass()); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/ElementMetadataTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/ElementMetadataTest.php index fb069f5bb9..125f9d3020 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/ElementMetadataTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/ElementMetadataTest.php @@ -12,40 +12,40 @@ use Symfony\Components\Validator\Mapping\ElementMetadata; class ElementMetadataTest extends \PHPUnit_Framework_TestCase { - protected $metadata; + protected $metadata; - public function setUp() - { - $this->metadata = new ElementMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - } + public function setUp() + { + $this->metadata = new ElementMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + } - public function testAddConstraints() - { - $this->metadata->addConstraint($constraint1 = new ConstraintA()); - $this->metadata->addConstraint($constraint2 = new ConstraintA()); + public function testAddConstraints() + { + $this->metadata->addConstraint($constraint1 = new ConstraintA()); + $this->metadata->addConstraint($constraint2 = new ConstraintA()); - $this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints()); - } + $this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints()); + } - public function testMultipleConstraintsOfTheSameType() - { - $constraint1 = new ConstraintA(array('property1' => 'A')); - $constraint2 = new ConstraintA(array('property1' => 'B')); + public function testMultipleConstraintsOfTheSameType() + { + $constraint1 = new ConstraintA(array('property1' => 'A')); + $constraint2 = new ConstraintA(array('property1' => 'B')); - $this->metadata->addConstraint($constraint1); - $this->metadata->addConstraint($constraint2); + $this->metadata->addConstraint($constraint1); + $this->metadata->addConstraint($constraint2); - $this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints()); - } + $this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints()); + } - public function testFindConstraintsByGroup() - { - $constraint1 = new ConstraintA(array('groups' => 'TestGroup')); - $constraint2 = new ConstraintB(); + public function testFindConstraintsByGroup() + { + $constraint1 = new ConstraintA(array('groups' => 'TestGroup')); + $constraint2 = new ConstraintB(); - $this->metadata->addConstraint($constraint1); - $this->metadata->addConstraint($constraint2); + $this->metadata->addConstraint($constraint1); + $this->metadata->addConstraint($constraint2); - $this->assertEquals(array($constraint1), $this->metadata->findConstraints('TestGroup')); - } + $this->assertEquals(array($constraint1), $this->metadata->findConstraints('TestGroup')); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/GetterMetadataTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/GetterMetadataTest.php index fb660bf490..6f07a749e3 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/GetterMetadataTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/GetterMetadataTest.php @@ -10,24 +10,24 @@ use Symfony\Tests\Components\Validator\Fixtures\Entity; class GetterMetadataTest extends \PHPUnit_Framework_TestCase { - const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; + const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; - public function testInvalidPropertyName() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\ValidatorException'); + public function testInvalidPropertyName() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\ValidatorException'); - new GetterMetadata(self::CLASSNAME, 'foobar'); - } + new GetterMetadata(self::CLASSNAME, 'foobar'); + } - public function testGetValueFromPublicGetter() - { - // private getters don't work yet because ReflectionMethod::setAccessible() - // does not exists yet in a stable PHP release + public function testGetValueFromPublicGetter() + { + // private getters don't work yet because ReflectionMethod::setAccessible() + // does not exists yet in a stable PHP release - $entity = new Entity('foobar'); - $metadata = new GetterMetadata(self::CLASSNAME, 'internal'); + $entity = new Entity('foobar'); + $metadata = new GetterMetadata(self::CLASSNAME, 'internal'); - $this->assertEquals('foobar from getter', $metadata->getValue($entity)); - } + $this->assertEquals('foobar from getter', $metadata->getValue($entity)); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/AnnotationLoaderTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/AnnotationLoaderTest.php index 118e3d8774..e506ef964c 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/AnnotationLoaderTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/AnnotationLoaderTest.php @@ -15,48 +15,48 @@ use Symfony\Components\Validator\Mapping\Loader\AnnotationLoader; class AnnotationLoaderTest extends \PHPUnit_Framework_TestCase { - public function testLoadClassMetadataReturnsTrueIfSuccessful() - { - $loader = new AnnotationLoader(); - $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + public function testLoadClassMetadataReturnsTrueIfSuccessful() + { + $loader = new AnnotationLoader(); + $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $this->assertTrue($loader->loadClassMetadata($metadata)); - } + $this->assertTrue($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadataReturnsFalseIfNotSuccessful() - { - $loader = new AnnotationLoader(); - $metadata = new ClassMetadata('\stdClass'); + public function testLoadClassMetadataReturnsFalseIfNotSuccessful() + { + $loader = new AnnotationLoader(); + $metadata = new ClassMetadata('\stdClass'); - $this->assertFalse($loader->loadClassMetadata($metadata)); - } + $this->assertFalse($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadata() - { - $loader = new AnnotationLoader(); - $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + public function testLoadClassMetadata() + { + $loader = new AnnotationLoader(); + $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $loader->loadClassMetadata($metadata); + $loader->loadClassMetadata($metadata); - $expected = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $expected->addConstraint(new NotNull()); - $expected->addConstraint(new Min(3)); - $expected->addConstraint(new Choice(array('A', 'B'))); - $expected->addConstraint(new All(array(new NotNull(), new Min(3)))); - $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3))))); - $expected->addConstraint(new Collection(array('fields' => array( - 'foo' => array(new NotNull(), new Min(3)), - 'bar' => new Min(5), - )))); - $expected->addPropertyConstraint('firstName', new Choice(array( - 'message' => 'Must be one of %choices%', - 'choices' => array('A', 'B'), - ))); - $expected->addGetterConstraint('lastName', new NotNull()); + $expected = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + $expected->addConstraint(new NotNull()); + $expected->addConstraint(new Min(3)); + $expected->addConstraint(new Choice(array('A', 'B'))); + $expected->addConstraint(new All(array(new NotNull(), new Min(3)))); + $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3))))); + $expected->addConstraint(new Collection(array('fields' => array( + 'foo' => array(new NotNull(), new Min(3)), + 'bar' => new Min(5), + )))); + $expected->addPropertyConstraint('firstName', new Choice(array( + 'message' => 'Must be one of %choices%', + 'choices' => array('A', 'B'), + ))); + $expected->addGetterConstraint('lastName', new NotNull()); - // load reflection class so that the comparison passes - $expected->getReflectionClass(); + // load reflection class so that the comparison passes + $expected->getReflectionClass(); - $this->assertEquals($expected, $metadata); - } + $this->assertEquals($expected, $metadata); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/FilesLoaderTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/FilesLoaderTest.php index 35a67dd022..df78849c4d 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/FilesLoaderTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/FilesLoaderTest.php @@ -11,33 +11,33 @@ use Symfony\Components\Validator\Mapping\ClassMetadata; class FilesLoaderTest extends \PHPUnit_Framework_TestCase { - public function testCallsGetFileLoaderInstanceForeachPath() - { - $loader = $this->getFilesLoader($this->getFileLoader()); - $this->assertEquals(4, $loader->getTimesCalled()); - } + public function testCallsGetFileLoaderInstanceForeachPath() + { + $loader = $this->getFilesLoader($this->getFileLoader()); + $this->assertEquals(4, $loader->getTimesCalled()); + } - public function testCallsActualFileLoaderForMetadata() - { - $fileLoader = $this->getFileLoader(); - $fileLoader->expects($this->exactly(4)) - ->method('loadClassMetadata'); - $loader = $this->getFilesLoader($fileLoader); - $loader->loadClassMetadata(new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity')); - } + public function testCallsActualFileLoaderForMetadata() + { + $fileLoader = $this->getFileLoader(); + $fileLoader->expects($this->exactly(4)) + ->method('loadClassMetadata'); + $loader = $this->getFilesLoader($fileLoader); + $loader->loadClassMetadata(new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity')); + } - public function getFilesLoader(LoaderInterface $loader) - { - return $this->getMockForAbstractClass('Symfony\Tests\Components\Validator\Fixtures\FilesLoader', array(array( - __DIR__ . '/constraint-mapping.xml', - __DIR__ . '/constraint-mapping.yaml', - __DIR__ . '/constraint-mapping.test', - __DIR__ . '/constraint-mapping.txt', - ), $loader)); - } + public function getFilesLoader(LoaderInterface $loader) + { + return $this->getMockForAbstractClass('Symfony\Tests\Components\Validator\Fixtures\FilesLoader', array(array( + __DIR__ . '/constraint-mapping.xml', + __DIR__ . '/constraint-mapping.yaml', + __DIR__ . '/constraint-mapping.test', + __DIR__ . '/constraint-mapping.txt', + ), $loader)); + } - public function getFileLoader() - { - return $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - } + public function getFileLoader() + { + return $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + } } \ No newline at end of file diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/LoaderChainTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/LoaderChainTest.php index c050029382..fe0aea8267 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/LoaderChainTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/LoaderChainTest.php @@ -9,70 +9,70 @@ use Symfony\Components\Validator\Mapping\Loader\LoaderChain; class LoaderChainTest extends \PHPUnit_Framework_TestCase { - public function testAllLoadersAreCalled() - { - $metadata = new ClassMetadata('\stdClass'); + public function testAllLoadersAreCalled() + { + $metadata = new ClassMetadata('\stdClass'); - $loader1 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - $loader1->expects($this->once()) - ->method('loadClassMetadata') - ->with($this->equalTo($metadata)); + $loader1 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + $loader1->expects($this->once()) + ->method('loadClassMetadata') + ->with($this->equalTo($metadata)); - $loader2 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - $loader2->expects($this->once()) - ->method('loadClassMetadata') - ->with($this->equalTo($metadata)); + $loader2 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + $loader2->expects($this->once()) + ->method('loadClassMetadata') + ->with($this->equalTo($metadata)); - $chain = new LoaderChain(array( - $loader1, - $loader2, - )); + $chain = new LoaderChain(array( + $loader1, + $loader2, + )); - $chain->loadClassMetadata($metadata); - } + $chain->loadClassMetadata($metadata); + } - public function testReturnsTrueIfAnyLoaderReturnedTrue() - { - $metadata = new ClassMetadata('\stdClass'); + public function testReturnsTrueIfAnyLoaderReturnedTrue() + { + $metadata = new ClassMetadata('\stdClass'); - $loader1 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - $loader1->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(true)); + $loader1 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + $loader1->expects($this->any()) + ->method('loadClassMetadata') + ->will($this->returnValue(true)); - $loader2 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - $loader2->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(false)); + $loader2 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + $loader2->expects($this->any()) + ->method('loadClassMetadata') + ->will($this->returnValue(false)); - $chain = new LoaderChain(array( - $loader1, - $loader2, - )); + $chain = new LoaderChain(array( + $loader1, + $loader2, + )); - $this->assertTrue($chain->loadClassMetadata($metadata)); - } + $this->assertTrue($chain->loadClassMetadata($metadata)); + } - public function testReturnsFalseIfNoLoaderReturnedTrue() - { - $metadata = new ClassMetadata('\stdClass'); + public function testReturnsFalseIfNoLoaderReturnedTrue() + { + $metadata = new ClassMetadata('\stdClass'); - $loader1 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - $loader1->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(false)); + $loader1 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + $loader1->expects($this->any()) + ->method('loadClassMetadata') + ->will($this->returnValue(false)); - $loader2 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); - $loader2->expects($this->any()) - ->method('loadClassMetadata') - ->will($this->returnValue(false)); + $loader2 = $this->getMock('Symfony\Components\Validator\Mapping\Loader\LoaderInterface'); + $loader2->expects($this->any()) + ->method('loadClassMetadata') + ->will($this->returnValue(false)); - $chain = new LoaderChain(array( - $loader1, - $loader2, - )); + $chain = new LoaderChain(array( + $loader1, + $loader2, + )); - $this->assertFalse($chain->loadClassMetadata($metadata)); - } + $this->assertFalse($chain->loadClassMetadata($metadata)); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/StaticMethodLoaderTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/StaticMethodLoaderTest.php index 9d55e732d8..13e5dbd8c1 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/StaticMethodLoaderTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/StaticMethodLoaderTest.php @@ -9,39 +9,39 @@ use Symfony\Components\Validator\Mapping\Loader\StaticMethodLoader; class StaticMethodLoaderTest extends \PHPUnit_Framework_TestCase { - public function testLoadClassMetadataReturnsTrueIfSuccessful() - { - $loader = new StaticMethodLoader('loadMetadata'); - $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderEntity'); + public function testLoadClassMetadataReturnsTrueIfSuccessful() + { + $loader = new StaticMethodLoader('loadMetadata'); + $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderEntity'); - $this->assertTrue($loader->loadClassMetadata($metadata)); - } + $this->assertTrue($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadataReturnsFalseIfNotSuccessful() - { - $loader = new StaticMethodLoader('loadMetadata'); - $metadata = new ClassMetadata('\stdClass'); + public function testLoadClassMetadataReturnsFalseIfNotSuccessful() + { + $loader = new StaticMethodLoader('loadMetadata'); + $metadata = new ClassMetadata('\stdClass'); - $this->assertFalse($loader->loadClassMetadata($metadata)); - } + $this->assertFalse($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadata() - { - $loader = new StaticMethodLoader('loadMetadata'); - $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderEntity'); + public function testLoadClassMetadata() + { + $loader = new StaticMethodLoader('loadMetadata'); + $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderEntity'); - $loader->loadClassMetadata($metadata); + $loader->loadClassMetadata($metadata); - $this->assertEquals(StaticLoaderEntity::$invokedWith, $metadata); - } + $this->assertEquals(StaticLoaderEntity::$invokedWith, $metadata); + } } class StaticLoaderEntity { - static public $invokedWith = null; + static public $invokedWith = null; - public static function loadMetadata(ClassMetadata $metadata) - { - self::$invokedWith = $metadata; - } + public static function loadMetadata(ClassMetadata $metadata) + { + self::$invokedWith = $metadata; + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/XmlFileLoaderTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/XmlFileLoaderTest.php index d804611596..eb335737d9 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/XmlFileLoaderTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/XmlFileLoaderTest.php @@ -15,45 +15,45 @@ use Symfony\Components\Validator\Mapping\Loader\XmlFileLoader; class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase { - public function testLoadClassMetadataReturnsTrueIfSuccessful() - { - $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml'); - $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + public function testLoadClassMetadataReturnsTrueIfSuccessful() + { + $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml'); + $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $this->assertTrue($loader->loadClassMetadata($metadata)); - } + $this->assertTrue($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadataReturnsFalseIfNotSuccessful() - { - $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml'); - $metadata = new ClassMetadata('\stdClass'); + public function testLoadClassMetadataReturnsFalseIfNotSuccessful() + { + $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml'); + $metadata = new ClassMetadata('\stdClass'); - $this->assertFalse($loader->loadClassMetadata($metadata)); - } + $this->assertFalse($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadata() - { - $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml'); - $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + public function testLoadClassMetadata() + { + $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml'); + $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $loader->loadClassMetadata($metadata); + $loader->loadClassMetadata($metadata); - $expected = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $expected->addConstraint(new NotNull()); - $expected->addConstraint(new Min(3)); - $expected->addConstraint(new Choice(array('A', 'B'))); - $expected->addConstraint(new All(array(new NotNull(), new Min(3)))); - $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3))))); - $expected->addConstraint(new Collection(array('fields' => array( - 'foo' => array(new NotNull(), new Min(3)), - 'bar' => array(new Min(5)), - )))); - $expected->addPropertyConstraint('firstName', new Choice(array( - 'message' => 'Must be one of %choices%', - 'choices' => array('A', 'B'), - ))); - $expected->addGetterConstraint('lastName', new NotNull()); + $expected = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + $expected->addConstraint(new NotNull()); + $expected->addConstraint(new Min(3)); + $expected->addConstraint(new Choice(array('A', 'B'))); + $expected->addConstraint(new All(array(new NotNull(), new Min(3)))); + $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3))))); + $expected->addConstraint(new Collection(array('fields' => array( + 'foo' => array(new NotNull(), new Min(3)), + 'bar' => array(new Min(5)), + )))); + $expected->addPropertyConstraint('firstName', new Choice(array( + 'message' => 'Must be one of %choices%', + 'choices' => array('A', 'B'), + ))); + $expected->addGetterConstraint('lastName', new NotNull()); - $this->assertEquals($expected, $metadata); - } + $this->assertEquals($expected, $metadata); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/YamlFileLoaderTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/YamlFileLoaderTest.php index ff50729985..014c7d69e1 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/Loader/YamlFileLoaderTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/Loader/YamlFileLoaderTest.php @@ -15,45 +15,45 @@ use Symfony\Components\Validator\Mapping\Loader\YamlFileLoader; class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase { - public function testLoadClassMetadataReturnsTrueIfSuccessful() - { - $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml'); - $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + public function testLoadClassMetadataReturnsTrueIfSuccessful() + { + $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml'); + $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $this->assertTrue($loader->loadClassMetadata($metadata)); - } + $this->assertTrue($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadataReturnsFalseIfNotSuccessful() - { - $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml'); - $metadata = new ClassMetadata('\stdClass'); + public function testLoadClassMetadataReturnsFalseIfNotSuccessful() + { + $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml'); + $metadata = new ClassMetadata('\stdClass'); - $this->assertFalse($loader->loadClassMetadata($metadata)); - } + $this->assertFalse($loader->loadClassMetadata($metadata)); + } - public function testLoadClassMetadata() - { - $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml'); - $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + public function testLoadClassMetadata() + { + $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml'); + $metadata = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $loader->loadClassMetadata($metadata); + $loader->loadClassMetadata($metadata); - $expected = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); - $expected->addConstraint(new NotNull()); - $expected->addConstraint(new Min(3)); - $expected->addConstraint(new Choice(array('A', 'B'))); - $expected->addConstraint(new All(array(new NotNull(), new Min(3)))); - $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3))))); - $expected->addConstraint(new Collection(array('fields' => array( - 'foo' => array(new NotNull(), new Min(3)), - 'bar' => array(new Min(5)), - )))); - $expected->addPropertyConstraint('firstName', new Choice(array( - 'message' => 'Must be one of %choices%', - 'choices' => array('A', 'B'), - ))); - $expected->addGetterConstraint('lastName', new NotNull()); + $expected = new ClassMetadata('Symfony\Tests\Components\Validator\Fixtures\Entity'); + $expected->addConstraint(new NotNull()); + $expected->addConstraint(new Min(3)); + $expected->addConstraint(new Choice(array('A', 'B'))); + $expected->addConstraint(new All(array(new NotNull(), new Min(3)))); + $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3))))); + $expected->addConstraint(new Collection(array('fields' => array( + 'foo' => array(new NotNull(), new Min(3)), + 'bar' => array(new Min(5)), + )))); + $expected->addPropertyConstraint('firstName', new Choice(array( + 'message' => 'Must be one of %choices%', + 'choices' => array('A', 'B'), + ))); + $expected->addGetterConstraint('lastName', new NotNull()); - $this->assertEquals($expected, $metadata); - } + $this->assertEquals($expected, $metadata); + } } diff --git a/tests/Symfony/Tests/Components/Validator/Mapping/PropertyMetadataTest.php b/tests/Symfony/Tests/Components/Validator/Mapping/PropertyMetadataTest.php index c56fd69d66..0304d499c7 100644 --- a/tests/Symfony/Tests/Components/Validator/Mapping/PropertyMetadataTest.php +++ b/tests/Symfony/Tests/Components/Validator/Mapping/PropertyMetadataTest.php @@ -10,21 +10,21 @@ use Symfony\Tests\Components\Validator\Fixtures\Entity; class PropertyMetadataTest extends \PHPUnit_Framework_TestCase { - const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; + const CLASSNAME = 'Symfony\Tests\Components\Validator\Fixtures\Entity'; - public function testInvalidPropertyName() - { - $this->setExpectedException('Symfony\Components\Validator\Exception\ValidatorException'); + public function testInvalidPropertyName() + { + $this->setExpectedException('Symfony\Components\Validator\Exception\ValidatorException'); - new PropertyMetadata(self::CLASSNAME, 'foobar'); - } + new PropertyMetadata(self::CLASSNAME, 'foobar'); + } - public function testGetValueFromPrivateProperty() - { - $entity = new Entity('foobar'); - $metadata = new PropertyMetadata(self::CLASSNAME, 'internal'); + public function testGetValueFromPrivateProperty() + { + $entity = new Entity('foobar'); + $metadata = new PropertyMetadata(self::CLASSNAME, 'internal'); - $this->assertEquals('foobar', $metadata->getValue($entity)); - } + $this->assertEquals('foobar', $metadata->getValue($entity)); + } } diff --git a/tests/Symfony/Tests/Components/Validator/MessageInterpolator/XliffMessageInterpolatorTest.php b/tests/Symfony/Tests/Components/Validator/MessageInterpolator/XliffMessageInterpolatorTest.php index 3b0bccd769..57069981ec 100644 --- a/tests/Symfony/Tests/Components/Validator/MessageInterpolator/XliffMessageInterpolatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/MessageInterpolator/XliffMessageInterpolatorTest.php @@ -8,34 +8,34 @@ use Symfony\Components\Validator\MessageInterpolator\XliffMessageInterpolator; class XliffMessageInterpolatorTest extends \PHPUnit_Framework_TestCase { - public function testInterpolateText() - { - $interpolator = new XliffMessageInterpolator(__DIR__.'/xliff.xml'); - $text = $interpolator->interpolate('original', array('param' => 'foobar')); + public function testInterpolateText() + { + $interpolator = new XliffMessageInterpolator(__DIR__.'/xliff.xml'); + $text = $interpolator->interpolate('original', array('param' => 'foobar')); - $this->assertEquals('translation with param foobar', $text); - } + $this->assertEquals('translation with param foobar', $text); + } - public function testInterpolateFromMultipleFiles() - { - $interpolator = new XliffMessageInterpolator(array( - __DIR__.'/xliff.xml', - __DIR__.'/xliff2.xml', - )); + public function testInterpolateFromMultipleFiles() + { + $interpolator = new XliffMessageInterpolator(array( + __DIR__.'/xliff.xml', + __DIR__.'/xliff2.xml', + )); - $text1 = $interpolator->interpolate('original', array('param' => 'foobar')); - $text2 = $interpolator->interpolate('second', array('param' => 'baz')); + $text1 = $interpolator->interpolate('original', array('param' => 'foobar')); + $text2 = $interpolator->interpolate('second', array('param' => 'baz')); - $this->assertEquals('translation with param foobar', $text1); - $this->assertEquals('second translation with param baz', $text2); - } + $this->assertEquals('translation with param foobar', $text1); + $this->assertEquals('second translation with param baz', $text2); + } - public function testConvertParamsToStrings() - { - $interpolator = new XliffMessageInterpolator(__DIR__.'/xliff.xml'); - $text = $interpolator->interpolate('original', array('param' => array())); + public function testConvertParamsToStrings() + { + $interpolator = new XliffMessageInterpolator(__DIR__.'/xliff.xml'); + $text = $interpolator->interpolate('original', array('param' => array())); - $this->assertEquals('translation with param Array', $text); - } + $this->assertEquals('translation with param Array', $text); + } } diff --git a/tests/Symfony/Tests/Components/Validator/ValidatorTest.php b/tests/Symfony/Tests/Components/Validator/ValidatorTest.php index cf585e333d..8cc0ed18e1 100644 --- a/tests/Symfony/Tests/Components/Validator/ValidatorTest.php +++ b/tests/Symfony/Tests/Components/Validator/ValidatorTest.php @@ -17,67 +17,67 @@ use Symfony\Components\Validator\Specification\Specification; class ValidatorTest_Class { - public $firstName = 'Bernhard'; + public $firstName = 'Bernhard'; - public $reference; + public $reference; - public function getLastName() - { - return 'Schussek'; - } + public function getLastName() + { + return 'Schussek'; + } - public function isAustralian() - { - return false; - } + public function isAustralian() + { + return false; + } } class ValidatorTest extends \PHPUnit_Framework_TestCase { - public function testValidatePropertyConstraint() - { - /* - $subject = new ValidatorTest_Class(); - $subjectClass = get_class($subject); + public function testValidatePropertyConstraint() + { + /* + $subject = new ValidatorTest_Class(); + $subjectClass = get_class($subject); - $constraint = new Constraint(); - $property = new PropertySpecification($subjectClass, 'firstName', array($constraint)); - $class = new ClassSpecification($subjectClass, array($property)); - $specification = new Specification(array($class)); - $metadata = new Metadata($specification); + $constraint = new Constraint(); + $property = new PropertySpecification($subjectClass, 'firstName', array($constraint)); + $class = new ClassSpecification($subjectClass, array($property)); + $specification = new Specification(array($class)); + $metadata = new Metadata($specification); - $validatorMock = $this->getMock('Symfony\Components\Validator\ConstraintValidatorInterface'); - $validatorMock->expects($this->once()) - ->method('isValid') - ->with($this->equalTo('Bernhard'), $this->equalTo($constraint)) - ->will($this->returnValue(false)); - $validatorMock->expects($this->atLeastOnce()) - ->method('getMessageTemplate') - ->will($this->returnValue('message')); - $validatorMock->expects($this->atLeastOnce()) - ->method('getMessageParameters') - ->will($this->returnValue(array('param' => 'value'))); + $validatorMock = $this->getMock('Symfony\Components\Validator\ConstraintValidatorInterface'); + $validatorMock->expects($this->once()) + ->method('isValid') + ->with($this->equalTo('Bernhard'), $this->equalTo($constraint)) + ->will($this->returnValue(false)); + $validatorMock->expects($this->atLeastOnce()) + ->method('getMessageTemplate') + ->will($this->returnValue('message')); + $validatorMock->expects($this->atLeastOnce()) + ->method('getMessageParameters') + ->will($this->returnValue(array('param' => 'value'))); - $factoryMock = $this->getMock('Symfony\Components\Validator\ConstraintValidatorFactoryInterface'); - $factoryMock->expects($this->once()) - ->method('getInstance') - ->with($this->equalTo($constraint->validatedBy())) - ->will($this->returnValue($validatorMock)); + $factoryMock = $this->getMock('Symfony\Components\Validator\ConstraintValidatorFactoryInterface'); + $factoryMock->expects($this->once()) + ->method('getInstance') + ->with($this->equalTo($constraint->validatedBy())) + ->will($this->returnValue($validatorMock)); - $validator = new Validator($metadata, $factoryMock); + $validator = new Validator($metadata, $factoryMock); - $builder = new PropertyPathBuilder(); - $expected = new ConstraintViolationList(); - $expected->add(new ConstraintViolation( - 'message', - array('param' => 'value'), - $subjectClass, - $builder->atProperty('firstName')->getPropertyPath(), - 'Bernhard' - )); + $builder = new PropertyPathBuilder(); + $expected = new ConstraintViolationList(); + $expected->add(new ConstraintViolation( + 'message', + array('param' => 'value'), + $subjectClass, + $builder->atProperty('firstName')->getPropertyPath(), + 'Bernhard' + )); - $this->assertEquals($expected, $validator->validateProperty($subject, 'firstName')); - */ - } + $this->assertEquals($expected, $validator->validateProperty($subject, 'firstName')); + */ + } } \ No newline at end of file