Remove JSMinifier implementation

This commit is contained in:
Aaron Carlino 2017-05-11 10:17:54 +12:00
parent 7fa47e234f
commit 5b46461879
2 changed files with 832 additions and 863 deletions

View File

@ -1,30 +0,0 @@
<?php
namespace SilverStripe\View;
use Exception;
use JSMin;
class JSMinifier implements Requirements_Minifier
{
public function minify($content, $type, $filename)
{
// Non-js files aren't minified
if ($type !== 'js') {
return $content . "\n";
}
// Combine JS
try {
require_once('jsmin/jsmin.php');
increase_time_limit_to();
$content = JSMin::minify($content);
} catch (Exception $e) {
$message = $e->getMessage();
user_error("Failed to minify {$filename}, exception: {$message}", E_USER_WARNING);
} finally {
return $content . ";\n";
}
}
}

View File

@ -8,7 +8,6 @@ use SilverStripe\Control\ContentNegotiator;
use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Debug;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
@ -31,7 +30,7 @@ use SilverStripe\View\SSTemplateParser;
use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore; use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore;
use Exception; use Exception;
classSSViewerTest extends SapphireTest class SSViewerTest extends SapphireTest
{ {
/** /**
@ -39,48 +38,48 @@ classSSViewerTest 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 +88,10 @@ public function testTemplateWithoutHeadRenders()
$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 +117,10 @@ public function testIncludeScopeInheritance()
$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 +150,10 @@ public function testIncludeTruthyness()
'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 +169,17 @@ private function getScopeInheritanceTestData()
) )
) )
); );
} }
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 +189,17 @@ private function assertExpectedStrings($result, $expected)
* @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 +217,10 @@ public function testRequirements()
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';
@ -242,10 +241,10 @@ public function testRequirementsCombine()
} }
$combinedTestFileContents = file_get_contents($combinedTestFilePath); $combinedTestFileContents = file_get_contents($combinedTestFilePath);
$this->assertContains($jsFileContents, $combinedTestFileContents); $this->assertContains($jsFileContents, $combinedTestFileContents);
} }
public function testRequirementsMinification() public function testRequirementsMinification()
{ {
$testBackend = Injector::inst()->create(Requirements_Backend::class); $testBackend = Injector::inst()->create(Requirements_Backend::class);
$testBackend->setSuffixRequirements(false); $testBackend->setSuffixRequirements(false);
$testBackend->setMinifyCombinedFiles(true); $testBackend->setMinifyCombinedFiles(true);
@ -280,12 +279,12 @@ public function testRequirementsMinification()
$testBackend->setMinifyCombinedFiles(true); $testBackend->setMinifyCombinedFiles(true);
$testBackend->setMinifier(null); $testBackend->setMinifier(null);
$testBackend->processCombinedFiles(); $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
@ -306,18 +305,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');
@ -333,18 +332,18 @@ public function testBasicInjection()
$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(
@ -355,10 +354,10 @@ public function testGlobalVariableCallsWithArguments()
'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'));
@ -370,10 +369,10 @@ public function testGlobalVariablesAreEscaped()
'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}'),
@ -459,10 +458,10 @@ public function testCoreGlobalVariableCalls()
(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',
@ -476,10 +475,10 @@ public function testNonFieldCastingHelpersNotUsedInHasValue()
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()
@ -508,10 +507,10 @@ public function testLocalFunctionsTakePriorityOverGlobals()
$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(
@ -574,10 +573,10 @@ public function testCurrentScopeLoopWith()
$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)]
@ -598,10 +597,10 @@ public function testObjectDotArguments()
$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
@ -624,10 +623,10 @@ public function testEscapedArguments()
{$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',
@ -676,10 +675,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
@ -721,10 +720,10 @@ public function testControls()
'[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',
@ -907,10 +906,10 @@ public function testIfBlocks()
'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"'
@ -956,10 +955,10 @@ public function testBaseTagGeneration()
$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>'
@ -1063,10 +1062,10 @@ public function testIncludeWithArguments()
$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(
@ -1080,11 +1079,11 @@ public function testNamespaceInclude()
$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(
@ -1115,19 +1114,19 @@ public function testRecursiveInclude()
$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>';
@ -1176,10 +1175,10 @@ public function testCastingHelpers()
'&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(
@ -1310,13 +1309,13 @@ public function testSSViewerBasicIteratorSupport()
//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(
@ -1398,13 +1397,13 @@ public function testUpInWith()
'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(
@ -1491,13 +1490,13 @@ public function testUpInLoop()
$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)
@ -1551,10 +1550,10 @@ public function testNestedLoops()
$data $data
) )
); );
} }
public function testLayout() public function testLayout()
{ {
$this->useTestTheme( $this->useTestTheme(
__DIR__.'/SSViewerTest', __DIR__.'/SSViewerTest',
'layouttest', 'layouttest',
@ -1566,13 +1565,13 @@ public function testLayout()
$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',
@ -1645,10 +1644,10 @@ public function testGetTemplatesByClass()
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';
@ -1710,10 +1709,10 @@ public function testRewriteHashlinks()
); );
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';
@ -1755,10 +1754,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';
@ -1844,27 +1843,27 @@ public function testRenderWithSourceFileComments()
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';
@ -1887,10 +1886,10 @@ public function testProcessOnlyIncludesRequirementsOnce()
$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'));
@ -1910,10 +1909,10 @@ public function testRequireCallInTemplateInclude()
'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(
@ -1954,10 +1953,10 @@ public function testCallsWithArguments()
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 %>
@ -1989,10 +1988,10 @@ public function testRepeatedCallsAreCached()
$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(
@ -2006,10 +2005,10 @@ public function testClosedBlockExtension()
$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(
@ -2023,13 +2022,13 @@ public function testOpenBlockExtension()
$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)) {
@ -2052,5 +2051,5 @@ public function testFromStringCaching()
$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);
} }
} }