| 1 |
<?php |
| 2 |
|
| 3 |
namespace ABlocks\import\ImageParsers\wp; |
| 4 |
|
| 5 |
use ABlocks\import\ImageParsers\AbstractImageParser; |
| 6 |
use DOMDocument; |
| 7 |
|
| 8 |
class CoreImageParser extends AbstractImageParser { |
| 9 |
|
| 10 |
public function parse() { |
| 11 |
$dom = new DOMDocument(); |
| 12 |
// Suppress warnings for malformed HTML. |
| 13 |
libxml_use_internal_errors( true ); |
| 14 |
$dom->loadHTML( $this->block['innerHTML'] ); |
| 15 |
libxml_clear_errors(); |
| 16 |
$imageHTML = $dom->getElementsByTagName( 'img' )->item( 0 ); |
| 17 |
if ( ! $imageHTML ) { |
| 18 |
return; |
| 19 |
} |
| 20 |
|
| 21 |
$imgSRC = $imageHTML->attributes->getNamedItem( 'src' ); |
| 22 |
if ( ! $imgSRC ) { |
| 23 |
return; |
| 24 |
} |
| 25 |
|
| 26 |
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Calling a property from native class `DOMDocument`. |
| 27 |
$imgURL = $imgSRC->nodeValue; |
| 28 |
if ( ! $this->check_external_url( $imgURL ) ) { |
| 29 |
return; |
| 30 |
} |
| 31 |
|
| 32 |
$attachment_id = $this->upload_file( $imgURL ); |
| 33 |
if ( is_wp_error( $attachment_id ) ) { |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
$attachment_url = wp_get_attachment_url( $attachment_id ); |
| 38 |
|
| 39 |
$this->block['attrs']['id'] = $attachment_id; |
| 40 |
$this->block['innerHTML'] = str_replace( $imgURL, $attachment_url, $this->block['innerHTML'] ); |
| 41 |
$this->block['innerContent'] = array( str_replace( $imgURL, $attachment_url, $this->block['innerHTML'] ) ); |
| 42 |
} |
| 43 |
} |
| 44 |
|