Skip to content

[Validator] Poorly implemented Visitor Pattern #7432

Closed
@drscre

Description

@drscre

Currently,

Validator\Mapping\MemberMetadata::accept() 

leaves traversing of properties that are arrays or \Traversable up to the visitor.
While the main purpose of Visitor Pattern is to decouple object structure from visitor functionality.

In the following example, i naively expected that, when visiting an entity, a MyValidationVisitor::vizit() method would be recursively invoked for every entity property.

$metadata = $validator->getMetadataFor($entity);

$visitor = new MyValidationVisitor();
$metadata->accept($visitor, $entity, ...);

In practice, i have to manually re-curse into array properties.

I believe, that the need to call accept() inside Vizitor::visit() brings confusion, so the following code from Validator\ValidationVisitor::validate() method must be re-factored and moved to Validator\Mapping\MemberMetadata::accept() in order to decouple validation from structure of validated objects

if (is_array($value) || ($traverse && $value instanceof \Traversable)) {
    foreach ($value as $key => $element) {
        // Ignore any scalar values in the collection
        if (is_object($element) || is_array($element)) {
            // Only repeat the traversal if $deep is set
            $this->validate($element, $group, $propertyPath.'['.$key.']', $deep, $deep);
        }
    }

    try {
        $this->metadataFactory->getMetadataFor($value)->accept($this, $value, $group, $propertyPath);
    } catch (NoSuchMetadataException $e) {
        // Metadata doesn't necessarily have to exist for
        // traversable objects, because we know how to validate
        // them anyway. Optionally, additional metadata is supported.
    }
} else {
    $this->metadataFactory->getMetadataFor($value)->accept($this, $value, $group, $propertyPath);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions