HasBlockTheme.php
79 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Concerns; |
| 4 | |
| 5 | use SureCartCore\Helpers\MixedType; |
| 6 | |
| 7 | trait HasBlockTheme { |
| 8 | |
| 9 | /** |
| 10 | * Register theme |
| 11 | * |
| 12 | * @param string $block_name Name of the block. |
| 13 | * @param string $slug Lowercase slug for style. |
| 14 | * @param string $name Display name of style. |
| 15 | * @param string $path Relative path in dist directory. |
| 16 | * |
| 17 | * @return void |
| 18 | */ |
| 19 | public function registerBlockTheme( $block_name, $slug, $name, $path ) { |
| 20 | $url = trailingslashit( \SureCart::core()->assets()->getUrl() ) . $path; |
| 21 | |
| 22 | wp_register_style( |
| 23 | "surecart/themes/$slug", |
| 24 | $url, |
| 25 | false, |
| 26 | $this->generateFileVersion( $url ) |
| 27 | ); |
| 28 | |
| 29 | register_block_style( |
| 30 | "surecart/$block_name", |
| 31 | [ |
| 32 | 'name' => $slug, |
| 33 | 'label' => $name, |
| 34 | 'style_handle' => "surecart/themes/$slug", |
| 35 | ] |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Remove the protocol from an http/https url. |
| 41 | * |
| 42 | * @param string $url Url for the source. |
| 43 | * @return string |
| 44 | */ |
| 45 | protected function removeProtocol( $url ) { |
| 46 | return preg_replace( '~^https?:~i', '', $url ); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Generate a version for a given asset src. |
| 51 | * |
| 52 | * @param string $src Source for the asset. |
| 53 | * @return integer|boolean |
| 54 | */ |
| 55 | protected function generateFileVersion( $src ) { |
| 56 | // Normalize both URLs in order to avoid problems with http, https |
| 57 | // and protocol-less cases. |
| 58 | $src = $this->removeProtocol( $src ); |
| 59 | $home_url = $this->removeProtocol( WP_CONTENT_URL ); |
| 60 | $version = false; |
| 61 | |
| 62 | // Generate the absolute path to the file. |
| 63 | $file_path = MixedType::normalizePath( |
| 64 | str_replace( |
| 65 | [ $home_url, '/' ], |
| 66 | [ WP_CONTENT_DIR, DIRECTORY_SEPARATOR ], |
| 67 | $src |
| 68 | ) |
| 69 | ); |
| 70 | |
| 71 | if ( file_exists( $file_path ) ) { |
| 72 | // Use the last modified time of the file as a version. |
| 73 | $version = filemtime( $file_path ); |
| 74 | } |
| 75 | |
| 76 | return $version; |
| 77 | } |
| 78 | } |
| 79 |