|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Cache; |
| 4 | + |
| 5 | +use FilesystemIterator; |
| 6 | +use Override; |
| 7 | +use PHPStan\Internal\DirectoryCreatorException; |
| 8 | +use PHPStan\Testing\PHPStanTestCase; |
| 9 | +use RecursiveDirectoryIterator; |
| 10 | +use RecursiveIteratorIterator; |
| 11 | +use function is_dir; |
| 12 | +use function rmdir; |
| 13 | +use function sys_get_temp_dir; |
| 14 | +use function uniqid; |
| 15 | +use function unlink; |
| 16 | + |
| 17 | +final class FileCacheStorageTest extends PHPStanTestCase |
| 18 | +{ |
| 19 | + |
| 20 | + private string $directory; |
| 21 | + |
| 22 | + protected function setUp(): void |
| 23 | + { |
| 24 | + parent::setUp(); |
| 25 | + |
| 26 | + $this->directory = sys_get_temp_dir() . '/' . uniqid('phpstan-cache-', true); |
| 27 | + } |
| 28 | + |
| 29 | + #[Override] |
| 30 | + protected function tearDown(): void |
| 31 | + { |
| 32 | + parent::tearDown(); |
| 33 | + |
| 34 | + if (!is_dir($this->directory)) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + $files = new RecursiveIteratorIterator( |
| 39 | + new RecursiveDirectoryIterator($this->directory, FilesystemIterator::SKIP_DOTS), |
| 40 | + RecursiveIteratorIterator::CHILD_FIRST, |
| 41 | + ); |
| 42 | + foreach ($files as $file) { |
| 43 | + if ($file->isDir()) { |
| 44 | + rmdir($file->getPathname()); |
| 45 | + continue; |
| 46 | + } |
| 47 | + |
| 48 | + unlink($file->getPathname()); |
| 49 | + } |
| 50 | + |
| 51 | + rmdir($this->directory); |
| 52 | + } |
| 53 | + |
| 54 | + public function testMissingEntry(): void |
| 55 | + { |
| 56 | + $storage = new FileCacheStorage($this->directory); |
| 57 | + |
| 58 | + $this->assertNull($storage->load('never-written', 'v1')); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @throws DirectoryCreatorException |
| 63 | + */ |
| 64 | + public function testEntrySavedAfterAMissIsLoadedBack(): void |
| 65 | + { |
| 66 | + $storage = new FileCacheStorage($this->directory); |
| 67 | + |
| 68 | + // the miss comes first on purpose: load() stat()s the file to avoid a |
| 69 | + // failing include(), and PHP's stat cache must not answer the second |
| 70 | + // load() with what the first one saw |
| 71 | + $this->assertNull($storage->load('key', 'v1')); |
| 72 | + $storage->save('key', 'v1', ['data' => 1]); |
| 73 | + |
| 74 | + $this->assertSame(['data' => 1], $storage->load('key', 'v1')); |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * @throws DirectoryCreatorException |
| 79 | + */ |
| 80 | + public function testEntryWithDifferentVariableKey(): void |
| 81 | + { |
| 82 | + $storage = new FileCacheStorage($this->directory); |
| 83 | + $storage->save('key', 'v1', ['data' => 1]); |
| 84 | + |
| 85 | + $this->assertNull($storage->load('key', 'v2')); |
| 86 | + $this->assertSame(['data' => 1], $storage->load('key', 'v1')); |
| 87 | + } |
| 88 | + |
| 89 | +} |
0 commit comments