Add sha1 and md5 hashing options in resource URL

This commit is contained in:
Brett Tasker 2020-05-12 18:10:18 +12:00
parent 6fe74fb41b
commit 1d19051c10
2 changed files with 42 additions and 6 deletions

View File

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