Adapted Form, Validator, File and I18N component to new coding standards

This commit is contained in:
Bernhard Schussek 2010-06-24 11:24:08 +02:00 committed by Fabien Potencier
parent ee83847cec
commit bcd4b6d140
227 changed files with 12877 additions and 13518 deletions

View File

@ -452,8 +452,7 @@ class File
*/
public function __construct($path)
{
if (!is_file($path))
{
if (!is_file($path)) {
throw new FileNotFoundException($path);
}
@ -489,12 +488,9 @@ class File
{
$name = $this->getName();
if (false !== ($pos = strrpos($name, '.')))
{
if (false !== ($pos = strrpos($name, '.'))) {
return substr($name, $pos);
}
else
{
} else {
return '';
}
}
@ -510,12 +506,9 @@ class File
{
$type = $this->getMimeType();
if (isset(self::$defaultExtensions[$type]))
{
if (isset(self::$defaultExtensions[$type])) {
return '.' . self::$defaultExtensions[$type];
}
else
{
} else {
return $this->getExtension();
}
}
@ -563,8 +556,7 @@ class File
*/
public function size()
{
if (false === ($size = filesize($this->getPath())))
{
if (false === ($size = filesize($this->getPath()))) {
throw new FileException(sprintf('Could not read file size of %s', $this->getPath()));
}
@ -578,8 +570,7 @@ class File
*/
public function move($newPath)
{
if (!rename($this->getPath(), $newPath))
{
if (!rename($this->getPath(), $newPath)) {
throw new FileException(sprintf('Could not move file %s to %s', $this->getPath(), $newPath));
}
}

View File

@ -37,26 +37,22 @@ class ContentTypeMimeTypeGuesser implements MimeTypeGuesserInterface
*/
public function guess($path)
{
if (!is_file($path))
{
if (!is_file($path)) {
throw new FileNotFoundException($path);
}
if (!is_readable($path))
{
if (!is_readable($path)) {
throw new AccessDeniedException($path);
}
if (!self::isSupported() || !is_readable($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, ';'))
{
if (false !== $pos = strpos($type, ';')) {
$type = substr($type, 0, $pos);
}

View File

@ -27,13 +27,11 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
*/
public function guess($path)
{
if (!is_file($path))
{
if (!is_file($path)) {
throw new FileNotFoundException($path);
}
if (!is_readable($path))
{
if (!is_readable($path)) {
throw new AccessDeniedException($path);
}
@ -41,8 +39,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
// need to use --mime instead of -i. see #6641
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return);
if ($return > 0)
{
if ($return > 0) {
ob_end_clean();
return null;
@ -50,8 +47,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-]+)#i', $type, $match))
{
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-]+)#i', $type, $match)) {
// it's not a type, but an error message
return null;
}

View File

@ -37,31 +37,26 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface
*/
public function guess($path)
{
if (!is_file($path))
{
if (!is_file($path)) {
throw new FileNotFoundException($path);
}
if (!is_readable($path))
{
if (!is_readable($path)) {
throw new AccessDeniedException($path);
}
if (!self::isSupported())
{
if (!self::isSupported()) {
return null;
}
if (!$finfo = new \finfo(FILEINFO_MIME))
{
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, ';'))
{
if (false !== $pos = strpos($type, ';')) {
$type = substr($type, 0, $pos);
}

View File

@ -50,8 +50,7 @@ class MimeTypeGuesser implements MimeTypeGuesserInterface
*/
static public function getInstance()
{
if (is_null(self::$instance))
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
@ -65,13 +64,11 @@ class MimeTypeGuesser implements MimeTypeGuesserInterface
{
$this->register(new FileBinaryMimeTypeGuesser());
if (ContentTypeMimeTypeGuesser::isSupported())
{
if (ContentTypeMimeTypeGuesser::isSupported()) {
$this->register(new ContentTypeMimeTypeGuesser());
}
if (FileinfoMimeTypeGuesser::isSupported())
{
if (FileinfoMimeTypeGuesser::isSupported()) {
$this->register(new FileinfoMimeTypeGuesser());
}
}
@ -102,24 +99,20 @@ class MimeTypeGuesser implements MimeTypeGuesserInterface
*/
public function guess($path)
{
if (!is_file($path))
{
if (!is_file($path)) {
throw new FileNotFoundException($path);
}
if (!is_readable($path))
{
if (!is_readable($path)) {
throw new AccessDeniedException($path);
}
$mimeType = null;
foreach ($this->guessers as $guesser)
{
foreach ($this->guessers as $guesser) {
$mimeType = $guesser->guess($path);
if (!is_null($mimeType))
{
if (!is_null($mimeType)) {
break;
}
}

View File

@ -39,20 +39,17 @@ class UploadedFile extends File
*/
public function __construct($path, $originalName, $mimeType, $size, $error)
{
if (!ini_get('file_uploads'))
{
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))
{
if (is_null($error)) {
$error = UPLOAD_ERR_OK;
}
if (is_null($mimeType))
{
if (is_null($mimeType)) {
$mimeType = 'application/octet-stream';
}
@ -75,8 +72,7 @@ class UploadedFile extends File
{
$mimeType = parent::getMimeType();
if (is_null($mimeType))
{
if (is_null($mimeType)) {
$mimeType = $this->mimeType;
}
@ -113,17 +109,13 @@ class UploadedFile extends File
*/
public function move($newPath)
{
if (!$this->moved)
{
if (!move_uploaded_file($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;
}
else
{
} else {
parent::move($newPath);
}
}

View File

@ -34,35 +34,28 @@ class ChoiceField extends HybridField
$this->addOption('empty_value', '');
$this->addOption('translate_choices', false);
if (count($this->getOption('preferred_choices')) > 0)
{
if (count($this->getOption('preferred_choices')) > 0) {
$this->preferredChoices = array_flip($this->getOption('preferred_choices'));
if (false && $diff = array_diff_key($this->options, $this->knownOptions))
{
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('expanded'))
{
if ($this->getOption('expanded')) {
$this->setFieldMode(self::GROUP);
$choices = $this->getOption('choices');
foreach ($this->getOption('preferred_choices') as $choice)
{
foreach ($this->getOption('preferred_choices') as $choice) {
$this->add($this->newChoiceField($choice, $choices[$choice]));
unset($choices[$choice]);
}
foreach ($this->getOption('choices') as $choice => $value)
{
foreach ($this->getOption('choices') as $choice => $value) {
$this->add($this->newChoiceField($choice, $value));
}
}
else
{
} else {
$this->setFieldMode(self::FIELD);
}
}
@ -75,16 +68,13 @@ class ChoiceField extends HybridField
*/
protected function newChoiceField($choice, $label)
{
if ($this->getOption('multiple'))
{
if ($this->getOption('multiple')) {
return new CheckboxField($choice, array(
'value' => $choice,
'label' => $label,
'translate_label' => $this->getOption('translate_choices'),
));
}
else
{
} else {
return new RadioField($choice, array(
'value' => $choice,
'label' => $label,
@ -101,8 +91,7 @@ class ChoiceField extends HybridField
*/
public function bind($value)
{
if (!$this->getOption('multiple') && $this->getOption('expanded'))
{
if (!$this->getOption('multiple') && $this->getOption('expanded')) {
$value = $value === null ? array() : array($value => true);
}
@ -124,21 +113,17 @@ class ChoiceField extends HybridField
*/
protected function transform($value)
{
if ($this->getOption('expanded'))
{
if ($this->getOption('expanded')) {
$choices = $this->getOption('choices');
foreach ($choices as $choice => $_)
{
foreach ($choices as $choice => $_) {
$choices[$choice] = $this->getOption('multiple')
? in_array($choice, (array)$value, true)
: ($choice === $value);
}
return $choices;
}
else
{
} else {
return parent::transform($value);
}
}
@ -158,29 +143,21 @@ class ChoiceField extends HybridField
*/
protected function reverseTransform($value)
{
if ($this->getOption('expanded'))
{
if ($this->getOption('expanded')) {
$choices = array();
foreach ($value as $choice => $selected)
{
if ($selected)
{
foreach ($value as $choice => $selected) {
if ($selected) {
$choices[] = $choice;
}
}
if ($this->getOption('multiple'))
{
if ($this->getOption('multiple')) {
return $choices;
}
else
{
} else {
return count($choices) > 0 ? current($choices) : null;
}
}
else
{
} else {
return parent::reverseTransform($value);
}
}
@ -190,19 +167,15 @@ class ChoiceField extends HybridField
*/
public function render(array $attributes = array())
{
if ($this->getOption('expanded'))
{
if ($this->getOption('expanded')) {
$html = "";
foreach ($this as $field)
{
foreach ($this as $field) {
$html .= $field->render()."\n";
}
return $html;
}
else
{
} else {
$attrs['id'] = $this->getId();
$attrs['name'] = $this->getName();
$attrs['disabled'] = $this->isDisabled();
@ -210,28 +183,24 @@ class ChoiceField extends HybridField
// 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'))
{
if ($this->getOption('multiple') && !$this->getOption('expanded')) {
$attrs['name'] .= '[]';
}
if ($this->getOption('multiple'))
{
if ($this->getOption('multiple')) {
$attrs['multiple'] = 'multiple';
}
$selected = array_flip(array_map('strval', (array)$this->getDisplayedData()));
$html = "\n";
if (!$this->isRequired())
{
if (!$this->isRequired()) {
$html .= $this->renderChoices(array('' => $this->getOption('empty_value')), $selected)."\n";
}
$choices = $this->getOption('choices');
if (count($this->preferredChoices) > 0)
{
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";
}
@ -251,27 +220,21 @@ class ChoiceField extends HybridField
{
$options = array();
foreach ($choices as $key => $option)
{
if (is_array($option))
{
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
{
} else {
$attributes = array('value' => $this->generator->escape($key));
if (isset($selected[strval($key)]))
{
if (isset($selected[strval($key)])) {
$attributes['selected'] = true;
}
if ($this->getOption('translate_choices'))
{
if ($this->getOption('translate_choices')) {
$option = $this->translate($option);
}

View File

@ -43,8 +43,7 @@ class CollectionField extends FieldGroup
{
$this->addOption('modifiable', false);
if ($this->getOption('modifiable'))
{
if ($this->getOption('modifiable')) {
$field = $this->newField('$$key$$', null);
// TESTME
$field->setRequired(false);
@ -54,13 +53,11 @@ class CollectionField extends FieldGroup
public function setData($collection)
{
if (!is_array($collection) && !$collection instanceof Traversable)
{
if (!is_array($collection) && !$collection instanceof Traversable) {
throw new UnexpectedTypeException('The data must be an array');
}
foreach ($collection as $name => $value)
{
foreach ($collection as $name => $value) {
$this->add($this->newField($name, $name));
}
@ -69,23 +66,18 @@ class CollectionField extends FieldGroup
public function bind($taintedData)
{
if (is_null($taintedData))
{
if (is_null($taintedData)) {
$taintedData = array();
}
foreach ($this as $name => $field)
{
if (!isset($taintedData[$name]) && $this->getOption('modifiable') && $name != '$$key$$')
{
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'))
{
foreach ($taintedData as $name => $value) {
if (!isset($this[$name]) && $this->getOption('modifiable')) {
$this->add($this->newField($name, $name));
}
}

View File

@ -55,14 +55,12 @@ abstract class Configurable
$this->configure();
// check option names
if ($diff = array_diff_key($this->options, $this->knownOptions))
{
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))
{
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));
}
}
@ -99,13 +97,11 @@ abstract class Configurable
{
$this->knownOptions[$name] = true;
if (!array_key_exists($name, $this->options))
{
if (!array_key_exists($name, $this->options)) {
$this->options[$name] = $value;
}
if (count($allowedValues) > 0 && !in_array($this->options[$name], $allowedValues))
{
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));
}
}
@ -122,8 +118,7 @@ abstract class Configurable
// 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))
{
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));
}
}

View File

@ -104,23 +104,18 @@ class DateField extends HybridField
$transformers = array();
if ($this->getOption('type') === self::STRING)
{
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)
{
} 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)
{
} 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'),
@ -128,8 +123,7 @@ class DateField extends HybridField
)));
}
if ($this->getOption('widget') === self::INPUT)
{
if ($this->getOption('widget') === self::INPUT) {
$transformers[] = new DateTimeToLocalizedStringTransformer(array(
'date_format' => $this->getOption('format'),
'time_format' => DateTimeToLocalizedStringTransformer::NONE,
@ -138,9 +132,7 @@ class DateField extends HybridField
));
$this->setFieldMode(self::FIELD);
}
else
{
} else {
$transformers[] = new DateTimeToArrayTransformer(array(
'input_timezone' => $this->getOption('data_timezone'),
'output_timezone' => $this->getOption('user_timezone'),
@ -159,8 +151,7 @@ class DateField extends HybridField
)));
}
if (count($transformers) > 0)
{
if (count($transformers) > 0) {
$this->setValueTransformer(new ValueTransformerChain($transformers));
}
}
@ -180,8 +171,7 @@ class DateField extends HybridField
{
$choices = array();
foreach ($values as $value)
{
foreach ($values as $value) {
$choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT);
}
@ -199,20 +189,16 @@ class DateField extends HybridField
{
$pattern = $this->formatter->getPattern();
if (preg_match('/M+/', $pattern, $matches))
{
if (preg_match('/M+/', $pattern, $matches)) {
$this->formatter->setPattern($matches[0]);
$choices = array();
foreach ($months as $month)
{
foreach ($months as $month) {
$choices[$month] = $this->formatter->format(gmmktime(0, 0, 0, $month));
}
$this->formatter->setPattern($pattern);
}
else
{
} else {
$choices = $this->generatePaddedChoices($months, 2);
}
@ -224,31 +210,25 @@ class DateField extends HybridField
*/
public function render(array $attributes = array())
{
if ($this->getOption('widget') === self::INPUT)
{
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
{
} else {
// set order as specified in the pattern
if ($this->getOption('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()))
{
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
{
else {
$pattern = '%year%-%month%-%day%';
}

View File

@ -74,15 +74,12 @@ class DateTimeField extends FieldGroup
$transformers = array();
if ($this->getOption('type') == self::STRING)
{
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)
{
} else if ($this->getOption('type') == self::TIMESTAMP) {
$transformers[] = new TimestampToDateTimeTransformer(array(
'input_timezone' => $this->getOption('data_timezone'),
'output_timezone' => $this->getOption('data_timezone'),

View File

@ -144,12 +144,9 @@ abstract class Field extends Configurable implements FieldInterface
*/
public function isRequired()
{
if (is_null($this->parent) || $this->parent->isRequired())
{
if (is_null($this->parent) || $this->parent->isRequired()) {
return $this->required;
}
else
{
} else {
return false;
}
}
@ -159,12 +156,9 @@ abstract class Field extends Configurable implements FieldInterface
*/
public function isDisabled()
{
if (is_null($this->parent) || !$this->parent->isDisabled())
{
if (is_null($this->parent) || !$this->parent->isDisabled()) {
return $this->getOption('disabled');
}
else
{
} else {
return true;
}
}
@ -237,18 +231,14 @@ abstract class Field extends Configurable implements FieldInterface
$this->bound = true;
$this->errors = array();
if (is_string($this->transformedData) && $this->getOption('trim'))
{
if (is_string($this->transformedData) && $this->getOption('trim')) {
$this->transformedData = trim($this->transformedData);
}
try
{
try {
$this->data = $this->processData($data = $this->reverseTransform($this->transformedData));
$this->transformedData = $this->transform($this->data);
}
catch (TransformationFailedException $e)
{
} catch (TransformationFailedException $e) {
// TODO better text
// TESTME
$this->addError('invalid (localized)');
@ -342,8 +332,7 @@ abstract class Field extends Configurable implements FieldInterface
{
$this->locale = $locale;
if ($this->valueTransformer !== null && $this->valueTransformer instanceof Localizable)
{
if ($this->valueTransformer !== null && $this->valueTransformer instanceof Localizable) {
$this->valueTransformer->setLocale($locale);
}
}
@ -357,8 +346,7 @@ abstract class Field extends Configurable implements FieldInterface
{
$this->translator = $translator;
if ($this->valueTransformer !== null && $this->valueTransformer instanceof Translatable)
{
if ($this->valueTransformer !== null && $this->valueTransformer instanceof Translatable) {
$this->valueTransformer->setTranslator($translator);
}
}
@ -375,8 +363,7 @@ abstract class Field extends Configurable implements FieldInterface
*/
protected function translate($text, array $parameters = array())
{
if ($this->translator !== null)
{
if ($this->translator !== null) {
$text = $this->translator->translate($text, $parameters);
}
@ -393,13 +380,11 @@ abstract class Field extends Configurable implements FieldInterface
*/
protected function injectLocaleAndTranslator($object)
{
if ($object instanceof Localizable)
{
if ($object instanceof Localizable) {
$object->setLocale($this->locale);
}
if (!is_null($this->translator) && $object instanceof Translatable)
{
if (!is_null($this->translator) && $object instanceof Translatable) {
$object->setTranslator($this->translator);
}
}
@ -434,16 +419,11 @@ abstract class Field extends Configurable implements FieldInterface
*/
protected function transform($value)
{
if ($value === null)
{
if ($value === null) {
return '';
}
else if (null === $this->valueTransformer)
{
} else if (null === $this->valueTransformer) {
return $value;
}
else
{
} else {
return $this->valueTransformer->transform($value);
}
}
@ -456,16 +436,11 @@ abstract class Field extends Configurable implements FieldInterface
*/
protected function reverseTransform($value)
{
if ($value === '')
{
if ($value === '') {
return null;
}
else if (null === $this->valueTransformer)
{
} else if (null === $this->valueTransformer) {
return $value;
}
else
{
} else {
return $this->valueTransformer->reverseTransform($value);
}
}
@ -477,13 +452,10 @@ abstract class Field extends Configurable implements FieldInterface
{
// TODO throw exception if not object or array
if ($this->propertyPath !== null)
{
if ($this->propertyPath !== null) {
$this->propertyPath->rewind();
$this->setData($this->readPropertyPath($objectOrArray, $this->propertyPath));
}
else
{
} else {
// pass object through if the property path is empty
$this->setData($objectOrArray);
}
@ -496,8 +468,7 @@ abstract class Field extends Configurable implements FieldInterface
{
// TODO throw exception if not object or array
if ($this->propertyPath !== null)
{
if ($this->propertyPath !== null) {
$this->propertyPath->rewind();
$this->updatePropertyPath($objectOrArray, $this->propertyPath);
}
@ -512,48 +483,38 @@ abstract class Field extends Configurable implements FieldInterface
*/
protected function readPropertyPath(&$objectOrArray, PropertyPath $propertyPath)
{
if (is_object($objectOrArray))
{
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))
{
else {
if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) {
$objectOrArray[$propertyPath->getCurrent()] = array();
}
$value =& $objectOrArray[$propertyPath->getCurrent()];
}
if ($propertyPath->hasNext())
{
if ($propertyPath->hasNext()) {
$propertyPath->next();
return $this->readPropertyPath($value, $propertyPath);
}
else
{
} else {
return $value;
}
}
protected function updatePropertyPath(&$objectOrArray, PropertyPath $propertyPath)
{
if ($propertyPath->hasNext())
{
if (is_object($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))
{
else {
if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) {
$objectOrArray[$propertyPath->getCurrent()] = array();
}
@ -563,9 +524,7 @@ abstract class Field extends Configurable implements FieldInterface
$propertyPath->next();
$this->updatePropertyPath($value, $propertyPath);
}
else
{
} else {
$this->updateProperty($objectOrArray, $propertyPath);
}
}
@ -585,51 +544,37 @@ abstract class Field extends Configurable implements FieldInterface
*/
protected function readProperty($object, PropertyPath $propertyPath)
{
if ($propertyPath->isIndex())
{
if (!$object instanceof \ArrayAccess)
{
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
{
} 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())
{
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())
{
} 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())
{
} 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
{
} else {
throw new InvalidPropertyException(sprintf('Neither property "%s" nor method "%s()" nor method "%s()" exists in class "%s"', $property, $getter, $isser, $reflClass->getName()));
}
}
@ -637,46 +582,33 @@ abstract class Field extends Configurable implements FieldInterface
protected function updateProperty(&$objectOrArray, PropertyPath $propertyPath)
{
if (is_object($objectOrArray) && $propertyPath->isIndex())
{
if (!$objectOrArray instanceof \ArrayAccess)
{
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))
{
} 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())
{
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())
{
} 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
{
} else {
throw new InvalidPropertyException(sprintf('Neither element "%s" nor method "%s()" exists in class "%s"', $property, $setter, $reflClass->getName()));
}
}
else
{
} else {
$objectOrArray[$propertyPath->getCurrent()] = $this->getData();
}
}
@ -688,12 +620,10 @@ abstract class Field extends Configurable implements FieldInterface
{
$html = '';
if ($this->hasErrors())
{
if ($this->hasErrors()) {
$html .= "<ul>\n";
foreach ($this->getErrors() as $error)
{
foreach ($this->getErrors() as $error) {
$html .= "<li>" . $error . "</li>\n";
}

View File

@ -59,8 +59,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function __clone()
{
foreach ($this->fields as $name => $field)
{
foreach ($this->fields as $name => $field) {
$this->fields[$name] = clone $field;
}
}
@ -101,8 +100,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function add(FieldInterface $field)
{
if ($this->isBound())
{
if ($this->isBound()) {
throw new AlreadyBoundException('You cannot add fields after binding a form');
}
@ -112,8 +110,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
$field->setLocale($this->locale);
$field->setGenerator($this->generator);
if ($this->translator !== null)
{
if ($this->translator !== null) {
$field->setTranslator($this->translator);
}
@ -121,8 +118,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
// if the property "data" is NULL, getTransformedData() returns an empty
// string
if (!empty($data) && $field->getPropertyPath() !== null)
{
if (!empty($data) && $field->getPropertyPath() !== null) {
$field->updateFromObject($data);
}
@ -158,18 +154,15 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function merge(FieldGroup $group)
{
if ($group->isBound())
{
if ($group->isBound()) {
throw new AlreadyBoundException('A bound form group cannot be merged');
}
foreach ($group as $field)
{
foreach ($group as $field) {
$group->remove($field->getKey());
$this->add($field);
if (($path = $group->getPropertyPath()) !== null)
{
if (($path = $group->getPropertyPath()) !== null) {
$field->setPropertyPath($path.'.'.$field->getPropertyPath());
}
}
@ -208,8 +201,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function get($key)
{
if (isset($this->fields[$key]))
{
if (isset($this->fields[$key])) {
return $this->fields[$key];
}
@ -237,17 +229,12 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
{
$fields = array();
foreach ($this->fields as $field)
{
if ($field instanceof FieldGroup)
{
if ($recursive)
{
foreach ($this->fields as $field) {
if ($field instanceof FieldGroup) {
if ($recursive) {
$fields = array_merge($fields, $field->getHiddenFields($recursive));
}
}
else if ($field->isHidden())
{
} else if ($field->isHidden()) {
$fields[] = $field;
}
}
@ -267,18 +254,15 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
// get transformed data and pass its values to child fields
$data = $this->getTransformedData();
if (!empty($data) && !is_array($data) && !is_object($data))
{
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))
{
if (!empty($data)) {
$iterator = new RecursiveFieldsWithPropertyPathIterator($this);
$iterator = new \RecursiveIteratorIterator($iterator);
foreach ($iterator as $field)
{
foreach ($iterator as $field) {
$field->updateFromObject($data);
}
}
@ -293,8 +277,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
{
$values = array();
foreach ($this->fields as $key => $field)
{
foreach ($this->fields as $key => $field) {
$values[$key] = $field->getDisplayedData();
}
@ -309,28 +292,22 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function bind($taintedData)
{
if ($taintedData === null)
{
if ($taintedData === null) {
$taintedData = array();
}
if (!is_array($taintedData))
{
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]))
{
foreach ($this->fields as $key => $field) {
if (!isset($taintedData[$key])) {
$taintedData[$key] = null;
}
}
foreach ($taintedData as $key => $value)
{
if ($this->has($key))
{
foreach ($taintedData as $key => $value) {
if ($this->has($key)) {
$this->fields[$key]->bind($value);
}
}
@ -339,8 +316,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
$iterator = new RecursiveFieldsWithPropertyPathIterator($this);
$iterator = new \RecursiveIteratorIterator($iterator);
foreach ($iterator as $field)
{
foreach ($iterator as $field) {
$field->updateObject($data);
}
@ -349,10 +325,8 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
$this->extraFields = array();
foreach ($taintedData as $key => $value)
{
if (!$this->has($key))
{
foreach ($taintedData as $key => $value) {
if (!$this->has($key)) {
$this->extraFields[] = $key;
}
}
@ -376,15 +350,12 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function isValid()
{
if (!parent::isValid())
{
if (!parent::isValid()) {
return false;
}
foreach ($this->fields as $field)
{
if (!$field->isValid())
{
foreach ($this->fields as $field) {
if (!$field->isValid()) {
return false;
}
}
@ -397,34 +368,25 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function addError($message, PropertyPath $path = null, $type = null)
{
if ($path !== null)
{
if ($type === self::FIELD_ERROR && $path->hasNext())
{
if ($path !== null) {
if ($type === self::FIELD_ERROR && $path->hasNext()) {
$path->next();
if ($this->has($path->getCurrent()) && !$this->get($path->getCurrent())->isHidden())
{
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)
{
} else if ($type === self::DATA_ERROR) {
$iterator = new RecursiveFieldsWithPropertyPathIterator($this);
$iterator = new \RecursiveIteratorIterator($iterator);
foreach ($iterator as $field)
{
if (null !== ($fieldPath = $field->getPropertyPath()))
{
foreach ($iterator as $field) {
if (null !== ($fieldPath = $field->getPropertyPath())) {
$fieldPath->rewind();
if ($fieldPath->getCurrent() === $path->getCurrent() && !$field->isHidden())
{
if ($path->hasNext())
{
if ($fieldPath->getCurrent() === $path->getCurrent() && !$field->isHidden()) {
if ($path->hasNext()) {
$path->next();
}
@ -447,10 +409,8 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
*/
public function isMultipart()
{
foreach ($this->fields as $field)
{
if ($field->isMultipart())
{
foreach ($this->fields as $field) {
if ($field->isMultipart()) {
return true;
}
}
@ -512,8 +472,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
{
$output = '';
foreach ($this->getHiddenFields($recursive) as $field)
{
foreach ($this->getHiddenFields($recursive) as $field) {
$output .= $field->render();
}
@ -598,8 +557,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
{
parent::setLocale($locale);
foreach ($this->fields as $field)
{
foreach ($this->fields as $field) {
$field->setLocale($locale);
}
}
@ -613,8 +571,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
{
parent::setTranslator($translator);
foreach ($this->fields as $field)
{
foreach ($this->fields as $field) {
$field->setTranslator($translator);
}
}
@ -629,8 +586,7 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
parent::setGenerator($generator);
// TESTME
foreach ($this->fields as $field)
{
foreach ($this->fields as $field) {
$field->setGenerator($generator);
}
}

View File

@ -63,27 +63,21 @@ class Form extends FieldGroup
$this->setData($object);
$this->setCsrfFieldName(self::$defaultCsrfFieldName);
if (self::$defaultCsrfSecret !== null)
{
if (self::$defaultCsrfSecret !== null) {
$this->setCsrfSecret(self::$defaultCsrfSecret);
}
else
{
} else {
$this->setCsrfSecret(md5(__FILE__.php_uname()));
}
if (self::$defaultCsrfProtection !== false)
{
if (self::$defaultCsrfProtection !== false) {
$this->enableCsrfProtection();
}
if (self::$defaultLocale !== null)
{
if (self::$defaultLocale !== null) {
$this->setLocale(self::$defaultLocale);
}
if (self::$defaultTranslator !== null)
{
if (self::$defaultTranslator !== null) {
$this->setTranslator(self::$defaultTranslator);
}
}
@ -175,37 +169,27 @@ class Form extends FieldGroup
*/
final public function bind($taintedValues, array $taintedFiles = null)
{
if ($taintedFiles === null)
{
if ($this->isMultipart() && $this->getParent() === 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
{
} 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)
{
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')
{
if ($propertyPath->getCurrent() == 'data') {
$type = self::DATA_ERROR;
$propertyPath->next(); // point at the first data element
}
else
{
} else {
$type = self::FIELD_ERROR;
}
@ -274,8 +258,7 @@ class Form extends FieldGroup
*/
public function enableCsrfProtection()
{
if (!$this->isCsrfProtected())
{
if (!$this->isCsrfProtected()) {
$field = new HiddenField($this->getCsrfFieldName(), array(
'property_path' => null,
));
@ -289,8 +272,7 @@ class Form extends FieldGroup
*/
public function disableCsrfProtection()
{
if ($this->isCsrfProtected())
{
if ($this->isCsrfProtected()) {
$this->remove($this->getCsrfFieldName());
}
}
@ -342,12 +324,9 @@ class Form extends FieldGroup
*/
public function isCsrfTokenValid()
{
if (!$this->isCsrfProtected())
{
if (!$this->isCsrfProtected()) {
return true;
}
else
{
} else {
return $this->get($this->getCsrfFieldName())->getDisplayedData() === $this->getCsrfToken();
}
}
@ -437,13 +416,11 @@ class Form extends FieldGroup
*/
public function isPostMaxSizeReached()
{
if (isset($_SERVER['CONTENT_LENGTH']))
{
if (isset($_SERVER['CONTENT_LENGTH'])) {
$length = (int) $_SERVER['CONTENT_LENGTH'];
$max = trim(ini_get('post_max_size'));
switch (strtolower(substr($max, -1)))
{
switch (strtolower(substr($max, -1))) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$max *= 1024;
@ -454,9 +431,7 @@ class Form extends FieldGroup
}
return $length > $max;
}
else
{
} else {
return false;
}
}
@ -471,14 +446,10 @@ class Form extends FieldGroup
*/
static protected function deepArrayUnion($array1, $array2)
{
foreach ($array2 as $key => $value)
{
if (is_array($value) && isset($array1[$key]) && is_array($array1[$key]))
{
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
$array1[$key] = self::deepArrayUnion($array1[$key], $value);
}
else
{
} else {
$array1[$key] = $value;
}
}
@ -506,15 +477,12 @@ class Form extends FieldGroup
$files = $data;
if ($fileKeys == $keys && isset($data['name']) && is_array($data['name']))
{
foreach ($fileKeys as $k)
{
if ($fileKeys == $keys && isset($data['name']) && is_array($data['name'])) {
foreach ($fileKeys as $k) {
unset($files[$k]);
}
foreach (array_keys($data['name']) as $key)
{
foreach (array_keys($data['name']) as $key) {
$files[$key] = self::fixPhpFilesArray(array(
'error' => $data['error'][$key],
'name' => $data['name'][$key],
@ -538,19 +506,14 @@ class Form extends FieldGroup
{
$fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
foreach ($files as $key => $data)
{
if (is_array($data))
{
foreach ($files as $key => $data) {
if (is_array($data)) {
$keys = array_keys($data);
sort($keys);
if ($keys == $fileKeys)
{
if ($keys == $fileKeys) {
$files[$key] = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']);
}
else
{
} else {
$files[$key] = self::convertFileInformation($data);
}
}

View File

@ -57,8 +57,7 @@ class HtmlGenerator implements HtmlGeneratorInterface
*/
public function tag($tag, $attributes = array())
{
if (empty($tag))
{
if (empty($tag)) {
return '';
}
@ -70,8 +69,7 @@ class HtmlGenerator implements HtmlGeneratorInterface
*/
public function contentTag($tag, $content = null, $attributes = array())
{
if (empty($tag))
{
if (empty($tag)) {
return '';
}
@ -83,12 +81,9 @@ class HtmlGenerator implements HtmlGeneratorInterface
*/
public function attribute($name, $value)
{
if (true === $value)
{
if (true === $value) {
return self::$xhtml ? sprintf('%s="%s"', $name, $this->escape($name)) : $this->escape($name);
}
else
{
} else {
return sprintf('%s="%s"', $name, $this->escape($value));
}
}
@ -113,12 +108,9 @@ class HtmlGenerator implements HtmlGeneratorInterface
*/
private function attributesCallback($name, $value)
{
if (false === $value || null === $value || ('' === $value && 'value' != $name))
{
if (false === $value || null === $value || ('' === $value && 'value' != $name)) {
return '';
}
else
{
} else {
return ' '.$this->attribute($name, $value);
}
}

View File

@ -30,8 +30,7 @@ class HybridField extends FieldGroup
*/
public function setFieldMode($mode)
{
if (count($this) > 0 && $mode === self::FIELD)
{
if (count($this) > 0 && $mode === self::FIELD) {
throw new FormException('Switching to mode FIELD is not allowed after adding nested fields');
}
@ -46,8 +45,7 @@ class HybridField extends FieldGroup
*/
public function add(FieldInterface $field)
{
if ($this->mode === self::FIELD)
{
if ($this->mode === self::FIELD) {
throw new FormException('You cannot add nested fields while in mode FIELD');
}
@ -59,12 +57,9 @@ class HybridField extends FieldGroup
*/
public function getDisplayedData()
{
if ($this->mode === self::GROUP)
{
if ($this->mode === self::GROUP) {
return parent::getDisplayedData();
}
else
{
} else {
return Field::getDisplayedData();
}
}
@ -74,12 +69,9 @@ class HybridField extends FieldGroup
*/
public function setData($data)
{
if ($this->mode === self::GROUP)
{
if ($this->mode === self::GROUP) {
parent::setData($data);
}
else
{
} else {
Field::setData($data);
}
}
@ -89,12 +81,9 @@ class HybridField extends FieldGroup
*/
public function bind($data)
{
if ($this->mode === self::GROUP)
{
if ($this->mode === self::GROUP) {
parent::bind($data);
}
else
{
} else {
Field::bind($data);
}
}

View File

@ -54,12 +54,9 @@ class MoneyField extends NumberField
{
$input = parent::render($attributes);
if ($this->getOption('currency'))
{
if ($this->getOption('currency')) {
return str_replace('%widget%', $input, $this->getPattern($this->locale, $this->getOption('currency')));
}
else
{
} else {
return $input;
}
}
@ -74,13 +71,11 @@ class MoneyField extends NumberField
*/
protected static function getPattern($locale, $currency)
{
if (!isset(self::$patterns[$locale]))
{
if (!isset(self::$patterns[$locale])) {
self::$patterns[$locale] = array();
}
if (!isset(self::$patterns[$locale][$currency]))
{
if (!isset(self::$patterns[$locale][$currency])) {
$format = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$pattern = $format->formatCurrency('123', $currency);
@ -92,16 +87,11 @@ class MoneyField extends NumberField
preg_match('/^([^\s\xc2\xa0]*)[\s\xc2\xa0]*123[,.]00[\s\xc2\xa0]*([^\s\xc2\xa0]*)$/', $pattern, $matches);
if (!empty($matches[1]))
{
if (!empty($matches[1])) {
self::$patterns[$locale] = $matches[1].' %widget%';
}
else if (!empty($matches[2]))
{
} else if (!empty($matches[2])) {
self::$patterns[$locale] = '%widget% '.$matches[2];
}
else
{
} else {
self::$patterns[$locale] = '%widget%';
}
}

View File

@ -43,8 +43,7 @@ class PropertyPath
*/
public function __construct($propertyPath)
{
if (empty($propertyPath))
{
if (empty($propertyPath)) {
throw new InvalidPropertyPathException('The property path must not be empty');
}
@ -55,15 +54,11 @@ class PropertyPath
// first element is evaluated differently - no leading dot for properties
$pattern = '/^((\w+)|\[(\w+)\])(.*)/';
while (preg_match($pattern, $remaining, $matches))
{
if (!empty($matches[2]))
{
while (preg_match($pattern, $remaining, $matches)) {
if (!empty($matches[2])) {
$this->elements[] = $matches[2];
$this->isProperty[] = true;
}
else
{
} else {
$this->elements[] = $matches[3];
$this->isProperty[] = false;
}
@ -73,8 +68,7 @@ class PropertyPath
$pattern = '/^(\.(\w+)|\[(\w+)\])(.*)/';
}
if (!empty($remaining))
{
if (!empty($remaining)) {
throw new InvalidPropertyPathException(sprintf(
'Could not parse property path "%s". Unexpected token "%s" at position %d',
$propertyPath,
@ -144,8 +138,7 @@ class PropertyPath
*/
public function next()
{
if (!$this->hasNext())
{
if (!$this->hasNext()) {
throw new \OutOfBoundsException('There is no next element in the path');
}

View File

@ -50,12 +50,10 @@ abstract class Renderer extends Configurable implements RendererInterface
{
$html = '';
if ($field->hasErrors())
{
if ($field->hasErrors()) {
$html .= "<ul>\n";
foreach ($field->getErrors() as $error)
{
foreach ($field->getErrors() as $error) {
$html .= "<li>" . $error . "</li>\n";
}

View File

@ -27,15 +27,13 @@ class TableRenderer extends Renderer
{
$html = "<table>\n";
foreach ($group as $field)
{
foreach ($group as $field) {
$label = self::humanize($field->getKey());
$html .= "<tr>\n";
$html .= "<td><label for=\"{$field->getId()}\">$label</label></td>\n";
$html .= "<td>\n";
if ($field->hasErrors())
{
if ($field->hasErrors()) {
$html .= $field->renderErrors()."\n";
}
$html .= $field->render()."\n";

View File

@ -78,8 +78,7 @@ class RepeatedField extends FieldGroup
*/
public function getData()
{
if ($this->isBound() && $this->isFirstEqualToSecond())
{
if ($this->isBound() && $this->isFirstEqualToSecond()) {
return $this->get('first')->getData();
}

View File

@ -45,18 +45,14 @@ class TimeField extends FieldGroup
$this->addOption('user_timezone', 'UTC');
$this->addOption('with_seconds', false);
if ($this->getOption('widget') == self::INPUT)
{
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'))
{
if ($this->getOption('with_seconds')) {
$this->add(new TextField('second', array('max_length' => 2)));
}
}
else
{
} else {
$this->add(new ChoiceField('hour', array(
'choices' => $this->generatePaddedChoices($this->getOption('hours'), 2),
)));
@ -64,8 +60,7 @@ class TimeField extends FieldGroup
'choices' => $this->generatePaddedChoices($this->getOption('minutes'), 2),
)));
if ($this->getOption('with_seconds'))
{
if ($this->getOption('with_seconds')) {
$this->add(new ChoiceField('second', array(
'choices' => $this->generatePaddedChoices($this->getOption('seconds'), 2),
)));
@ -74,23 +69,18 @@ class TimeField extends FieldGroup
$transformers = array();
if ($this->getOption('type') == self::STRING)
{
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)
{
} 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)
{
} 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'),
@ -114,8 +104,7 @@ class TimeField extends FieldGroup
*/
public function render(array $attributes = array())
{
if ($this->getOption('widget') == self::INPUT)
{
if ($this->getOption('widget') == self::INPUT) {
$attributes = array_merge(array(
'size' => '1',
), $attributes);
@ -124,8 +113,7 @@ class TimeField extends FieldGroup
$html = $this->get('hour')->render($attributes);
$html .= ':' . $this->get('minute')->render($attributes);
if ($this->getOption('with_seconds'))
{
if ($this->getOption('with_seconds')) {
$html .= ':' . $this->get('second')->render($attributes);
}
@ -147,8 +135,7 @@ class TimeField extends FieldGroup
{
$choices = array();
foreach ($values as $value)
{
foreach ($values as $value) {
$choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT);
}

View File

@ -29,8 +29,7 @@ class TimezoneField extends ChoiceField
{
$data = parent::getDisplayedData();
if ($data == null && $this->isRequired())
{
if ($data == null && $this->isRequired()) {
$data = date_default_timezone_get();
}
@ -49,30 +48,22 @@ class TimezoneField extends ChoiceField
*/
protected static function getTimezoneChoices()
{
if (count(self::$timezones) == 0)
{
foreach (\DateTimeZone::listIdentifiers() as $timezone)
{
if (count(self::$timezones) == 0) {
foreach (\DateTimeZone::listIdentifiers() as $timezone) {
$parts = explode('/', $timezone);
if (count($parts) > 2)
{
if (count($parts) > 2) {
$region = $parts[0];
$name = $parts[1].' - '.$parts[2];
}
else if (count($parts) > 1)
{
} else if (count($parts) > 1) {
$region = $parts[0];
$name = $parts[1];
}
else
{
} else {
$region = 'Other';
$name = $parts[0];
}
if (!isset(self::$timezones[$region]))
{
if (!isset(self::$timezones[$region])) {
self::$timezones[$region] = array();
}

View File

@ -42,10 +42,8 @@ abstract class ToggleField extends InputField
'checked' => ((string)$this->getDisplayedData() !== '' && $this->getDisplayedData() !== 0),
), $attributes));
if ($label = $this->getOption('label'))
{
if ($this->getOption('translate_label'))
{
if ($label = $this->getOption('label')) {
if ($this->getOption('translate_label')) {
$label = $this->translate($label);
}

View File

@ -26,8 +26,7 @@ abstract class BaseDateTimeTransformer extends BaseValueTransformer
*/
protected function getIntlFormatConstant($format)
{
switch ($format)
{
switch ($format) {
case self::FULL:
return \IntlDateFormatter::FULL;
case self::LONG:

View File

@ -18,8 +18,7 @@ class BooleanToStringTransformer extends BaseValueTransformer
*/
public function transform($value)
{
if (!is_bool($value))
{
if (!is_bool($value)) {
throw new \InvalidArgumentException(sprintf('Expected argument of type boolean but got %s.', gettype($value)));
}
@ -34,8 +33,7 @@ class BooleanToStringTransformer extends BaseValueTransformer
*/
public function reverseTransform($value)
{
if (!is_string($value))
{
if (!is_string($value)) {
throw new \InvalidArgumentException(sprintf('Expected argument of type string but got %s.', gettype($value)));
}

View File

@ -40,16 +40,14 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
*/
public function transform($dateTime)
{
if (!$dateTime instanceof \DateTime)
{
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)
{
if ($inputTimezone != $outputTimezone) {
$dateTime->setTimezone(new \DateTimeZone($outputTimezone));
}
@ -62,10 +60,8 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
'second' => $dateTime->format('s'),
), array_flip($this->getOption('fields')));
if (!$this->getOption('pad'))
{
foreach ($result as &$entry)
{
if (!$this->getOption('pad')) {
foreach ($result as &$entry) {
$entry = (int)$entry;
}
}
@ -84,8 +80,7 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
$inputTimezone = $this->getOption('input_timezone');
$outputTimezone = $this->getOption('output_timezone');
if (!is_array($value))
{
if (!is_array($value)) {
throw new \InvalidArgumentException(sprintf('Expected argument of type array, %s given', gettype($value)));
}
@ -100,8 +95,7 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer
$outputTimezone
));
if ($inputTimezone != $outputTimezone)
{
if ($inputTimezone != $outputTimezone) {
$dateTime->setTimezone(new \DateTimeZone($inputTimezone));
}

View File

@ -31,13 +31,11 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
$this->addOption('input_timezone', 'UTC');
$this->addOption('output_timezone', 'UTC');
if (!in_array($this->getOption('date_format'), self::$formats, true))
{
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))
{
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')));
}
}
@ -50,23 +48,20 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
*/
public function transform($dateTime)
{
if (!$dateTime instanceof \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')
{
if ($inputTimezone != 'UTC') {
$dateTime->setTimezone(new \DateTimeZone('UTC'));
}
$value = $this->getIntlDateFormatter()->format((int)$dateTime->format('U'));
if (intl_get_error_code() != 0)
{
if (intl_get_error_code() != 0) {
throw new TransformationFailedException(intl_get_error_message());
}
@ -83,23 +78,20 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
{
$inputTimezone = $this->getOption('input_timezone');
if (!is_string($value))
{
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)
{
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')
{
if ($inputTimezone != 'UTC') {
$dateTime->setTimezone(new \DateTimeZone($inputTimezone));
}

View File

@ -32,8 +32,7 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransform
*/
public function transform($value)
{
if (!is_numeric($value))
{
if (!is_numeric($value)) {
throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value)));
}

View File

@ -32,16 +32,14 @@ class NumberToLocalizedStringTransformer extends BaseValueTransformer
*/
public function transform($value)
{
if (!is_numeric($value))
{
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()))
{
if (intl_is_failure($formatter->getErrorCode())) {
throw new TransformationFailedException($formatter->getErrorMessage());
}
@ -55,16 +53,14 @@ class NumberToLocalizedStringTransformer extends BaseValueTransformer
*/
public function reverseTransform($value)
{
if (!is_string($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()))
{
if (intl_is_failure($formatter->getErrorCode())) {
throw new TransformationFailedException($formatter->getErrorMessage());
}
@ -80,8 +76,7 @@ class NumberToLocalizedStringTransformer extends BaseValueTransformer
{
$formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL);
if ($this->getOption('precision') !== null)
{
if ($this->getOption('precision') !== null) {
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->getOption('precision'));
}

View File

@ -28,8 +28,7 @@ class PercentToLocalizedStringTransformer extends BaseValueTransformer
$this->addOption('type', self::FRACTIONAL);
$this->addOption('precision', 0);
if (!in_array($this->getOption('type'), self::$types, true))
{
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)));
}
@ -44,21 +43,18 @@ class PercentToLocalizedStringTransformer extends BaseValueTransformer
*/
public function transform($value)
{
if (!is_numeric($value))
{
if (!is_numeric($value)) {
throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value)));
}
if (self::FRACTIONAL == $this->getOption('type'))
{
if (self::FRACTIONAL == $this->getOption('type')) {
$value *= 100;
}
$formatter = $this->getNumberFormatter();
$value = $formatter->format($value);
if (intl_is_failure($formatter->getErrorCode()))
{
if (intl_is_failure($formatter->getErrorCode())) {
throw new TransformationFailedException($formatter->getErrorMessage());
}
@ -74,8 +70,7 @@ class PercentToLocalizedStringTransformer extends BaseValueTransformer
*/
public function reverseTransform($value)
{
if (!is_string($value))
{
if (!is_string($value)) {
throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value)));
}
@ -83,13 +78,11 @@ class PercentToLocalizedStringTransformer extends BaseValueTransformer
// replace normal spaces so that the formatter can read them
$value = $formatter->parse(str_replace(' ', ' ', $value));
if (intl_is_failure($formatter->getErrorCode()))
{
if (intl_is_failure($formatter->getErrorCode())) {
throw new TransformationFailedException($formatter->getErrorMessage());
}
if (self::FRACTIONAL == $this->getOption('type'))
{
if (self::FRACTIONAL == $this->getOption('type')) {
$value /= 100;
}

View File

@ -33,19 +33,15 @@ class StringToDateTimeTransformer extends BaseValueTransformer
$inputTimezone = $this->getOption('input_timezone');
$outputTimezone = $this->getOption('output_timezone');
try
{
try {
$dateTime = new \DateTime("$value $inputTimezone");
if ($inputTimezone != $outputTimezone)
{
if ($inputTimezone != $outputTimezone) {
$dateTime->setTimeZone(new \DateTimeZone($outputTimezone));
}
return $dateTime;
}
catch (\Exception $e)
{
} catch (\Exception $e) {
throw new \InvalidArgumentException('Expected a valid date string. ' . $e->getMessage(), 0, $e);
}
}
@ -59,8 +55,7 @@ class StringToDateTimeTransformer extends BaseValueTransformer
*/
public function reverseTransform($value)
{
if (!$value instanceof \DateTime)
{
if (!$value instanceof \DateTime) {
throw new \InvalidArgumentException('Expected value of type \DateTime');
}

View File

@ -32,19 +32,15 @@ class TimestampToDateTimeTransformer extends BaseValueTransformer
$inputTimezone = $this->getOption('input_timezone');
$outputTimezone = $this->getOption('output_timezone');
try
{
try {
$dateTime = new \DateTime("@$value $inputTimezone");
if ($inputTimezone != $outputTimezone)
{
if ($inputTimezone != $outputTimezone) {
$dateTime->setTimezone(new \DateTimeZone($outputTimezone));
}
return $dateTime;
}
catch (\Exception $e)
{
} catch (\Exception $e) {
throw new \InvalidArgumentException('Expected a valid timestamp. ' . $e->getMessage(), 0, $e);
}
}
@ -57,8 +53,7 @@ class TimestampToDateTimeTransformer extends BaseValueTransformer
*/
public function reverseTransform($value)
{
if (!$value instanceof \DateTime)
{
if (!$value instanceof \DateTime) {
throw new \InvalidArgumentException('Expected value of type \DateTime');
}

View File

@ -38,8 +38,7 @@ class ValueTransformerChain implements ValueTransformerInterface
*/
public function transform($value)
{
foreach ($this->transformers as $transformer)
{
foreach ($this->transformers as $transformer) {
$value = $transformer->transform($value);
}
@ -60,8 +59,7 @@ class ValueTransformerChain implements ValueTransformerInterface
*/
public function reverseTransform($value)
{
for ($i = count($this->transformers) - 1; $i >= 0; --$i)
{
for ($i = count($this->transformers) - 1; $i >= 0; --$i) {
$value = $this->transformers[$i]->reverseTransform($value);
}
@ -73,8 +71,7 @@ class ValueTransformerChain implements ValueTransformerInterface
*/
public function setLocale($locale)
{
foreach ($this->transformers as $transformer)
{
foreach ($this->transformers as $transformer) {
$transformer->setLocale($locale);
}
}

View File

@ -54,58 +54,44 @@ class Constraint
$invalidOptions = array();
$missingOptions = array_flip((array)$this->requiredOptions());
if (is_array($options) && count($options) == 1 && isset($options['value']))
{
if (is_array($options) && count($options) == 1 && isset($options['value'])) {
$options = $options['value'];
}
if (is_array($options) && count($options) > 0 && is_string(key($options)))
{
foreach ($options as $option => $value)
{
if (property_exists($this, $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
{
} else {
$invalidOptions[] = $option;
}
}
}
else if ($options)
{
} else if ($options) {
$option = $this->defaultOption();
if (is_null($option))
{
if (is_null($option)) {
throw new ConstraintDefinitionException(
sprintf('No default option is configured for constraint %s', get_class($this))
);
}
if (property_exists($this, $option))
{
if (property_exists($this, $option)) {
$this->$option = $options;
unset($missingOptions[$option]);
}
else
{
} else {
$invalidOptions[] = $option;
}
}
if (count($invalidOptions) > 0)
{
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)
{
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)
@ -130,8 +116,7 @@ class Constraint
*/
public function addImplicitGroupName($group)
{
if (in_array(Constraint::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups))
{
if (in_array(Constraint::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups)) {
$this->groups[] = $group;
}
}

View File

@ -13,8 +13,7 @@ class ConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
{
$className = $constraint->validatedBy();
if (!isset($this->validators[$className]))
{
if (!isset($this->validators[$className])) {
$this->validators[$className] = new $className();
}

View File

@ -10,8 +10,7 @@ class ConstraintViolationList implements \IteratorAggregate, \Countable
{
$string = '';
foreach ($this->violations as $violation)
{
foreach ($this->violations as $violation) {
$param = $violation->getMessageParameters();
$message = str_replace(array_keys($param), $param, $violation->getMessageTemplate());
$string .= <<<EOF
@ -31,8 +30,7 @@ EOF;
public function addAll(ConstraintViolationList $violations)
{
foreach ($violations->violations as $violation)
{
foreach ($violations->violations as $violation) {
$this->violations[] = $violation;
}
}

View File

@ -10,13 +10,11 @@ class AllValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_array($value) && !$value instanceof \Traversable)
{
if (!is_array($value) && !$value instanceof \Traversable) {
throw new UnexpectedTypeException($value, 'array or Traversable');
}
@ -28,10 +26,8 @@ class AllValidator extends ConstraintValidator
// array instead of wrapped inside
$constraints = is_array($constraint->constraints) ? $constraint->constraints : array($constraint->constraints);
foreach ($value as $key => $element)
{
foreach ($constraints as $constr)
{
foreach ($value as $key => $element) {
foreach ($constraints as $constr) {
$walker->walkConstraint($constr, $element, $group, $propertyPath.'['.$key.']');
}
}

View File

@ -9,13 +9,11 @@ class AssertFalseValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if ($value)
{
if ($value) {
$this->setMessage($constraint->message);
return false;

View File

@ -9,13 +9,11 @@ class AssertTrueValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!$value)
{
if (!$value) {
$this->setMessage($constraint->message);
return false;

View File

@ -9,20 +9,16 @@ class AssertTypeValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
$type = $constraint->type == 'boolean' ? 'bool' : $constraint->type;
$function = 'is_' . $type;
if (function_exists($function) && call_user_func($function, $value))
{
if (function_exists($function) && call_user_func($function, $value)) {
return true;
}
else if ($value instanceof $constraint->type)
{
} else if ($value instanceof $constraint->type) {
return true;
}

View File

@ -9,8 +9,7 @@ class BlankValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value !== '' && $value !== null)
{
if ($value !== '' && $value !== null) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -26,47 +26,33 @@ class ChoiceValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if (!$constraint->choices && !$constraint->callback)
{
if (!$constraint->choices && !$constraint->callback) {
throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice');
}
if ($value === null)
{
if ($value === null) {
return true;
}
if ($constraint->multiple && !is_array($value))
{
if ($constraint->multiple && !is_array($value)) {
throw new UnexpectedTypeException($value, 'array');
}
if ($constraint->callback)
{
if (is_callable(array($this->context->getCurrentClass(), $constraint->callback)))
{
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))
{
} else if (is_callable($constraint->callback)) {
$choices = call_user_func($constraint->callback);
}
else
{
} else {
throw new ConstraintDefinitionException('The Choice constraint expects a valid callback');
}
}
else
{
} else {
$choices = $constraint->choices;
}
if ($constraint->multiple)
{
foreach ($value as $_value)
{
if (!in_array($_value, $choices, true))
{
if ($constraint->multiple) {
foreach ($value as $_value) {
if (!in_array($_value, $choices, true)) {
$this->setMessage($constraint->message, array('value' => $_value));
return false;
@ -75,22 +61,18 @@ class ChoiceValidator extends ConstraintValidator
$count = count($value);
if ($constraint->min !== null && $count < $constraint->min)
{
if ($constraint->min !== null && $count < $constraint->min) {
$this->setMessage($constraint->minMessage, array('limit' => $constraint->min));
return false;
}
if ($constraint->max !== null && $count > $constraint->max)
{
if ($constraint->max !== null && $count > $constraint->max) {
$this->setMessage($constraint->maxMessage, array('limit' => $constraint->max));
return false;
}
}
elseif (!in_array($value, $choices, true))
{
} elseif (!in_array($value, $choices, true)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -11,13 +11,11 @@ class CollectionValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_array($value) && !($value instanceof \Traversable && $value instanceof \ArrayAccess))
{
if (!is_array($value) && !($value instanceof \Traversable && $value instanceof \ArrayAccess)) {
throw new UnexpectedTypeException($value, 'array or Traversable and ArrayAccess');
}
@ -28,34 +26,27 @@ class CollectionValidator extends ConstraintValidator
$missingFields = array();
$extraFields = array();
foreach ($value as $field => $fieldValue)
{
foreach ($value as $field => $fieldValue) {
$extraFields[$field] = $fieldValue;
}
foreach ($constraint->fields as $field => $constraints)
{
if (array_key_exists($field, $value))
{
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)
{
foreach ($constraints as $constr) {
$walker->walkConstraint($constr, $value[$field], $group, $propertyPath.'['.$field.']');
}
unset($extraFields[$field]);
}
else
{
} else {
$missingFields[] = $field;
}
}
if (count($extraFields) > 0 && !$constraint->allowExtraFields)
{
if (count($extraFields) > 0 && !$constraint->allowExtraFields) {
$this->setMessage($constraint->extraFieldsMessage, array(
'fields' => '"'.implode('", "', array_keys($extraFields)).'"'
));
@ -63,8 +54,7 @@ class CollectionValidator extends ConstraintValidator
return false;
}
if (count($missingFields) > 0 && !$constraint->allowMissingFields)
{
if (count($missingFields) > 0 && !$constraint->allowMissingFields) {
$this->setMessage($constraint->missingFieldsMessage, array(
'fields' => '"'.implode('", "', $missingFields).'"'
));

View File

@ -12,20 +12,17 @@ class DateTimeValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
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))
{
if (!preg_match(self::PATTERN, $value, $matches)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -12,20 +12,17 @@ class DateValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
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))
{
if (!preg_match(self::PATTERN, $value, $matches)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -12,31 +12,26 @@ class EmailValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
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))
{
if (!preg_match(self::PATTERN, $value)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;
}
if ($constraint->checkMX)
{
if ($constraint->checkMX) {
$host = substr($value, strpos($value, '@'));
if (!$this->checkMX($host))
{
if (!$this->checkMX($host)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;
@ -63,23 +58,18 @@ class EmailValidator extends ConstraintValidator
@exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output);
if (empty($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))
{
foreach ($output as $line) {
if (preg_match('/^'.$host.'/', $line)) {
return true;
}
}
return false;
}
else if (function_exists('checkdnsrr'))
{
} else if (function_exists('checkdnsrr')) {
return checkdnsrr($host, 'MX');
}

View File

@ -12,59 +12,46 @@ class FileValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !$value instanceof File && !(is_object($value) && method_exists($value, '__toString()')))
{
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))
{
if (!file_exists($path)) {
$this->setMessage($constraint->notFoundMessage, array('file' => $path));
return false;
}
if (!is_readable($path))
{
if (!is_readable($path)) {
$this->setMessage($constraint->notReadableMessage, array('file' => $path));
return false;
}
if ($constraint->maxSize)
{
if (ctype_digit((string)$constraint->maxSize))
{
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))
{
} 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))
{
} else if (preg_match('/^(\d)M$/', $constraint->maxSize, $matches)) {
$size = round(filesize($path) / 1000000, 2);
$limit = $matches[1];
$suffix = ' MB';
}
else
{
} else {
throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize));
}
if ($size > $limit)
{
if ($size > $limit) {
$this->setMessage($constraint->maxSizeMessage, array(
'size' => $size . $suffix,
'limit' => $limit . $suffix,
@ -75,15 +62,12 @@ class FileValidator extends ConstraintValidator
}
}
if ($constraint->mimeTypes)
{
if (!$value instanceof File)
{
if ($constraint->mimeTypes) {
if (!$value instanceof File) {
throw new ConstraintValidationException();
}
if (!in_array($value->getMimeType(), (array)$constraint->mimeTypes))
{
if (!in_array($value->getMimeType(), (array)$constraint->mimeTypes)) {
$this->setMessage($constraint->mimeTypesMessage, array(
'type' => '"'.$value->getMimeType().'"',
'types' => '"'.implode('", "', (array)$constraint->mimeTypes).'"',

View File

@ -10,13 +10,11 @@ class MaxLengthValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
throw new UnexpectedTypeException($value, 'string');
}
@ -24,8 +22,7 @@ class MaxLengthValidator extends ConstraintValidator
$length = function_exists('mb_strlen') ? mb_strlen($value, $constraint->charset) : strlen($value);
if ($length > $constraint->limit)
{
if ($length > $constraint->limit) {
$this->setMessage($constraint->message, array(
'value' => $value,
'limit' => $constraint->limit,

View File

@ -10,18 +10,15 @@ class MaxValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_numeric($value))
{
if (!is_numeric($value)) {
throw new UnexpectedTypeException($value, 'numeric');
}
if ($value > $constraint->limit)
{
if ($value > $constraint->limit) {
$this->setMessage($constraint->message, array(
'value' => $value,
'limit' => $constraint->limit,

View File

@ -10,13 +10,11 @@ class MinLengthValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
throw new UnexpectedTypeException($value, 'string');
}
@ -24,8 +22,7 @@ class MinLengthValidator extends ConstraintValidator
$length = function_exists('mb_strlen') ? mb_strlen($value, $constraint->charset) : strlen($value);
if ($length < $constraint->limit)
{
if ($length < $constraint->limit) {
$this->setMessage($constraint->message, array(
'value' => $value,
'limit' => $constraint->limit,

View File

@ -10,18 +10,15 @@ class MinValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_numeric($value))
{
if (!is_numeric($value)) {
throw new UnexpectedTypeException($value, 'numeric');
}
if ($value < $constraint->limit)
{
if ($value < $constraint->limit) {
$this->setMessage($constraint->message, array(
'value' => $value,
'limit' => $constraint->limit,

View File

@ -9,8 +9,7 @@ class NotBlankValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === '' || $value === null)
{
if ($value === '' || $value === null) {
$this->setMessage($constraint->message);
return false;

View File

@ -9,8 +9,7 @@ class NotNullValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if (is_null($value))
{
if (is_null($value)) {
$this->setMessage($constraint->message);
return false;

View File

@ -9,8 +9,7 @@ class NullValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if (!is_null($value))
{
if (!is_null($value)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -10,13 +10,11 @@ class RegexValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
throw new UnexpectedTypeException($value, 'string');
}

View File

@ -12,20 +12,17 @@ class TimeValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
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))
{
if (!preg_match(self::PATTERN, $value)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -21,13 +21,11 @@ class UrlValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()')))
{
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
throw new UnexpectedTypeException($value, 'string');
}
@ -35,8 +33,7 @@ class UrlValidator extends ConstraintValidator
$pattern = sprintf(self::PATTERN, implode('|', $constraint->protocols));
if (!preg_match($pattern, $value))
{
if (!preg_match($pattern, $value)) {
$this->setMessage($constraint->message, array('value' => $value));
return false;

View File

@ -11,8 +11,7 @@ class ValidValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value === null)
{
if ($value === null) {
return true;
}
@ -21,25 +20,17 @@ class ValidValidator extends ConstraintValidator
$propertyPath = $this->context->getPropertyPath();
$factory = $this->context->getClassMetadataFactory();
if (is_array($value))
{
foreach ($value as $key => $element)
{
if (is_array($value)) {
foreach ($value as $key => $element) {
$walker->walkConstraint($constraint, $element, $group, $propertyPath.'['.$key.']');
}
}
else if (!is_object($value))
{
} else if (!is_object($value)) {
throw new UnexpectedTypeException($value, 'object or array');
}
else if ($constraint->class && !$value instanceof $constraint->class)
{
} else if ($constraint->class && !$value instanceof $constraint->class) {
$this->setMessage($constraint->message, array('class' => $constraint->class));
return false;
}
else
{
} else {
$metadata = $factory->getClassMetadata(get_class($value));
$walker->walkClass($metadata, $value, $group, $propertyPath);
}

View File

@ -32,8 +32,7 @@ class DependencyInjectionValidatorFactory implements ConstraintValidatorFactoryI
$className = $constraint->validatedBy();
$id = $this->getServiceIdFromClass($className);
if (!$this->container->hasService($id))
{
if (!$this->container->hasService($id)) {
$this->container->setService($id, new $className());
}

View File

@ -47,15 +47,13 @@ class DependencyInjectionValidatorFactory implements ConstraintValidatorFactoryI
$className = $constraint->validatedBy();
$id = $this->getServiceIdFromClass($className);
if (!$this->container->hasService($id))
{
if (!$this->container->hasService($id)) {
$this->container->setService($id, new $className());
}
$validator = $this->container->getService($id);
if (!$validator instanceof ConstraintValidatorInterface)
{
if (!$validator instanceof ConstraintValidatorInterface) {
throw new \LogicException('Service "' . $id . '" is not instance of ConstraintValidatorInterface');
}

View File

@ -34,15 +34,12 @@ class GraphWalker
{
$this->context->setCurrentClass($metadata->getClassName());
foreach ($metadata->findConstraints($group) as $constraint)
{
foreach ($metadata->findConstraints($group) as $constraint) {
$this->walkConstraint($constraint, $object, $group, $propertyPath);
}
if ($object !== null)
{
foreach ($metadata->getConstrainedProperties() as $property)
{
if ($object !== null) {
foreach ($metadata->getConstrainedProperties() as $property) {
$localPropertyPath = empty($propertyPath) ? $property : $propertyPath.'.'.$property;
$this->walkProperty($metadata, $property, $object, $group, $localPropertyPath);
@ -52,16 +49,14 @@ class GraphWalker
public function walkProperty(ClassMetadata $metadata, $property, $object, $group, $propertyPath)
{
foreach ($metadata->getMemberMetadatas($property) as $member)
{
foreach ($metadata->getMemberMetadatas($property) as $member) {
$this->walkMember($member, $member->getValue($object), $group, $propertyPath);
}
}
public function walkPropertyValue(ClassMetadata $metadata, $property, $value, $group, $propertyPath)
{
foreach ($metadata->getMemberMetadatas($property) as $member)
{
foreach ($metadata->getMemberMetadatas($property) as $member) {
$this->walkMember($member, $value, $group, $propertyPath);
}
}
@ -70,8 +65,7 @@ class GraphWalker
{
$this->context->setCurrentProperty($metadata->getPropertyName());
foreach ($metadata->findConstraints($group) as $constraint)
{
foreach ($metadata->findConstraints($group) as $constraint) {
$this->walkConstraint($constraint, $value, $group, $propertyPath);
}
}
@ -85,8 +79,7 @@ class GraphWalker
$validator->initialize($this->context);
if (!$validator->isValid($value, $constraint))
{
if (!$validator->isValid($value, $constraint)) {
$this->context->addViolation(
$validator->getMessageTemplate(),
$validator->getMessageParameters(),

View File

@ -16,13 +16,11 @@ class GroupChain
public function addGroupSequence(array $groups)
{
if (count($groups) == 0)
{
if (count($groups) == 0) {
throw new \InvalidArgumentException('A group sequence must contain at least one group');
}
if (!in_array($groups, $this->groupSequences, true))
{
if (!in_array($groups, $this->groupSequences, true)) {
$this->groupSequences[] = $groups;
}
}

View File

@ -65,8 +65,7 @@ class ClassMetadata extends ElementMetadata
*/
public function addPropertyConstraint($property, Constraint $constraint)
{
if (!isset($this->properties[$property]))
{
if (!isset($this->properties[$property])) {
$this->properties[$property] = new PropertyMetadata($this->getClassName(), $property);
$this->addMemberMetadata($this->properties[$property]);
@ -91,8 +90,7 @@ class ClassMetadata extends ElementMetadata
*/
public function addGetterConstraint($property, Constraint $constraint)
{
if (!isset($this->getters[$property]))
{
if (!isset($this->getters[$property])) {
$this->getters[$property] = new GetterMetadata($this->getClassName(), $property);
$this->addMemberMetadata($this->getters[$property]);
@ -112,34 +110,26 @@ class ClassMetadata extends ElementMetadata
*/
public function mergeConstraints(ClassMetadata $source)
{
foreach ($source->getConstraints() as $constraint)
{
foreach ($source->getConstraints() as $constraint) {
$this->addConstraint(clone $constraint);
}
foreach ($source->getConstrainedProperties() as $property)
{
foreach ($source->getMemberMetadatas($property) as $member)
{
foreach ($source->getConstrainedProperties() as $property) {
foreach ($source->getMemberMetadatas($property) as $member) {
$member = clone $member;
foreach ($member->getConstraints() as $constraint)
{
foreach ($member->getConstraints() as $constraint) {
$constraint->addImplicitGroupName($this->getShortClassName());
}
$this->addMemberMetadata($member);
if (!$member->isPrivate())
{
if (!$member->isPrivate()) {
$property = $member->getPropertyName();
if ($member instanceof PropertyMetadata && !isset($this->properties[$property]))
{
if ($member instanceof PropertyMetadata && !isset($this->properties[$property])) {
$this->properties[$property] = $member;
}
else if ($member instanceof GetterMetadata && !isset($this->getters[$property]))
{
} else if ($member instanceof GetterMetadata && !isset($this->getters[$property])) {
$this->getters[$property] = $member;
}
}
@ -156,8 +146,7 @@ class ClassMetadata extends ElementMetadata
{
$property = $metadata->getPropertyName();
if (!isset($this->members[$property]))
{
if (!isset($this->members[$property])) {
$this->members[$property] = array();
}
@ -223,8 +212,7 @@ class ClassMetadata extends ElementMetadata
*/
public function getReflectionClass()
{
if (!$this->reflClass)
{
if (!$this->reflClass) {
$this->reflClass = new \ReflectionClass($this->getClassName());
}

View File

@ -19,19 +19,16 @@ class ClassMetadataFactory implements ClassMetadataFactoryInterface
{
$class = ltrim($class, '\\');
if (!isset($this->loadedClasses[$class]))
{
if (!isset($this->loadedClasses[$class])) {
$metadata = new ClassMetadata($class);
// Include constraints from the parent class
if ($parent = $metadata->getReflectionClass()->getParentClass())
{
if ($parent = $metadata->getReflectionClass()->getParentClass()) {
$metadata->mergeConstraints($this->getClassMetadata($parent->getName()));
}
// Include constraints from all implemented interfaces
foreach ($metadata->getReflectionClass()->getInterfaces() as $interface)
{
foreach ($metadata->getReflectionClass()->getInterfaces() as $interface) {
$metadata->mergeConstraints($this->getClassMetadata($interface->getName()));
}

View File

@ -20,8 +20,7 @@ class ElementMetadata
$this->constraints = array();
$this->constraintsByGroup = array();
foreach ($constraints as $constraint)
{
foreach ($constraints as $constraint) {
$this->addConstraint(clone $constraint);
}
}
@ -35,10 +34,8 @@ class ElementMetadata
{
$this->constraints[] = $constraint;
foreach ($constraint->groups as $group)
{
if (!isset($this->constraintsByGroup[$group]))
{
foreach ($constraint->groups as $group) {
if (!isset($this->constraintsByGroup[$group])) {
$this->constraintsByGroup[$group] = array();
}

View File

@ -17,16 +17,11 @@ class GetterMetadata extends MemberMetadata
$getMethod = 'get'.ucfirst($property);
$isMethod = 'is'.ucfirst($property);
if (method_exists($class, $getMethod))
{
if (method_exists($class, $getMethod)) {
$method = $getMethod;
}
else if (method_exists($class, $isMethod))
{
} else if (method_exists($class, $isMethod)) {
$method = $isMethod;
}
else
{
} else {
throw new ValidatorException(sprintf('Neither method %s nor %s exists in class %s', $getMethod, $isMethod, $class));
}

View File

@ -26,22 +26,17 @@ class AnnotationLoader implements LoaderInterface
$reflClass = $metadata->getReflectionClass();
$loaded = false;
if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass))
{
foreach ($annot->constraints as $constraint)
{
if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) {
foreach ($annot->constraints as $constraint) {
$metadata->addConstraint($constraint);
}
$loaded = true;
}
foreach ($reflClass->getProperties() as $property)
{
if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass))
{
foreach ($annot->constraints as $constraint)
{
foreach ($reflClass->getProperties() as $property) {
if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) {
foreach ($annot->constraints as $constraint) {
$metadata->addPropertyConstraint($property->getName(), $constraint);
}
@ -49,12 +44,9 @@ class AnnotationLoader implements LoaderInterface
}
}
foreach ($reflClass->getMethods() as $method)
{
if ($annot = $this->reader->getMethodAnnotation($method, $annotClass))
{
foreach ($annot->constraints as $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));

View File

@ -12,13 +12,11 @@ abstract class FileLoader implements LoaderInterface
public function __construct($file)
{
if (!file_exists($file))
{
if (!file_exists($file)) {
throw new MappingException(sprintf('The mapping file %s does not exist', $file));
}
if (!is_readable($file))
{
if (!is_readable($file)) {
throw new MappingException(sprintf('The mapping file %s is not readable', $file));
}

View File

@ -28,10 +28,8 @@ class LoaderChain implements LoaderInterface
*/
public function __construct(array $loaders)
{
foreach ($loaders as $loader)
{
if (!$loader instanceof LoaderInterface)
{
foreach ($loaders as $loader) {
if (!$loader instanceof LoaderInterface) {
throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader)));
}
}
@ -46,8 +44,7 @@ class LoaderChain implements LoaderInterface
{
$success = false;
foreach ($this->loaders as $loader)
{
foreach ($this->loaders as $loader) {
$success = $loader->loadClassMetadata($metadata) || $success;
}

View File

@ -21,12 +21,10 @@ class StaticMethodLoader implements LoaderInterface
{
$reflClass = $metadata->getReflectionClass();
if ($reflClass->hasMethod($this->methodName))
{
if ($reflClass->hasMethod($this->methodName)) {
$reflMethod = $reflClass->getMethod($this->methodName);
if (!$reflMethod->isStatic())
{
if (!$reflMethod->isStatic()) {
throw new MappingException(sprintf('The method %s::%s should be static', $reflClass->getName(), $this->methodName));
}

View File

@ -18,38 +18,30 @@ class XmlFileLoader extends FileLoader
*/
public function loadClassMetadata(ClassMetadata $metadata)
{
if (is_null($this->classes))
{
if (is_null($this->classes)) {
$this->classes = array();
$xml = $this->parseFile($this->file);
foreach ($xml->class as $class)
{
foreach ($xml->class as $class) {
$this->classes[(string)$class['name']] = $class;
}
}
if (isset($this->classes[$metadata->getClassName()]))
{
if (isset($this->classes[$metadata->getClassName()])) {
$xml = $this->classes[$metadata->getClassName()];
foreach ($this->parseConstraints($xml->constraint) as $constraint)
{
foreach ($this->parseConstraints($xml->constraint) as $constraint) {
$metadata->addConstraint($constraint);
}
foreach ($xml->property as $property)
{
foreach ($this->parseConstraints($property->constraint) as $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)
{
foreach ($xml->getter as $getter) {
foreach ($this->parseConstraints($getter->constraint) as $constraint) {
$metadata->addGetterConstraint((string)$getter['property'], $constraint);
}
}
@ -70,35 +62,22 @@ class XmlFileLoader extends FileLoader
{
$constraints = array();
foreach ($nodes as $node)
{
foreach ($nodes as $node) {
$className = 'Symfony\\Components\\Validator\\Constraints\\'.$node['name'];
if (count($node) > 0)
{
if (count($node->value) > 0)
{
if (count($node) > 0) {
if (count($node->value) > 0) {
$options = $this->parseValues($node->value);
}
else if (count($node->constraint) > 0)
{
} else if (count($node->constraint) > 0) {
$options = $this->parseConstraints($node->constraint);
}
else if (count($node->option) > 0)
{
} else if (count($node->option) > 0) {
$options = $this->parseOptions($node->option);
}
else
{
} else {
$options = array();
}
}
else if (strlen((string)$node) > 0)
{
} else if (strlen((string)$node) > 0) {
$options = trim($node);
}
else
{
} else {
$options = null;
}
@ -118,34 +97,22 @@ class XmlFileLoader extends FileLoader
{
$values = array();
foreach ($nodes as $node)
{
if (count($node) > 0)
{
if (count($node->value) > 0)
{
foreach ($nodes as $node) {
if (count($node) > 0) {
if (count($node->value) > 0) {
$value = $this->parseValues($node->value);
}
else if (count($node->constraint) > 0)
{
} else if (count($node->constraint) > 0) {
$value = $this->parseConstraints($node->constraint);
}
else
{
} else {
$value = array();
}
}
else
{
} else {
$value = trim($node);
}
if (isset($node['key']))
{
if (isset($node['key'])) {
$values[(string)$node['key']] = $value;
}
else
{
} else {
$values[] = $value;
}
}
@ -163,25 +130,16 @@ class XmlFileLoader extends FileLoader
{
$options = array();
foreach ($nodes as $node)
{
if (count($node) > 0)
{
if (count($node->value) > 0)
{
foreach ($nodes as $node) {
if (count($node) > 0) {
if (count($node->value) > 0) {
$value = $this->parseValues($node->value);
}
else if (count($node->constraint) > 0)
{
} else if (count($node->constraint) > 0) {
$value = $this->parseConstraints($node->constraint);
}
else
{
} else {
$value = array();
}
}
else
{
} else {
$value = trim($node);
}
@ -199,12 +157,10 @@ class XmlFileLoader extends FileLoader
{
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
if (!$dom->load($file, LIBXML_COMPACT))
{
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'))
{
if (!$dom->schemaValidate(__DIR__.'/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd')) {
throw new MappingException(implode("\n", $this->getXmlErrors()));
}
$dom->validateOnParse = true;
@ -217,8 +173,7 @@ class XmlFileLoader extends FileLoader
protected function getXmlErrors()
{
$errors = array();
foreach (libxml_get_errors() as $error)
{
foreach (libxml_get_errors() as $error) {
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code,

View File

@ -19,42 +19,32 @@ class YamlFileLoader extends FileLoader
*/
public function loadClassMetadata(ClassMetadata $metadata)
{
if (is_null($this->classes))
{
if (is_null($this->classes)) {
$this->classes = Yaml::load($this->file);
}
// TODO validation
if (isset($this->classes[$metadata->getClassName()]))
{
if (isset($this->classes[$metadata->getClassName()])) {
$yaml = $this->classes[$metadata->getClassName()];
if (isset($yaml['constraints']))
{
foreach ($this->parseNodes($yaml['constraints']) as $constraint)
{
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)
{
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)
{
if (isset($yaml['getters'])) {
foreach ($yaml['getters'] as $getter => $constraints) {
foreach ($this->parseNodes($constraints) as $constraint) {
$metadata->addGetterConstraint($getter, $constraint);
}
}
@ -76,24 +66,18 @@ class YamlFileLoader extends FileLoader
{
$values = array();
foreach ($nodes as $name => $childNodes)
{
if (is_numeric($name) && is_array($childNodes) && count($childNodes) == 1)
{
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))
{
if (is_array($options)) {
$options = $this->parseNodes($options);
}
$values[] = new $className($options);
}
else
{
if (is_array($childNodes))
{
} else {
if (is_array($childNodes)) {
$childNodes = $this->parseNodes($childNodes);
}

View File

@ -100,8 +100,7 @@ abstract class MemberMetadata extends ElementMetadata
*/
public function getReflectionMember()
{
if (!$this->reflMember)
{
if (!$this->reflMember) {
$this->reflMember = $this->newReflectionMember();
}

View File

@ -14,8 +14,7 @@ class PropertyMetadata extends MemberMetadata
*/
public function __construct($class, $name)
{
if (!property_exists($class, $name))
{
if (!property_exists($class, $name)) {
throw new ValidatorException(sprintf('Property %s does not exists in class %s', $name, $class));
}

View File

@ -15,13 +15,11 @@ class XliffMessageInterpolator implements MessageInterpolatorInterface
{
$files = (array)$file;
foreach ($files as $file)
{
foreach ($files as $file) {
$xml = $this->parseFile($file);
$xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
foreach ($xml->xpath('//xliff:trans-unit') as $translation)
{
foreach ($xml->xpath('//xliff:trans-unit') as $translation) {
$this->translations[(string)$translation->source] = (string)$translation->target;
}
}
@ -32,16 +30,14 @@ class XliffMessageInterpolator implements MessageInterpolatorInterface
*/
public function interpolate($text, array $parameters = array())
{
if (isset($this->translations[$text]))
{
if (isset($this->translations[$text])) {
$text = $this->translations[$text];
}
$sources = array();
$targets = array();
foreach ($parameters as $key => $value)
{
foreach ($parameters as $key => $value) {
$sources[] = '%'.$key.'%';
$targets[] = (string)$value;
}
@ -59,12 +55,10 @@ class XliffMessageInterpolator implements MessageInterpolatorInterface
{
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
if (!$dom->load($file, LIBXML_COMPACT))
{
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'))
{
if (!$dom->schemaValidate(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd')) {
throw new \Exception(implode("\n", $this->getXmlErrors()));
}
$dom->validateOnParse = true;
@ -82,8 +76,7 @@ class XliffMessageInterpolator implements MessageInterpolatorInterface
protected function getXmlErrors()
{
$errors = array();
foreach (libxml_get_errors() as $error)
{
foreach (libxml_get_errors() as $error) {
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code,

View File

@ -75,21 +75,17 @@ class Validator implements ValidatorInterface
{
$walker = new GraphWalker($root, $this->metadataFactory, $this->validatorFactory, $this->messageInterpolator);
foreach ($groupChain->getGroups() as $group)
{
foreach ($groupChain->getGroups() as $group) {
$closure($walker, $group);
}
foreach ($groupChain->getGroupSequences() as $sequence)
{
foreach ($groupChain->getGroupSequences() as $sequence) {
$violationCount = count($walker->getViolations());
foreach ($sequence as $group)
{
foreach ($sequence as $group) {
$closure($walker, $group);
if (count($walker->getViolations()) > $violationCount)
{
if (count($walker->getViolations()) > $violationCount) {
break;
}
}
@ -100,19 +96,15 @@ class Validator implements ValidatorInterface
protected function buildSimpleGroupChain($groups)
{
if (is_null($groups))
{
if (is_null($groups)) {
$groups = array(Constraint::DEFAULT_GROUP);
}
else
{
} else {
$groups = (array)$groups;
}
$chain = new GroupChain();
foreach ($groups as $group)
{
foreach ($groups as $group) {
$chain->addGroup($group);
}
@ -121,25 +113,18 @@ class Validator implements ValidatorInterface
protected function buildGroupChain(ClassMetadata $metadata, $groups)
{
if (is_null($groups))
{
if (is_null($groups)) {
$groups = array(Constraint::DEFAULT_GROUP);
}
else
{
} else {
$groups = (array)$groups;
}
$chain = new GroupChain();
foreach ($groups as $group)
{
if ($group == Constraint::DEFAULT_GROUP && $metadata->hasGroupSequence())
{
foreach ($groups as $group) {
if ($group == Constraint::DEFAULT_GROUP && $metadata->hasGroupSequence()) {
$chain->addGroupSequence($metadata->getGroupSequence());
}
else
{
} else {
$chain->addGroup($group);
}
}

View File

@ -12,8 +12,7 @@ class UploadedFileTest extends \PHPUnit_Framework_TestCase
public function testFileUploadsMustBeEnabled()
{
// we can't change this setting without modifying php.ini :(
if (!ini_get('file_uploads'))
{
if (!ini_get('file_uploads')) {
$this->setExpectedException('Symfony\Components\File\Exception\FileException');
new UploadedFile(
@ -29,8 +28,7 @@ class UploadedFileTest extends \PHPUnit_Framework_TestCase
public function testErrorIsOkByDefault()
{
// we can't change this setting without modifying php.ini :(
if (ini_get('file_uploads'))
{
if (ini_get('file_uploads')) {
$file = new UploadedFile(
__DIR__.'/Fixtures/test.gif',
'original.gif',

View File

@ -21,8 +21,7 @@ class DateTimeToLocalizedStringTransformerTest extends DateTimeTestCase
public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE)
{
if ($expected instanceof \DateTime && $actual instanceof \DateTime)
{
if ($expected instanceof \DateTime && $actual instanceof \DateTime) {
$expected = $expected->format('c');
$actual = $actual->format('c');
}

View File

@ -49,8 +49,7 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
$constraint = new Min(4);
foreach ($array as $key => $value)
{
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.']'));
@ -72,8 +71,7 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
// can't test method calls with different arguments
$constraints = array($constraint, $constraint);
foreach ($array as $key => $value)
{
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.']'));

View File

@ -110,8 +110,7 @@ class AssertTypeValidatorTest extends \PHPUnit_Framework_TestCase
protected function createFile()
{
if (!self::$file)
{
if (!self::$file) {
self::$file = fopen(__FILE__, 'r');
}
@ -120,8 +119,7 @@ class AssertTypeValidatorTest extends \PHPUnit_Framework_TestCase
public static function tearDownAfterClass()
{
if (self::$file)
{
if (self::$file) {
fclose(self::$file);
}
}

View File

@ -53,8 +53,7 @@ class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$constraint = new Min(4);
foreach ($array as $key => $value)
{
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.']'));
@ -80,8 +79,7 @@ class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
// can't test method calls with different arguments
$constraints = array($constraint, $constraint);
foreach ($array as $key => $value)
{
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.']'));

View File

@ -33,8 +33,7 @@ class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
*/
public function testValidValues($value, $skip = false)
{
if (!$skip)
{
if (!$skip) {
$constraint = new MaxLength(array('limit' => 5));
$this->assertTrue($this->validator->isValid($value, $constraint));
}
@ -55,8 +54,7 @@ class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
*/
public function testInvalidValues($value, $skip = false)
{
if (!$skip)
{
if (!$skip) {
$constraint = new MaxLength(array('limit' => 5));
$this->assertFalse($this->validator->isValid($value, $constraint));
}

View File

@ -33,8 +33,7 @@ class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase
*/
public function testValidValues($value, $skip = false)
{
if (!$skip)
{
if (!$skip) {
$constraint = new MinLength(array('limit' => 6));
$this->assertTrue($this->validator->isValid($value, $constraint));
}
@ -55,8 +54,7 @@ class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase
*/
public function testInvalidValues($value, $skip = false)
{
if (!$skip)
{
if (!$skip) {
$constraint = new MinLength(array('limit' => 6));
$this->assertFalse($this->validator->isValid($value, $constraint));
}

View File

@ -9,8 +9,7 @@ class ConstraintAValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
if ($value != 'VALID')
{
if ($value != 'VALID') {
$this->setMessage('message', array('param' => 'value'));
return false;
}