|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tatter\Assets\Test; |
| 4 | + |
| 5 | +use CodeIgniter\Publisher\Publisher; |
| 6 | +use org\bovigo\vfs\vfsStream; |
| 7 | +use org\bovigo\vfs\vfsStreamDirectory; |
| 8 | +use Tatter\Assets\Asset; |
| 9 | +use Tatter\Assets\Config\Assets as AssetsConfig; |
| 10 | + |
| 11 | +/** |
| 12 | + * Asset Test Trait |
| 13 | + * |
| 14 | + * Trait to set up a VFS instance for testing |
| 15 | + * Assets, Bundles, and Publishers. |
| 16 | + */ |
| 17 | +trait AssetsTestTrait |
| 18 | +{ |
| 19 | + /** |
| 20 | + * Virtual workspace |
| 21 | + * |
| 22 | + * @var vfsStreamDirectory|null |
| 23 | + */ |
| 24 | + protected $root; |
| 25 | + |
| 26 | + /** |
| 27 | + * @var AssetsConfig |
| 28 | + */ |
| 29 | + protected $config; |
| 30 | + |
| 31 | + /** |
| 32 | + * Whether the publishers have been run. |
| 33 | + * |
| 34 | + * @var bool |
| 35 | + */ |
| 36 | + private $published = false; |
| 37 | + |
| 38 | + /** |
| 39 | + * Creates the VFS (if necessary) and updates the Assets config. |
| 40 | + */ |
| 41 | + protected function setUpAssetsTestTrait(): void |
| 42 | + { |
| 43 | + if ($this->root === null) { |
| 44 | + $this->root = vfsStream::setup('root'); |
| 45 | + } |
| 46 | + |
| 47 | + // Create the config |
| 48 | + $this->config = config('Assets'); |
| 49 | + $this->config->directory = $this->root->url() . DIRECTORY_SEPARATOR; |
| 50 | + $this->config->useTimestamps = false; // These make testing much harder |
| 51 | + |
| 52 | + Asset::useConfig($this->config); |
| 53 | + |
| 54 | + // Add VFS as an allowed Publisher directory |
| 55 | + config('Publisher')->restrictions[$this->config->directory] = '*'; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Resets the VFS if $refreshVfs is truthy. |
| 60 | + */ |
| 61 | + protected function tearDownAssetsTestTrait(): void |
| 62 | + { |
| 63 | + if (! empty($this->refreshVfs)) { |
| 64 | + $this->root = null; |
| 65 | + $this->published = false; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Publishes all files once so they are |
| 71 | + * available for bundles. |
| 72 | + */ |
| 73 | + protected function publishAll(): void |
| 74 | + { |
| 75 | + if ($this->published) { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + foreach (Publisher::discover() as $publisher) { |
| 80 | + $publisher->publish(); |
| 81 | + } |
| 82 | + |
| 83 | + $this->published = true; |
| 84 | + } |
| 85 | +} |
0 commit comments