This commit is contained in:
Oliver Davies 2019-04-10 23:12:03 +01:00
parent 09cf724f70
commit 3941c5abd7
4 changed files with 68 additions and 12 deletions

View file

@ -25,7 +25,8 @@
},
"autoload": {
"psr-4": {
"Opdavies\\GmailFilterBuilder\\": "src/"
"Opdavies\\GmailFilterBuilder\\": "src/",
"Spatie\\CollectionMacros\\Macros\\": "src/Collection/Macros/"
}
},
"autoload-dev": {

View file

@ -0,0 +1,32 @@
<?php
namespace Spatie\CollectionMacros\Macros;
use Illuminate\Support\Collection;
/**
* Get the consecutive values in the collection defined by the given chunk size.
*
* @param int $chunkSize
* @param bool $preserveKeys
*
* @mixin \Illuminate\Support\Collection
*
* @return \Illuminate\Support\Collection
*/
class EachCons
{
public function __invoke()
{
return function (int $chunkSize, bool $preserveKeys = false): Collection {
$size = $this->count() - $chunkSize + 1;
$result = collect(range(0, $size))->reduce(function ($result, $index) use ($chunkSize, $preserveKeys) {
$next = $this->slice($index, $chunkSize);
return $next->count() === $chunkSize ? $result->push($preserveKeys ? $next : $next->values()) : $result;
}, new static([]));
return $preserveKeys ? $result : $result->values();
};
}
}

View file

@ -2,6 +2,7 @@
namespace Opdavies\GmailFilterBuilder\Model;
use Spatie\CollectionMacros\Macros\EachCons;
use Tightenco\Collect\Support\Collection;
class FilterGroup
@ -44,4 +45,30 @@ class FilterGroup
{
return $this->filters->map->getConditions();
}
public function getUpdatedConditions(): Collection
{
Collection::macro('eachCons', ((new EachCons())->__invoke()));
$conditions = clone $this->getConditions();
return $conditions->eachCons(2)->map(function ($filter) {
list($previous, $current) = $filter;
return $previous->zip($current)->map(function (Collection $a): array {
// dump(['a' => $a]);
if ($a[1] === null) {
return [$a[0]];
}
if ($a[0] == $a[1]) {
return [$a[0]];
}
return [$a[0], "!{$a[1]}"];
})->flatten(1);
});
}
}

View file

@ -89,20 +89,16 @@ class OtherwiseHasTest extends TestCase
->trash()
)->otherwise(
Filter::create()
->has('to:me@example.com subject:Baz')
->has('to:me@example.com')
->trash()
);
$this->assertSame('subject:Foo', $filters->all()->get(0)->getConditions()->get(1));
$expected = [
['to:me@example.com', 'subject:Foo'],
['to:me@example.com', '!subject:Foo', 'subject:Bar'],
['to:me@example.com', '!subject:Foo', '!subject:Bar'],
];
// The subject condition from the first filter should be present but
// negated.
$this->assertSame('!subject:Foo', $filters->all()->get(1)->getConditions()->get(1));
// Both subject conditions from both previous filters should be present
// but negated.
// $this->assertSame('!subject:[Foo|Bar]', $filters->all()->get(2)->getConditions()->get(1));
$this->assertSame('!subject:Foo', $filters->all()->get(2)->getConditions()->get(1));
$this->assertSame('!subject:Bar', $filters->all()->get(2)->getConditions()->get(2));
$this->assertSame($expected, $filters->getUpdatedConditions()->toArray());
}
}