/** * Rewrites require js script. * * @param string Input module path * @param string Rewritten module javascript */ public static function rewrite(\Adadgio\Common\Config $config, $modulePath, $kernelMode = false) { $script = file_get_contents($modulePath); $moduleBasename = basename($modulePath); $moduleRawname = Dependency::removeExtension($moduleBasename, Dependency::EXT_JS); // check if the rewrite happens inside the "_build" directory or the top directory (for kernel file) // depending on that option, use the config build dir to prefix the modules or just not prefix (for kernel file) $buildDirectory = true === $kernelMode ? '' : $config->get('build_dir'); // when the module is a shim... if ($name = Dependency::isInGlobalpathes($modulePath)) { $moduleBasename = basename($buildDirectory) . '/' . $name; $moduleBasename = ltrim($moduleBasename, '/'); // there might be exceptions for non AMD compliant modules if ($config->has('amd_compliance_wrap')) { $wrap = $config->get('amd_compliance_wrap'); if (isset($wrap[$name])) { $script = "define('{$moduleBasename}', function () { \n{$script}" . "\n" . "});"; } } } else { // else rewrite a normal module $moduleBasename = self::unquote($moduleBasename); $moduleBasename = basename($buildDirectory) . '/' . Dependency::removeExtension($moduleBasename); $moduleBasename = ltrim($moduleBasename, '/'); } // rewrite the module name itself when there are no dependencies by finding strings // like "define(function () {..." and adding the current module name after the define call $script = preg_replace_callback(static::DEFINE_MODU_REGEX, function ($match) use($config, $moduleBasename, $buildDirectory) { if (empty($moduleBasename)) { exit('Nooot'); } return sprintf("define('%s' ,function", $moduleBasename); }, $script); // remove trailing commas in the script. if fixes a lot of stuf... // read and replace all the current module dependencies pathes inside the script so that // they are relative to the build directory by rewriting strings like "define(['dep1'], ['dep2']... function" $script = preg_replace_callback(static::DEFINE_DEPS_REGEX, function ($match) use($config, $moduleBasename, $buildDirectory) { // $def = $m[1]; // start of expression"define(" // $mod = $m[2]; // module name "framework/Config/GlobalConfig" // $func = $m[3]; // rest of expression "" $imports = array_map('trim', array_filter(explode(',', $match[1]))); $imports = array_filter($imports); foreach ($imports as $i => $import) { $basename = basename(self::unquote($import)); $imports[$i] = self::quote(basename($buildDirectory) . '/' . $basename); // self::quote } $importStr = implode(',', $imports); return sprintf("define('%s', [%s], function", $moduleBasename, $importStr); }, $script); return $script; }