Skip to content

Instantly share code, notes, and snippets.

@mayoz
Last active September 23, 2020 16:25
Show Gist options
  • Save mayoz/17a96a87605bd4e615613da031e16699 to your computer and use it in GitHub Desktop.
Save mayoz/17a96a87605bd4e615613da031e16699 to your computer and use it in GitHub Desktop.
Refactor normalizer to cleaner implementation
<?php
namespace App\Normalizer;
class CompositeNormalizer implements Normalizer
{
protected $normalizers;
/**
* @param Normalizer[] $normalizers
*/
public function __construct($normalizers)
{
$this->normalizers = $normalizers;
}
/**
* @param array[] $segments
* @return array[]
*/
public function normalize($segments): array;
{
foreach ($this->normalizers as $normalizer) {
$segments = (new $normalizer)->normalize($segments)
}
return $segments;
}
}
<?php
namespace App\Normalizer;
class ConditionNormalizer implements Normalizer
{
const CONDITIONS = [
'foo',
'bar',
'baz',
];
/**
* @param array[] $segments
* @return array[]
*/
public function normalize($segments): array
{
foreach ($segments as $segment) {
if ($this->check($segment) {
$segment['conditionLogic'] = 'or';
}
}
return $segments;
}
/**
* @param array $segment
* @return bool
*/
protected function check($segment): bool
{
return !empty($segment['conditionList'])
&& in_array($segment['conditionList'][0]->id, self::CONDITIONS)) {
}
}
<?php
namespace App\Normalizer;
class DateRangeNormalizer implements Normalizer
{
/**
* @param array[] $segments
* @return array[]
*/
public function normalize($segments): array;
{
foreach ($segments as $segment) {
// run your logic, manipulate $segment variable if need
}
return $segments;
}
}
<?php
namespace App\Normalizer;
interface Normalizer
{
/**
* @param array[] $segments
* @return array[]
*/
public function normalize($segments): array;
}
@mayoz
Copy link
Author

mayoz commented Mar 17, 2020

Usage example:

$normalizers = [
    ConditionNormalizer::class,
    DateRangeNormalizer::class,
    // ...
];

$normlizedData = (new CompositeNormalizer($normalizers))->normalize($data);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment