monomelodies / karma-ng-php2js-preprocessor

Preprocess PHP files for inclusion in Angular unit tests
MIT License
0 stars 1 forks source link

The module won't load if ES6 is not available #1

Open obregon08 opened 8 years ago

obregon08 commented 8 years ago

I ran into this issue because I didn't have Babel setup. Sooo... I decided to just replace ES6 specific stuff with ES5. Below the updated lib/php2js.js file.

var util = require('util');
var exec = require('child_process').exec;

var TEMPLATE = "angular.module('%s', []).run(['$templateCache', function($templateCache) {\
    $templateCache.put('%s',\n    '%s');\
}]);\
";

var SINGLE_MODULE_TPL = "(function(module) {\
    try {\
        module = angular.module('%s');\
    } catch (e) {\
        module = angular.module('%s', []);\
    }\
    module.run(['$templateCache', function($templateCache) {\
        $templateCache.put('%s', '%s');\
    }]);\
})();\
";

var REQUIRE_MODULE_TPL = 'require([\'%s\'], function(angular) {%s});\n';

var ANGULAR2_TPL = "window.$templateCache = window.$templateCache || {};\
window.$templateCache['%s'] = '%s';\
";

/**
 * Helper to escape HTML content for inclusion in Javascript string.
 *
 * @param string content Unescaped content
 * @return string Escaped content
 */
function escapeContent(content) {
    return content.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\r?\n/g, "\\n' +\n    '");
}

/**
 * Main "constructor" method.
 *
 * @param Logger logger Karma preprocessor logger
 * @param string basePath The base path for the file processed
 * @param object config Config object
 * @return function Processor function
 */
function createPhp2JsPreprocessor(logger, basePath, config) {
    config = typeof config === 'object' ? config : {}
    var log = logger.create('preprocessor.html2js');
    var getModuleName = typeof config.moduleName === 'function' ? config.moduleName : function() { return config.moduleName; }
    var stripPrefix = new RegExp('^' + (config.stripPrefix || ''));
    var prependPrefix = config.prependPrefix || '';
    var stripSuffix = new RegExp((config.stripSuffix || config.stripSuffix || '') + '$');
    var cacheIdFromPath = undefined;
    var phpBin = config.phpBin ? config.phpBin : '/usr/bin/php';
    if (config.cacheIdFromPath && config.cacheIdFromPath != 'default') {
        cacheIdFromPath = config.cacheIdFromPath;
    } else {
        cacheIdFromPath = function(filepath){ return prependPrefix + filepath.replace(stripPrefix, '').replace(stripSuffix, '').replace(/\.php$/, '.html');}
    }
    var enableRequireJs = config.enableRequireJs;
    var requireJsAngularId = config.requireJsAngularId || 'angular';
    var angular = config.angular || 1;
    return function (content, file, done) {
        log.debug('Executing "%s".', file.originalPath);
        exec(phpBin + ' ' + file.originalPath, function(err, stdout, stderr) {
            log.debug('Processing "%s".', file.originalPath);

            if (err) {
                console.log('Err:', err);
            }
            var originalPath = file.originalPath.replace(basePath + '/', '');
            var htmlPath = cacheIdFromPath(originalPath);
            var moduleName = getModuleName(htmlPath, originalPath);

            if (!/\.js$/.test(file.path)) {
                file.path = file.path + '.js'
            }
            var tpl = '';
            if (angular === 2 || angular === '2') {
                tpl = util.format(ANGULAR2_TPL, htmlPath, escapeContent(stdout));
            } else {
                if (moduleName) {
                    tpl = util.format(SINGLE_MODULE_TPL, moduleName, moduleName, htmlPath, escapeContent(stdout));
                } else {
                    tpl = util.format(TEMPLATE, htmlPath, htmlPath, escapeContent(stdout));
                }

                if (enableRequireJs) {
                    tpl = util.format(REQUIRE_MODULE_TPL, requireJsAngularId, tpl);
                }
            }
            done(tpl);
        });
    };
}

createPhp2JsPreprocessor.$inject = ['logger', 'config.basePath', 'config.ngPhp2JsPreprocessor'];

module.exports = createPhp2JsPreprocessor;
monomelodies commented 8 years ago

You shouldn't need Babel - recent versions of the V8 engine support const and let natively. You should upgrade your NodeJS environment. Thanks for pointing that out though - maybe i'll add a note to that extent in the README.md.

Out of curiosity, which version are you using now and how are you calling the library exactly?

(If I'd had written this in ES6 I would also have used classes and lambda functions ;)).

obregon08 commented 8 years ago

For compatibility reasons with the rest of the ecosystem in which other developers at work run their dev boxes, I'm pretty much forced to these versions:

$ node -v
v0.12.14
$ npm -v 
2.15.1
$ php -v
PHP 5.5.37 (cli) (built: Jul  6 2016 12:02:06) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
monomelodies commented 8 years ago

That's... pretty ancient. But having said that, just replacing const/let with var doesn't hurt it in any way either, so if you create a pull request I'll be happy to merge it in.