minify framework source code
@return int
765574
public function minifyCommand()
    {
        $ManaPHPSrcDir = $this->alias->get('@manaphp');
        $ManaPHPDstDir = $ManaPHPSrcDir . '_' . date('ymd');
        $totalClassLines = 0;
        $totalInterfaceLines = 0;
        $totalLines = 0;
        $fileLines = [];
        $sourceFiles = $this->_getSourceFiles($ManaPHPSrcDir);
        foreach ($sourceFiles as $file) {
            $dstFile = str_replace($ManaPHPSrcDir, $ManaPHPDstDir, $file);

            $content = $this->_minify($this->filesystem->fileGet($file));
            $lineCount = substr_count($content, strpos($content, "\r") !== false ? "\r" : "\n");

            if (strpos($file, 'Interface.php')) {
                $totalInterfaceLines += $lineCount;
                $totalLines += $lineCount;
            } else {
                $totalClassLines += $lineCount;
                $totalLines += $lineCount;
            }

            $this->console->writeLn($content);
            $this->filesystem->filePut($dstFile, $content);
            $fileLines[$file] = $lineCount;
        }

        asort($fileLines);

        $i = 1;
        $this->console->writeLn('------------------------------------------------------');

        foreach ($fileLines as $file => $line) {
            $this->console->writeLn(sprintf('%3d %3d %.3f', $i++, $line, $line / $totalLines * 100) . ' ' . substr($file, strpos($file, 'ManaPHP')));
        }

        $this->console->writeLn('------------------------------------------------------');
        $this->console->writeLn('total     lines: ' . $totalLines);
        $this->console->writeLn('class     lines: ' . $totalClassLines);
        $this->console->writeLn('interface lines:  ' . $totalInterfaceLines);

        return 0;
    }
834067
public function getCss(){

		$precision = ini_get('precision');
		@ini_set('precision',16);
		$locale = setlocale(LC_NUMERIC, 0);
		setlocale(LC_NUMERIC, "C");

		try {

	 		$root = new Less_Tree_Ruleset(array(), $this->rules );
			$root->root = true;
			$root->firstRoot = true;


			$this->PreVisitors($root);

			self::$has_extends = false;
			$evaldRoot = $root->compile($this->env);



			$this->PostVisitors($evaldRoot);

			if( Less_Parser::$options['sourceMap'] ){
				$generator = new Less_SourceMap_Generator($evaldRoot, Less_Parser::$contentsMap, Less_Parser::$options );
				// will also save file
				// FIXME: should happen somewhere else?
				$css = $generator->generateCSS();
			}else{
				$css = $evaldRoot->toCSS();
			}

			if( Less_Parser::$options['compress'] ){
				$css = preg_replace('/(^(\s)+)|((\s)+$)/', '', $css);
			}

		} catch (Exception $exc) {
			// Intentional fall-through so we can reset environment
		}

		//reset php settings
		@ini_set('precision',$precision);
		setlocale(LC_NUMERIC, $locale);

		// If you previously defined $this->mb_internal_encoding
		// is required to return the encoding as it was before
		if ($this->mb_internal_encoding != '') {
			@ini_set("mbstring.internal_encoding", $this->mb_internal_encoding);
			$this->mb_internal_encoding = '';
		}

		// Rethrow exception after we handled resetting the environment
		if (!empty($exc)) {
			throw $exc;
		}



		return $css;
	}
101875
public function process(MinifyContext $context)
    {
        $context->setContents($this->trailingWhitespaces($context->getContents()));
        $context->setContents($this->runMinificationRules($context->getContents()));
        $context->setContents($this->removeSpacesAroundPlaceholders($context->getContents()));

        return $context->setContents($this->maxHtmlLineLength($context->getContents(), $this->maxHtmlLineLength));
    }
446302
public function minify()
    {
        $css_files = $this->cleanStack($this->get(), 'file');

        $organized_css = array('rest'=>array());
        foreach ($css_files as $_file) {
            if (!empty($_file['media'])) {
                if (!isset($organized_css[ $_file['media'] ])) {
                    $organized_css[ $_file['media'] ] = array();
                }
                $organized_css[ $_file['media'] ][] = $_file;
            } else {
                $organized_css['rest'][] = $_file;
            }
        }

        foreach ($organized_css as $media=>$stack) {
            $cleaned_stack = $this->extractFromStack($stack, 'file');
            if (!empty($cleaned_stack)) {
                $this->addMinified(
                    $this->minifyStack($cleaned_stack), $media=='rest' ? 'screen' : $media
                );
            }
        }

        return $this;
    }
583760
public function getDefaultOptions()
    {
        return array(
            'isPublic' => true,
            'encodeOutput' => function_exists('gzdeflate'),
            'encodeMethod' => null, // determine later
            'encodeLevel' => 9,

            'minifiers' => array(
                Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
                Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
                Minify::TYPE_HTML => array('Minify_HTML', 'minify'),
            ),
            'minifierOptions' => array(), // no minifier options

            'contentTypeCharset' => 'utf-8',
            'maxAge' => 1800, // 30 minutes
            'rewriteCssUris' => true,
            'bubbleCssImports' => false,
            'quiet' => false, // serve() will send headers and output
            'debug' => false,
            'concatOnly' => false,

            // if you override these, the response codes MUST be directly after
            // the first space.
            'badRequestHeader' => 'HTTP/1.0 400 Bad Request',
            'errorHeader' => 'HTTP/1.0 500 Internal Server Error',

            // callback function to see/modify content of all sources
            'postprocessor' => null,
            // file to require to load preprocessor
            'postprocessorRequire' => null,

            /**
             * If this string is not empty AND the serve() option 'bubbleCssImports' is
             * NOT set, then serve() will check CSS files for @import declarations that
             * appear too late in the combined stylesheet. If found, serve() will prepend
             * the output with this warning.
             */
            'importWarning' => "/* See https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#imports-can-appear-in-invalid-locations-in-combined-css-files */\n"
        );
    }
102173
protected function minifyCss()
    {
        $output = '';

        // Core variables and mixins
        $output .= '@import "variables.less";';
        $output .= '@import "mixins.less";';

        // Reset and dependencies
        $output .= $this->prepareCssForLess('normalize');
        $output .= $this->prepareCssForLess('print');
        $output .= $this->prepareCssForLess('glyphicons');

        // Core CSS
        $output .= $this->prepareCssForLess('scaffolding');
        $output .= $this->prepareCssForLess('type');
        $output .= $this->prepareCssForLess('code');
        $output .= $this->prepareCssForLess('grid');
        $output .= $this->prepareCssForLess('tables');
        $output .= $this->prepareCssForLess('forms');
        $output .= $this->prepareCssForLess('buttons');

        // Components
        $output .= $this->prepareCssForLess('component-animations');
        $output .= $this->prepareCssForLess('dropdowns');
        $output .= $this->prepareCssForLess('button-groups');
        $output .= $this->prepareCssForLess('input-groups');
        $output .= $this->prepareCssForLess('navs');
        $output .= $this->prepareCssForLess('navbar');
        $output .= $this->prepareCssForLess('breadcrumbs');
        $output .= $this->prepareCssForLess('pagination');
        $output .= $this->prepareCssForLess('pager');
        $output .= $this->prepareCssForLess('labels');
        $output .= $this->prepareCssForLess('badges');
        $output .= $this->prepareCssForLess('jumbotron');
        $output .= $this->prepareCssForLess('thumbnails');
        $output .= $this->prepareCssForLess('alerts');
        $output .= $this->prepareCssForLess('progress-bars');
        $output .= $this->prepareCssForLess('media');
        $output .= $this->prepareCssForLess('list-group');
        $output .= $this->prepareCssForLess('panels');
        $output .= $this->prepareCssForLess('responsive-embed');
        $output .= $this->prepareCssForLess('wells');
        $output .= $this->prepareCssForLess('close');

        // Components w/ JavaScript
        $output .= $this->prepareCssForLess('modals');
        $output .= $this->prepareCssForLess('tooltip');
        $output .= $this->prepareCssForLess('popovers');
        $output .= $this->prepareCssForLess('carousel');

        // Utility classes
        $output .= $this->prepareCssForLess('utilities');
        $output .= $this->prepareCssForLess('responsive-utilities');

        $less = new \Less_Parser();
        $less->SetImportDirs([base_path('vendor/twbs/bootstrap/less') => 'bootstrap']);

        $css = $less->parse($output, 'bootstrap.components.less')->getCss();

        $minifier = new Minify\CSS();
        $minifier->add($css);

        return $minifier->minify();
    }
12275
protected function minify(string $view): string
    {
        $html = $this->compile($view);

        if ($this->minify)
        {
            $html = \Minify_HTML::minify(\trim($html), [
                'cssMinifier' => [\Minify_CSSmin::class, 'minify'],
                'jsMinifier'  => [JSMin::class, 'minify'],
            ]);
        }

        if (!empty($this->extends))
        {
            $html = (new HTML($html, $this->extends))
                ->apply();
        }

        return $html;
    }
849713
public function minify()
    {
        $cleaned_stack = $this->cleanStack($this->get(), 'path');
        if (!empty($cleaned_stack)) {
            foreach ($cleaned_stack as $i=>$item) {
                if (isset($item['minified']) && true===$item['minified']) {
                    unset($cleaned_stack[$i]);
                }
            }
        }
        if (!empty($cleaned_stack)) {
            $this->addMinified(
                $this->minifyStack($this->extractFromStack($cleaned_stack, 'path'))
            );
        }
        return $this;
    }
1223338
public function generate($minify = false)
    {
        $generated = [
            '@context' => 'https://schema.org',
        ];

        if (!empty($this->type)) {
            $generated['@type'] = $this->type;
        }


        if (!empty($this->title)) {
            $generated['name'] = $this->title;
        }


        if (!empty($this->description)) {
            $generated['description'] = $this->description;
        }

        if (!empty($this->url)) {
            $generated['url'] = $this->url;
        }

        if (!empty($this->images)) {
            $generated['image'] = count($this->images) === 1 ? reset($this->images) : json_encode($this->images);
        }

        $generated = array_merge($generated, $this->values);

        return '<script type="application/ld+json">' . json_encode($generated) . '</script>';
    }
1067155
public function GetDeclarationCode()
    {
        $code = "";
        
        if($this->is_const)
            $code .= "const ";
        
        $code .= $this->type;
        
        if($this->is_reference)
            $code .= "&";
        
        if($this->is_pointer)
        {
            for($i=0; $i<$this->indirection_level; $i++)
            {
                $code .= "*";
            }
        }
        
        $code .= " " . $this->name;
        
        if($this->is_array)
            $code .= "[]";
        
        if(trim($this->default_value) != "")
            $code .= " = " . $this->default_value;
    }
935714
protected function compileCss()
    {
        $base = $this->path . "css" . DIRECTORY_SEPARATOR;
        if ($this->debug || !file_exists($base . $this->hash . ".css")) {
            $data = '';
            if (0 < count($this->files)) {
                $minifier = new CSS();
                foreach ($this->files as $file) {
                    $data = $this->processCssLine($file, $base, $data);
                }
            }
            if($this->debug) {
                $this->storeContents($base . $this->hash . ".css", $data);
            } else {
                $minifier = new CSS();
                $minifier->add($data);
                ini_set('max_execution_time', -1);
                ini_set('memory_limit', -1);
                GeneratorHelper::createDir($base);
                $minifier->minify($base . $this->hash . ".css");
                ini_restore('memory_limit');
                ini_restore('max_execution_time');
            }
            unset($minifier);
        }
        return $this;
    }
1326113
public function process(MinifyContext $context)
    {
        Collection::make($this->redundantAttributes)->each(function ($attributes, $element) use (&$context) {
            Collection::make($attributes)->each(function ($value, $attribute) use ($element, &$context) {
                $contents = preg_replace_callback(
                    '/
                        '.$element.'                    # Match the given element
                        ((?!\s*'.$attribute.'\s*=).)*   # Match everything except the given attribute
                        (
                            \s*'.$attribute.'\s*        # Match the attribute
                            =\s*                        # Match the equals sign
                            (["\']?)                    # Match the opening quotes
                            \s*'.$value.'\s*            # Match the value
                            \3?                         # Match the captured opening quotes again
                            \s*
                        )
                    /xis',
                    function ($match) {
                        return $this->removeAttribute($match[0], $match[2]);
                    }, $context->getContents());

                $context->setContents($contents);
            });
        });

        return $context;
    }
3685
public static function minify($input)
    {
        $output = '';
        $input = self::merge($input);

        $inQuotes        = array();
        $noSpacesAround  = '{}()[]<>|&!?:;,+-*/="\'';

        $input = preg_replace("`(\r\n|\r)`", "\n", $input);
        $inputs = str_split($input);
        $inputs_count = count($inputs);
        $prevChr = null;
        for ($i=0; $i<$inputs_count; $i++) {
            $chr = $inputs[$i];
            $nextChr = $i+1 < $inputs_count ? $inputs[$i+1] : null;

            switch ($chr) {
                case '/':
                    if (!count($inQuotes) && $nextChr == '*' && $inputs[$i+2] != '@') {
                        $i = 1 + strpos($input, '*/', $i);
                        continue 2;
                    } elseif (!count($inQuotes) && $nextChr == '/') {
                        if (strpos($input, "\n", $i)) {
                            $i = strpos($input, "\n", $i);
                        } else {
                            $i = strlen($input);
                        }
                        continue 2;
                    } elseif (!count($inQuotes)) {
                        $eolPos = strpos($input, "\n", $i);
                        if ($eolPos===false) {
                            $eolPos = $inputs_count;
                        }
                        $eol = substr($input, $i, $eolPos-$i);
                        if (!preg_match('`^(/.+(?<=\\\/)/(?!/)[gim]*)[^gim]`U', $eol, $m)) {
                            preg_match('`^(/.+(?<!/)/(?!/)[gim]*)[^gim]`U', $eol, $m);
                        }
                        // it's a RegExp
                        if (isset($m[1])) {
                            $output .= $m[1];
                            $i += strlen($m[1])-1;
                            continue 2;
                        }
                    }
                    break;

                case "'":
                case '"':
                    if ($prevChr != '\\' || ($prevChr == '\\' && $inputs[$i-2] == '\\')) {
                        if (end($inQuotes) == $chr) {
                            array_pop($inQuotes);
                        } elseif (!count($inQuotes)) {
                            $inQuotes[] = $chr;
                        }
                    }
                    break;

                case ' ':
                case "\t":
                case "\n":
                    if (!count($inQuotes)) {
                        if (strstr("{$noSpacesAround} \t\n", $nextChr)
                            || strstr("{$noSpacesAround} \t\n", $prevChr)
                        ) {
                            continue 2;
                        }
                        $chr = ' ';
                    }
                    break;

                default:
                    break;
            }

            $output .= $chr;
            $prevChr = $chr;
        }
        $output = trim($output);
        $output = str_replace(';}', '}', $output);

        return $output;
    }
193168
public function minify($file, $type = null)
    {
        if ($type === null) {
            $type = File::getExtension($file);
        }

        $type = strtolower($type);

        if ($type === 'css') {
            $content = CssMinifier::process(file_get_contents($file));
        } elseif ($type === 'js') {
            $content = JsMinifier::process(file_get_contents($file));
        } else {
            return $this;
        }

        $dest = dirname($file) . '/' . File::stripExtension(File::getFilename($file)) . '.min.' . $type;

        file_put_contents($dest, $content);

        $this->out('Minify file: ' . $dest);

        return $this;
    }
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;
    }
812640
protected function combineMinify()
    {
        $type = $this->options['contentType']; // ease readability

        // when combining scripts, make sure all statements separated and
        // trailing single line comment is terminated
        $implodeSeparator = ($type === self::TYPE_JS) ? "\n;" : '';

        // allow the user to pass a particular array of options to each
        // minifier (designated by type). source objects may still override
        // these
        if (isset($this->options['minifierOptions'][$type])) {
            $defaultOptions = $this->options['minifierOptions'][$type];
        } else {
            $defaultOptions = array();
        }

        // if minifier not set, default is no minification. source objects
        // may still override this
        if (isset($this->options['minifiers'][$type])) {
            $defaultMinifier = $this->options['minifiers'][$type];
        } else {
            $defaultMinifier = false;
        }

        // process groups of sources with identical minifiers/options
        $content = array();
        $i = 0;
        $l = count($this->sources);
        $groupToProcessTogether = array();
        $lastMinifier = null;
        $lastOptions = null;
        do {
            // get next source
            $source = null;
            if ($i < $l) {
                $source = $this->sources[$i];
                $sourceContent = $source->getContent();

                // allow the source to override our minifier and options
                $minifier = $source->getMinifier();
                if (!$minifier) {
                    $minifier = $defaultMinifier;
                }
                $options = array_merge($defaultOptions, $source->getMinifierOptions());
            }
            // do we need to process our group right now?
            if ($i > 0                               // yes, we have at least the first group populated
                && (
                    ! $source                        // yes, we ran out of sources
                    || $type === self::TYPE_CSS      // yes, to process CSS individually (avoiding PCRE bugs/limits)
                    || $minifier !== $lastMinifier   // yes, minifier changed
                    || $options !== $lastOptions)) { // yes, options changed
                // minify previous sources with last settings
                $imploded = implode($implodeSeparator, $groupToProcessTogether);
                $groupToProcessTogether = array();
                if ($lastMinifier) {
                    try {
                        $content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
                    } catch (Exception $e) {
                        throw new Exception("Exception in minifier: " . $e->getMessage());
                    }
                } else {
                    $content[] = $imploded;
                }
            }
            // add content to the group
            if ($source) {
                $groupToProcessTogether[] = $sourceContent;
                $lastMinifier = $minifier;
                $lastOptions = $options;
            }
            $i++;
        } while ($source);

        $content = implode($implodeSeparator, $content);

        if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
            $content = $this->handleCssImports($content);
        }

        // do any post-processing (esp. for editing build URIs)
        if ($this->options['postprocessorRequire']) {
            require_once $this->options['postprocessorRequire'];
        }
        if ($this->options['postprocessor']) {
            $content = call_user_func($this->options['postprocessor'], $content, $type);
        }

        return $content;
    }
391399
function minifyCodeGoogle(code, callback, minificationLevel, description){
    for (var i in minifyCache) {
      var item = minifyCache[i];
      if (item.code==code && item.level==minificationLevel) {
        console.log("Found code in minification cache - using that"+description);
        // move to front of cache
        minifyCache.splice(i,1); // remove old
        minifyCache.push(item); // add at front
        // callback
        callback(item.minified);
        return;
      }
    }
    closureCompilerGoogle(code,  minificationLevel, 'compiled_code', function(minified) {
      if (minified.trim()!="") {
        Espruino.Core.Notifications.info('No errors'+description+'. Minifying ' + code.length + ' bytes to ' + minified.length + ' bytes');
        if (minifyCache.length>100)
          minifyCache = minifyCache.slice(-100);
        minifyCache.push({ level : minificationLevel, code : code, minified : minified });
        callback(minified);
      } else {
        Espruino.Core.Notifications.warning("Errors while minifying"+description+" - sending unminified code.");
        callback(code);
        // get errors...
        closureCompilerGoogle(code,  minificationLevel, 'errors',function(errors) {
          errors.split("\n").forEach(function (err) {
            if (err.trim()!="")
              Espruino.Core.Notifications.error(err.trim()+description);
          });
        });
      }
    });
  }