ServiceTestTrait.php in Purge 8.3
File
tests/src/Traits/ServiceTestTrait.php
View source
<?php
namespace Drupal\Tests\purge\Traits;
use Drupal\purge\ServiceBase;
use Drupal\purge\ServiceInterface;
trait ServiceTestTrait {
protected $serviceId;
protected $service;
public function setUp($switch_to_memory_queue = TRUE) : void {
parent::setUp($switch_to_memory_queue);
$this
->initializeService();
}
protected function initializeService($variable = 'service', $service = NULL) : void {
if (is_null($this->{$variable})) {
if (is_null($service)) {
$this->{$variable} = $this->container
->get($this->serviceId);
}
else {
$this->{$variable} = $this->container
->get($service);
}
}
if ($this->{$variable} instanceof ServiceInterface) {
$this->{$variable}
->reload();
}
}
public function testCodeContract() : void {
$this
->assertTrue($this->service instanceof ServiceInterface);
$this
->assertTrue($this->service instanceof ServiceBase);
}
public function assertIterator(array $expected_plugins, $type = NULL) : void {
$this
->assertTrue($this->service instanceof \Iterator);
$items = 0;
foreach ($this->service as $instance) {
if ($type) {
$this
->assertTrue($instance instanceof $type, var_export($instance
->getPluginId(), TRUE));
}
$items++;
}
$this
->assertEquals(count($expected_plugins), $items);
$this
->assertFalse($this->service
->current(), '::current returns FALSE');
$this
->assertFalse($this->service
->valid(), '::valid returns FALSE');
$this
->assertNull($this->service
->rewind(), '::rewind returns NULL');
$count_expected_plugins = count($expected_plugins);
for ($i = 0; $i < $count_expected_plugins; $i++) {
$this
->assertTrue($this->service
->valid(), '$this->service->valid() returns TRUE');
$k = array_search($this->service
->current()
->getPluginId(), $expected_plugins);
$this
->assertTrue(is_int($k) && isset($expected_plugins[$k]), 'is_int($k) && isset($expected_plugins[$k]) returns TRUE');
unset($expected_plugins[$k]);
$this
->assertNull($this->service
->next(), '$this->service->next() returns NULL');
}
$this
->assertTrue(empty($expected_plugins));
}
}