FixtureTrait.php in Mini site 8
File
tests/src/Traits/FixtureTrait.php
View source
<?php
namespace Drupal\Tests\minisite\Traits;
use Symfony\Component\Filesystem\Filesystem;
trait FixtureTrait {
protected $fixtureDir;
protected function fixtureSetUp() {
$fs = new Filesystem();
$this->fixtureDir = sys_get_temp_dir() . \DIRECTORY_SEPARATOR . uniqid();
$fs
->mkdir($this->fixtureDir);
}
protected function fixtureTearDown() {
$fs = new Filesystem();
if ($fs
->exists($this->fixtureDir)) {
$fs
->remove($this->fixtureDir);
}
$this->fixtureDir = NULL;
}
public function fixtureCreateFiles(array $files) {
$paths = [];
$dirs = [];
foreach ($files as $name => $value) {
if (is_int($name)) {
$path = $this->fixtureDir . \DIRECTORY_SEPARATOR . $value;
$dirs[] = $path;
$paths[$path] = $value;
unset($files[$name]);
}
}
$fs = new Filesystem();
$fs
->mkdir($dirs);
foreach ($files as $name => $content) {
$path = $this->fixtureDir . \DIRECTORY_SEPARATOR . $name;
$fs
->dumpFile($path, $content);
$paths[$path] = $name;
}
return $paths;
}
public function fixtureCreateFile($filename, $content = '') {
$created_files = $this
->fixtureCreateFiles([
$filename => $content,
]);
$created_file = key($created_files);
return $created_file;
}
public function fixtureCreateArchive(array $files, $type = 'zip', $filename = NULL) {
$filename = empty($filename) ? uniqid() : $filename;
$filename = basename($filename, '.' . $type) . '.' . $type;
$file_path = $this->fixtureDir . \DIRECTORY_SEPARATOR . uniqid() . \DIRECTORY_SEPARATOR . $filename;
$fs = new Filesystem();
$fs
->mkdir(dirname($file_path));
switch ($type) {
case 'zip':
$archive = new \ZipArchive();
if ($archive
->open($file_path, \ZipArchive::CREATE) !== TRUE) {
throw new \RuntimeException(sprintf('Cannot open file "%s"', $file_path));
}
break;
default:
throw new \RuntimeException(sprintf('Unsupported archive type "%s" provided.', $type));
}
$files = $this
->fixtureCreateFiles($files);
foreach ($files as $absolute_path => $path) {
if (is_dir($absolute_path)) {
$archive
->addEmptyDir($path);
}
else {
$archive
->addFile($absolute_path, $path);
}
}
$archive
->close();
return $file_path;
}
public function fixtureHtmlPage() {
$content = implode('<br/>', func_get_args());
$html = <<<HEREDOC
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{<span class="php-variable">$content</span>}
</body>
</html>
HEREDOC;
return $html;
}
public function fixtureLink($text, $url) {
return "<a href=\"{$url}\">{$text}</a>";
}
public function getFixtureFileDir() {
return __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'fixtures';
}
}