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) 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':
$method = 'filemtime';
break;
case 'sha1':
$method = 'sha1_file';
break;
case 'md5':
$method = 'md5_file';
break;
}
if ($query) { if ($query) {
$query .= '&'; $query .= '&';
} }
$query .= "m=" . filemtime($absolutePath); $query .= "m=" . call_user_func($method, $absolutePath);
break;
}
} }
// 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 */