I use PHP-Parser in my project. I would like to compare two nodes, using PHPUnit's assertEquals function.
Despite the nodes are the same, it gives a false result. The reason is, that one of the nodes contains two protected attributes, and the other does not:
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
Is it possible to compare the nodes excluding protected attributes?
Example data
The first object:
array(1) {
[0]=>
object(PhpParser\Node\Stmt\Expression)#5924 (2) {
["expr"]=>
object(PhpParser\Node\Expr\Assign)#5923 (3) {
["var"]=>
object(PhpParser\Node\Expr\Variable)#5918 (2) {
["name"]=>
string(1) "x"
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["expr"]=>
object(PhpParser\Node\Expr\ArrayDimFetch)#5922 (3) {
["var"]=>
object(PhpParser\Node\Expr\Variable)#5919 (2) {
["name"]=>
string(3) "arr"
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["dim"]=>
object(PhpParser\Node\Scalar\String_)#5934 (2) {
["value"]=>
string(3) "FOO"
["attributes":protected]=>
array(0) {
}
}
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
}
The second object:
array(1) {
[0]=>
object(PhpParser\Node\Stmt\Expression)#5930 (2) {
["expr"]=>
object(PhpParser\Node\Expr\Assign)#5929 (3) {
["var"]=>
object(PhpParser\Node\Expr\Variable)#250 (2) {
["name"]=>
string(1) "x"
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["expr"]=>
object(PhpParser\Node\Expr\ArrayDimFetch)#5928 (3) {
["var"]=>
object(PhpParser\Node\Expr\Variable)#5926 (2) {
["name"]=>
string(3) "arr"
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["dim"]=>
object(PhpParser\Node\Scalar\String_)#5927 (2) {
["value"]=>
string(3) "FOO"
["attributes":protected]=>
array(3) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
["kind"]=>
int(1)
}
}
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
["attributes":protected]=>
array(2) {
["startLine"]=>
int(2)
["endLine"]=>
int(2)
}
}
}
Note the PhpParser\Node\Scalar\String_ object with ["value"]=> string(3) "FOO"
Instances of objects will always not be equal. You could write a compare function like the other answers, but simply encoding as JSON will hide all the protected properties and keep the public ones. Then comparing the strings will be enough.
An example here
http://sandbox.onlinephpfunctions.com/code/174b9bf5317a200dd42a83c082d3c95558baae90