DiscoveryCachedTraitTest.php 2.3 KB

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