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\Core\Convert;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Debug;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\DataObject;
@ -31,7 +30,7 @@ use SilverStripe\View\SSTemplateParser;
use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore;
use Exception;
classSSViewerTest extends SapphireTest
class SSViewerTest extends SapphireTest
{
/**
@ -39,48 +38,48 @@ classSSViewerTest extends SapphireTest
*
* @var array
*/
protected $oldServer = array();
protected $oldServer = array();
protected static $extra_dataobjects = array(
protected static $extra_dataobjects = array(
SSViewerTest\TestObject::class,
);
protected function setUp()
{
protected function setUp()
{
parent::setUp();
SSViewer::config()->update('source_file_comments', false);
SSViewer_FromString::config()->update('cache_template', false);
TestAssetStore::activate('SSViewerTest');
$this->oldServer = $_SERVER;
}
}
protected function tearDown()
{
protected function tearDown()
{
$_SERVER = $this->oldServer;
TestAssetStore::reset();
parent::tearDown();
}
}
/**
* Tests for {@link Config::inst()->get('SSViewer', 'theme')} for different behaviour
* of user defined themes via {@link SiteConfig} and default theme
* when no user themes are defined.
*/
public function testCurrentTheme()
{
public function testCurrentTheme()
{
SSViewer::config()->update('theme', 'mytheme');
$this->assertEquals(
'mytheme',
SSViewer::config()->uninherited('theme'),
'Current theme is the default - user has not defined one'
);
}
}
/**
* Test that a template without a <head> tag still renders.
*/
public function testTemplateWithoutHeadRenders()
{
public function testTemplateWithoutHeadRenders()
{
$data = new ArrayData(
array(
'Var' => 'var value'
@ -89,10 +88,10 @@ public function testTemplateWithoutHeadRenders()
$result = $data->renderWith("SSViewerTestPartialTemplate");
$this->assertEquals('Test partial template: var value', trim(preg_replace("/<!--.*-->/U", '', $result)));
}
}
public function testIncludeScopeInheritance()
{
public function testIncludeScopeInheritance()
{
$data = $this->getScopeInheritanceTestData();
$expected = array(
'Item 1 - First-ODD top:Item 1',
@ -118,10 +117,10 @@ public function testIncludeScopeInheritance()
$result = $data->renderWith('SSViewerTestIncludeScopeInheritanceWithArgs');
$this->assertExpectedStrings($result, $expected);
}
}
public function testIncludeTruthyness()
{
public function testIncludeTruthyness()
{
$data = new ArrayData(
array(
'Title' => 'TruthyTest',
@ -151,10 +150,10 @@ public function testIncludeTruthyness()
'7 _ 7 - Last-ODD top:7'
);
$this->assertExpectedStrings($result, $expected);
}
}
private function getScopeInheritanceTestData()
{
private function getScopeInheritanceTestData()
{
return new ArrayData(
array(
'Title' => 'TopTitleValue',
@ -170,17 +169,17 @@ private function getScopeInheritanceTestData()
)
)
);
}
}
private function assertExpectedStrings($result, $expected)
{
private function assertExpectedStrings($result, $expected)
{
foreach ($expected as $expectedStr) {
$this->assertTrue(
(boolean) preg_match("/{$expectedStr}/", $result),
"Didn't find '{$expectedStr}' in:\n{$result}"
);
}
}
}
/**
* Small helper to render templates from strings
@ -190,17 +189,17 @@ private function assertExpectedStrings($result, $expected)
* @param bool $cacheTemplate
* @return string
*/
public function render($templateString, $data = null, $cacheTemplate = false)
{
public function render($templateString, $data = null, $cacheTemplate = false)
{
$t = SSViewer::fromString($templateString, $cacheTemplate);
if (!$data) {
$data = new SSViewerTest\TestFixture();
}
return trim(''.$t->process($data));
}
}
public function testRequirements()
{
public function testRequirements()
{
$requirements = $this->getMockBuilder(Requirements_Backend::class)->setMethods(array("javascript", "css"))
->getMock();
$jsFile = FRAMEWORK_DIR . '/tests/forms/a.js';
@ -218,10 +217,10 @@ public function testRequirements()
Requirements::set_backend($origReq);
$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->setSuffixRequirements(false);
//$combinedTestFilePath = BASE_PATH . '/' . $testBackend->getCombinedFilesFolder() . '/testRequirementsCombine.js';
@ -242,10 +241,10 @@ public function testRequirementsCombine()
}
$combinedTestFileContents = file_get_contents($combinedTestFilePath);
$this->assertContains($jsFileContents, $combinedTestFileContents);
}
}
public function testRequirementsMinification()
{
public function testRequirementsMinification()
{
$testBackend = Injector::inst()->create(Requirements_Backend::class);
$testBackend->setSuffixRequirements(false);
$testBackend->setMinifyCombinedFiles(true);
@ -280,12 +279,12 @@ public function testRequirementsMinification()
$testBackend->setMinifyCombinedFiles(true);
$testBackend->setMinifier(null);
$testBackend->processCombinedFiles();
}
}
public function testComments()
{
public function testComments()
{
$output = $this->render(
<<<SS
This is my template<%-- this is a comment --%>This is some content<%-- this is another comment --%>Final content
@ -306,18 +305,18 @@ content
SS;
$this->assertEquals($shouldbe, $output);
}
}
public function testBasicText()
{
public function testBasicText()
{
$this->assertEquals('"', $this->render('"'), 'Double-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 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 wrapped injection');
$this->assertEquals('A[out:Test]!', $this->render('A$Test!'), 'Basic surrounded injection');
@ -333,18 +332,18 @@ public function testBasicInjection()
$this->render('{\\\\$Test}'),
'Escapes before injections are correctly unescaped'
);
}
}
public function testGlobalVariableCalls()
{
public function testGlobalVariableCalls()
{
$this->assertEquals('automatic', $this->render('$SSViewerTest_GlobalAutomatic'));
$this->assertEquals('reference', $this->render('$SSViewerTest_GlobalReferencedByString'));
$this->assertEquals('reference', $this->render('$SSViewerTest_GlobalReferencedInArray'));
}
}
public function testGlobalVariableCallsWithArguments()
{
public function testGlobalVariableCallsWithArguments()
{
$this->assertEquals('zz', $this->render('$SSViewerTest_GlobalThatTakesArguments'));
$this->assertEquals('zFooz', $this->render('$SSViewerTest_GlobalThatTakesArguments("Foo")'));
$this->assertEquals(
@ -355,10 +354,10 @@ public function testGlobalVariableCallsWithArguments()
'zreferencez',
$this->render('$SSViewerTest_GlobalThatTakesArguments($SSViewerTest_GlobalReferencedByString)')
);
}
}
public function testGlobalVariablesAreEscaped()
{
public function testGlobalVariablesAreEscaped()
{
$this->assertEquals('<div></div>', $this->render('$SSViewerTest_GlobalHTMLFragment'));
$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',
$this->render('$SSViewerTest_GlobalThatTakesArguments($SSViewerTest_GlobalHTMLEscaped)')
);
}
}
public function testCoreGlobalVariableCalls()
{
public function testCoreGlobalVariableCalls()
{
$this->assertEquals(
Director::absoluteBaseURL(),
$this->render('{$absoluteBaseURL}'),
@ -459,10 +458,10 @@ public function testCoreGlobalVariableCalls()
(bool)$this->render('{$hasPerm(\'ADMIN\')}'),
'Permissions template functions result correct result'
);
}
}
public function testNonFieldCastingHelpersNotUsedInHasValue()
{
public function testNonFieldCastingHelpersNotUsedInHasValue()
{
// check if Link without $ in front of variable
$result = $this->render(
'A<% if Link %>$Link<% end_if %>B',
@ -476,10 +475,10 @@ public function testNonFieldCastingHelpersNotUsedInHasValue()
new SSViewerTest\TestObject()
);
$this->assertEquals('Asome/url.htmlB', $result, 'casting helper not used for <% if $Link %>');
}
}
public function testLocalFunctionsTakePriorityOverGlobals()
{
public function testLocalFunctionsTakePriorityOverGlobals()
{
$data = new ArrayData(
array(
'Page' => new SSViewerTest\TestObject()
@ -508,10 +507,10 @@ public function testLocalFunctionsTakePriorityOverGlobals()
$result,
"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 = new ArrayData(
array(
@ -574,10 +573,10 @@ public function testCurrentScopeLoopWith()
$data
);
$this->assertEquals("SubKid1SubKid2Number6", $result, "Loop in current scope works");
}
}
public function testObjectDotArguments()
{
public function testObjectDotArguments()
{
$this->assertEquals(
'[out:TestObject.methodWithOneArgument(one)]
[out:TestObject.methodWithTwoArguments(one,two)]
@ -598,10 +597,10 @@ public function testObjectDotArguments()
$TestMethod(Arg1)'
)
);
}
}
public function testEscapedArguments()
{
public function testEscapedArguments()
{
$this->assertEquals(
'[out:Foo(Arg1,Arg2).Bar.Val].Suffix
[out:Foo(Arg1,Arg2).Val]_Suffix
@ -624,10 +623,10 @@ public function testEscapedArguments()
{$Foo}.Suffix'
)
);
}
}
public function testLoopWhitespace()
{
public function testLoopWhitespace()
{
$this->assertEquals(
'before[out:SingleItem.Test]after
beforeTestafter',
@ -676,10 +675,10 @@ $ItemOnItsOwnLine
after'
)
);
}
}
public function testControls()
{
public function testControls()
{
// Single item controls
$this->assertEquals(
'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]',
$this->render('<% loop Loop2(Arg1, Arg2, Arg3) %>$Item<% end_loop %>')
);
}
}
public function testIfBlocks()
{
public function testIfBlocks()
{
// Basic test
$this->assertEquals(
'AC',
@ -907,10 +906,10 @@ public function testIfBlocks()
'ABC',
$this->render('A<% if NotSet %><% else %>B<% end_if %>C')
);
}
}
public function testBaseTagGeneration()
{
public function testBaseTagGeneration()
{
// XHTML wil have a closed base tag
$tmpl1 = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
@ -956,10 +955,10 @@ public function testBaseTagGeneration()
$response = new HTTPResponse($this->render($tmpl1));
$negotiator->xhtml($response);
$this->assertRegExp('/<head><base href=".*" \/><\/head>/', $response->getBody());
}
}
public function testIncludeWithArguments()
{
public function testIncludeWithArguments()
{
$this->assertEquals(
$this->render('<% include SSViewerTestIncludeWithArguments %>'),
'<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 %>');
$res = $tmpl->process($data);
$this->assertEqualIgnoringWhitespace('A B', $res, 'Objects can be passed as named arguments');
}
}
public function testNamespaceInclude()
{
public function testNamespaceInclude()
{
$data = new ArrayData([]);
$this->assertEquals(
@ -1080,11 +1079,11 @@ public function testNamespaceInclude()
$this->render('tests:( <% include Namespace/NamespaceInclude %> )', $data),
'Forward slashes work for namespace references in includes'
);
}
}
public function testRecursiveInclude()
{
public function testRecursiveInclude()
{
$view = new SSViewer(array('Includes/SSViewerTestRecursiveInclude'));
$data = new ArrayData(
@ -1115,19 +1114,19 @@ public function testRecursiveInclude()
$rationalisedResult = trim(preg_replace('/\s+/', ' ', $result));
$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);
}
}
/**
* See {@link ViewableDataTest} for more extensive casting tests,
* this test just ensures that basic casting is correctly applied during template parsing.
*/
public function testCastingHelpers()
{
public function testCastingHelpers()
{
$vd = new SSViewerTest\TestViewableData();
$vd->TextValue = '<b>html</b>';
$vd->HTMLValue = '<b>html</b>';
@ -1176,10 +1175,10 @@ public function testCastingHelpers()
'&lt;b&gt;html&lt;/b&gt;',
$t = SSViewer::fromString('$UncastedValue.XML')->process($vd)
);
}
}
public function testSSViewerBasicIteratorSupport()
{
public function testSSViewerBasicIteratorSupport()
{
$data = new ArrayData(
array(
'Set' => new ArrayList(
@ -1310,13 +1309,13 @@ public function testSSViewerBasicIteratorSupport()
//test MultipleOf 11
$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");
}
}
/**
* 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 = new ArrayData(
@ -1398,13 +1397,13 @@ public function testUpInWith()
'Foo',
$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
*/
public function testUpInLoop()
{
public function testUpInLoop()
{
// Data to run the loop tests on - one sequence of three items, each with a subitem
$data = new ArrayData(
@ -1491,13 +1490,13 @@ public function testUpInLoop()
$data
)
);
}
}
/**
* 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
// (of a different size to the main sequence)
@ -1551,10 +1550,10 @@ public function testNestedLoops()
$data
)
);
}
}
public function testLayout()
{
public function testLayout()
{
$this->useTestTheme(
__DIR__.'/SSViewerTest',
'layouttest',
@ -1566,13 +1565,13 @@ public function testLayout()
$this->assertEquals("[file_link]\n\n", $template->process(new ArrayData(array())));
}
);
}
}
/**
* @covers \SilverStripe\View\SSViewer::get_templates_by_class()
*/
public function testGetTemplatesByClass()
{
public function testGetTemplatesByClass()
{
$this->useTestTheme(
__DIR__ . '/SSViewerTest',
'layouttest',
@ -1645,10 +1644,10 @@ public function testGetTemplatesByClass()
SSViewer::get_templates_by_class(array());
}
);
}
}
public function testRewriteHashlinks()
{
public function testRewriteHashlinks()
{
SSViewer::config()->update('rewrite_hash_links', true);
$_SERVER['HTTP_HOST'] = 'www.mysite.com';
@ -1710,10 +1709,10 @@ public function testRewriteHashlinks()
);
unlink($tmplFile);
}
}
public function testRewriteHashlinksInPhpMode()
{
public function testRewriteHashlinksInPhpMode()
{
SSViewer::config()->update('rewrite_hash_links', 'php');
$tmplFile = TEMP_FOLDER . '/SSViewerTest_testRewriteHashlinksInPhpMode_' . sha1(rand()) . '.ss';
@ -1755,10 +1754,10 @@ EOC;
);
unlink($tmplFile);
}
}
public function testRenderWithSourceFileComments()
{
public function testRenderWithSourceFileComments()
{
Director::set_environment_type('dev');
SSViewer::config()->update('source_file_comments', true);
$i = __DIR__ . '/SSViewerTest/templates/Includes';
@ -1844,27 +1843,27 @@ public function testRenderWithSourceFileComments()
foreach ($templates as $template) {
$this->_renderWithSourceFileComments('SSViewerTestComments/'.$template['name'], $template['expected']);
}
}
private function _renderWithSourceFileComments($name, $expected)
{
}
private function _renderWithSourceFileComments($name, $expected)
{
$viewer = new SSViewer(array($name));
$data = new ArrayData(array());
$result = $viewer->process($data);
$expected = str_replace(array("\r", "\n"), '', $expected);
$result = str_replace(array("\r", "\n"), '', $result);
$this->assertEquals($result, $expected);
}
}
public function testLoopIteratorIterator()
{
public function testLoopIteratorIterator()
{
$list = new PaginatedList(new ArrayList());
$viewer = new SSViewer_FromString('<% loop List %>$ID - $FirstName<br /><% end_loop %>');
$result = $viewer->process(new ArrayData(array('List' => $list)));
$this->assertEquals($result, '');
}
}
public function testProcessOnlyIncludesRequirementsOnce()
{
public function testProcessOnlyIncludesRequirementsOnce()
{
$template = new SSViewer(array('SSViewerTestProcess'));
$basePath = $this->getCurrentRelativePath() . '/SSViewerTest';
@ -1887,10 +1886,10 @@ public function testProcessOnlyIncludesRequirementsOnce()
$template->includeRequirements(false);
$this->assertEquals(0, substr_count($template->process(array()), "a.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)
if (FRAMEWORK_DIR === 'framework') {
$template = new SSViewer(array('SSViewerTestProcess'));
@ -1910,10 +1909,10 @@ public function testRequireCallInTemplateInclude()
'named \'framework\', since templates require hard coded paths'
);
}
}
}
public function testCallsWithArguments()
{
public function testCallsWithArguments()
{
$data = new ArrayData(
array(
'Set' => new ArrayList(
@ -1954,10 +1953,10 @@ public function testCallsWithArguments()
foreach ($tests as $template => $expected) {
$this->assertEquals($expected, trim($this->render($template, $data)));
}
}
}
public function testRepeatedCallsAreCached()
{
public function testRepeatedCallsAreCached()
{
$data = new SSViewerTest\CacheTestData();
$template = '
<% if $TestWithCall %>
@ -1989,10 +1988,10 @@ public function testRepeatedCallsAreCached()
$data->testLoopCalls,
'SSViewerTest_CacheTestData::TestLoopCall() should only be called once. Subsequent calls should be cached'
);
}
}
public function testClosedBlockExtension()
{
public function testClosedBlockExtension()
{
$count = 0;
$parser = new SSTemplateParser();
$parser->addClosedBlock(
@ -2006,10 +2005,10 @@ public function testClosedBlockExtension()
$template->process(new SSViewerTest\TestFixture());
$this->assertEquals(1, $count);
}
}
public function testOpenBlockExtension()
{
public function testOpenBlockExtension()
{
$count = 0;
$parser = new SSTemplateParser();
$parser->addOpenBlock(
@ -2023,13 +2022,13 @@ public function testOpenBlockExtension()
$template->process(new SSViewerTest\TestFixture());
$this->assertEquals(1, $count);
}
}
/**
* Tests if caching for SSViewer_FromString is working
*/
public function testFromStringCaching()
{
public function testFromStringCaching()
{
$content = 'Test content';
$cacheFile = TEMP_FOLDER . '/.cache.' . sha1($content);
if (file_exists($cacheFile)) {
@ -2052,5 +2051,5 @@ public function testFromStringCaching()
$this->render($content, null, true);
$this->assertTrue(file_exists($cacheFile), 'Cache file wasn\'t created when it was meant to');
unlink($cacheFile);
}
}
}