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) public function __construct($path)
{ {
if (!is_file($path)) if (!is_file($path)) {
{
throw new FileNotFoundException($path); throw new FileNotFoundException($path);
} }
@ -489,12 +488,9 @@ class File
{ {
$name = $this->getName(); $name = $this->getName();
if (false !== ($pos = strrpos($name, '.'))) if (false !== ($pos = strrpos($name, '.'))) {
{
return substr($name, $pos); return substr($name, $pos);
} } else {
else
{
return ''; return '';
} }
} }
@ -510,12 +506,9 @@ class File
{ {
$type = $this->getMimeType(); $type = $this->getMimeType();
if (isset(self::$defaultExtensions[$type])) if (isset(self::$defaultExtensions[$type])) {
{
return '.' . self::$defaultExtensions[$type]; return '.' . self::$defaultExtensions[$type];
} } else {
else
{
return $this->getExtension(); return $this->getExtension();
} }
} }
@ -563,8 +556,7 @@ class File
*/ */
public function size() 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())); throw new FileException(sprintf('Could not read file size of %s', $this->getPath()));
} }
@ -578,8 +570,7 @@ class File
*/ */
public function move($newPath) 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)); 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) public function guess($path)
{ {
if (!is_file($path)) if (!is_file($path)) {
{
throw new FileNotFoundException($path); throw new FileNotFoundException($path);
} }
if (!is_readable($path)) if (!is_readable($path)) {
{
throw new AccessDeniedException($path); throw new AccessDeniedException($path);
} }
if (!self::isSupported() || !is_readable($path)) if (!self::isSupported() || !is_readable($path)) {
{
return null; return null;
} }
$type = mime_content_type($path); $type = mime_content_type($path);
// remove charset (added as of PHP 5.3) // remove charset (added as of PHP 5.3)
if (false !== $pos = strpos($type, ';')) if (false !== $pos = strpos($type, ';')) {
{
$type = substr($type, 0, $pos); $type = substr($type, 0, $pos);
} }

View File

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

View File

@ -37,31 +37,26 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface
*/ */
public function guess($path) public function guess($path)
{ {
if (!is_file($path)) if (!is_file($path)) {
{
throw new FileNotFoundException($path); throw new FileNotFoundException($path);
} }
if (!is_readable($path)) if (!is_readable($path)) {
{
throw new AccessDeniedException($path); throw new AccessDeniedException($path);
} }
if (!self::isSupported()) if (!self::isSupported()) {
{
return null; return null;
} }
if (!$finfo = new \finfo(FILEINFO_MIME)) if (!$finfo = new \finfo(FILEINFO_MIME)) {
{
return null; return null;
} }
$type = $finfo->file($path); $type = $finfo->file($path);
// remove charset (added as of PHP 5.3) // remove charset (added as of PHP 5.3)
if (false !== $pos = strpos($type, ';')) if (false !== $pos = strpos($type, ';')) {
{
$type = substr($type, 0, $pos); $type = substr($type, 0, $pos);
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -55,14 +55,12 @@ abstract class Configurable
$this->configure(); $this->configure();
// check option names // 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)); 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 // 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)); 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; $this->knownOptions[$name] = true;
if (!array_key_exists($name, $this->options)) if (!array_key_exists($name, $this->options)) {
{
$this->options[$name] = $value; $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)); 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 // only test if the option is set, otherwise an error will be thrown
// anyway // 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)); 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(); $transformers = array();
if ($this->getOption('type') === self::STRING) if ($this->getOption('type') === self::STRING) {
{
$transformers[] = new StringToDateTimeTransformer(array( $transformers[] = new StringToDateTimeTransformer(array(
'input_timezone' => $this->getOption('data_timezone'), 'input_timezone' => $this->getOption('data_timezone'),
'output_timezone' => $this->getOption('data_timezone'), 'output_timezone' => $this->getOption('data_timezone'),
'format' => 'Y-m-d', 'format' => 'Y-m-d',
)); ));
} } else if ($this->getOption('type') === self::TIMESTAMP) {
else if ($this->getOption('type') === self::TIMESTAMP)
{
$transformers[] = new TimestampToDateTimeTransformer(array( $transformers[] = new TimestampToDateTimeTransformer(array(
'output_timezone' => $this->getOption('data_timezone'), 'output_timezone' => $this->getOption('data_timezone'),
'input_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( $transformers[] = new ReversedTransformer(new DateTimeToArrayTransformer(array(
'input_timezone' => $this->getOption('data_timezone'), 'input_timezone' => $this->getOption('data_timezone'),
'output_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( $transformers[] = new DateTimeToLocalizedStringTransformer(array(
'date_format' => $this->getOption('format'), 'date_format' => $this->getOption('format'),
'time_format' => DateTimeToLocalizedStringTransformer::NONE, 'time_format' => DateTimeToLocalizedStringTransformer::NONE,
@ -138,9 +132,7 @@ class DateField extends HybridField
)); ));
$this->setFieldMode(self::FIELD); $this->setFieldMode(self::FIELD);
} } else {
else
{
$transformers[] = new DateTimeToArrayTransformer(array( $transformers[] = new DateTimeToArrayTransformer(array(
'input_timezone' => $this->getOption('data_timezone'), 'input_timezone' => $this->getOption('data_timezone'),
'output_timezone' => $this->getOption('user_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)); $this->setValueTransformer(new ValueTransformerChain($transformers));
} }
} }
@ -180,8 +171,7 @@ class DateField extends HybridField
{ {
$choices = array(); $choices = array();
foreach ($values as $value) foreach ($values as $value) {
{
$choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT); $choices[$value] = str_pad($value, $padLength, '0', STR_PAD_LEFT);
} }
@ -199,20 +189,16 @@ class DateField extends HybridField
{ {
$pattern = $this->formatter->getPattern(); $pattern = $this->formatter->getPattern();
if (preg_match('/M+/', $pattern, $matches)) if (preg_match('/M+/', $pattern, $matches)) {
{
$this->formatter->setPattern($matches[0]); $this->formatter->setPattern($matches[0]);
$choices = array(); $choices = array();
foreach ($months as $month) foreach ($months as $month) {
{
$choices[$month] = $this->formatter->format(gmmktime(0, 0, 0, $month)); $choices[$month] = $this->formatter->format(gmmktime(0, 0, 0, $month));
} }
$this->formatter->setPattern($pattern); $this->formatter->setPattern($pattern);
} } else {
else
{
$choices = $this->generatePaddedChoices($months, 2); $choices = $this->generatePaddedChoices($months, 2);
} }
@ -224,31 +210,25 @@ class DateField extends HybridField
*/ */
public function render(array $attributes = array()) 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( return $this->generator->tag('input', array_merge(array(
'id' => $this->getId(), 'id' => $this->getId(),
'name' => $this->getName(), 'name' => $this->getName(),
'value' => $this->getDisplayedData(), 'value' => $this->getDisplayedData(),
'type' => 'text', 'type' => 'text',
), $attributes)); ), $attributes));
} } else {
else
{
// set order as specified in the pattern // set order as specified in the pattern
if ($this->getOption('pattern')) if ($this->getOption('pattern')) {
{
$pattern = $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) // 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 // 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()); $pattern = preg_replace(array('/y+/', '/M+/', '/d+/'), array('%year%', '%month%', '%day%'), $this->formatter->getPattern());
} }
// default fallback // default fallback
else else {
{
$pattern = '%year%-%month%-%day%'; $pattern = '%year%-%month%-%day%';
} }

View File

@ -74,15 +74,12 @@ class DateTimeField extends FieldGroup
$transformers = array(); $transformers = array();
if ($this->getOption('type') == self::STRING) if ($this->getOption('type') == self::STRING) {
{
$transformers[] = new StringToDateTimeTransformer(array( $transformers[] = new StringToDateTimeTransformer(array(
'input_timezone' => $this->getOption('data_timezone'), 'input_timezone' => $this->getOption('data_timezone'),
'output_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( $transformers[] = new TimestampToDateTimeTransformer(array(
'input_timezone' => $this->getOption('data_timezone'), 'input_timezone' => $this->getOption('data_timezone'),
'output_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() public function isRequired()
{ {
if (is_null($this->parent) || $this->parent->isRequired()) if (is_null($this->parent) || $this->parent->isRequired()) {
{
return $this->required; return $this->required;
} } else {
else
{
return false; return false;
} }
} }
@ -159,12 +156,9 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
public function isDisabled() public function isDisabled()
{ {
if (is_null($this->parent) || !$this->parent->isDisabled()) if (is_null($this->parent) || !$this->parent->isDisabled()) {
{
return $this->getOption('disabled'); return $this->getOption('disabled');
} } else {
else
{
return true; return true;
} }
} }
@ -237,18 +231,14 @@ abstract class Field extends Configurable implements FieldInterface
$this->bound = true; $this->bound = true;
$this->errors = array(); $this->errors = array();
if (is_string($this->transformedData) && $this->getOption('trim')) if (is_string($this->transformedData) && $this->getOption('trim')) {
{
$this->transformedData = trim($this->transformedData); $this->transformedData = trim($this->transformedData);
} }
try try {
{
$this->data = $this->processData($data = $this->reverseTransform($this->transformedData)); $this->data = $this->processData($data = $this->reverseTransform($this->transformedData));
$this->transformedData = $this->transform($this->data); $this->transformedData = $this->transform($this->data);
} } catch (TransformationFailedException $e) {
catch (TransformationFailedException $e)
{
// TODO better text // TODO better text
// TESTME // TESTME
$this->addError('invalid (localized)'); $this->addError('invalid (localized)');
@ -342,8 +332,7 @@ abstract class Field extends Configurable implements FieldInterface
{ {
$this->locale = $locale; $this->locale = $locale;
if ($this->valueTransformer !== null && $this->valueTransformer instanceof Localizable) if ($this->valueTransformer !== null && $this->valueTransformer instanceof Localizable) {
{
$this->valueTransformer->setLocale($locale); $this->valueTransformer->setLocale($locale);
} }
} }
@ -357,8 +346,7 @@ abstract class Field extends Configurable implements FieldInterface
{ {
$this->translator = $translator; $this->translator = $translator;
if ($this->valueTransformer !== null && $this->valueTransformer instanceof Translatable) if ($this->valueTransformer !== null && $this->valueTransformer instanceof Translatable) {
{
$this->valueTransformer->setTranslator($translator); $this->valueTransformer->setTranslator($translator);
} }
} }
@ -375,8 +363,7 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
protected function translate($text, array $parameters = array()) protected function translate($text, array $parameters = array())
{ {
if ($this->translator !== null) if ($this->translator !== null) {
{
$text = $this->translator->translate($text, $parameters); $text = $this->translator->translate($text, $parameters);
} }
@ -393,13 +380,11 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
protected function injectLocaleAndTranslator($object) protected function injectLocaleAndTranslator($object)
{ {
if ($object instanceof Localizable) if ($object instanceof Localizable) {
{
$object->setLocale($this->locale); $object->setLocale($this->locale);
} }
if (!is_null($this->translator) && $object instanceof Translatable) if (!is_null($this->translator) && $object instanceof Translatable) {
{
$object->setTranslator($this->translator); $object->setTranslator($this->translator);
} }
} }
@ -434,16 +419,11 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
protected function transform($value) protected function transform($value)
{ {
if ($value === null) if ($value === null) {
{
return ''; return '';
} } else if (null === $this->valueTransformer) {
else if (null === $this->valueTransformer)
{
return $value; return $value;
} } else {
else
{
return $this->valueTransformer->transform($value); return $this->valueTransformer->transform($value);
} }
} }
@ -456,16 +436,11 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
protected function reverseTransform($value) protected function reverseTransform($value)
{ {
if ($value === '') if ($value === '') {
{
return null; return null;
} } else if (null === $this->valueTransformer) {
else if (null === $this->valueTransformer)
{
return $value; return $value;
} } else {
else
{
return $this->valueTransformer->reverseTransform($value); return $this->valueTransformer->reverseTransform($value);
} }
} }
@ -477,13 +452,10 @@ abstract class Field extends Configurable implements FieldInterface
{ {
// TODO throw exception if not object or array // TODO throw exception if not object or array
if ($this->propertyPath !== null) if ($this->propertyPath !== null) {
{
$this->propertyPath->rewind(); $this->propertyPath->rewind();
$this->setData($this->readPropertyPath($objectOrArray, $this->propertyPath)); $this->setData($this->readPropertyPath($objectOrArray, $this->propertyPath));
} } else {
else
{
// pass object through if the property path is empty // pass object through if the property path is empty
$this->setData($objectOrArray); $this->setData($objectOrArray);
} }
@ -496,8 +468,7 @@ abstract class Field extends Configurable implements FieldInterface
{ {
// TODO throw exception if not object or array // TODO throw exception if not object or array
if ($this->propertyPath !== null) if ($this->propertyPath !== null) {
{
$this->propertyPath->rewind(); $this->propertyPath->rewind();
$this->updatePropertyPath($objectOrArray, $this->propertyPath); $this->updatePropertyPath($objectOrArray, $this->propertyPath);
} }
@ -512,48 +483,38 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
protected function readPropertyPath(&$objectOrArray, PropertyPath $propertyPath) protected function readPropertyPath(&$objectOrArray, PropertyPath $propertyPath)
{ {
if (is_object($objectOrArray)) if (is_object($objectOrArray)) {
{
$value = $this->readProperty($objectOrArray, $propertyPath); $value = $this->readProperty($objectOrArray, $propertyPath);
} }
// arrays need to be treated separately (due to PHP bug?) // arrays need to be treated separately (due to PHP bug?)
// http://bugs.php.net/bug.php?id=52133 // http://bugs.php.net/bug.php?id=52133
else else {
{ if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) {
if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray))
{
$objectOrArray[$propertyPath->getCurrent()] = array(); $objectOrArray[$propertyPath->getCurrent()] = array();
} }
$value =& $objectOrArray[$propertyPath->getCurrent()]; $value =& $objectOrArray[$propertyPath->getCurrent()];
} }
if ($propertyPath->hasNext()) if ($propertyPath->hasNext()) {
{
$propertyPath->next(); $propertyPath->next();
return $this->readPropertyPath($value, $propertyPath); return $this->readPropertyPath($value, $propertyPath);
} } else {
else
{
return $value; return $value;
} }
} }
protected function updatePropertyPath(&$objectOrArray, PropertyPath $propertyPath) protected function updatePropertyPath(&$objectOrArray, PropertyPath $propertyPath)
{ {
if ($propertyPath->hasNext()) if ($propertyPath->hasNext()) {
{ if (is_object($objectOrArray)) {
if (is_object($objectOrArray))
{
$value = $this->readProperty($objectOrArray, $propertyPath); $value = $this->readProperty($objectOrArray, $propertyPath);
} }
// arrays need to be treated separately (due to PHP bug?) // arrays need to be treated separately (due to PHP bug?)
// http://bugs.php.net/bug.php?id=52133 // http://bugs.php.net/bug.php?id=52133
else else {
{ if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray)) {
if (!array_key_exists($propertyPath->getCurrent(), $objectOrArray))
{
$objectOrArray[$propertyPath->getCurrent()] = array(); $objectOrArray[$propertyPath->getCurrent()] = array();
} }
@ -563,9 +524,7 @@ abstract class Field extends Configurable implements FieldInterface
$propertyPath->next(); $propertyPath->next();
$this->updatePropertyPath($value, $propertyPath); $this->updatePropertyPath($value, $propertyPath);
} } else {
else
{
$this->updateProperty($objectOrArray, $propertyPath); $this->updateProperty($objectOrArray, $propertyPath);
} }
} }
@ -585,51 +544,37 @@ abstract class Field extends Configurable implements FieldInterface
*/ */
protected function readProperty($object, PropertyPath $propertyPath) protected function readProperty($object, PropertyPath $propertyPath)
{ {
if ($propertyPath->isIndex()) if ($propertyPath->isIndex()) {
{ if (!$object instanceof \ArrayAccess) {
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))); throw new InvalidPropertyException(sprintf('Index "%s" cannot be read from object of type "%s" because it doesn\'t implement \ArrayAccess', $propertyPath->getCurrent(), get_class($object)));
} }
return $object[$propertyPath->getCurrent()]; return $object[$propertyPath->getCurrent()];
} } else {
else
{
$reflClass = new \ReflectionClass($object); $reflClass = new \ReflectionClass($object);
$getter = 'get'.ucfirst($propertyPath->getCurrent()); $getter = 'get'.ucfirst($propertyPath->getCurrent());
$isser = 'is'.ucfirst($propertyPath->getCurrent()); $isser = 'is'.ucfirst($propertyPath->getCurrent());
$property = $propertyPath->getCurrent(); $property = $propertyPath->getCurrent();
if ($reflClass->hasMethod($getter)) if ($reflClass->hasMethod($getter)) {
{ if (!$reflClass->getMethod($getter)->isPublic()) {
if (!$reflClass->getMethod($getter)->isPublic())
{
throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $getter, $reflClass->getName())); throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $getter, $reflClass->getName()));
} }
return $object->$getter(); return $object->$getter();
} } else if ($reflClass->hasMethod($isser)) {
else if ($reflClass->hasMethod($isser)) if (!$reflClass->getMethod($isser)->isPublic()) {
{
if (!$reflClass->getMethod($isser)->isPublic())
{
throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $isser, $reflClass->getName())); throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $isser, $reflClass->getName()));
} }
return $object->$isser(); return $object->$isser();
} } else if ($reflClass->hasProperty($property)) {
else if ($reflClass->hasProperty($property)) if (!$reflClass->getProperty($property)->isPublic()) {
{
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))); 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; 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())); 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) protected function updateProperty(&$objectOrArray, PropertyPath $propertyPath)
{ {
if (is_object($objectOrArray) && $propertyPath->isIndex()) if (is_object($objectOrArray) && $propertyPath->isIndex()) {
{ if (!$objectOrArray instanceof \ArrayAccess) {
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))); 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(); $objectOrArray[$propertyPath->getCurrent()] = $this->getData();
} } else if (is_object($objectOrArray)) {
else if (is_object($objectOrArray))
{
$reflClass = new \ReflectionClass($objectOrArray); $reflClass = new \ReflectionClass($objectOrArray);
$setter = 'set'.ucfirst($propertyPath->getCurrent()); $setter = 'set'.ucfirst($propertyPath->getCurrent());
$property = $propertyPath->getCurrent(); $property = $propertyPath->getCurrent();
if ($reflClass->hasMethod($setter)) if ($reflClass->hasMethod($setter)) {
{ if (!$reflClass->getMethod($setter)->isPublic()) {
if (!$reflClass->getMethod($setter)->isPublic())
{
throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName())); throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
} }
$objectOrArray->$setter($this->getData()); $objectOrArray->$setter($this->getData());
} } else if ($reflClass->hasProperty($property)) {
else if ($reflClass->hasProperty($property)) if (!$reflClass->getProperty($property)->isPublic()) {
{
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))); 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(); $objectOrArray->$property = $this->getData();
} } else {
else
{
throw new InvalidPropertyException(sprintf('Neither element "%s" nor method "%s()" exists in class "%s"', $property, $setter, $reflClass->getName())); 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(); $objectOrArray[$propertyPath->getCurrent()] = $this->getData();
} }
} }
@ -688,12 +620,10 @@ abstract class Field extends Configurable implements FieldInterface
{ {
$html = ''; $html = '';
if ($this->hasErrors()) if ($this->hasErrors()) {
{
$html .= "<ul>\n"; $html .= "<ul>\n";
foreach ($this->getErrors() as $error) foreach ($this->getErrors() as $error) {
{
$html .= "<li>" . $error . "</li>\n"; $html .= "<li>" . $error . "</li>\n";
} }

View File

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

View File

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

View File

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

View File

@ -30,8 +30,7 @@ class HybridField extends FieldGroup
*/ */
public function setFieldMode($mode) 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'); 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) 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'); throw new FormException('You cannot add nested fields while in mode FIELD');
} }
@ -59,12 +57,9 @@ class HybridField extends FieldGroup
*/ */
public function getDisplayedData() public function getDisplayedData()
{ {
if ($this->mode === self::GROUP) if ($this->mode === self::GROUP) {
{
return parent::getDisplayedData(); return parent::getDisplayedData();
} } else {
else
{
return Field::getDisplayedData(); return Field::getDisplayedData();
} }
} }
@ -74,12 +69,9 @@ class HybridField extends FieldGroup
*/ */
public function setData($data) public function setData($data)
{ {
if ($this->mode === self::GROUP) if ($this->mode === self::GROUP) {
{
parent::setData($data); parent::setData($data);
} } else {
else
{
Field::setData($data); Field::setData($data);
} }
} }
@ -89,12 +81,9 @@ class HybridField extends FieldGroup
*/ */
public function bind($data) public function bind($data)
{ {
if ($this->mode === self::GROUP) if ($this->mode === self::GROUP) {
{
parent::bind($data); parent::bind($data);
} } else {
else
{
Field::bind($data); Field::bind($data);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -31,13 +31,11 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
$this->addOption('input_timezone', 'UTC'); $this->addOption('input_timezone', 'UTC');
$this->addOption('output_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'))); 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'))); 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) public function transform($dateTime)
{ {
if (!$dateTime instanceof \DateTime) if (!$dateTime instanceof \DateTime) {
{
throw new \InvalidArgumentException('Expected value of type \DateTime'); throw new \InvalidArgumentException('Expected value of type \DateTime');
} }
$inputTimezone = $this->getOption('input_timezone'); $inputTimezone = $this->getOption('input_timezone');
// convert time to UTC before passing it to the formatter // convert time to UTC before passing it to the formatter
if ($inputTimezone != 'UTC') if ($inputTimezone != 'UTC') {
{
$dateTime->setTimezone(new \DateTimeZone('UTC')); $dateTime->setTimezone(new \DateTimeZone('UTC'));
} }
$value = $this->getIntlDateFormatter()->format((int)$dateTime->format('U')); $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()); throw new TransformationFailedException(intl_get_error_message());
} }
@ -83,23 +78,20 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer
{ {
$inputTimezone = $this->getOption('input_timezone'); $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))); throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value)));
} }
$timestamp = $this->getIntlDateFormatter()->parse($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()); throw new TransformationFailedException(intl_get_error_message());
} }
// read timestamp into DateTime object - the formatter delivers in UTC // read timestamp into DateTime object - the formatter delivers in UTC
$dateTime = new \DateTime(sprintf('@%s UTC', $timestamp)); $dateTime = new \DateTime(sprintf('@%s UTC', $timestamp));
if ($inputTimezone != 'UTC') if ($inputTimezone != 'UTC') {
{
$dateTime->setTimezone(new \DateTimeZone($inputTimezone)); $dateTime->setTimezone(new \DateTimeZone($inputTimezone));
} }

View File

@ -32,8 +32,7 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransform
*/ */
public function transform($value) public function transform($value)
{ {
if (!is_numeric($value)) if (!is_numeric($value)) {
{
throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($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) public function transform($value)
{ {
if (!is_numeric($value)) if (!is_numeric($value)) {
{
throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value))); throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($value)));
} }
$formatter = $this->getNumberFormatter(); $formatter = $this->getNumberFormatter();
$value = $formatter->format($value); $value = $formatter->format($value);
if (intl_is_failure($formatter->getErrorCode())) if (intl_is_failure($formatter->getErrorCode())) {
{
throw new TransformationFailedException($formatter->getErrorMessage()); throw new TransformationFailedException($formatter->getErrorMessage());
} }
@ -55,16 +53,14 @@ class NumberToLocalizedStringTransformer extends BaseValueTransformer
*/ */
public function reverseTransform($value) 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))); throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value)));
} }
$formatter = $this->getNumberFormatter(); $formatter = $this->getNumberFormatter();
$value = $formatter->parse($value); $value = $formatter->parse($value);
if (intl_is_failure($formatter->getErrorCode())) if (intl_is_failure($formatter->getErrorCode())) {
{
throw new TransformationFailedException($formatter->getErrorMessage()); throw new TransformationFailedException($formatter->getErrorMessage());
} }
@ -80,8 +76,7 @@ class NumberToLocalizedStringTransformer extends BaseValueTransformer
{ {
$formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL); $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')); $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('type', self::FRACTIONAL);
$this->addOption('precision', 0); $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))); 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) public function transform($value)
{ {
if (!is_numeric($value)) if (!is_numeric($value)) {
{
throw new \InvalidArgumentException(sprintf('Numeric argument expected, %s given', gettype($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; $value *= 100;
} }
$formatter = $this->getNumberFormatter(); $formatter = $this->getNumberFormatter();
$value = $formatter->format($value); $value = $formatter->format($value);
if (intl_is_failure($formatter->getErrorCode())) if (intl_is_failure($formatter->getErrorCode())) {
{
throw new TransformationFailedException($formatter->getErrorMessage()); throw new TransformationFailedException($formatter->getErrorMessage());
} }
@ -74,8 +70,7 @@ class PercentToLocalizedStringTransformer extends BaseValueTransformer
*/ */
public function reverseTransform($value) 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))); 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 // replace normal spaces so that the formatter can read them
$value = $formatter->parse(str_replace(' ', ' ', $value)); $value = $formatter->parse(str_replace(' ', ' ', $value));
if (intl_is_failure($formatter->getErrorCode())) if (intl_is_failure($formatter->getErrorCode())) {
{
throw new TransformationFailedException($formatter->getErrorMessage()); throw new TransformationFailedException($formatter->getErrorMessage());
} }
if (self::FRACTIONAL == $this->getOption('type')) if (self::FRACTIONAL == $this->getOption('type')) {
{
$value /= 100; $value /= 100;
} }

View File

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

View File

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

View File

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

View File

@ -54,58 +54,44 @@ class Constraint
$invalidOptions = array(); $invalidOptions = array();
$missingOptions = array_flip((array)$this->requiredOptions()); $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']; $options = $options['value'];
} }
if (is_array($options) && count($options) > 0 && is_string(key($options))) if (is_array($options) && count($options) > 0 && is_string(key($options))) {
{ foreach ($options as $option => $value) {
foreach ($options as $option => $value) if (property_exists($this, $option)) {
{
if (property_exists($this, $option))
{
$this->$option = $value; $this->$option = $value;
unset($missingOptions[$option]); unset($missingOptions[$option]);
} } else {
else
{
$invalidOptions[] = $option; $invalidOptions[] = $option;
} }
} }
} } else if ($options) {
else if ($options)
{
$option = $this->defaultOption(); $option = $this->defaultOption();
if (is_null($option)) if (is_null($option)) {
{
throw new ConstraintDefinitionException( throw new ConstraintDefinitionException(
sprintf('No default option is configured for constraint %s', get_class($this)) 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; $this->$option = $options;
unset($missingOptions[$option]); unset($missingOptions[$option]);
} } else {
else
{
$invalidOptions[] = $option; $invalidOptions[] = $option;
} }
} }
if (count($invalidOptions) > 0) if (count($invalidOptions) > 0) {
{
throw new InvalidOptionsException( throw new InvalidOptionsException(
sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), get_class($this)), sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), get_class($this)),
$invalidOptions $invalidOptions
); );
} }
if (count($missingOptions) > 0) if (count($missingOptions) > 0) {
{
throw new MissingOptionsException( throw new MissingOptionsException(
sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), get_class($this)), sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), get_class($this)),
array_keys($missingOptions) array_keys($missingOptions)
@ -130,8 +116,7 @@ class Constraint
*/ */
public function addImplicitGroupName($group) 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; $this->groups[] = $group;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,31 +12,26 @@ class EmailValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if ($value === null) if ($value === null) {
{
return true; 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'); throw new UnexpectedTypeException($value, 'string');
} }
$value = (string)$value; $value = (string)$value;
if (!preg_match(self::PATTERN, $value)) if (!preg_match(self::PATTERN, $value)) {
{
$this->setMessage($constraint->message, array('value' => $value)); $this->setMessage($constraint->message, array('value' => $value));
return false; return false;
} }
if ($constraint->checkMX) if ($constraint->checkMX) {
{
$host = substr($value, strpos($value, '@')); $host = substr($value, strpos($value, '@'));
if (!$this->checkMX($host)) if (!$this->checkMX($host)) {
{
$this->setMessage($constraint->message, array('value' => $value)); $this->setMessage($constraint->message, array('value' => $value));
return false; return false;
@ -63,23 +58,18 @@ class EmailValidator extends ConstraintValidator
@exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output); @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()?'); throw new ValidatorError('Unable to execute DNS lookup. Are you sure PHP can call exec()?');
} }
foreach ($output as $line) foreach ($output as $line) {
{ if (preg_match('/^'.$host.'/', $line)) {
if (preg_match('/^'.$host.'/', $line))
{
return true; return true;
} }
} }
return false; return false;
} } else if (function_exists('checkdnsrr')) {
else if (function_exists('checkdnsrr'))
{
return checkdnsrr($host, 'MX'); return checkdnsrr($host, 'MX');
} }

View File

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

View File

@ -10,13 +10,11 @@ class MaxLengthValidator extends ConstraintValidator
{ {
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if ($value === null) if ($value === null) {
{
return true; 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'); 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); $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( $this->setMessage($constraint->message, array(
'value' => $value, 'value' => $value,
'limit' => $constraint->limit, 'limit' => $constraint->limit,

View File

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

View File

@ -10,13 +10,11 @@ class MinLengthValidator extends ConstraintValidator
{ {
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if ($value === null) if ($value === null) {
{
return true; 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'); 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); $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( $this->setMessage($constraint->message, array(
'value' => $value, 'value' => $value,
'limit' => $constraint->limit, 'limit' => $constraint->limit,

View File

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

View File

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

View File

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

View File

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

View File

@ -10,13 +10,11 @@ class RegexValidator extends ConstraintValidator
{ {
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if ($value === null) if ($value === null) {
{
return true; 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'); throw new UnexpectedTypeException($value, 'string');
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,13 +16,11 @@ class GroupChain
public function addGroupSequence(array $groups) 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'); 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; $this->groupSequences[] = $groups;
} }
} }

View File

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

View File

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

View File

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

View File

@ -17,16 +17,11 @@ class GetterMetadata extends MemberMetadata
$getMethod = 'get'.ucfirst($property); $getMethod = 'get'.ucfirst($property);
$isMethod = 'is'.ucfirst($property); $isMethod = 'is'.ucfirst($property);
if (method_exists($class, $getMethod)) if (method_exists($class, $getMethod)) {
{
$method = $getMethod; $method = $getMethod;
} } else if (method_exists($class, $isMethod)) {
else if (method_exists($class, $isMethod))
{
$method = $isMethod; $method = $isMethod;
} } else {
else
{
throw new ValidatorException(sprintf('Neither method %s nor %s exists in class %s', $getMethod, $isMethod, $class)); 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(); $reflClass = $metadata->getReflectionClass();
$loaded = false; $loaded = false;
if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) {
{ foreach ($annot->constraints as $constraint) {
foreach ($annot->constraints as $constraint)
{
$metadata->addConstraint($constraint); $metadata->addConstraint($constraint);
} }
$loaded = true; $loaded = true;
} }
foreach ($reflClass->getProperties() as $property) foreach ($reflClass->getProperties() as $property) {
{ if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) {
if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) foreach ($annot->constraints as $constraint) {
{
foreach ($annot->constraints as $constraint)
{
$metadata->addPropertyConstraint($property->getName(), $constraint); $metadata->addPropertyConstraint($property->getName(), $constraint);
} }
@ -49,12 +44,9 @@ class AnnotationLoader implements LoaderInterface
} }
} }
foreach ($reflClass->getMethods() as $method) foreach ($reflClass->getMethods() as $method) {
{ if ($annot = $this->reader->getMethodAnnotation($method, $annotClass)) {
if ($annot = $this->reader->getMethodAnnotation($method, $annotClass)) foreach ($annot->constraints as $constraint) {
{
foreach ($annot->constraints as $constraint)
{
// TODO: clean this up // TODO: clean this up
$name = lcfirst(substr($method->getName(), 0, 3)=='get' ? substr($method->getName(), 3) : substr($method->getName(), 2)); $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) public function __construct($file)
{ {
if (!file_exists($file)) if (!file_exists($file)) {
{
throw new MappingException(sprintf('The mapping file %s does not exist', $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)); 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) public function __construct(array $loaders)
{ {
foreach ($loaders as $loader) foreach ($loaders as $loader) {
{ if (!$loader instanceof LoaderInterface) {
if (!$loader instanceof LoaderInterface)
{
throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader))); throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader)));
} }
} }
@ -46,8 +44,7 @@ class LoaderChain implements LoaderInterface
{ {
$success = false; $success = false;
foreach ($this->loaders as $loader) foreach ($this->loaders as $loader) {
{
$success = $loader->loadClassMetadata($metadata) || $success; $success = $loader->loadClassMetadata($metadata) || $success;
} }

View File

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

View File

@ -19,42 +19,32 @@ class YamlFileLoader extends FileLoader
*/ */
public function loadClassMetadata(ClassMetadata $metadata) public function loadClassMetadata(ClassMetadata $metadata)
{ {
if (is_null($this->classes)) if (is_null($this->classes)) {
{
$this->classes = Yaml::load($this->file); $this->classes = Yaml::load($this->file);
} }
// TODO validation // TODO validation
if (isset($this->classes[$metadata->getClassName()])) if (isset($this->classes[$metadata->getClassName()])) {
{
$yaml = $this->classes[$metadata->getClassName()]; $yaml = $this->classes[$metadata->getClassName()];
if (isset($yaml['constraints'])) if (isset($yaml['constraints'])) {
{ foreach ($this->parseNodes($yaml['constraints']) as $constraint) {
foreach ($this->parseNodes($yaml['constraints']) as $constraint)
{
$metadata->addConstraint($constraint); $metadata->addConstraint($constraint);
} }
} }
if (isset($yaml['properties'])) if (isset($yaml['properties'])) {
{ foreach ($yaml['properties'] as $property => $constraints) {
foreach ($yaml['properties'] as $property => $constraints) foreach ($this->parseNodes($constraints) as $constraint) {
{
foreach ($this->parseNodes($constraints) as $constraint)
{
$metadata->addPropertyConstraint($property, $constraint); $metadata->addPropertyConstraint($property, $constraint);
} }
} }
} }
if (isset($yaml['getters'])) if (isset($yaml['getters'])) {
{ foreach ($yaml['getters'] as $getter => $constraints) {
foreach ($yaml['getters'] as $getter => $constraints) foreach ($this->parseNodes($constraints) as $constraint) {
{
foreach ($this->parseNodes($constraints) as $constraint)
{
$metadata->addGetterConstraint($getter, $constraint); $metadata->addGetterConstraint($getter, $constraint);
} }
} }
@ -76,24 +66,18 @@ class YamlFileLoader extends FileLoader
{ {
$values = array(); $values = array();
foreach ($nodes as $name => $childNodes) foreach ($nodes as $name => $childNodes) {
{ if (is_numeric($name) && is_array($childNodes) && count($childNodes) == 1) {
if (is_numeric($name) && is_array($childNodes) && count($childNodes) == 1)
{
$className = 'Symfony\\Components\\Validator\\Constraints\\'.key($childNodes); $className = 'Symfony\\Components\\Validator\\Constraints\\'.key($childNodes);
$options = current($childNodes); $options = current($childNodes);
if (is_array($options)) if (is_array($options)) {
{
$options = $this->parseNodes($options); $options = $this->parseNodes($options);
} }
$values[] = new $className($options); $values[] = new $className($options);
} } else {
else if (is_array($childNodes)) {
{
if (is_array($childNodes))
{
$childNodes = $this->parseNodes($childNodes); $childNodes = $this->parseNodes($childNodes);
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -49,8 +49,7 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
$constraint = new Min(4); $constraint = new Min(4);
foreach ($array as $key => $value) foreach ($array as $key => $value) {
{
$this->walker->expects($this->once()) $this->walker->expects($this->once())
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->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 // can't test method calls with different arguments
$constraints = array($constraint, $constraint); $constraints = array($constraint, $constraint);
foreach ($array as $key => $value) foreach ($array as $key => $value) {
{
$this->walker->expects($this->exactly(2)) $this->walker->expects($this->exactly(2))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->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() protected function createFile()
{ {
if (!self::$file) if (!self::$file) {
{
self::$file = fopen(__FILE__, 'r'); self::$file = fopen(__FILE__, 'r');
} }
@ -120,8 +119,7 @@ class AssertTypeValidatorTest extends \PHPUnit_Framework_TestCase
public static function tearDownAfterClass() public static function tearDownAfterClass()
{ {
if (self::$file) if (self::$file) {
{
fclose(self::$file); fclose(self::$file);
} }
} }

View File

@ -53,8 +53,7 @@ class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$constraint = new Min(4); $constraint = new Min(4);
foreach ($array as $key => $value) foreach ($array as $key => $value) {
{
$this->walker->expects($this->once()) $this->walker->expects($this->once())
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->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 // can't test method calls with different arguments
$constraints = array($constraint, $constraint); $constraints = array($constraint, $constraint);
foreach ($array as $key => $value) foreach ($array as $key => $value) {
{
$this->walker->expects($this->exactly(2)) $this->walker->expects($this->exactly(2))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->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) public function testValidValues($value, $skip = false)
{ {
if (!$skip) if (!$skip) {
{
$constraint = new MaxLength(array('limit' => 5)); $constraint = new MaxLength(array('limit' => 5));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
} }
@ -55,8 +54,7 @@ class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value, $skip = false) public function testInvalidValues($value, $skip = false)
{ {
if (!$skip) if (!$skip) {
{
$constraint = new MaxLength(array('limit' => 5)); $constraint = new MaxLength(array('limit' => 5));
$this->assertFalse($this->validator->isValid($value, $constraint)); $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) public function testValidValues($value, $skip = false)
{ {
if (!$skip) if (!$skip) {
{
$constraint = new MinLength(array('limit' => 6)); $constraint = new MinLength(array('limit' => 6));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
} }
@ -55,8 +54,7 @@ class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value, $skip = false) public function testInvalidValues($value, $skip = false)
{ {
if (!$skip) if (!$skip) {
{
$constraint = new MinLength(array('limit' => 6)); $constraint = new MinLength(array('limit' => 6));
$this->assertFalse($this->validator->isValid($value, $constraint)); $this->assertFalse($this->validator->isValid($value, $constraint));
} }

View File

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