Merge pull request #9509 from brettt89/pulls/url_generator_nonce_sha1_md5

This commit is contained in:
Guy Marriott 2020-05-12 10:10:16 -07:00 committed by GitHub
commit e5d0400596
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 6 deletions

View File

@ -50,8 +50,8 @@ class SimpleResourceURLGenerator implements ResourceURLGenerator
*/ */
public function setNonceStyle($nonceStyle) public function setNonceStyle($nonceStyle)
{ {
if ($nonceStyle && $nonceStyle !== 'mtime') { if ($nonceStyle && !in_array($nonceStyle, ['mtime', 'sha1', 'md5'])) {
throw new InvalidArgumentException('The only allowed NonceStyle is mtime'); throw new InvalidArgumentException("NonceStyle '$nonceStyle' is not supported");
} }
$this->nonceStyle = $nonceStyle; $this->nonceStyle = $nonceStyle;
return $this; return $this;
@ -104,12 +104,20 @@ class SimpleResourceURLGenerator implements ResourceURLGenerator
if ($this->nonceStyle && $exists && is_file($absolutePath)) { if ($this->nonceStyle && $exists && is_file($absolutePath)) {
switch ($this->nonceStyle) { switch ($this->nonceStyle) {
case 'mtime': case 'mtime':
if ($query) { $method = 'filemtime';
$query .= '&'; break;
} case 'sha1':
$query .= "m=" . filemtime($absolutePath); $method = 'sha1_file';
break;
case 'md5':
$method = 'md5_file';
break; break;
} }
if ($query) {
$query .= '&';
}
$query .= "m=" . call_user_func($method, $absolutePath);
} }
// Add back querystring // Add back querystring

View File

@ -41,6 +41,34 @@ class SimpleResourceURLGeneratorTest extends SapphireTest
); );
} }
public function testAddSha1()
{
/** @var SimpleResourceURLGenerator $generator */
$generator = Injector::inst()->get(ResourceURLGenerator::class);
$generator->setNonceStyle('sha1');
$hash = sha1_file(
__DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/basemodule/client/file.js'
);
$this->assertEquals(
'/' . RESOURCES_DIR . '/basemodule/client/file.js?m=' . $hash,
$generator->urlForResource('basemodule/client/file.js')
);
}
public function testAddMd5()
{
/** @var SimpleResourceURLGenerator $generator */
$generator = Injector::inst()->get(ResourceURLGenerator::class);
$generator->setNonceStyle('md5');
$hash = md5_file(
__DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/basemodule/client/file.js'
);
$this->assertEquals(
'/' . RESOURCES_DIR . '/basemodule/client/file.js?m=' . $hash,
$generator->urlForResource('basemodule/client/file.js')
);
}
public function testVendorResource() public function testVendorResource()
{ {
/** @var SimpleResourceURLGenerator $generator */ /** @var SimpleResourceURLGenerator $generator */