| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\GlobalClasses\Usage; |
| 4 |
|
| 5 |
use Elementor\Core\Base\Document as ElementorDocument; |
| 6 |
use Elementor\Plugin; |
| 7 |
|
| 8 |
/** |
| 9 |
* Tracks usage of global CSS classes within a specific Elementor document. |
| 10 |
*/ |
| 11 |
class Document_Usage { |
| 12 |
|
| 13 |
|
| 14 |
/** @var ElementorDocument */ |
| 15 |
private ElementorDocument $document; |
| 16 |
|
| 17 |
/** |
| 18 |
* Map of known global class ID => true for O(1) membership checks. |
| 19 |
* |
| 20 |
* @var array<string, true> |
| 21 |
*/ |
| 22 |
private array $valid_class_id_set; |
| 23 |
|
| 24 |
/** @var array<string, Css_Class_Usage> */ |
| 25 |
private array $usages = []; |
| 26 |
|
| 27 |
/** |
| 28 |
* Constructor. |
| 29 |
* |
| 30 |
* @param ElementorDocument $document The Elementor document object. |
| 31 |
* @param array<string, true> $valid_class_id_set Known global class IDs (e.g. from array_fill_keys). |
| 32 |
*/ |
| 33 |
public function __construct( ElementorDocument $document, array $valid_class_id_set ) { |
| 34 |
$this->document = $document; |
| 35 |
$this->valid_class_id_set = $valid_class_id_set; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Analyze the document to find and record usage of global CSS classes. |
| 40 |
*/ |
| 41 |
public function analyze(): void { |
| 42 |
$page_id = $this->document->get_main_id(); |
| 43 |
$page_title = $this->document->get_post()->post_title; |
| 44 |
$elements_data = $this->document->get_elements_raw_data() ?? []; |
| 45 |
|
| 46 |
$document_type = $this->document->get_type(); |
| 47 |
if ( empty( $document_type ) ) { |
| 48 |
$document_type = get_post_type( $page_id ) ?? 'unknown'; |
| 49 |
} |
| 50 |
|
| 51 |
if ( empty( $elements_data ) ) { |
| 52 |
return; |
| 53 |
} |
| 54 |
|
| 55 |
Plugin::$instance->db->iterate_data( |
| 56 |
$elements_data, |
| 57 |
function ( $element_data ) use ( $page_id, $page_title, $document_type ) { |
| 58 |
$class_values = $element_data['settings']['classes']['value'] ?? []; |
| 59 |
|
| 60 |
if ( empty( $class_values ) || ! is_array( $class_values ) ) { |
| 61 |
return; |
| 62 |
} |
| 63 |
|
| 64 |
foreach ( $class_values as $class_id ) { |
| 65 |
if ( ! isset( $this->valid_class_id_set[ $class_id ] ) ) { |
| 66 |
continue; |
| 67 |
} |
| 68 |
|
| 69 |
if ( ! isset( $this->usages[ $class_id ] ) ) { |
| 70 |
$this->usages[ $class_id ] = new Css_Class_Usage( $class_id ); |
| 71 |
} |
| 72 |
|
| 73 |
$this->usages[ $class_id ]->track_usage( |
| 74 |
$page_id, |
| 75 |
$page_title, |
| 76 |
$element_data['id'] ?? 'unknown', |
| 77 |
$document_type |
| 78 |
); |
| 79 |
} |
| 80 |
} |
| 81 |
); |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Get all recorded usages of global CSS classes in this document. |
| 86 |
* |
| 87 |
* @return array<string, Css_Class_Usage> |
| 88 |
*/ |
| 89 |
public function get_usages(): array { |
| 90 |
return $this->usages; |
| 91 |
} |
| 92 |
} |
| 93 |
|