Version 1
[yaffs-website] / web / core / tests / Drupal / Tests / Component / PhpStorage / PhpStorageTestBase.php
1 <?php
2
3 namespace Drupal\Tests\Component\PhpStorage;
4
5 use Drupal\Component\PhpStorage\PhpStorageInterface;
6 use Drupal\Tests\UnitTestCase;
7 use org\bovigo\vfs\vfsStream;
8
9 /**
10  * Base test for PHP storages.
11  */
12 abstract class PhpStorageTestBase extends UnitTestCase {
13
14   /**
15    * A unique per test class directory path to test php storage.
16    *
17    * @var string
18    */
19   protected $directory;
20
21   /**
22    * {@inheritdoc}
23    */
24   protected function setUp() {
25     parent::setUp();
26     vfsStream::setup('exampleDir');
27     $this->directory = vfsStream::url('exampleDir');
28   }
29
30   /**
31    * Assert that a PHP storage's load/save/delete operations work.
32    */
33   public function assertCRUD($php) {
34     $name = $this->randomMachineName() . '/' . $this->randomMachineName() . '.php';
35
36     // Find a global that doesn't exist.
37     do {
38       $random = mt_rand(10000, 100000);
39     } while (isset($GLOBALS[$random]));
40
41     // Write out a PHP file and ensure it's successfully loaded.
42     $code = "<?php\n\$GLOBALS[$random] = TRUE;";
43     $success = $php->save($name, $code);
44     $this->assertTrue($success, 'Saved php file');
45     $php->load($name);
46     $this->assertTrue($GLOBALS[$random], 'File saved correctly with correct value');
47
48     // Run additional asserts.
49     $this->additionalAssertCRUD($php, $name);
50
51     // If the file was successfully loaded, it must also exist, but ensure the
52     // exists() method returns that correctly.
53     $this->assertTrue($php->exists($name), 'Exists works correctly');
54
55     // Delete the file, and then ensure exists() returns FALSE.
56     $this->assertTrue($php->delete($name), 'Delete succeeded');
57     $this->assertFalse($php->exists($name), 'Delete deleted file');
58
59     // Ensure delete() can be called on a non-existing file. It should return
60     // FALSE, but not trigger errors.
61     $this->assertFalse($php->delete($name), 'Delete fails on missing file');
62     unset($GLOBALS[$random]);
63   }
64
65   /**
66    * Additional asserts to be run.
67    *
68    * @param \Drupal\Component\PhpStorage\PhpStorageInterface $php
69    *   The PHP storage object.
70    * @param string $name
71    *   The name of an object. It should exist in the storage.
72    */
73   protected function additionalAssertCRUD(PhpStorageInterface $php, $name) {
74     // By default do not do any additional asserts. This is a way of extending
75     // tests in contrib.
76   }
77
78 }