View source
<?php
namespace Drupal\Tests\file\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\file\Entity\File;
class FileFieldPathTest extends FileFieldTestBase {
protected $defaultTheme = 'stark';
public function testUploadPath() {
$node_storage = $this->container
->get('entity_type.manager')
->getStorage('node');
$field_name = strtolower($this
->randomMachineName());
$type_name = 'article';
$this
->createFileField($field_name, 'node', $type_name);
$test_file = $this
->getTestFile('text');
$nid = $this
->uploadNodeFile($test_file, $field_name, $type_name);
$node_storage
->resetCache([
$nid,
]);
$node = $node_storage
->load($nid);
$node_file = $node->{$field_name}->entity;
$date_formatter = $this->container
->get('date.formatter');
$expected_filename = 'public://' . $date_formatter
->format(REQUEST_TIME, 'custom', 'Y') . '-' . $date_formatter
->format(REQUEST_TIME, 'custom', 'm') . '/' . $test_file
->getFilename();
$this
->assertPathMatch($expected_filename, $node_file
->getFileUri(), new FormattableMarkup('The file %file was uploaded to the correct path.', [
'%file' => $node_file
->getFileUri(),
]));
$this
->updateFileField($field_name, $type_name, [
'file_directory' => 'foo/bar/baz',
]);
$nid = $this
->uploadNodeFile($test_file, $field_name, $type_name);
$node_storage
->resetCache([
$nid,
]);
$node = $node_storage
->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
$this
->assertPathMatch('public://foo/bar/baz/' . $test_file
->getFilename(), $node_file
->getFileUri(), new FormattableMarkup('The file %file was uploaded to the correct path.', [
'%file' => $node_file
->getFileUri(),
]));
$this
->updateFileField($field_name, $type_name, [
'file_directory' => '[current-user:uid]/[current-user:name]',
]);
$nid = $this
->uploadNodeFile($test_file, $field_name, $type_name);
$node_storage
->resetCache([
$nid,
]);
$node = $node_storage
->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
$data = [
'user' => $this->adminUser,
];
$subdirectory = \Drupal::token()
->replace('[user:uid]/[user:name]', $data);
$this
->assertPathMatch('public://' . $subdirectory . '/' . $test_file
->getFilename(), $node_file
->getFileUri(), new FormattableMarkup('The file %file was uploaded to the correct path with token replacements.', [
'%file' => $node_file
->getFileUri(),
]));
}
public function assertPathMatch($expected_path, $actual_path, $message) {
$pos = strrpos($expected_path, '.');
$base_path = substr($expected_path, 0, $pos);
$extension = substr($expected_path, $pos + 1);
$result = (bool) preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\\.' . preg_quote($extension, '/') . '/', $actual_path);
$this
->assertTrue($result, $message);
}
}