<?php

namespace onespace\tools\helpers;

/**
 * Some common tools used the various UI Widget classes.
 * 
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

trait Minifier {

    /**
     * Minifies the resultant CSS on the fly.
     * 
     * @param   string  $css
     * 
     * @return  string
     * 
     * @access  protected
     */

    protected function minifyCss(string $css): string {
        $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css); // Remove comments
        $css = preg_replace('/\s+/', ' ', $css); // Remove multiple spaces
        $css = preg_replace('/\s*([:;,{}])\s*/', '$1', $css); // Remove spaces around selectors, properties, and values
        $css = str_replace(';}', '}', $css); // Remove empty declarations
        return $css;
    }


    /**
     * Minifies the resultant JS on the fly.
     * 
     * @param   string  $js
     * 
     * @return  string
     * 
     * @access  protected
     */

    protected function minifyJs(string $js): string {
        // Remove single-line comments (//...)
        $js = preg_replace('#\s*//.*$#m', '', $js);
        // Remove multi-line comments (/*...*/)
        $js = preg_replace('#/\*.*?\*/#s', '', $js);
        // Remove spaces and newlines
        $js = preg_replace('/\s+/S', ' ', $js);
        return $js;
    }
}
