Files
blog/Article/Modificators/PerexCreator.php
T

60 lines
1.7 KiB
PHP
Executable File

<?php
namespace Modules\Blog\Modificators;
class PerexCreator
{
/**
* @var \DOMDocument
*/
protected $DOMDocument;
protected $perex;
public function __construct()
{
$this->DOMDocument = new \DOMDocument('1.0', 'UTF-8');
$this->maxLength = 300;
$this->maxImages = 2;
$this->perex = '';
}
private function addHtml($node)
{
$this->perex .= strip_tags($this->DOMDocument->saveHTML($node), '<p><strong><em><b><i><u>');
}
public function create($html)
{
if (empty($html)) {
return null;
}
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
$this->DOMDocument->loadHTML($html);
$texts = $this->DOMDocument->getElementsByTagName('p');
$images = $this->DOMDocument->getElementsByTagName('img');
$iframes = $this->DOMDocument->getElementsByTagName('iframe');
$textId = 0;
$imgId = 0;
if ($texts->length > 1) {
$this->addHtml($texts[$textId++]);
}
if (mb_strlen($this->perex) < $this->maxLength) {
if ($iframes->length > 0) {
$this->perex .= $this->DOMDocument->saveHTML($iframes[0]);
} elseif ($images->length > 0) {
while ($imgId < $images->length && $imgId < $this->maxImages) {
$this->perex .= $this->DOMDocument->saveHTML($images[$imgId++]);
}
} else {
while (mb_strlen($this->perex) < $this->maxLength && $textId < $texts->length) {
$this->addHtml($texts[$textId++]);
}
}
}
return $this->perex;
}
}