Created
November 23, 2016 16:09
-
-
Save yceruto/90b1ac46c8e33d51ec21079725949f77 to your computer and use it in GitHub Desktop.
Custom groups exclusion strategy with strict option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Serializer\Exclusion; | |
use JMS\Serializer\Context; | |
use JMS\Serializer\Exclusion\GroupsExclusionStrategy; | |
use JMS\Serializer\Metadata\PropertyMetadata; | |
class CustomGroupsExclusionStrategy extends GroupsExclusionStrategy | |
{ | |
private $groups = array(); | |
private $strict; | |
public function __construct(array $groups, $strict = false) | |
{ | |
if (empty($groups)) { | |
$groups = array(self::DEFAULT_GROUP); | |
} | |
$this->groups = $groups; | |
$this->strict = $strict; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext) | |
{ | |
$groups = $this->getGroupsFor($navigatorContext); | |
if (!$property->groups) { | |
return !in_array(self::DEFAULT_GROUP, $groups); | |
} | |
return $this->strict | |
? $this->shouldSkipUsingStrictGroups($property, $groups) | |
: $this->shouldSkipUsingGroups($property, $groups); | |
} | |
private function shouldSkipUsingGroups(PropertyMetadata $property, $groups) | |
{ | |
foreach ($property->groups as $group) { | |
if (in_array($group, $groups)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
private function shouldSkipUsingStrictGroups(PropertyMetadata $property, $groups) | |
{ | |
foreach ($groups as $group) { | |
if (!in_array($group, $property->groups)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
private function getGroupsFor(Context $navigatorContext) | |
{ | |
$paths = $navigatorContext->getCurrentPath(); | |
$groups = $this->groups; | |
foreach ($paths as $index => $path) { | |
if (!array_key_exists($path, $groups)) { | |
if ($index > 0) { | |
$groups = array('Default'); | |
} | |
break; | |
} | |
$groups = $groups[$path]; | |
} | |
return $groups; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment