New API for minified files using injectable service

This commit is contained in:
Aaron Carlino 2017-05-10 16:24:30 +12:00
parent 4dea6cb0d5
commit 7fa47e234f
4 changed files with 1698 additions and 1589 deletions

View File

@ -169,13 +169,13 @@ replaced. For instance, the below will set a new set of dependencies to write to
--- ---
Name: myrequirements Name: myrequirements
--- ---
Requirements: SilverStripe\View\Requirements:
disable_flush_combined: true disable_flush_combined: true
Requirements_Backend: SilverStripe\View\Requirements_Backend:
combine_in_dev: true combine_in_dev: true
combine_hash_querystring: true combine_hash_querystring: true
default_combined_files_folder: 'combined' default_combined_files_folder: 'combined'
Injector: SilverStripe\Core\Injector\Injector:
MySiteAdapter: MySiteAdapter:
class: 'SilverStripe\Filesystem\Flysystem\AssetAdapter' class: 'SilverStripe\Filesystem\Flysystem\AssetAdapter'
constructor: constructor:
@ -192,7 +192,7 @@ replaced. For instance, the below will set a new set of dependencies to write to
class: SilverStripe\Filesystem\Storage\FlysystemGeneratedAssetHandler class: SilverStripe\Filesystem\Storage\FlysystemGeneratedAssetHandler
properties: properties:
Filesystem: '%$MySiteBackend' Filesystem: '%$MySiteBackend'
Requirements_Backend: SilverStripe\View\Requirements_Backend:
properties: properties:
AssetHandler: '%$MySiteAssetHandler' AssetHandler: '%$MySiteAssetHandler'
@ -248,6 +248,49 @@ $scripts = array(
Requirements::combine_files('scripts.js', $scripts, array('async' => true, 'defer' => true)); Requirements::combine_files('scripts.js', $scripts, array('async' => true, 'defer' => true));
``` ```
### Minification of CSS and JS files
You can minify combined Javascript and CSS files at runtime using an implementation of the
`SilverStripe\View\Requirements_Minifier` interface.
```php
namespace MyProject;
use SilverStripe\View\Requirements_Minifier;
class MyMinifier implements Requirements_Minifier
{
/**
* Minify the given content
*
* @param string $content
* @param string $type Either js or css
* @param string $filename Name of file to display in case of error
* @return string minified content
*/
public function minify ($content, $type, $fileName)
{
// Minify $content;
return $minifiedContent;
}
}
```
Then, inject this service in `Requirements_Backend`.
```yaml
SilverStripe\Core\Injector\Injector:
SilverStripe\View\Requirements_Backend:
properties:
Minifier: %$MyProject\MyMinifier
```
<div class="alert" markdown='1'>
While the framework does afford you the option of minification at runtime, we recommend using one of many frontend build
tools to do this for you, e.g. [Webpack](https://webpack.github.io/), [Gulp](http://gulpjs.com/), or [Grunt](https://gruntjs.com/).
</div>
## Clearing assets ## Clearing assets

View File

@ -3,6 +3,7 @@
namespace SilverStripe\View; namespace SilverStripe\View;
use InvalidArgumentException; use InvalidArgumentException;
use Exception;
use SilverStripe\Assets\File; use SilverStripe\Assets\File;
use SilverStripe\Assets\Storage\GeneratedAssetHandler; use SilverStripe\Assets\Storage\GeneratedAssetHandler;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
@ -10,7 +11,6 @@ use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injectable; use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Debug; use SilverStripe\Dev\Debug;
use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
@ -121,11 +121,11 @@ class Requirements_Backend
protected $combinedFiles = array(); protected $combinedFiles = array();
/** /**
* Use the JSMin library to minify any javascript file passed to {@link combine_files()}. * Use the injected minification service to minify any javascript file passed to {@link combine_files()}.
* *
* @var bool * @var bool
*/ */
protected $minifyCombinedJSFiles = true; protected $minifyCombinedFiles = false;
/** /**
* Whether or not file headers should be written when combining files * Whether or not file headers should be written when combining files
@ -191,6 +191,11 @@ class Requirements_Backend
*/ */
protected $assetHandler = null; protected $assetHandler = null;
/**
* @var Requirements_Minifier
*/
protected $minifier = null;
/** /**
* Gets the backend storage for generated files * Gets the backend storage for generated files
* *
@ -211,6 +216,26 @@ class Requirements_Backend
$this->assetHandler = $handler; $this->assetHandler = $handler;
} }
/**
* Gets the minification service for this backend
*
* @return Requirements_Minifier
*/
public function getMinifier()
{
return $this->minifier;
}
/**
* Set a new minification service for this backend
*
* @param Requirements_Minifier $minifier
*/
public function setMinifier(Requirements_Minifier $minifier = null)
{
$this->minifier = $minifier;
}
/** /**
* Enable or disable the combination of CSS and JavaScript files * Enable or disable the combination of CSS and JavaScript files
* *
@ -340,24 +365,24 @@ class Requirements_Backend
} }
/** /**
* Check if minify js files should be combined * Check if minify files should be combined
* *
* @return bool * @return bool
*/ */
public function getMinifyCombinedJSFiles() public function getMinifyCombinedFiles()
{ {
return $this->minifyCombinedJSFiles; return $this->minifyCombinedFiles;
} }
/** /**
* Set if combined js files should be minified * Set if combined files should be minified
* *
* @param bool $minify * @param bool $minify
* @return $this * @return $this
*/ */
public function setMinifyCombinedJSFiles($minify) public function setMinifyCombinedFiles($minify)
{ {
$this->minifyCombinedJSFiles = $minify; $this->minifyCombinedFiles = $minify;
return $this; return $this;
} }
@ -1278,7 +1303,20 @@ class Requirements_Backend
$combinedFileID = File::join_paths($this->getCombinedFilesFolder(), $combinedFile); $combinedFileID = File::join_paths($this->getCombinedFilesFolder(), $combinedFile);
// Send file combination request to the backend, with an optional callback to perform regeneration // Send file combination request to the backend, with an optional callback to perform regeneration
$minify = $this->getMinifyCombinedJSFiles(); $minify = $this->getMinifyCombinedFiles();
if ($minify && !$this->minifier) {
throw new Exception(
sprintf(
'Cannot minify files without a minification service defined.
Set %s::minifyCombinedFiles to false, or inject a %s service on
%s.properties.minifier',
__CLASS__,
Requirements_Minifier::class,
__CLASS__
)
);
}
$combinedURL = $this $combinedURL = $this
->getAssetHandler() ->getAssetHandler()
->getContentURL( ->getContentURL(
@ -1287,12 +1325,11 @@ class Requirements_Backend
// Physically combine all file content // Physically combine all file content
$combinedData = ''; $combinedData = '';
$base = Director::baseFolder() . '/'; $base = Director::baseFolder() . '/';
$minifier = Injector::inst()->get('SilverStripe\\View\\Requirements_Minifier');
foreach ($fileList as $file) { foreach ($fileList as $file) {
$fileContent = file_get_contents($base . $file); $fileContent = file_get_contents($base . $file);
// Use configured minifier // Use configured minifier
if ($minify) { if ($minify) {
$fileContent = $minifier->minify($fileContent, $type, $file); $fileContent = $this->minifier->minify($fileContent, $type, $file);
} }
if ($this->writeHeaderComment) { if ($this->writeHeaderComment) {

View File

@ -86,7 +86,7 @@ class RequirementsTest extends SapphireTest
$backend->clear(); $backend->clear();
$backend->clearCombinedFiles(); $backend->clearCombinedFiles();
$backend->setCombinedFilesFolder('_combinedfiles'); $backend->setCombinedFilesFolder('_combinedfiles');
$backend->setMinifyCombinedJSFiles(false); $backend->setMinifyCombinedFiles(false);
Requirements::flush(); Requirements::flush();
} }

View File

@ -20,6 +20,7 @@ use SilverStripe\Security\SecurityToken;
use SilverStripe\Security\Permission; use SilverStripe\Security\Permission;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements_Backend; use SilverStripe\View\Requirements_Backend;
use SilverStripe\View\Requirements_Minifier;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use SilverStripe\View\Requirements; use SilverStripe\View\Requirements;
use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModel; use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModel;
@ -28,10 +29,9 @@ use SilverStripe\View\ViewableData;
use SilverStripe\View\SSViewer_FromString; use SilverStripe\View\SSViewer_FromString;
use SilverStripe\View\SSTemplateParser; use SilverStripe\View\SSTemplateParser;
use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore; use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore;
use JSMin;
use Exception; use Exception;
class SSViewerTest extends SapphireTest classSSViewerTest extends SapphireTest
{ {
/** /**
@ -39,48 +39,48 @@ class SSViewerTest extends SapphireTest
* *
* @var array * @var array
*/ */
protected $oldServer = array(); protected $oldServer = array();
protected static $extra_dataobjects = array( protected static $extra_dataobjects = array(
SSViewerTest\TestObject::class, SSViewerTest\TestObject::class,
); );
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
SSViewer::config()->update('source_file_comments', false); SSViewer::config()->update('source_file_comments', false);
SSViewer_FromString::config()->update('cache_template', false); SSViewer_FromString::config()->update('cache_template', false);
TestAssetStore::activate('SSViewerTest'); TestAssetStore::activate('SSViewerTest');
$this->oldServer = $_SERVER; $this->oldServer = $_SERVER;
} }
protected function tearDown() protected function tearDown()
{ {
$_SERVER = $this->oldServer; $_SERVER = $this->oldServer;
TestAssetStore::reset(); TestAssetStore::reset();
parent::tearDown(); parent::tearDown();
} }
/** /**
* Tests for {@link Config::inst()->get('SSViewer', 'theme')} for different behaviour * Tests for {@link Config::inst()->get('SSViewer', 'theme')} for different behaviour
* of user defined themes via {@link SiteConfig} and default theme * of user defined themes via {@link SiteConfig} and default theme
* when no user themes are defined. * when no user themes are defined.
*/ */
public function testCurrentTheme() public function testCurrentTheme()
{ {
SSViewer::config()->update('theme', 'mytheme'); SSViewer::config()->update('theme', 'mytheme');
$this->assertEquals( $this->assertEquals(
'mytheme', 'mytheme',
SSViewer::config()->uninherited('theme'), SSViewer::config()->uninherited('theme'),
'Current theme is the default - user has not defined one' 'Current theme is the default - user has not defined one'
); );
} }
/** /**
* Test that a template without a <head> tag still renders. * Test that a template without a <head> tag still renders.
*/ */
public function testTemplateWithoutHeadRenders() public function testTemplateWithoutHeadRenders()
{ {
$data = new ArrayData( $data = new ArrayData(
array( array(
'Var' => 'var value' 'Var' => 'var value'
@ -89,10 +89,10 @@ class SSViewerTest extends SapphireTest
$result = $data->renderWith("SSViewerTestPartialTemplate"); $result = $data->renderWith("SSViewerTestPartialTemplate");
$this->assertEquals('Test partial template: var value', trim(preg_replace("/<!--.*-->/U", '', $result))); $this->assertEquals('Test partial template: var value', trim(preg_replace("/<!--.*-->/U", '', $result)));
} }
public function testIncludeScopeInheritance() public function testIncludeScopeInheritance()
{ {
$data = $this->getScopeInheritanceTestData(); $data = $this->getScopeInheritanceTestData();
$expected = array( $expected = array(
'Item 1 - First-ODD top:Item 1', 'Item 1 - First-ODD top:Item 1',
@ -118,10 +118,10 @@ class SSViewerTest extends SapphireTest
$result = $data->renderWith('SSViewerTestIncludeScopeInheritanceWithArgs'); $result = $data->renderWith('SSViewerTestIncludeScopeInheritanceWithArgs');
$this->assertExpectedStrings($result, $expected); $this->assertExpectedStrings($result, $expected);
} }
public function testIncludeTruthyness() public function testIncludeTruthyness()
{ {
$data = new ArrayData( $data = new ArrayData(
array( array(
'Title' => 'TruthyTest', 'Title' => 'TruthyTest',
@ -151,10 +151,10 @@ class SSViewerTest extends SapphireTest
'7 _ 7 - Last-ODD top:7' '7 _ 7 - Last-ODD top:7'
); );
$this->assertExpectedStrings($result, $expected); $this->assertExpectedStrings($result, $expected);
} }
private function getScopeInheritanceTestData() private function getScopeInheritanceTestData()
{ {
return new ArrayData( return new ArrayData(
array( array(
'Title' => 'TopTitleValue', 'Title' => 'TopTitleValue',
@ -170,17 +170,17 @@ class SSViewerTest extends SapphireTest
) )
) )
); );
} }
private function assertExpectedStrings($result, $expected) private function assertExpectedStrings($result, $expected)
{ {
foreach ($expected as $expectedStr) { foreach ($expected as $expectedStr) {
$this->assertTrue( $this->assertTrue(
(boolean) preg_match("/{$expectedStr}/", $result), (boolean) preg_match("/{$expectedStr}/", $result),
"Didn't find '{$expectedStr}' in:\n{$result}" "Didn't find '{$expectedStr}' in:\n{$result}"
); );
} }
} }
/** /**
* Small helper to render templates from strings * Small helper to render templates from strings
@ -190,17 +190,17 @@ class SSViewerTest extends SapphireTest
* @param bool $cacheTemplate * @param bool $cacheTemplate
* @return string * @return string
*/ */
public function render($templateString, $data = null, $cacheTemplate = false) public function render($templateString, $data = null, $cacheTemplate = false)
{ {
$t = SSViewer::fromString($templateString, $cacheTemplate); $t = SSViewer::fromString($templateString, $cacheTemplate);
if (!$data) { if (!$data) {
$data = new SSViewerTest\TestFixture(); $data = new SSViewerTest\TestFixture();
} }
return trim(''.$t->process($data)); return trim(''.$t->process($data));
} }
public function testRequirements() public function testRequirements()
{ {
$requirements = $this->getMockBuilder(Requirements_Backend::class)->setMethods(array("javascript", "css")) $requirements = $this->getMockBuilder(Requirements_Backend::class)->setMethods(array("javascript", "css"))
->getMock(); ->getMock();
$jsFile = FRAMEWORK_DIR . '/tests/forms/a.js'; $jsFile = FRAMEWORK_DIR . '/tests/forms/a.js';
@ -218,10 +218,10 @@ class SSViewerTest extends SapphireTest
Requirements::set_backend($origReq); Requirements::set_backend($origReq);
$this->assertFalse((bool)trim($template), "Should be no content in this return."); $this->assertFalse((bool)trim($template), "Should be no content in this return.");
} }
public function testRequirementsCombine() public function testRequirementsCombine()
{ {
$testBackend = Injector::inst()->create(Requirements_Backend::class); $testBackend = Injector::inst()->create(Requirements_Backend::class);
$testBackend->setSuffixRequirements(false); $testBackend->setSuffixRequirements(false);
//$combinedTestFilePath = BASE_PATH . '/' . $testBackend->getCombinedFilesFolder() . '/testRequirementsCombine.js'; //$combinedTestFilePath = BASE_PATH . '/' . $testBackend->getCombinedFilesFolder() . '/testRequirementsCombine.js';
@ -230,15 +230,6 @@ class SSViewerTest extends SapphireTest
$jsFileContents = file_get_contents(BASE_PATH . '/' . $jsFile); $jsFileContents = file_get_contents(BASE_PATH . '/' . $jsFile);
$testBackend->combineFiles('testRequirementsCombine.js', array($jsFile)); $testBackend->combineFiles('testRequirementsCombine.js', array($jsFile));
// first make sure that our test js file causes an exception to be thrown
try {
include_once 'jsmin/jsmin.php';
JSMin::minify($jsFileContents);
$this->fail('JSMin did not throw exception on minify bad file: ');
} catch (Exception $e) {
// exception thrown... good
}
// secondly, make sure that requirements is generated, even though minification failed // secondly, make sure that requirements is generated, even though minification failed
$testBackend->processCombinedFiles(); $testBackend->processCombinedFiles();
$js = array_keys($testBackend->getJavascript()); $js = array_keys($testBackend->getJavascript());
@ -251,12 +242,50 @@ class SSViewerTest extends SapphireTest
} }
$combinedTestFileContents = file_get_contents($combinedTestFilePath); $combinedTestFileContents = file_get_contents($combinedTestFilePath);
$this->assertContains($jsFileContents, $combinedTestFileContents); $this->assertContains($jsFileContents, $combinedTestFileContents);
} }
public function testRequirementsMinification()
{
$testBackend = Injector::inst()->create(Requirements_Backend::class);
$testBackend->setSuffixRequirements(false);
$testBackend->setMinifyCombinedFiles(true);
$testFile = $this->getCurrentRelativePath() . '/SSViewerTest/javascript/RequirementsTest_a.js';
$testFileContent = file_get_contents($testFile);
$mockMinifier = $this->getMockBuilder(Requirements_Minifier::class)
->setMethods(['minify'])
->getMock();
$mockMinifier->expects($this->once())
->method('minify')
->with(
$testFileContent,
'js',
$testFile
);
$testBackend->setMinifier($mockMinifier);
$testBackend->combineFiles('testRequirementsMinified.js', array($testFile));
$testBackend->processCombinedFiles();
$testBackend->setMinifyCombinedFiles(false);
$mockMinifier->expects($this->never())
->method('minify');
$testBackend->processCombinedFiles();
$this->setExpectedExceptionRegExp(
Exception::class,
'/minification service/'
);
$testBackend->setMinifyCombinedFiles(true);
$testBackend->setMinifier(null);
$testBackend->processCombinedFiles();
}
public function testComments() public function testComments()
{ {
$output = $this->render( $output = $this->render(
<<<SS <<<SS
This is my template<%-- this is a comment --%>This is some content<%-- this is another comment --%>Final content This is my template<%-- this is a comment --%>This is some content<%-- this is another comment --%>Final content
@ -277,18 +306,18 @@ content
SS; SS;
$this->assertEquals($shouldbe, $output); $this->assertEquals($shouldbe, $output);
} }
public function testBasicText() public function testBasicText()
{ {
$this->assertEquals('"', $this->render('"'), 'Double-quotes are left alone'); $this->assertEquals('"', $this->render('"'), 'Double-quotes are left alone');
$this->assertEquals("'", $this->render("'"), 'Single-quotes are left alone'); $this->assertEquals("'", $this->render("'"), 'Single-quotes are left alone');
$this->assertEquals('A', $this->render('\\A'), 'Escaped characters are unescaped'); $this->assertEquals('A', $this->render('\\A'), 'Escaped characters are unescaped');
$this->assertEquals('\\A', $this->render('\\\\A'), 'Escaped back-slashed are correctly unescaped'); $this->assertEquals('\\A', $this->render('\\\\A'), 'Escaped back-slashed are correctly unescaped');
} }
public function testBasicInjection() public function testBasicInjection()
{ {
$this->assertEquals('[out:Test]', $this->render('$Test'), 'Basic stand-alone injection'); $this->assertEquals('[out:Test]', $this->render('$Test'), 'Basic stand-alone injection');
$this->assertEquals('[out:Test]', $this->render('{$Test}'), 'Basic stand-alone wrapped injection'); $this->assertEquals('[out:Test]', $this->render('{$Test}'), 'Basic stand-alone wrapped injection');
$this->assertEquals('A[out:Test]!', $this->render('A$Test!'), 'Basic surrounded injection'); $this->assertEquals('A[out:Test]!', $this->render('A$Test!'), 'Basic surrounded injection');
@ -304,18 +333,18 @@ SS;
$this->render('{\\\\$Test}'), $this->render('{\\\\$Test}'),
'Escapes before injections are correctly unescaped' 'Escapes before injections are correctly unescaped'
); );
} }
public function testGlobalVariableCalls() public function testGlobalVariableCalls()
{ {
$this->assertEquals('automatic', $this->render('$SSViewerTest_GlobalAutomatic')); $this->assertEquals('automatic', $this->render('$SSViewerTest_GlobalAutomatic'));
$this->assertEquals('reference', $this->render('$SSViewerTest_GlobalReferencedByString')); $this->assertEquals('reference', $this->render('$SSViewerTest_GlobalReferencedByString'));
$this->assertEquals('reference', $this->render('$SSViewerTest_GlobalReferencedInArray')); $this->assertEquals('reference', $this->render('$SSViewerTest_GlobalReferencedInArray'));
} }
public function testGlobalVariableCallsWithArguments() public function testGlobalVariableCallsWithArguments()
{ {
$this->assertEquals('zz', $this->render('$SSViewerTest_GlobalThatTakesArguments')); $this->assertEquals('zz', $this->render('$SSViewerTest_GlobalThatTakesArguments'));
$this->assertEquals('zFooz', $this->render('$SSViewerTest_GlobalThatTakesArguments("Foo")')); $this->assertEquals('zFooz', $this->render('$SSViewerTest_GlobalThatTakesArguments("Foo")'));
$this->assertEquals( $this->assertEquals(
@ -326,10 +355,10 @@ SS;
'zreferencez', 'zreferencez',
$this->render('$SSViewerTest_GlobalThatTakesArguments($SSViewerTest_GlobalReferencedByString)') $this->render('$SSViewerTest_GlobalThatTakesArguments($SSViewerTest_GlobalReferencedByString)')
); );
} }
public function testGlobalVariablesAreEscaped() public function testGlobalVariablesAreEscaped()
{ {
$this->assertEquals('<div></div>', $this->render('$SSViewerTest_GlobalHTMLFragment')); $this->assertEquals('<div></div>', $this->render('$SSViewerTest_GlobalHTMLFragment'));
$this->assertEquals('&lt;div&gt;&lt;/div&gt;', $this->render('$SSViewerTest_GlobalHTMLEscaped')); $this->assertEquals('&lt;div&gt;&lt;/div&gt;', $this->render('$SSViewerTest_GlobalHTMLEscaped'));
@ -341,10 +370,10 @@ SS;
'z&lt;div&gt;&lt;/div&gt;z', 'z&lt;div&gt;&lt;/div&gt;z',
$this->render('$SSViewerTest_GlobalThatTakesArguments($SSViewerTest_GlobalHTMLEscaped)') $this->render('$SSViewerTest_GlobalThatTakesArguments($SSViewerTest_GlobalHTMLEscaped)')
); );
} }
public function testCoreGlobalVariableCalls() public function testCoreGlobalVariableCalls()
{ {
$this->assertEquals( $this->assertEquals(
Director::absoluteBaseURL(), Director::absoluteBaseURL(),
$this->render('{$absoluteBaseURL}'), $this->render('{$absoluteBaseURL}'),
@ -430,10 +459,10 @@ SS;
(bool)$this->render('{$hasPerm(\'ADMIN\')}'), (bool)$this->render('{$hasPerm(\'ADMIN\')}'),
'Permissions template functions result correct result' 'Permissions template functions result correct result'
); );
} }
public function testNonFieldCastingHelpersNotUsedInHasValue() public function testNonFieldCastingHelpersNotUsedInHasValue()
{ {
// check if Link without $ in front of variable // check if Link without $ in front of variable
$result = $this->render( $result = $this->render(
'A<% if Link %>$Link<% end_if %>B', 'A<% if Link %>$Link<% end_if %>B',
@ -447,10 +476,10 @@ SS;
new SSViewerTest\TestObject() new SSViewerTest\TestObject()
); );
$this->assertEquals('Asome/url.htmlB', $result, 'casting helper not used for <% if $Link %>'); $this->assertEquals('Asome/url.htmlB', $result, 'casting helper not used for <% if $Link %>');
} }
public function testLocalFunctionsTakePriorityOverGlobals() public function testLocalFunctionsTakePriorityOverGlobals()
{ {
$data = new ArrayData( $data = new ArrayData(
array( array(
'Page' => new SSViewerTest\TestObject() 'Page' => new SSViewerTest\TestObject()
@ -479,10 +508,10 @@ SS;
$result, $result,
"Local Object's public function called. Did not return the actual baseURL of the current site" "Local Object's public function called. Did not return the actual baseURL of the current site"
); );
} }
public function testCurrentScopeLoopWith() public function testCurrentScopeLoopWith()
{ {
// Data to run the loop tests on - one sequence of three items, each with a subitem // Data to run the loop tests on - one sequence of three items, each with a subitem
$data = new ArrayData( $data = new ArrayData(
array( array(
@ -545,10 +574,10 @@ SS;
$data $data
); );
$this->assertEquals("SubKid1SubKid2Number6", $result, "Loop in current scope works"); $this->assertEquals("SubKid1SubKid2Number6", $result, "Loop in current scope works");
} }
public function testObjectDotArguments() public function testObjectDotArguments()
{ {
$this->assertEquals( $this->assertEquals(
'[out:TestObject.methodWithOneArgument(one)] '[out:TestObject.methodWithOneArgument(one)]
[out:TestObject.methodWithTwoArguments(one,two)] [out:TestObject.methodWithTwoArguments(one,two)]
@ -569,10 +598,10 @@ SS;
$TestMethod(Arg1)' $TestMethod(Arg1)'
) )
); );
} }
public function testEscapedArguments() public function testEscapedArguments()
{ {
$this->assertEquals( $this->assertEquals(
'[out:Foo(Arg1,Arg2).Bar.Val].Suffix '[out:Foo(Arg1,Arg2).Bar.Val].Suffix
[out:Foo(Arg1,Arg2).Val]_Suffix [out:Foo(Arg1,Arg2).Val]_Suffix
@ -595,10 +624,10 @@ SS;
{$Foo}.Suffix' {$Foo}.Suffix'
) )
); );
} }
public function testLoopWhitespace() public function testLoopWhitespace()
{ {
$this->assertEquals( $this->assertEquals(
'before[out:SingleItem.Test]after 'before[out:SingleItem.Test]after
beforeTestafter', beforeTestafter',
@ -647,10 +676,10 @@ $ItemOnItsOwnLine
after' after'
) )
); );
} }
public function testControls() public function testControls()
{ {
// Single item controls // Single item controls
$this->assertEquals( $this->assertEquals(
'a[out:Foo.Bar.Item]b 'a[out:Foo.Bar.Item]b
@ -692,10 +721,10 @@ after'
'[out:Loop2(Arg1,Arg2,Arg3).Item][out:Loop2(Arg1,Arg2,Arg3).Item]', '[out:Loop2(Arg1,Arg2,Arg3).Item][out:Loop2(Arg1,Arg2,Arg3).Item]',
$this->render('<% loop Loop2(Arg1, Arg2, Arg3) %>$Item<% end_loop %>') $this->render('<% loop Loop2(Arg1, Arg2, Arg3) %>$Item<% end_loop %>')
); );
} }
public function testIfBlocks() public function testIfBlocks()
{ {
// Basic test // Basic test
$this->assertEquals( $this->assertEquals(
'AC', 'AC',
@ -878,10 +907,10 @@ after'
'ABC', 'ABC',
$this->render('A<% if NotSet %><% else %>B<% end_if %>C') $this->render('A<% if NotSet %><% else %>B<% end_if %>C')
); );
} }
public function testBaseTagGeneration() public function testBaseTagGeneration()
{ {
// XHTML wil have a closed base tag // XHTML wil have a closed base tag
$tmpl1 = '<?xml version="1.0" encoding="UTF-8"?> $tmpl1 = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
@ -927,10 +956,10 @@ after'
$response = new HTTPResponse($this->render($tmpl1)); $response = new HTTPResponse($this->render($tmpl1));
$negotiator->xhtml($response); $negotiator->xhtml($response);
$this->assertRegExp('/<head><base href=".*" \/><\/head>/', $response->getBody()); $this->assertRegExp('/<head><base href=".*" \/><\/head>/', $response->getBody());
} }
public function testIncludeWithArguments() public function testIncludeWithArguments()
{ {
$this->assertEquals( $this->assertEquals(
$this->render('<% include SSViewerTestIncludeWithArguments %>'), $this->render('<% include SSViewerTestIncludeWithArguments %>'),
'<p>[out:Arg1]</p><p>[out:Arg2]</p>' '<p>[out:Arg1]</p><p>[out:Arg2]</p>'
@ -1034,10 +1063,10 @@ after'
$tmpl = SSViewer::fromString('<% include SSViewerTestIncludeObjectArguments A=$Nested.Object, B=$Object %>'); $tmpl = SSViewer::fromString('<% include SSViewerTestIncludeObjectArguments A=$Nested.Object, B=$Object %>');
$res = $tmpl->process($data); $res = $tmpl->process($data);
$this->assertEqualIgnoringWhitespace('A B', $res, 'Objects can be passed as named arguments'); $this->assertEqualIgnoringWhitespace('A B', $res, 'Objects can be passed as named arguments');
} }
public function testNamespaceInclude() public function testNamespaceInclude()
{ {
$data = new ArrayData([]); $data = new ArrayData([]);
$this->assertEquals( $this->assertEquals(
@ -1051,11 +1080,11 @@ after'
$this->render('tests:( <% include Namespace/NamespaceInclude %> )', $data), $this->render('tests:( <% include Namespace/NamespaceInclude %> )', $data),
'Forward slashes work for namespace references in includes' 'Forward slashes work for namespace references in includes'
); );
} }
public function testRecursiveInclude() public function testRecursiveInclude()
{ {
$view = new SSViewer(array('Includes/SSViewerTestRecursiveInclude')); $view = new SSViewer(array('Includes/SSViewerTestRecursiveInclude'));
$data = new ArrayData( $data = new ArrayData(
@ -1086,19 +1115,19 @@ after'
$rationalisedResult = trim(preg_replace('/\s+/', ' ', $result)); $rationalisedResult = trim(preg_replace('/\s+/', ' ', $result));
$this->assertEquals('A A1 A1 i A1 ii A2 A3', $rationalisedResult); $this->assertEquals('A A1 A1 i A1 ii A2 A3', $rationalisedResult);
} }
public function assertEqualIgnoringWhitespace($a, $b, $message = '') public function assertEqualIgnoringWhitespace($a, $b, $message = '')
{ {
$this->assertEquals(preg_replace('/\s+/', '', $a), preg_replace('/\s+/', '', $b), $message); $this->assertEquals(preg_replace('/\s+/', '', $a), preg_replace('/\s+/', '', $b), $message);
} }
/** /**
* See {@link ViewableDataTest} for more extensive casting tests, * See {@link ViewableDataTest} for more extensive casting tests,
* this test just ensures that basic casting is correctly applied during template parsing. * this test just ensures that basic casting is correctly applied during template parsing.
*/ */
public function testCastingHelpers() public function testCastingHelpers()
{ {
$vd = new SSViewerTest\TestViewableData(); $vd = new SSViewerTest\TestViewableData();
$vd->TextValue = '<b>html</b>'; $vd->TextValue = '<b>html</b>';
$vd->HTMLValue = '<b>html</b>'; $vd->HTMLValue = '<b>html</b>';
@ -1147,10 +1176,10 @@ after'
'&lt;b&gt;html&lt;/b&gt;', '&lt;b&gt;html&lt;/b&gt;',
$t = SSViewer::fromString('$UncastedValue.XML')->process($vd) $t = SSViewer::fromString('$UncastedValue.XML')->process($vd)
); );
} }
public function testSSViewerBasicIteratorSupport() public function testSSViewerBasicIteratorSupport()
{ {
$data = new ArrayData( $data = new ArrayData(
array( array(
'Set' => new ArrayList( 'Set' => new ArrayList(
@ -1281,13 +1310,13 @@ after'
//test MultipleOf 11 //test MultipleOf 11
$result = $this->render('<% loop Set %><% if MultipleOf(11) %>$Number<% end_if %><% end_loop %>', $data); $result = $this->render('<% loop Set %><% if MultipleOf(11) %>$Number<% end_if %><% end_loop %>', $data);
$this->assertEquals("", $result, "Only numbers that are multiples of 11 are returned. I.e. nothing returned"); $this->assertEquals("", $result, "Only numbers that are multiples of 11 are returned. I.e. nothing returned");
} }
/** /**
* Test $Up works when the scope $Up refers to was entered with a "with" block * Test $Up works when the scope $Up refers to was entered with a "with" block
*/ */
public function testUpInWith() public function testUpInWith()
{ {
// Data to run the loop tests on - three levels deep // Data to run the loop tests on - three levels deep
$data = new ArrayData( $data = new ArrayData(
@ -1369,13 +1398,13 @@ after'
'Foo', 'Foo',
$this->render('<% with Foo.Bar.Baz.Up.Qux %>{$Up.Up.Name}<% end_with %>', $data) $this->render('<% with Foo.Bar.Baz.Up.Qux %>{$Up.Up.Name}<% end_with %>', $data)
); );
} }
/** /**
* Test $Up works when the scope $Up refers to was entered with a "loop" block * Test $Up works when the scope $Up refers to was entered with a "loop" block
*/ */
public function testUpInLoop() public function testUpInLoop()
{ {
// Data to run the loop tests on - one sequence of three items, each with a subitem // Data to run the loop tests on - one sequence of three items, each with a subitem
$data = new ArrayData( $data = new ArrayData(
@ -1462,13 +1491,13 @@ after'
$data $data
) )
); );
} }
/** /**
* Test that nested loops restore the loop variables correctly when pushing and popping states * Test that nested loops restore the loop variables correctly when pushing and popping states
*/ */
public function testNestedLoops() public function testNestedLoops()
{ {
// Data to run the loop tests on - one sequence of three items, one with child elements // Data to run the loop tests on - one sequence of three items, one with child elements
// (of a different size to the main sequence) // (of a different size to the main sequence)
@ -1522,10 +1551,10 @@ after'
$data $data
) )
); );
} }
public function testLayout() public function testLayout()
{ {
$this->useTestTheme( $this->useTestTheme(
__DIR__.'/SSViewerTest', __DIR__.'/SSViewerTest',
'layouttest', 'layouttest',
@ -1537,13 +1566,13 @@ after'
$this->assertEquals("[file_link]\n\n", $template->process(new ArrayData(array()))); $this->assertEquals("[file_link]\n\n", $template->process(new ArrayData(array())));
} }
); );
} }
/** /**
* @covers \SilverStripe\View\SSViewer::get_templates_by_class() * @covers \SilverStripe\View\SSViewer::get_templates_by_class()
*/ */
public function testGetTemplatesByClass() public function testGetTemplatesByClass()
{ {
$this->useTestTheme( $this->useTestTheme(
__DIR__ . '/SSViewerTest', __DIR__ . '/SSViewerTest',
'layouttest', 'layouttest',
@ -1616,10 +1645,10 @@ after'
SSViewer::get_templates_by_class(array()); SSViewer::get_templates_by_class(array());
} }
); );
} }
public function testRewriteHashlinks() public function testRewriteHashlinks()
{ {
SSViewer::config()->update('rewrite_hash_links', true); SSViewer::config()->update('rewrite_hash_links', true);
$_SERVER['HTTP_HOST'] = 'www.mysite.com'; $_SERVER['HTTP_HOST'] = 'www.mysite.com';
@ -1681,10 +1710,10 @@ after'
); );
unlink($tmplFile); unlink($tmplFile);
} }
public function testRewriteHashlinksInPhpMode() public function testRewriteHashlinksInPhpMode()
{ {
SSViewer::config()->update('rewrite_hash_links', 'php'); SSViewer::config()->update('rewrite_hash_links', 'php');
$tmplFile = TEMP_FOLDER . '/SSViewerTest_testRewriteHashlinksInPhpMode_' . sha1(rand()) . '.ss'; $tmplFile = TEMP_FOLDER . '/SSViewerTest_testRewriteHashlinksInPhpMode_' . sha1(rand()) . '.ss';
@ -1726,10 +1755,10 @@ EOC;
); );
unlink($tmplFile); unlink($tmplFile);
} }
public function testRenderWithSourceFileComments() public function testRenderWithSourceFileComments()
{ {
Director::set_environment_type('dev'); Director::set_environment_type('dev');
SSViewer::config()->update('source_file_comments', true); SSViewer::config()->update('source_file_comments', true);
$i = __DIR__ . '/SSViewerTest/templates/Includes'; $i = __DIR__ . '/SSViewerTest/templates/Includes';
@ -1815,27 +1844,27 @@ EOC;
foreach ($templates as $template) { foreach ($templates as $template) {
$this->_renderWithSourceFileComments('SSViewerTestComments/'.$template['name'], $template['expected']); $this->_renderWithSourceFileComments('SSViewerTestComments/'.$template['name'], $template['expected']);
} }
} }
private function _renderWithSourceFileComments($name, $expected) private function _renderWithSourceFileComments($name, $expected)
{ {
$viewer = new SSViewer(array($name)); $viewer = new SSViewer(array($name));
$data = new ArrayData(array()); $data = new ArrayData(array());
$result = $viewer->process($data); $result = $viewer->process($data);
$expected = str_replace(array("\r", "\n"), '', $expected); $expected = str_replace(array("\r", "\n"), '', $expected);
$result = str_replace(array("\r", "\n"), '', $result); $result = str_replace(array("\r", "\n"), '', $result);
$this->assertEquals($result, $expected); $this->assertEquals($result, $expected);
} }
public function testLoopIteratorIterator() public function testLoopIteratorIterator()
{ {
$list = new PaginatedList(new ArrayList()); $list = new PaginatedList(new ArrayList());
$viewer = new SSViewer_FromString('<% loop List %>$ID - $FirstName<br /><% end_loop %>'); $viewer = new SSViewer_FromString('<% loop List %>$ID - $FirstName<br /><% end_loop %>');
$result = $viewer->process(new ArrayData(array('List' => $list))); $result = $viewer->process(new ArrayData(array('List' => $list)));
$this->assertEquals($result, ''); $this->assertEquals($result, '');
} }
public function testProcessOnlyIncludesRequirementsOnce() public function testProcessOnlyIncludesRequirementsOnce()
{ {
$template = new SSViewer(array('SSViewerTestProcess')); $template = new SSViewer(array('SSViewerTestProcess'));
$basePath = $this->getCurrentRelativePath() . '/SSViewerTest'; $basePath = $this->getCurrentRelativePath() . '/SSViewerTest';
@ -1858,10 +1887,10 @@ EOC;
$template->includeRequirements(false); $template->includeRequirements(false);
$this->assertEquals(0, substr_count($template->process(array()), "a.css")); $this->assertEquals(0, substr_count($template->process(array()), "a.css"));
$this->assertEquals(0, substr_count($template->process(array()), "b.css")); $this->assertEquals(0, substr_count($template->process(array()), "b.css"));
} }
public function testRequireCallInTemplateInclude() public function testRequireCallInTemplateInclude()
{ {
//TODO undo skip test on the event that templates ever obtain the ability to reference MODULE_DIR (or something to that effect) //TODO undo skip test on the event that templates ever obtain the ability to reference MODULE_DIR (or something to that effect)
if (FRAMEWORK_DIR === 'framework') { if (FRAMEWORK_DIR === 'framework') {
$template = new SSViewer(array('SSViewerTestProcess')); $template = new SSViewer(array('SSViewerTestProcess'));
@ -1881,10 +1910,10 @@ EOC;
'named \'framework\', since templates require hard coded paths' 'named \'framework\', since templates require hard coded paths'
); );
} }
} }
public function testCallsWithArguments() public function testCallsWithArguments()
{ {
$data = new ArrayData( $data = new ArrayData(
array( array(
'Set' => new ArrayList( 'Set' => new ArrayList(
@ -1925,10 +1954,10 @@ EOC;
foreach ($tests as $template => $expected) { foreach ($tests as $template => $expected) {
$this->assertEquals($expected, trim($this->render($template, $data))); $this->assertEquals($expected, trim($this->render($template, $data)));
} }
} }
public function testRepeatedCallsAreCached() public function testRepeatedCallsAreCached()
{ {
$data = new SSViewerTest\CacheTestData(); $data = new SSViewerTest\CacheTestData();
$template = ' $template = '
<% if $TestWithCall %> <% if $TestWithCall %>
@ -1960,10 +1989,10 @@ EOC;
$data->testLoopCalls, $data->testLoopCalls,
'SSViewerTest_CacheTestData::TestLoopCall() should only be called once. Subsequent calls should be cached' 'SSViewerTest_CacheTestData::TestLoopCall() should only be called once. Subsequent calls should be cached'
); );
} }
public function testClosedBlockExtension() public function testClosedBlockExtension()
{ {
$count = 0; $count = 0;
$parser = new SSTemplateParser(); $parser = new SSTemplateParser();
$parser->addClosedBlock( $parser->addClosedBlock(
@ -1977,10 +2006,10 @@ EOC;
$template->process(new SSViewerTest\TestFixture()); $template->process(new SSViewerTest\TestFixture());
$this->assertEquals(1, $count); $this->assertEquals(1, $count);
} }
public function testOpenBlockExtension() public function testOpenBlockExtension()
{ {
$count = 0; $count = 0;
$parser = new SSTemplateParser(); $parser = new SSTemplateParser();
$parser->addOpenBlock( $parser->addOpenBlock(
@ -1994,13 +2023,13 @@ EOC;
$template->process(new SSViewerTest\TestFixture()); $template->process(new SSViewerTest\TestFixture());
$this->assertEquals(1, $count); $this->assertEquals(1, $count);
} }
/** /**
* Tests if caching for SSViewer_FromString is working * Tests if caching for SSViewer_FromString is working
*/ */
public function testFromStringCaching() public function testFromStringCaching()
{ {
$content = 'Test content'; $content = 'Test content';
$cacheFile = TEMP_FOLDER . '/.cache.' . sha1($content); $cacheFile = TEMP_FOLDER . '/.cache.' . sha1($content);
if (file_exists($cacheFile)) { if (file_exists($cacheFile)) {
@ -2023,5 +2052,5 @@ EOC;
$this->render($content, null, true); $this->render($content, null, true);
$this->assertTrue(file_exists($cacheFile), 'Cache file wasn\'t created when it was meant to'); $this->assertTrue(file_exists($cacheFile), 'Cache file wasn\'t created when it was meant to');
unlink($cacheFile); unlink($cacheFile);
} }
} }