Updated to Drupal 8.5. Core Media not yet in use.
[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\Component\Utility\Random;
7 use org\bovigo\vfs\vfsStream;
8 use PHPUnit\Framework\TestCase;
9
10 /**
11  * Base test for PHP storages.
12  */
13 abstract class PhpStorageTestBase extends TestCase {
14
15   /**
16    * A unique per test class directory path to test php storage.
17    *
18    * @var string
19    */
20   protected $directory;
21
22   /**
23    * {@inheritdoc}
24    */
25   protected function setUp() {
26     parent::setUp();
27     vfsStream::setup('exampleDir');
28     $this->directory = vfsStream::url('exampleDir');
29   }
30
31   /**
32    * Assert that a PHP storage's load/save/delete operations work.
33    */
34   public function assertCRUD($php) {
35     // Random generator.
36     $random_generator = new Random();
37
38     $name = $random_generator->name(8, TRUE) . '/' . $random_generator->name(8, TRUE) . '.php';
39
40     // Find a global that doesn't exist.
41     do {
42       $random = mt_rand(10000, 100000);
43     } while (isset($GLOBALS[$random]));
44
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');
49     $php->load($name);
50     $this->assertTrue($GLOBALS[$random], 'File saved correctly with correct value');
51
52     // Run additional asserts.
53     $this->additionalAssertCRUD($php, $name);
54
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');
58
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');
62
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]);
67   }
68
69   /**
70    * Additional asserts to be run.
71    *
72    * @param \Drupal\Component\PhpStorage\PhpStorageInterface $php
73    *   The PHP storage object.
74    * @param string $name
75    *   The name of an object. It should exist in the storage.
76    */
77   protected function additionalAssertCRUD(PhpStorageInterface $php, $name) {
78     // By default do not do any additional asserts. This is a way of extending
79     // tests in contrib.
80   }
81
82 }