| 1 |
<?php |
| 2 |
namespace Hurrytimer; |
| 3 |
|
| 4 |
use Hurrytimer\Traits\Singleton; |
| 5 |
|
| 6 |
class CSS_Builder{ |
| 7 |
|
| 8 |
use Singleton; |
| 9 |
|
| 10 |
const OPTION_NAME = 'hurrytimer_css_build_hash'; |
| 11 |
|
| 12 |
public function generate_css(){ |
| 13 |
ob_start(); |
| 14 |
include HURRYT_DIR . '/assets/css/main.css'; |
| 15 |
include HURRYT_DIR . '/includes/css_template.php'; |
| 16 |
$css = ob_get_clean(); |
| 17 |
$css = wp_strip_all_tags($css); |
| 18 |
|
| 19 |
$uploads = wp_upload_dir(); |
| 20 |
|
| 21 |
$uploads_dir = $uploads['basedir']; |
| 22 |
|
| 23 |
$path = $uploads_dir . '/hurrytimer/css/'; |
| 24 |
|
| 25 |
if( ! file_exists( $path ) ){ |
| 26 |
mkdir( $path, 0777, true ); |
| 27 |
} |
| 28 |
|
| 29 |
if(!file_exists($uploads_dir . '/hurrytimer/index.html')){ |
| 30 |
file_put_contents($uploads_dir . '/hurrytimer/index.html', ''); |
| 31 |
} |
| 32 |
if(!file_exists($uploads_dir . '/hurrytimer/css/index.html')){ |
| 33 |
file_put_contents($uploads_dir . '/hurrytimer/css/index.html', ''); |
| 34 |
} |
| 35 |
array_map('unlink', glob($path . "*.css")); |
| 36 |
$build_version = substr( md5( time() ), 0, 16 ); |
| 37 |
$css_path = $uploads_dir . '/hurrytimer/css/' . $build_version . '.css'; |
| 38 |
file_put_contents($css_path, $css); |
| 39 |
|
| 40 |
update_option(self::OPTION_NAME, $build_version); |
| 41 |
|
| 42 |
return $css_path; |
| 43 |
} |
| 44 |
|
| 45 |
public function get_css_url(){ |
| 46 |
$uploads = wp_upload_dir(); |
| 47 |
$uploads_dir = $uploads['basedir']; |
| 48 |
|
| 49 |
$version = get_option(self::OPTION_NAME); |
| 50 |
if(empty($version)){ |
| 51 |
$css_path = $this->generate_css(); |
| 52 |
} |
| 53 |
$subpath = '/hurrytimer/css/' . $version . '.css'; |
| 54 |
$css_path = $uploads_dir . $subpath; |
| 55 |
|
| 56 |
// Ensure the file exists, otherwise generate it. |
| 57 |
if( ! file_exists( $css_path ) ){ |
| 58 |
$css_path = $this->generate_css(); |
| 59 |
} |
| 60 |
|
| 61 |
return set_url_scheme( $uploads['baseurl'] . $subpath); |
| 62 |
} |
| 63 |
|
| 64 |
} |