Skip to content

Variable "this" has value of null in an "Expression" validation constraint inside an "All" validation constraint #20477

@zsolt-racz

Description

@zsolt-racz

I have possibly found a bug in the Validator component when combining these two constraints: Expression and All. I'm going to show it on an example:

Considering these two classes:

namespace AppBundle;
class ParentClass {

	private $name;
	private $children;

	public function __construct(){
		$this->children = new ArrayCollection();
	}

	public function getName() {
		return $this->name;
	}

	public function setName( $name ) {
		$this->name = $name;
	}

	public function getChildren() {
		return $this->children;
	}

	public function addChild( $child ) {
		$this->children->add($child);
	}
}

and

namespace AppBundle;
class ChildClass {

	private $name;

	public function getName() {
		return $this->name;
	}

	public function setName( $name ) {
		$this->name = $name;
	}

}

With the following validation rules stored in validation.yml:

AppBundle\ParentClass:
    properties:
        children:
            - NotBlank: ~
            - Valid: ~
            - All:
                - Expression:
                    expression: "this.getName() != value.getName()"

AppBundle\ChildClass:
    properties:
        name:
            - NotBlank: ~

I would like to achieve to forbid assigning the parent's name to children. So the getName() method of the parent should return a distinct value from getName() methods of all children.

However after trying to validate an instance of ParentClass constructed like this:

    $validator = $this->get('validator');

    $parent = new ParentClass();
    $parent->setName("foo");

    $child = new ChildClass();
    $child->setName("bar");

    $parent->addChild($child);
    $validator->validate($parent);

A RuntimeException is thrown with the following message:

Unable to get a property on a non-object. 

As I figured out, the variable value is correctly assigned to child objects, however the variable this in the expression has a value of null. I would expect a reference to the parent object in this variable, regarding to the documentation:

this: The object being validated (e.g. an instance of BlogPost);


Symfony 3.1.6, PHP 7.0.8, Linux Mint 18

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions