Skip to content

Allow to mark JSON properties & XML nodes as optional #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 2, 2017
Merged
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ $matcher->getError(); // returns null or error message
* ``inArray($value)``
* ``oneOf(...$expanders)`` - example usage ``"@string@.oneOf(contains('foo'), contains('bar'), contains('baz'))"``
* ``matchRegex($regex)`` - example usage ``"@string@.matchRegex('/^lorem.+/')"``
* ``optional()`` - work's only with ``ArrayMatcher``, ``JsonMatcher`` and ``XmlMatcher``

##Example usage

Expand Down Expand Up @@ -237,7 +238,8 @@ $matcher->match(
'id' => 1,
'firstName' => 'Norbert',
'lastName' => 'Orzechowicz',
'roles' => array('ROLE_USER')
'roles' => array('ROLE_USER'),
'position' => 'Developer',
),
array(
'id' => 2,
Expand All @@ -261,7 +263,8 @@ $matcher->match(
'id' => '@integer@.greaterThan(0)',
'firstName' => '@string@',
'lastName' => 'Orzechowicz',
'roles' => '@array@'
'roles' => '@array@',
'position' => '@string@.optional()'
),
array(
'id' => '@integer@',
Expand Down Expand Up @@ -303,7 +306,8 @@ $matcher->match(
"firstName": @string@,
"lastName": @string@,
"created": "@string@.isDateTime()",
"roles": @array@
"roles": @array@,
"posiiton": "@string@.optional()"
}
]
}'
Expand Down Expand Up @@ -347,6 +351,7 @@ XML
<m:GetStockPrice>
<m:StockName>@string@</m:StockName>
<m:StockValue>@string@</m:StockValue>
<m:StockQty>@integer@.optional()</m:StockQty>
</m:GetStockPrice>
</soap:Body>

Expand Down
32 changes: 30 additions & 2 deletions src/Matcher/ArrayMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Coduo\PHPMatcher\Matcher;

use Coduo\PHPMatcher\Exception\Exception;
use Coduo\PHPMatcher\Parser;
use Coduo\ToString\StringConverter;
use Symfony\Component\PropertyAccess\PropertyAccess;
Expand Down Expand Up @@ -153,19 +154,46 @@ function ($item) use ($skipPattern) {
}
);

$notExistingKeys = array_diff_key($pattern, $values);

$notExistingKeys = $this->findNotExistingKeys($pattern, $values);
if (count($notExistingKeys) > 0) {
$keyNames = array_keys($notExistingKeys);
$path = $this->formatFullPath($parentPath, $this->formatAccessPath($keyNames[0]));
$this->setMissingElementInError('value', $path);

return false;
}
}

return true;
}

/**
* Finds not existing keys
* Excludes keys with pattern which includes Optional Expander
*
* @param $pattern
* @param $values
* @return array
*/
private function findNotExistingKeys($pattern, $values)
{
$notExistingKeys = array_diff_key($pattern, $values);

return array_filter($notExistingKeys, function ($pattern) use ($values) {
if (is_array($pattern)) {
return !$this->match($values, $pattern);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@norzechowicz I'm not pretty sure that we must check if values match to pattern because it already hasn't array_diff_key($pattern, $values) and also because OptionalExpander works only with top level match

}

try {
$typePattern = $this->parser->parse($pattern);
} catch (Exception $e) {
return true;
}

return !$typePattern->hasExpander('optional');
});
}

/**
* @param $value
* @param $pattern
Expand Down
26 changes: 26 additions & 0 deletions src/Matcher/Pattern/Expander/Optional.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Coduo\PHPMatcher\Matcher\Pattern\Expander;

use Coduo\PHPMatcher\Matcher\Pattern\PatternExpander;

final class Optional implements PatternExpander
{
/**
* @param mixed $value
*
* @return boolean
*/
public function match($value)
{
return true;
}

/**
* @return string|null
*/
public function getError()
{
return null;
}
}
9 changes: 9 additions & 0 deletions src/Matcher/Pattern/Pattern.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,13 @@ public function matchExpanders($value);
* @return null|string
*/
public function getError();

/**
* Checks whether a Pattern has added Expander.
*
* @param string $expanderName The name of the expander
*
* @return bool true if the specified pattern has expander, false otherwise
*/
public function hasExpander(string $expanderName);
}
31 changes: 29 additions & 2 deletions src/Matcher/Pattern/TypePattern.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Coduo\PHPMatcher\Matcher\Pattern;

use Coduo\PHPMatcher\Parser\ExpanderInitializer;

final class TypePattern implements Pattern
{
/**
Expand All @@ -19,13 +21,20 @@ final class TypePattern implements Pattern
*/
private $error;

/**
* @var ExpanderInitializer
*/
private $expanderInitializer;

/**
* @param string $type
* @param ExpanderInitializer $expanderInitializer
*/
public function __construct($type)
public function __construct($type, ExpanderInitializer $expanderInitializer)
{
$this->type = $type;
$this->expanders = array();
$this->expanderInitializer = $expanderInitializer;
}

/**
Expand Down Expand Up @@ -69,10 +78,28 @@ public function matchExpanders($value)
}

/**
* @return null|string
* {@inheritdoc}
*/
public function getError()
{
return $this->error;
}

/**
* {@inheritdoc}
*/
public function hasExpander(string $expanderName)
{
foreach ($this->expanders as $expander) {
if (!$this->expanderInitializer->hasExpanderDefinition($expanderName)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait, why do we need to use expanderInitializer? Can't we check if expander deos not exists in $this->expanders field?

Copy link
Contributor Author

@teklakct teklakct Aug 1, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm afraid not. Until hasExpander checks if expander exist using its name (simple string - key in $expanderDefinitions list) but in $this->expanders there is a expander instances. I think using expnaderInitializer is better than using some kind of regexp to check if the class name matches with $expanderName. These also should be some rules name new expanders.

I have tried, without success, not to used expanderInitializer. Do you have a better idea?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case I would rather like to expose expanderName from expander instance than inject expander initializer here

Copy link
Contributor Author

@teklakct teklakct Aug 1, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 ok, I'll try with that

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any easiest way to expand expander name than add getName to expander interface PatternExpander::getName()?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding getName sounds good

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or you can add PatternExpander::is($name) instead of getName - that should fit better in this case

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we use constants for expander name , there is no need to use getName neither is($name) I'll revert changes to PatternExpander interface

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is because constant can't be a part of interface. Please add both is($name) and the constant

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this case, I propose to I add abstract Expander class with is($name). What do you think about that? Are there any disadvantages to using abstract expander?

continue;
}

if ($this->expanderInitializer->getExpanderDefinition($expanderName) === get_class($expander)) {
return true;
}
}

return false;
}
}
2 changes: 1 addition & 1 deletion src/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function hasValidSyntax($pattern)
public function parse($pattern)
{
$AST = $this->getAST($pattern);
$pattern = new Pattern\TypePattern((string) $AST->getType());
$pattern = new Pattern\TypePattern((string) $AST->getType(), $this->expanderInitializer);
foreach ($AST->getExpanders() as $expander) {
$pattern->addExpander($this->expanderInitializer->initialize($expander));
}
Expand Down
2 changes: 1 addition & 1 deletion src/Parser/ExpanderInitializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ final class ExpanderInitializer
"count" => "Coduo\\PHPMatcher\\Matcher\\Pattern\\Expander\\Count",
"contains" => "Coduo\\PHPMatcher\\Matcher\\Pattern\\Expander\\Contains",
"matchRegex" => "Coduo\\PHPMatcher\\Matcher\\Pattern\\Expander\\MatchRegex",

"optional" => "Coduo\\PHPMatcher\\Matcher\\Pattern\\Expander\\Optional",
"oneOf" => "Coduo\\PHPMatcher\\Matcher\\Pattern\\Expander\\OneOf"
);

Expand Down
30 changes: 30 additions & 0 deletions tests/Matcher/Pattern/Expander/OptionalTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Coduo\PHPMatcher\Tests\Matcher\Pattern\Expander;

use Coduo\PHPMatcher\Matcher\Pattern\Expander\Optional;

class OptionalTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider examplesProvider
*/
public function test_optional_expander_match($value, $expectedResult)
{
$expander = new Optional();
$this->assertEquals($expectedResult, $expander->match($value));
}

public static function examplesProvider()
{
return array(
array(array(), true),
array(array('data'), true),
array('', true),
array(0, true),
array(10.1, true),
array(null, true),
array('Lorem ipsum', true),
);
}
}
45 changes: 45 additions & 0 deletions tests/Matcher/Pattern/PatternTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Coduo\PHPMatcher\Tests\Matcher\Pattern;

use Coduo\PHPMatcher\Matcher\Pattern\Expander\IsEmail;
use Coduo\PHPMatcher\Matcher\Pattern\Expander\IsEmpty;
use Coduo\PHPMatcher\Matcher\Pattern\Expander\Optional;
use Coduo\PHPMatcher\Matcher\Pattern\Pattern;
use Coduo\PHPMatcher\Matcher\Pattern\TypePattern;
use Coduo\PHPMatcher\Parser\ExpanderInitializer;

class PatternTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Pattern
*/
private $pattern;

public function setUp()
{
$this->pattern = new TypePattern('dummy', new ExpanderInitializer());
$this->pattern->addExpander(new isEmail());
$this->pattern->addExpander(new isEmpty());
$this->pattern->addExpander(new Optional());
}

/**
* @dataProvider examplesProvider
*/
public function test_has_expander($expander, $expectedResult)
{
$this->assertEquals($expectedResult, $this->pattern->hasExpander($expander));
}

public static function examplesProvider()
{
return array(
array("isEmail", true),
array("isEmpty", true),
array("optional", true),
array("isUrl", false),
array("non existing expander", false),
);
}
}
3 changes: 2 additions & 1 deletion tests/Matcher/Pattern/RegexConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Coduo\PHPMatcher\Matcher\Pattern\TypePattern;
use Coduo\PHPMatcher\Matcher\Pattern\RegexConverter;
use Coduo\PHPMatcher\Parser\ExpanderInitializer;

class RegexConverterTest extends \PHPUnit\Framework\TestCase
{
Expand All @@ -22,6 +23,6 @@ public function setUp()
*/
public function test_convert_unknown_type()
{
$this->converter->toRegex(new TypePattern("not_a_type"));
$this->converter->toRegex(new TypePattern("not_a_type", new ExpanderInitializer()));
}
}
57 changes: 57 additions & 0 deletions tests/MatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,23 @@ public function jsonDataProvider()
"nextPage": "@string@"
}',
),
'excludes missing property from match for optional property' => array(
/** @lang JSON */
'{
"users":[],
"prevPage": "http:\/\/example.com\/api\/users\/1?limit=2",
"currPage": 2
}',
/** @lang JSON */
'{
"users":[
"@...@"
],
"prevPage": "@string@.optional()",
"nextPage": "@string@.optional()",
"currPage": "@integer@.optional()"
}',
),
);
}

Expand Down Expand Up @@ -208,6 +225,46 @@ public function test_matcher_with_xml()
</m:GetStockPrice>
</soap:Body>

</soap:Envelope>
XML;

$this->assertTrue($this->matcher->match($xml, $xmlPattern));
$this->assertTrue(PHPMatcher::match($xml, $xmlPattern));
}



public function test_matcher_with_xml_including_optional_node()
{
$xml = <<<XML
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
<m:StockValue>Any Value</m:StockValue>
</m:GetStockPrice>
</soap:Body>

</soap:Envelope>
XML;
$xmlPattern = <<<XML
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="@string@"
soap:encodingStyle="@string@">

<soap:Body xmlns:m="@string@">
<m:GetStockPrice>
<m:StockName>@string@.optional()</m:StockName>
<m:StockValue>@string@.optional()</m:StockValue>
<m:StockQty>@integer@.optional()</m:StockQty>
</m:GetStockPrice>
</soap:Body>

</soap:Envelope>
XML;

Expand Down