View source
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\file\Entity\File;
class SaveTest extends FileManagedUnitTestBase {
public function testFileSave() {
$file = File::create([
'uid' => 1,
'filename' => 'druplicon.txt',
'uri' => 'public://druplicon.txt',
'filemime' => 'text/plain',
]);
$file
->setPermanent();
file_put_contents($file
->getFileUri(), 'hello world');
$file
->save();
$this
->assertFileHooksCalled([
'insert',
]);
$this
->assertGreaterThan(0, $file
->id());
$loaded_file = File::load($file
->id());
$this
->assertNotNull($loaded_file, 'Record exists in the database.');
$this
->assertEquals($file
->isPermanent(), $loaded_file
->isPermanent(), 'Status was saved correctly.');
$this
->assertEquals(filesize($file
->getFileUri()), $file
->getSize(), 'File size was set correctly.');
$this
->assertGreaterThan(1, $file
->getChangedTime());
$this
->assertEquals('en', $loaded_file->langcode->value, 'Langcode was defaulted correctly.');
file_test_reset();
$file->status->value = 7;
$file
->save();
$this
->assertFileHooksCalled([
'load',
'update',
]);
$this
->assertEquals($file
->id(), $file
->id(), 'The file ID of an existing file is not changed when updating the database.');
$loaded_file = File::load($file
->id());
$this
->assertGreaterThanOrEqual($file
->getChangedTime(), $loaded_file
->getChangedTime());
$this
->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
$this
->assertEquals($file
->isPermanent(), $loaded_file
->isPermanent(), 'Status was saved correctly.');
$this
->assertEquals('en', $loaded_file->langcode->value, 'Langcode was saved correctly.');
$uppercase_values = [
'uid' => 1,
'filename' => 'DRUPLICON.txt',
'uri' => 'public://DRUPLICON.txt',
'filemime' => 'text/plain',
];
$file
->setPermanent();
$uppercase_file = File::create($uppercase_values);
file_put_contents($uppercase_file
->getFileUri(), 'hello world');
$violations = $uppercase_file
->validate();
$this
->assertCount(0, $violations, 'No violations when adding an URI with an existing filename in upper case.');
$uppercase_file
->save();
$uppercase_file_duplicate = File::create($uppercase_values);
file_put_contents($uppercase_file_duplicate
->getFileUri(), 'hello world');
$violations = $uppercase_file_duplicate
->validate();
$this
->assertCount(1, $violations);
$this
->assertEquals(t('The file %value already exists. Enter a unique file URI.', [
'%value' => $uppercase_file_duplicate
->getFileUri(),
]), $violations[0]
->getMessage());
$fids = \Drupal::entityQuery('file')
->accessCheck(FALSE)
->condition('uri', $uppercase_file
->getFileUri())
->execute();
$this
->assertCount(1, $fids);
$this
->assertEquals([
$uppercase_file
->id() => $uppercase_file
->id(),
], $fids);
$file = File::create([
'uid' => 1,
'filename' => 'no-druplicon.txt',
'uri' => 'public://no-druplicon.txt',
'filemime' => 'text/plain',
]);
$file
->setPermanent();
file_put_contents($file
->getFileUri(), '');
$file
->save();
$this
->assertSame(0, $file
->getSize());
}
}