2ed15bbfe29bb14d8014f129cef79224ec7485e9
[yaffs-website] / web / core / tests / Drupal / Tests / Component / Plugin / Discovery / DiscoveryCachedTraitTest.php
1 <?php
2
3 namespace Drupal\Tests\Component\Plugin\Discovery;
4
5 use PHPUnit\Framework\TestCase;
6
7 /**
8  * @coversDefaultClass \Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait
9  * @uses \Drupal\Component\Plugin\Discovery\DiscoveryTrait
10  * @group Plugin
11  */
12 class DiscoveryCachedTraitTest extends TestCase {
13
14   /**
15    * Data provider for testGetDefinition().
16    *
17    * @return array
18    *   - Expected result from getDefinition().
19    *   - Cached definitions to be placed into self::$definitions
20    *   - Definitions to be returned by getDefinitions().
21    *   - Plugin name to query for.
22    */
23   public function providerGetDefinition() {
24     return [
25       ['definition', [], ['plugin_name' => 'definition'], 'plugin_name'],
26       ['definition', ['plugin_name' => 'definition'], [], 'plugin_name'],
27       [NULL, ['plugin_name' => 'definition'], [], 'bad_plugin_name'],
28     ];
29   }
30
31   /**
32    * @covers ::getDefinition
33    * @dataProvider providerGetDefinition
34    */
35   public function testGetDefinition($expected, $cached_definitions, $get_definitions, $plugin_id) {
36     // Mock a DiscoveryCachedTrait.
37     $trait = $this->getMockForTrait('Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait');
38     $reflection_definitions = new \ReflectionProperty($trait, 'definitions');
39     $reflection_definitions->setAccessible(TRUE);
40     // getDefinition() needs the ::$definitions property to be set in one of two
41     // ways: 1) As existing cached data, or 2) as a side-effect of calling
42     // getDefinitions().
43     // If there are no cached definitions, then we have to fake the side-effect
44     // of getDefinitions().
45     if (count($cached_definitions) < 1) {
46       $trait->expects($this->once())
47         ->method('getDefinitions')
48         // Use a callback method, so we can perform the side-effects.
49         ->willReturnCallback(function () use ($reflection_definitions, $trait, $get_definitions) {
50           $reflection_definitions->setValue($trait, $get_definitions);
51           return $get_definitions;
52         });
53     }
54     else {
55       // Put $cached_definitions into our mocked ::$definitions.
56       $reflection_definitions->setValue($trait, $cached_definitions);
57     }
58     // Call getDefinition(), with $exception_on_invalid always FALSE.
59     $this->assertSame(
60       $expected,
61       $trait->getDefinition($plugin_id, FALSE)
62     );
63   }
64
65 }