Add ability to load filters from partials

Issue #12
This commit is contained in:
Oliver Davies 2018-08-21 09:14:22 +01:00
parent bac720c679
commit d8b10d8f49
4 changed files with 101 additions and 0 deletions

43
src/Service/Partials.php Normal file
View file

@ -0,0 +1,43 @@
<?php
namespace Opdavies\GmailFilterBuilder\Service;
/**
* Load and combine partials from multiple files.
*/
class Partials
{
/**
* Load partials from a directory.
*
* @param string $directoryName The name of the directory containing the partials.
*
* @return array The loaded filters.
*/
public static function load($directoryName = 'filters')
{
$files = (new static())->getFilePattern($directoryName);
return collect(glob($files))
->map(function (string $filename) {
return include $filename;
})
->flatten(1)
->all();
}
/**
* Build the glob pattern to load partials from the directory.
*
* Assumes it is always relative to the current directory, and that the
* filters are always in files with a .php extension.
*
* @param string $directoryName The name of the directory.
*
* @return string The full path.
*/
protected function getFilePattern(string $directoryName)
{
return __DIR__ . DIRECTORY_SEPARATOR . $directoryName . DIRECTORY_SEPARATOR . '/*.php';
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Opdavies\Tests\GmailFilterBuilder\Service;
use Opdavies\GmailFilterBuilder\Model\Filter;
use Opdavies\GmailFilterBuilder\Service\Partials;
use PHPUnit\Framework\TestCase;
class PartialsTest extends TestCase
{
/**
* Test loading partials from multiple partial files.
*/
public function testLoadingFiltersFromPartials()
{
/** @var Filter[] $filters */
$filters = FakePartials::load('filters');
$this->assertCount(3, $filters);
$this->assertSame('foo@example.com', $filters[0]->getProperties()['from'][0]);
$this->assertSame('bar@example.com', $filters[1]->getProperties()['from'][0]);
$this->assertSame('baz@example.com', $filters[2]->getProperties()['from'][0]);
}
}
class FakePartials extends Partials
{
/**
* {@inheritdoc}
*/
protected function getFilePattern(string $directoryName)
{
return __DIR__ . '/../../stubs/filters/*.php';
}
}

13
tests/stubs/filters/a.php Normal file
View file

@ -0,0 +1,13 @@
<?php
use Opdavies\GmailFilterBuilder\Model\Filter;
return [
Filter::create()
->from('foo@example.com')
->labelAndArchive('Test'),
Filter::create()
->from('bar@example.com')
->labelAndArchive('Test 2'),
];

View file

@ -0,0 +1,9 @@
<?php
use Opdavies\GmailFilterBuilder\Model\Filter;
return [
Filter::create()
->from('baz@example.com')
->labelAndArchive('Test 3'),
];