TemplateParser: Don't fatal on cache misses

Also add regression test, and coverage for more methods.

Was trying to eval the code which had the hmac integrity check in front of it,
which causes a syntax error in valid PHP code.

Follows-up db1866da4, 50c50bea2e.

Bug: T93436
Bug: T93511
Change-Id: Ie90074e4885de7340e53f59fdd479f5384b5eac6
This commit is contained in:
Timo Tijhof 2015-03-22 22:01:52 +00:00
parent 41b86bea62
commit cfcaa33fcc
3 changed files with 56 additions and 6 deletions

View file

@ -74,7 +74,7 @@ class TemplateParser {
/**
* Returns a given template function if found, otherwise throws an exception.
* @param string $templateName The name of the template (without file suffix)
* @return Function
* @return callable
* @throws RuntimeException
*/
public function getTemplate( $templateName ) {
@ -114,11 +114,8 @@ class TemplateParser {
if ( !$code ) {
$code = $this->compileForEval( $fileContents, $filename );
// Prefix the code with a keyed hash (64 hex chars) as an integrity check
$code = hash_hmac( 'sha256', $code, $secretKey ) . $code;
// Cache the compiled PHP code
$cache->set( $key, $code );
// Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
$cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
} else {
// Verify the integrity of the cached PHP code
$keyedHash = substr( $code, 0, 64 );

View file

@ -0,0 +1 @@
hello world!

View file

@ -4,6 +4,58 @@
* @group Templates
*/
class TemplateParserTest extends MediaWikiTestCase {
protected $templateDir;
protected function setUp() {
parent::setUp();
$this->setMwGlobals( array(
'wgSecretKey' => 'foo',
'wgMemc' => new EmptyBagOStuff(),
) );
$this->templateDir = dirname( __DIR__ ) . '/data/templates/';
}
/**
* @covers TemplateParser::getTemplateFilename
* @dataProvider provideGetTemplateFilename
*/
public function testGetTemplateFilename( $dir, $name, $result, $exception = false ) {
if ( $exception ) {
$this->setExpectedException( $exception );
}
$tp = new TemplateParser( $dir );
$path = $tp->getTemplateFilename( $name );
$this->assertEquals( $result, $path );
}
public static function provideGetTemplateFilename() {
return array(
array(
'dir/templates',
'foobar',
'dir/templates/foobar.mustache',
),
array(
'dir/templates',
'../foobar',
'',
'UnexpectedValueException'
),
);
}
/**
* @covers TemplateParser::getTemplate
*/
public function testGetTemplate() {
$tp = new TemplateParser( $this->templateDir );
$this->assertTrue( is_callable( $tp->getTemplate( 'foobar' ) ) );
}
/**
* @covers TemplateParser::compile
*/