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