Minifies JavaScript

@param string $script Script to minify
@param string $error Error message (if any)
@return string Minified script or source string if error happened
331018
public static function minifyJavaScript($script, &$error = '') {
		require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
		try {
			$error = '';
			$script = trim(JSMin::minify(str_replace(CR, '', $script)));
		}
		catch (JSMinException $e) {
			$error = 'Error while minifying JavaScript: ' . $e->getMessage();
			self::devLog($error, 't3lib_div', 2,
				array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
		}
		return $script;
	}
146571
public static function buildHtmlScript($script, array $attributes = []): string
    {
        $scriptCleaned = trim($script);
        if ($scriptCleaned !== '') {
            return self::buildHtmlElement('script', $attributes, "\n" . $scriptCleaned . "\n");
        }
        return '';
    }
580241
public function prepare(Script $script)
    {
        $script->addCustomScriptLabel(ScriptLabel::MouseClick, $this->getScriptMouseClick());
        $script->addCustomScriptLabel(ScriptLabel::OnInit, $this->getScriptInit());
        $script->addCustomScriptLabel(ScriptLabel::Loop, $this->getScriptLoop());
    }
752912
function minifycss($file)
    {
        $minifiedFileName = $this->checkIfFileWasUpdated($file);
        if ($minifiedFileName) {
            $fileContent = file_get_contents(ROOTPATH . $file);
            $cssmin = new CSSmin();
            file_put_contents(ROOTPATH . $minifiedFileName, $cssmin->run($fileContent));
            return $minifiedFileName;
        }
        return $file;
    }
170588
public function scriptBlock($script, $options = array()) {
		$options = array_merge(array('block' => 'script', 'key' => null), $options);

		$key = $options['key'];
		unset($options['key']);
		if (!$key) {
			$key = md5($script);
		}

		$this->scriptBlock[$key] = compact('script', 'options');
	}
270893
private function _basicCompression($script)
    {
        $parser = new ParseMaster();
        // make safe
        $parser->escapeChar = '\\';
        // protect strings
        $parser->add('/\'[^\'\\n\\r]*\'/', self::IGNORE);
        $parser->add('/"[^"\\n\\r]*"/', self::IGNORE);
        // remove comments
        $parser->add('/\\/\\/[^\\n\\r]*[\\n\\r]/', ' ');
        $parser->add('/\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\//', ' ');
        // protect regular expressions
        $parser->add('/\\s+(\\/[^\\/\\n\\r\\*][^\\/\\n\\r]*\\/g?i?)/', '$2'); // IGNORE
        $parser->add('/[^\\w\\x24\\/\'"*)\\?:]\\/[^\\/\\n\\r\\*][^\\/\\n\\r]*\\/g?i?/', self::IGNORE);
        // remove: ;;; doSomething();
        if ($this->_specialChars) $parser->add('/;;;[^\\n\\r]+[\\n\\r]/');
        // remove redundant semi-colons
        $parser->add('/\\(;;\\)/', self::IGNORE); // protect for (;;) loops
        $parser->add('/;+\\s*([};])/', '$2');
        // apply the above
        $script = $parser->exec($script);

        // remove white-space
        $parser->add('/(\\b|\\x24)\\s+(\\b|\\x24)/', '$2 $3');
        $parser->add('/([+\\-])\\s+([+\\-])/', '$2 $3');
        $parser->add('/\\s+/', '');
        // done
        return $parser->exec($script);
    }
579529
public function minify($htmlText = "")
    {
        if ($this->shouldMinify) {
            $options = [
                'cssMinifier' => '\Minify_CSSmin::minify',
                'jsMinifier' => '\JSMin\JSMin::minify',
            ];
            $htmlText = \Minify_HTML::minify($htmlText, $options);
        }

        return $htmlText;
    }
209467
protected function compressInlineJsCode($js)
    {
        if (!($js = (string) $js)) {
            return $js; // Nothing to do.
        }
        if (($compressed_js = \WebSharks\JsMinifier\Core::compress($js))) {
            return '/*<![CDATA[*/'.$compressed_js.'/*]]>*/';
        }
        return $js;
    }
89444
protected function sendAjaxError($error)
    {
        if ($this->getRequest()->is('json')) {
            $this->getResponse()->withStatus(500);
            $response = [
                'status' => APP_OFF,
                'msg' => $error->getMessage()
            ];
            $this->set(compact('response'));
            $this->render('/Error/errorjson');
        }
    }
371804
public function min(float $min, string $error = 'not at least %d') : Real
    {
        return $this->pipe(
            self::predicate(
                function (float $value) use ($min) : bool {
                    return $value >= $min;
                },
                sprintf($error, $min)
            )
        );
    }
504672
function script($script, $scriptId = null) {
        if (!isset($scriptId) || !isset($this->_scriptIds[$scriptId])) {
            $this->_scripts[] = $script;
            if (isset($scriptId)) $this->_scriptIds[$scriptId] = true;
        }
    }
925138
private function preg_error_message( $error ) {
		static $error_names = null;

		if ( null === $error_names ) {
			$definitions    = get_defined_constants( true );
			$pcre_constants = array_key_exists( 'pcre', $definitions )
				? $definitions['pcre']
				: array();
			$error_names    = array_flip( $pcre_constants );
		}

		return isset( $error_names[ $error ] )
			? $error_names[ $error ]
			: '<unknown error>';
	}
685059
private function fixSelfExecutingFunction($script)
    {
        if (preg_match('/^function[\s\(]/', $script)) {
            $script = preg_replace('/;$/', '', $script);
            $script = '(' . $script . ')';
        }

        return $script;
    }
1231204
protected function addDoValidate(&$script)
    {
        $table = $this->getTable();

        $script .= "
    /**
     * This function performs the validation work for complex object models.
     *
     * In addition to checking the current object, all related objects will
     * also be validated.  If all pass then <code>true</code> is returned; otherwise
     * an aggregated array of ValidationFailed objects will be returned.
     *
     * @param array \$columns Array of column names to validate.
     * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objects otherwise.
     */
    protected function doValidate(\$columns = null)
    {
        if (!\$this->alreadyInValidation) {
            \$this->alreadyInValidation = true;
            \$retval = null;

            \$failureMap = array();
";
        if (count($table->getForeignKeys()) != 0) {
            $script .= "

            // We call the validate method on the following object(s) if they
            // were passed to this object by their corresponding set
            // method.  This object relates to these object(s) by a
            // foreign key reference.
";
            foreach ($table->getForeignKeys() as $fk) {
                $aVarName = $this->getFKVarName($fk);
                $script .= "
            if (\$this->" . $aVarName . " !== null) {
                if (!\$this->" . $aVarName . "->validate(\$columns)) {
                    \$failureMap = array_merge(\$failureMap, \$this->" . $aVarName . "->getValidationFailures());
                }
            }
";
            } /* for () */
        } /* if count(fkeys) */

        $script .= "

            if ((\$retval = " . $this->getPeerClassname() . "::doValidate(\$this, \$columns)) !== true) {
                \$failureMap = array_merge(\$failureMap, \$retval);
            }

";

        foreach ($table->getReferrers() as $refFK) {
            if ($refFK->isLocalPrimaryKey()) {
                $varName = $this->getPKRefFKVarName($refFK);
                $script .= "
                if (\$this->$varName !== null) {
                    if (!\$this->" . $varName . "->validate(\$columns)) {
                        \$failureMap = array_merge(\$failureMap, \$this->" . $varName . "->getValidationFailures());
                    }
                }
";
            } else {
                $collName = $this->getRefFKCollVarName($refFK);
                $script .= "
                if (\$this->$collName !== null) {
                    foreach (\$this->$collName as \$referrerFK) {
                        if (!\$referrerFK->validate(\$columns)) {
                            \$failureMap = array_merge(\$failureMap, \$referrerFK->getValidationFailures());
                        }
                    }
                }
";
            }
        } /* foreach getReferrers() */

        $script .= "

            \$this->alreadyInValidation = false;
        }

        return (!empty(\$failureMap) ? \$failureMap : true);
    }
";
    }
596250
protected function setJavascriptFileCDN($jsFileName)
    {
        $onlyFileName = pathinfo($jsFileName)['basename'];
        $patternFound = null;
        if (in_array($onlyFileName, ['jquery.placeholder.min.js', 'jquery.easing.1.3.min.js'])) {
            $patternFound = $this->setJavascriptFileCDNjQueryLibs($jsFileName);
        } elseif (strpos($onlyFileName, '-') !== false) {
            $patternFound = $this->setJavascriptFileCDNbyPattern($jsFileName);
        }
        if (is_null($patternFound)) {
            $patternFound = [false, $this->sanitizeString($jsFileName), ''];
        }
        return $patternFound;
    }
321895
public function setJs($script, array $options = array())
    {
        $options['type'] = 'js';
        $options['asset'] = $script;

        return $this->asset->set($options);
    }
770080
public function minify($content, $type, $fileName)
    {
        if ($type == 'css') {
            $minifier = new Minify\CSS();
            $minifier->add($content);
            return $minifier->minify();
        } elseif ($type == 'js') {
            $minifier = new Minify\JS();
            $minifier->add($content);
            return $minifier->minify() . ';';
        }
        return $content;
    }