3 namespace Drupal\Tests\Component\PhpStorage;
5 use Drupal\Component\PhpStorage\PhpStorageInterface;
6 use Drupal\Component\Utility\Random;
7 use org\bovigo\vfs\vfsStream;
8 use PHPUnit\Framework\TestCase;
11 * Base test for PHP storages.
13 abstract class PhpStorageTestBase extends TestCase {
16 * A unique per test class directory path to test php storage.
25 protected function setUp() {
27 vfsStream::setup('exampleDir');
28 $this->directory = vfsStream::url('exampleDir');
32 * Assert that a PHP storage's load/save/delete operations work.
34 public function assertCRUD($php) {
36 $random_generator = new Random();
38 $name = $random_generator->name(8, TRUE) . '/' . $random_generator->name(8, TRUE) . '.php';
40 // Find a global that doesn't exist.
42 $random = mt_rand(10000, 100000);
43 } while (isset($GLOBALS[$random]));
45 // Write out a PHP file and ensure it's successfully loaded.
46 $code = "<?php\n\$GLOBALS[$random] = TRUE;";
47 $success = $php->save($name, $code);
48 $this->assertTrue($success, 'Saved php file');
50 $this->assertTrue($GLOBALS[$random], 'File saved correctly with correct value');
52 // Run additional asserts.
53 $this->additionalAssertCRUD($php, $name);
55 // If the file was successfully loaded, it must also exist, but ensure the
56 // exists() method returns that correctly.
57 $this->assertTrue($php->exists($name), 'Exists works correctly');
59 // Delete the file, and then ensure exists() returns FALSE.
60 $this->assertTrue($php->delete($name), 'Delete succeeded');
61 $this->assertFalse($php->exists($name), 'Delete deleted file');
63 // Ensure delete() can be called on a non-existing file. It should return
64 // FALSE, but not trigger errors.
65 $this->assertFalse($php->delete($name), 'Delete fails on missing file');
66 unset($GLOBALS[$random]);
70 * Additional asserts to be run.
72 * @param \Drupal\Component\PhpStorage\PhpStorageInterface $php
73 * The PHP storage object.
75 * The name of an object. It should exist in the storage.
77 protected function additionalAssertCRUD(PhpStorageInterface $php, $name) {
78 // By default do not do any additional asserts. This is a way of extending