View source
<?php
namespace Drupal\Tests\file_link\Kernel;
use Drupal\Core\Site\Settings;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
class FileLinkValidationTest extends KernelTestBase {
protected static $modules = [
'file_link',
'file_link_test',
'entity_test',
'link',
'field',
'user',
'system',
];
protected $entity;
protected function setUp() {
parent::setUp();
$this
->installConfig([
'file_link_test',
]);
$this
->installEntitySchema('entity_test');
$this->entity = EntityTest::create([
'name' => 'Foo',
'type' => 'article',
]);
$settings = Settings::getAll();
$settings['file_link.follow_redirect_on_validate'] = FALSE;
new Settings($settings);
}
public function testWithExtension() {
$this->entity
->set('url_with_extension', [
'uri' => static::getFullUrl(''),
]);
$violations = $this->entity
->get('url_with_extension')
->validate();
$this
->assertSame(static::getViolationMessage('Provided file URL has no extension: @uri', ''), (string) $violations
->get(0)
->getMessage());
$this->entity
->set('url_with_extension', [
'uri' => static::getFullUrl('/'),
]);
$violations = $this->entity
->get('url_with_extension')
->validate();
$this
->assertSame(static::getViolationMessage('Provided file URL has no extension: @uri', '/'), (string) $violations
->get(0)
->getMessage());
$this->entity
->set('url_with_extension', [
'uri' => static::getFullUrl('/foo'),
]);
$violations = $this->entity
->get('url_with_extension')
->validate();
$this
->assertSame(static::getViolationMessage('Provided file URL has no extension: @uri', '/foo'), (string) $violations
->get(0)
->getMessage());
$this->entity
->set('url_with_extension', [
'uri' => static::getFullUrl('/foo.pdf'),
]);
$violations = $this->entity
->get('url_with_extension')
->validate();
$this
->assertSame(static::getViolationMessage('Provided file URL has no valid extension: @uri', '/foo.pdf'), (string) $violations
->get(0)
->getMessage());
$this->entity
->set('url_with_extension', [
'uri' => static::getFullUrl('/foo.md'),
]);
$violations = $this->entity
->get('url_with_extension')
->validate();
$this
->assertSame(0, $violations
->count());
}
public function testWithoutExtension() {
$this->entity
->set('url_without_extension', [
'uri' => static::getFullUrl(''),
]);
$violations = $this->entity
->get('url_without_extension')
->validate();
$this
->assertSame(0, $violations
->count());
}
protected static function getFullUrl($path) {
return Url::fromUri('base:/' . drupal_get_path('module', 'file_link_test') . $path, [
'absolute' => TRUE,
])
->toString();
}
protected static function getViolationMessage($message, $path) {
return (new TranslatableMarkup($message, [
'@uri' => static::getFullUrl($path),
]))
->__toString();
}
}