| 1 |
<?php |
| 2 |
|
| 3 |
namespace Hurrytimer; |
| 4 |
|
| 5 |
use Hurrytimer\Traits\Singleton; |
| 6 |
|
| 7 |
class CSS_Builder |
| 8 |
{ |
| 9 |
use Singleton; |
| 10 |
|
| 11 |
public function get_build_url() |
| 12 |
{ |
| 13 |
$hash = $this->get_current_build_hash(); |
| 14 |
|
| 15 |
$file = $this->get_build_path( $hash ); |
| 16 |
|
| 17 |
if ( !file_exists( $file ) ) { |
| 18 |
$hash = $this->build(); |
| 19 |
} |
| 20 |
|
| 21 |
$upload_dir = wp_get_upload_dir(); |
| 22 |
|
| 23 |
return set_url_scheme( trailingslashit( $upload_dir[ 'baseurl' ] ) . $this->get_build_relative_path( $hash ) ); |
| 24 |
} |
| 25 |
|
| 26 |
private function get_current_build_hash() |
| 27 |
{ |
| 28 |
return get_option( 'hurrytimer_css_build_hash' ); |
| 29 |
} |
| 30 |
|
| 31 |
public function delete_build( $hash ) |
| 32 |
{ |
| 33 |
$file = $this->get_build_path( $hash ); |
| 34 |
|
| 35 |
@unlink( $file ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Re/Build CSS file |
| 40 |
*/ |
| 41 |
public function build() |
| 42 |
{ |
| 43 |
ob_start(); |
| 44 |
include HURRYT_DIR . 'assets/css/main.css'; |
| 45 |
include __DIR__ . '/css_template.php'; |
| 46 |
|
| 47 |
$css = ob_get_clean(); |
| 48 |
|
| 49 |
$this->delete_build( $this->get_current_build_hash() ); |
| 50 |
|
| 51 |
$hash = substr( md5( time() ), 0, 16 ); |
| 52 |
|
| 53 |
$file = $this->get_build_path( $hash ); |
| 54 |
|
| 55 |
file_put_contents( $file, $css ); |
| 56 |
|
| 57 |
update_option( 'hurrytimer_css_build_hash', $hash ); |
| 58 |
|
| 59 |
return $hash; |
| 60 |
} |
| 61 |
|
| 62 |
private function get_build_relative_path( $hash ) |
| 63 |
{ |
| 64 |
$uploads_dir = wp_get_upload_dir(); |
| 65 |
|
| 66 |
$relative_dir = implode( DIRECTORY_SEPARATOR, [ 'hurrytimer', 'css' ] ); |
| 67 |
|
| 68 |
$path = trailingslashit( $uploads_dir[ 'basedir' ] ) . $relative_dir; |
| 69 |
|
| 70 |
if ( !file_exists( $path ) ) { |
| 71 |
mkdir( $path, 0777, true ); |
| 72 |
} |
| 73 |
|
| 74 |
return apply_filters( 'hurryt_css_path', trailingslashit( $relative_dir ) . $hash . '.css' ); |
| 75 |
} |
| 76 |
|
| 77 |
public function get_build_path( $hash ) |
| 78 |
{ |
| 79 |
$upload_dir = wp_get_upload_dir(); |
| 80 |
|
| 81 |
return trailingslashit( $upload_dir[ 'basedir' ] ) . $this->get_build_relative_path( $hash ); |
| 82 |
|
| 83 |
} |
| 84 |
|
| 85 |
} |