Skip to content

Commit

Permalink
Refactored rule::depends into rule::conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
boekkooi committed Jan 29, 2015
1 parent 5eb19f3 commit 550ae0d
Show file tree
Hide file tree
Showing 13 changed files with 559 additions and 221 deletions.
25 changes: 2 additions & 23 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,10 @@
<?php
$finder = Symfony\CS\Finder\DefaultFinder::create()
->in(__DIR__ . '/src')
->in(__DIR__ . '/tests')
;

return Symfony\CS\Config\Config::create()
->fixers(array(
'encoding',
'linefeed',
'indentation',
'trailing_spaces',
'unused_use',
'visibility',
'short_tag',
'php_closing_tag',
'return',
'braces',
'lowercase_constants',
'lowercase_keywords',
'include',
'function_declaration',
'controls_spaces',
'spaces_cast',
'elseif',
'eof_ending',
'standardize_not_equal',
'new_with_braces'
))
->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
->finder($finder)
;

1 change: 0 additions & 1 deletion src/DependencyInjection/Compiler/ExtensionPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ protected function registerRuleCompilers(ContainerBuilder $container)
$container->getDefinition('boekkooi.jquery_validation.rule_compiler')->replaceArgument(0, $references);
}


/**
* @param ContainerBuilder $container
* @return array|null
Expand Down
10 changes: 5 additions & 5 deletions src/Form/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ abstract class Rule
public $message;

/**
* A list of field names that require to be valid before the rule is used
* @var array
* A list rule conditions.
* @var RuleCondition[]
*/
public $depends;
public $conditions;

public function __construct($name, $options = null, RuleMessage $message = null, array $depends = array())
public function __construct($name, $options = null, RuleMessage $message = null, array $conditions = array())
{
$this->name = $name;
$this->options = $options;
$this->message = $message;
$this->depends = $depends;
$this->conditions = $conditions;
}
}
39 changes: 39 additions & 0 deletions src/Form/Rule/Condition/FieldDependency.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
namespace Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Condition;

use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleCondition;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Util\FormHelper;

/**
* @author Warnar Boekkooi <[email protected]>
*/
class FieldDependency implements RuleCondition
{
const FIELD_VALID = '=';
const FIELD_INVALID = '!';

/**
* Dependent field
* @var string
*/
public $field;

/**
* @var string
*/
public $condition;

public function __construct($field, $condition = self::FIELD_VALID)
{
$this->field = FormHelper::getFormName($field);
$this->condition = $condition;
}

/**
* {@inheritdoc}
*/
public function macro()
{
return 'field_dependency';
}
}
4 changes: 2 additions & 2 deletions src/Form/Rule/ConstraintRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ class ConstraintRule extends Rule
*/
public $groups;

public function __construct($name, $options = null, RuleMessage $message = null, array $groups = array(Constraint::DEFAULT_GROUP), array $depends = array())
public function __construct($name, $options = null, RuleMessage $message = null, array $groups = array(Constraint::DEFAULT_GROUP), array $conditions = array())
{
parent::__construct($name, $options, $message, $depends);
parent::__construct($name, $options, $message, $conditions);

$this->groups = $groups;
}
Expand Down
5 changes: 3 additions & 2 deletions src/Form/Rule/Processor/CompoundCopyToChildPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleContextBuilder;
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleProcessorContext;
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleProcessorInterface;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Condition\FieldDependency;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\ConstraintRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping\RequiredRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleCollection;
Expand Down Expand Up @@ -102,7 +103,7 @@ private function registerRulesForChildren(FormRuleContextBuilder $formRuleContex
if ($collection->containsKey($name)) {
$childRule = $collection[$name];
$childRule->message = $rule->message;
$childRule->depends = $rule->depends;
$childRule->conditions = $rule->conditions;
if ($childRule instanceof ConstraintRule && $rule instanceof ConstraintRule) {
$childRule->groups = array_unique(
array_merge($childRule->groups, $rule->groups)
Expand All @@ -114,7 +115,7 @@ private function registerRulesForChildren(FormRuleContextBuilder $formRuleContex

$rule = clone $rule;
$rule->message = $message;
$rule->depends[] = $childView->vars['full_name'];
$rule->conditions[] = new FieldDependency($childView->vars['full_name']);
}
}

Expand Down
56 changes: 36 additions & 20 deletions src/Form/Rule/Processor/DateTimeToArrayTransformerPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@

use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleContextBuilder;
use Boekkooi\Bundle\JqueryValidationBundle\Form\FormRuleProcessorContext;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Condition\FieldDependency;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping\MaxRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping\MinRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping\NumberRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\Mapping\RequiredRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleCollection;
use Boekkooi\Bundle\JqueryValidationBundle\Form\RuleMessage;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\TransformerRule;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Util\FormViewRecursiveIterator;
use Boekkooi\Bundle\JqueryValidationBundle\Form\Util\FormHelper;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer;
use Symfony\Component\Form\FormView;

/**
Expand All @@ -36,55 +38,58 @@ public function process(FormRuleProcessorContext $context, FormRuleContextBuilde
return;
}

/** @var \Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer $transformer */
$transformer = $this->findTransformer($formConfig, 'Symfony\\Component\\Form\\Extension\\Core\\DataTransformer\\DateTimeToArrayTransformer');
if ($transformer === null) {
return;
}
$view = $context->getView();

/** @var FormView[] $it */
$it = new \RecursiveIteratorIterator(
new FormViewRecursiveIterator($view->getIterator()),
\RecursiveIteratorIterator::LEAVES_ONLY
);
$fields = $this->getTransformerFields($transformer);
$invalidMessage = $this->getFormRuleMessage($formConfig);

$depends = array();
foreach ($it as $childView) {
$views = array();
$conditions = array();
foreach ($fields as $fieldName) {
$childView = $view->children[$fieldName];

// Get child rules collection
$childRules = $formRuleContext->get($childView);
if ($childRules === null) {
$formRuleContext->add($childView, new RuleCollection());
$childRules = $formRuleContext->get($childView);
}

// Register rules
$this->addNumberCheck(
$childView,
$childRules,
$invalidMessage,
$depends
$conditions
);
$depends[] = $childView->vars['full_name'];

$views[] = FormHelper::getFormName($childView);
$conditions[] = new FieldDependency($childView);
}

if ($this->useGroupRule && count($depends) > 1) {
$rules = $formRuleContext->get(array_shift($depends));
if ($this->useGroupRule && count($views) > 1) {
$rules = $formRuleContext->get(array_shift($views));
$rules->set(
CompoundCopyToChildPass::RULE_NAME_GROUP_REQUIRED,
new TransformerRule(CompoundCopyToChildPass::RULE_NAME_GROUP_REQUIRED, $depends, $invalidMessage)
new TransformerRule(CompoundCopyToChildPass::RULE_NAME_GROUP_REQUIRED, $views, $invalidMessage)
);
}
}

private function addNumberCheck(FormView $view, RuleCollection $rules, RuleMessage $message = null, array $depends = array())
private function addNumberCheck(FormView $view, RuleCollection $rules, RuleMessage $message = null, array $conditions = array())
{
if (!$this->useGroupRule && count($depends) > 0) {
if (!$this->useGroupRule && count($conditions) > 0) {
$rules->set(
RequiredRule::RULE_NAME,
new TransformerRule(
RequiredRule::RULE_NAME,
true,
$message,
$depends
$conditions
)
);
}
Expand All @@ -98,7 +103,7 @@ private function addNumberCheck(FormView $view, RuleCollection $rules, RuleMessa
NumberRule::RULE_NAME,
true,
$message,
$depends
$conditions
)
);

Expand All @@ -125,11 +130,22 @@ private function addNumberCheck(FormView $view, RuleCollection $rules, RuleMessa
}
$rules->set(
MinRule::RULE_NAME,
new TransformerRule(MinRule::RULE_NAME, $min, $message, $depends)
new TransformerRule(MinRule::RULE_NAME, $min, $message, $conditions)
);
$rules->set(
MaxRule::RULE_NAME,
new TransformerRule(MaxRule::RULE_NAME, $max, $message, $depends)
new TransformerRule(MaxRule::RULE_NAME, $max, $message, $conditions)
);
}

private function getTransformerFields(DateTimeToArrayTransformer $transformer)
{
$property = new \ReflectionProperty(
'Symfony\\Component\\Form\\Extension\\Core\\DataTransformer\\DateTimeToArrayTransformer',
'fields'
);
$property->setAccessible(true);

return $property->getValue($transformer);
}
}
14 changes: 14 additions & 0 deletions src/Form/RuleCondition.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php
namespace Boekkooi\Bundle\JqueryValidationBundle\Form;

/**
* @author Warnar Boekkooi <[email protected]>
*/
interface RuleCondition
{
/**
* Get the twig macro name to call.
* @return string
*/
public function macro();
}
11 changes: 11 additions & 0 deletions src/Form/RuleMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,21 @@
*/
class RuleMessage
{
/**
* A message text.
* @var string
*/
public $message;

/**
* A list of message parameters.
* @var array
*/
public $parameters;

/**
* @var null
*/
public $plural;

public function __construct($message, array $parameters = array(), $plural = null)
Expand Down
16 changes: 16 additions & 0 deletions src/Resources/views/Form/conditions.js.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{% macro field_dependency(condition, rule) %}
{%- set isRequired = rule.name is sameas('required') -%}

{%- if isRequired -%}
var dep = form.find("[name=\"{{ condition.field|e('js') }}\"]")[0];
{%- endif -%}

if (
{%- if condition.condition is sameas('!') -%}!{%- endif -%}
(
{%- if isRequired -%}
!$.validator.methods.required.call(validator, validator.elementValue(dep), dep, true) || {% endif -%}
"{{ condition.field|e('js') }}" in validator.errorMap || "{{ condition.field|e('js') }}" in validator.invalid)) {
return false;
}
{% endmacro %}
50 changes: 23 additions & 27 deletions src/Resources/views/Form/macros.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -44,46 +44,42 @@

{# Generate a rule #}
{% macro rule(rule, includeGroupDeps) %}
{%- import _self as gen -%}
{% import "BoekkooiJqueryValidationBundle:Form:conditions.js.twig" as macro_conditions %}

{%- set hasGroups = includeGroupDeps|default(false) and rule.groups|length > 0 -%}
{%- set hasDepends = (rule.depends is not empty) -%}
{%- set hasConditions = (rule.conditions is not empty) -%}

{%- if hasGroups or hasDepends -%}
{%- if hasGroups or hasConditions -%}
{%- set hasParams = rule.options is not sameas(true) -%}

{
{%- if hasParams -%}
param: {{- rule.options|json_encode()|raw -}},
{%- endif -%}
depends: function() {
{%- if hasDepends and rule.name is sameas('required') %}
var dep = form.find("[name=\"{{ rule.depends|e('js')|last }}\"]")[0];
{% endif %}

return
{%- if hasGroups %} (
{%- for group in rule.groups -%}
validator.settings.validation_groups["{{ group|e('js') }}"] {%- if not loop.last %} || {% endif -%}
{%- if hasConditions %}
{%- if hasGroups -%}
if (!(
{%- for group in rule.groups -%}
validator.settings.validation_groups["{{ group|e('js') }}"] {%- if not loop.last %} || {% endif -%}
{%- endfor -%}
)) {
return false;
}
{%- endif -%}

{%- for condition in rule.conditions -%}
{{ attribute(macro_conditions, condition.macro, [condition, rule]) }}
{%- endfor -%}
)
{%- endif -%}

{%- if hasGroups and hasDepends %} && {% endif -%}

{%- if hasDepends %}
{% if rule.name is sameas('required') %}
$.validator.methods.required.call(validator, validator.elementValue(dep), dep, true) &&
{% endif %}

!(
{%- for selector in rule.depends -%}
"{{ selector|e('js') }}" in validator.errorMap ||
"{{ selector|e('js') }}" in validator.invalid {%- if not loop.last %} || {% endif -%}
{%- endfor -%}
)
return true;
{% else %}
return (
{%- for group in rule.groups -%}
validator.settings.validation_groups["{{ group|e('js') }}"] {%- if not loop.last %} || {% endif -%}
{%- endfor -%}
);
{%- endif -%}
;
}
}
{%- else -%}
Expand Down
Loading

0 comments on commit 550ae0d

Please sign in to comment.