forked from laysense/laysense.cn
56 lines
2.3 KiB
PHP
56 lines
2.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use DOMDocument;
|
|
use DOMElement;
|
|
use DOMXPath;
|
|
use PDO;
|
|
|
|
final class PagepanFeatureIcons
|
|
{
|
|
public static function migrate(PDO $pdo): void
|
|
{
|
|
$query = $pdo->query("SELECT body FROM sections WHERE page_slug = 'pagepan' AND key = 'features'");
|
|
$body = $query->fetchColumn();
|
|
if (!is_string($body) || $body === '') {
|
|
return;
|
|
}
|
|
$paths = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/pagepan-feature-icons.json'), true, flags: JSON_THROW_ON_ERROR);
|
|
$document = new DOMDocument('1.0', 'UTF-8');
|
|
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $body . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
|
$xpath = new DOMXPath($document);
|
|
|
|
$changed = false;
|
|
foreach ($xpath->query('//article[contains(concat(" ", normalize-space(@class), " "), " feature-card ")]') as $card) {
|
|
$heading = $xpath->query('(./h2 | ./h3 | ./h4)[1]', $card)->item(0);
|
|
if (!$heading instanceof DOMElement || $card->getElementsByTagName('img')->length > 0) {
|
|
continue;
|
|
}
|
|
$title = trim($heading->textContent);
|
|
if (!isset($paths[$title])) {
|
|
continue;
|
|
}
|
|
$icon = $document->createElement('img');
|
|
foreach (['src' => $paths[$title], 'alt' => '', 'width' => '50', 'height' => '50', 'loading' => 'lazy'] as $key => $value) {
|
|
$icon->setAttribute($key, $value);
|
|
}
|
|
$card->insertBefore($icon, $card->firstChild);
|
|
$changed = true;
|
|
}
|
|
|
|
if ($changed) {
|
|
$updated = '';
|
|
foreach ($document->getElementsByTagName('body')->item(0)->childNodes as $child) {
|
|
$updated .= $document->saveHTML($child);
|
|
}
|
|
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = 'pagepan' AND key = 'features'")
|
|
->execute([trim($updated)]);
|
|
$pdo->prepare("UPDATE pages SET updated_at = ? WHERE slug = 'pagepan'")
|
|
->execute([(new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('Y-m-d H:i:s')]);
|
|
}
|
|
}
|
|
}
|