1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
<?php
namespace Elementor\Modules\Components;
use Elementor\Modules\Components\Documents\Component as Component_Document; use Elementor\Plugin; use Elementor\Modules\Components\Components_REST_API;
if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. }
class Components_Repository {
public static function make(): Components_Repository { return new self(); }
public function all() { // Components count is limited to 50, if we increase this number, we need to iterate the posts in batches. $posts = get_posts( [ 'post_type' => Component_Document::TYPE, 'post_status' => 'publish', 'posts_per_page' => Components_REST_API::MAX_COMPONENTS, ] );
$components = [];
foreach ( $posts as $post ) { $doc = Plugin::$instance->documents->get( $post->ID );
if ( ! $doc ) { continue; }
$components[] = [ 'id' => $doc->get_main_id(), 'name' => $doc->get_post()->post_title, 'styles' => $this->extract_styles( $doc->get_elements_data() ), ]; }
return Components::make( $components ); }
public function create( string $name, array $content ) { $document = Plugin::$instance->documents->create( Component_Document::get_type(), [ 'post_title' => $name, 'post_status' => 'publish', ] );
$saved = $document->save( [ 'elements' => $content, ] );
if ( ! $saved ) { throw new \Exception( 'Failed to create component' ); }
return $document->get_main_id(); } private function extract_styles( array $elements, array $styles = [] ) { foreach ( $elements as $element ) { if ( isset( $element['styles'] ) ) { $styles = array_merge( $styles, $element['styles'] ); }
if ( isset( $element['elements'] ) ) { $styles = $this->extract_styles( $element['elements'], $styles ); } }
return $styles; } }
|