From 41fc695c4e3a7da2d991620e308b4b45a866e537 Mon Sep 17 00:00:00 2001
From: Roberto Butti
Date: Sat, 30 Dec 2023 22:12:25 +0100
Subject: [PATCH 1/2] Modernizing Code Base
---
.gitignore | 4 +-
rector.php | 8 +-
src/PHPePub/Core/EPub.php | 531 ++++++++----------
src/PHPePub/Core/EPubChapterSplitter.php | 21 +-
src/PHPePub/Core/Logger.php | 26 +-
src/PHPePub/Core/Structure/NCX/NavMap.php | 26 +-
src/PHPePub/Core/Structure/NCX/NavPoint.php | 72 +--
src/PHPePub/Core/Structure/Ncx.php | 128 ++---
src/PHPePub/Core/Structure/OPF/DublinCore.php | 2 +-
src/PHPePub/Core/Structure/OPF/Guide.php | 25 +-
src/PHPePub/Core/Structure/OPF/Item.php | 70 +--
src/PHPePub/Core/Structure/OPF/Itemref.php | 14 +-
src/PHPePub/Core/Structure/OPF/Manifest.php | 26 +-
src/PHPePub/Core/Structure/OPF/MetaValue.php | 28 +-
src/PHPePub/Core/Structure/OPF/Metadata.php | 33 +-
src/PHPePub/Core/Structure/OPF/Reference.php | 16 +-
src/PHPePub/Core/Structure/OPF/Spine.php | 27 +-
src/PHPePub/Core/Structure/Opf.php | 65 ++-
src/PHPePub/Helpers/CalibreHelper.php | 3 +-
src/PHPePub/Helpers/Enum.php | 6 +-
src/PHPePub/Helpers/FileHelper.php | 4 +-
src/PHPePub/Helpers/IBooksHelper.php | 14 +-
src/PHPePub/Helpers/ImageHelper.php | 117 ++--
.../Helpers/Rendition/RenditionHelper.php | 8 +-
src/PHPePub/Helpers/StringHelper.php | 39 +-
src/PHPePub/Helpers/URLHelper.php | 8 +-
src/PHPePub/Helpers/enums/Boolean.php | 4 +-
src/lib.uuid.php | 112 ++--
test.php | 2 +-
tests/EPub.Example2b.php | 6 +-
tests/EPub.Example3.php | 4 +-
tests/EPub.Example3_1.php | 6 +-
tests/EPub.Example3_2.php | 6 +-
tests/EPub.ExampleSimple.php | 2 +-
34 files changed, 663 insertions(+), 800 deletions(-)
diff --git a/.gitignore b/.gitignore
index b2932df..6089c48 100644
--- a/.gitignore
+++ b/.gitignore
@@ -83,4 +83,6 @@ legacy/vendor
legacy/vendor/*
testData
-testData/*
\ No newline at end of file
+testData/*
+
+/ExampleBook*.epub
\ No newline at end of file
diff --git a/rector.php b/rector.php
index c2fe993..7a251be 100644
--- a/rector.php
+++ b/rector.php
@@ -5,13 +5,17 @@
use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;
+use Rector\Set\ValueObject\SetList;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->paths([
__DIR__ . '/src',
]);
$rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);
- $rectorConfig->sets([
- LevelSetList::UP_TO_PHP_82
+ $rectorConfig->sets([SetList::CODE_QUALITY,
+ SetList::DEAD_CODE,
+ SetList::EARLY_RETURN,
+ SetList::TYPE_DECLARATION,
+ LevelSetList::UP_TO_PHP_81
]);
};
diff --git a/src/PHPePub/Core/EPub.php b/src/PHPePub/Core/EPub.php
index bf50f81..a7abeb7 100644
--- a/src/PHPePub/Core/EPub.php
+++ b/src/PHPePub/Core/EPub.php
@@ -2,7 +2,6 @@
namespace PHPePub\Core;
-use com\grandt\BinStringStatic;
use Masterminds\HTML5;
use DOMDocument;
use DOMXPath;
@@ -80,59 +79,58 @@ class EPub
* Used for building the TOC.
* If this list is overwritten it MUST contain at least "text" as an element.
*/
- public $referencesOrder = null;
+ public $referencesOrder;
public $pluginDir = 'extLib';
public $isLogging = true;
public $encodeHTML = false;
/** @var $Zip Zip */
- private $zip;
- private $title = '';
- private $language = 'en';
- private $identifier = '';
- private $identifierType = '';
- private $description = '';
- private $author = '';
- private $authorSortKey = '';
- private $publisherName = '';
- private $publisherURL = '';
- private $date = 0;
- private $rights = '';
- private $coverage = '';
- private $relation = '';
- private $sourceURL = '';
- private $chapterCount = 0;
+ private \PHPZip\Zip\File\Zip $zip;
+ private string $title = '';
+ private string $language = 'en';
+ private string $identifier = '';
+ private string $identifierType = '';
+ private string $description = '';
+ private string $author = '';
+ private string $authorSortKey = '';
+ private string $publisherName = '';
+ private string $publisherURL = '';
+ private int $date = 0;
+ private string $rights = '';
+ private string $coverage = '';
+ private string $relation = '';
+ private string $sourceURL = '';
+ private int $chapterCount = 0;
/** @var $opf Opf */
- private $opf = null;
+ private ?\PHPePub\Core\Structure\Opf $opf = null;
/** @var $ncx Ncx */
- private $ncx = null;
- private $isFinalized = false;
- private $isInitialized = false;
- private $isCoverImageSet = false;
- private $buildTOC = false; // ISO 8601 long
- private $tocTitle = null; // short date format to placate ePubChecker.
- private $tocFileName = null;
- private $tocNavAdded = false;
- private $tocCSSClass = null;
- private $tocAddReferences = false;
- private $tocCssFileName = null;
- private $fileList = [];
- private $dateformat = 'Y-m-d\TH:i:s.000000P';
- private $dateformatShort = 'Y-m-d';
- private $headerDateFormat = "D, d M Y H:i:s T";
- private $docRoot = null;
- private $bookRoot = 'OEBPS/';
- private $EPubMark = true;
- private $generator = '';
- private $log = null;
- private $htmlContentHeader = "\n\n\n \n \n\n\n";
- private $htmlContentFooter = "\n\n";
-
- /** @var array $viewport */
- private $viewport = null;
-
- private $dangermode = false;
+ private ?\PHPePub\Core\Structure\Ncx $ncx = null;
+ private bool $isFinalized = false;
+ private bool $isInitialized = false;
+ private bool $isCoverImageSet = false;
+ private bool $buildTOC = false; // ISO 8601 long
+ private $tocTitle; // short date format to placate ePubChecker.
+ private ?string $tocFileName = null;
+ private bool $tocNavAdded = false;
+ private $tocCSSClass;
+ private bool $tocAddReferences = false;
+ private ?string $tocCssFileName = null;
+ private array $fileList = [];
+ private string $dateformat = 'Y-m-d\TH:i:s.000000P';
+ private string $dateformatShort = 'Y-m-d';
+ private string $headerDateFormat = "D, d M Y H:i:s T";
+ private ?string $docRoot = null;
+ private string $bookRoot = 'OEBPS/';
+ private bool $EPubMark = true;
+ private string $generator = '';
+ private ?\PHPePub\Core\Logger $log = null;
+ private string $htmlContentHeader = "\n\n\n \n \n\n\n";
+ private string $htmlContentFooter = "\n\n";
+
+ private ?array $viewport = null;
+
+ private bool $dangermode = false;
/**
* Class constructor.
@@ -158,7 +156,7 @@ public function __construct(
$this->setUp();
}
- private function setUp()
+ private function setUp(): void
{
$this->referencesOrder = [Reference::COVER => 'Cover Page', Reference::TITLE_PAGE => 'Title Page', Reference::ACKNOWLEDGEMENTS => 'Acknowledgements', Reference::BIBLIOGRAPHY => 'Bibliography', Reference::COLOPHON => 'Colophon', Reference::COPYRIGHT_PAGE => 'Copyright', Reference::DEDICATION => 'Dedication', Reference::EPIGRAPH => 'Epigraph', Reference::FOREWORD => 'Foreword', Reference::TABLE_OF_CONTENTS => 'Table of Contents', Reference::NOTES => 'Notes', Reference::PREFACE => 'Preface', Reference::TEXT => 'First Page', Reference::LIST_OF_ILLUSTRATIONS => 'List of Illustrations', Reference::LIST_OF_TABLES => 'List of Tables', Reference::GLOSSARY => 'Glossary', Reference::INDEX => 'Index'];
@@ -213,7 +211,7 @@ public function __destruct()
*
* @return mixed $success FALSE if the addition failed, else the new NavPoint.
*/
- public function addChapter($chapterName, $fileName, $chapterData = null, $autoSplit = false, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = "")
+ public function addChapter($chapterName, $fileName, $chapterData = null, $autoSplit = false, $externalReferences = EPub::EXTERNAL_REF_IGNORE, string $baseDir = ""): bool|\PHPePub\Core\Structure\NCX\NavPoint
{
if ($this->isFinalized) {
return false;
@@ -328,9 +326,8 @@ public function addChapter($chapterName, $fileName, $chapterData = null, $autoSp
* find all id attributes in the html document.
*
* @param string $chapterData
- * @return array
*/
- public function findIdAttributes($chapterData)
+ public function findIdAttributes($chapterData): array
{
switch ($this->htmlFormat) {
case EPub::FORMAT_HTML5:
@@ -359,7 +356,7 @@ public function findIdAttributes($chapterData)
* @param string $partName
* @param string $chapterData
*/
- public function extractIdAttributes($partName, $chapterData)
+ public function extractIdAttributes($partName, $chapterData): void
{
$item = $this->opf->getItemById($partName);
$ids = $this->findIdAttributes($chapterData);
@@ -392,7 +389,7 @@ public function extractIdAttributes($partName, $chapterData)
*
* @return bool false if unsuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
*/
- protected function processChapterExternalReferences(mixed &$doc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "")
+ protected function processChapterExternalReferences(mixed &$doc, $externalReferences = EPub::EXTERNAL_REF_ADD, string $baseDir = "", $htmlDir = ""): bool
{
if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
return false;
@@ -478,7 +475,7 @@ protected function processChapterExternalReferences(mixed &$doc, $externalRefere
*
* @return bool FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
*/
- protected function processChapterStyles(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "")
+ protected function processChapterStyles(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = ""): bool
{
if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
return false;
@@ -511,7 +508,7 @@ protected function processChapterStyles(&$xmlDoc, $externalReferences = EPub::EX
*
* @return bool FALSE if unsuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
*/
- protected function processCSSExternalReferences(&$cssFile, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $cssDir = "")
+ protected function processCSSExternalReferences(&$cssFile, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $cssDir = ""): bool
{
if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
return false;
@@ -554,10 +551,8 @@ protected function processCSSExternalReferences(&$cssFile, $externalReferences =
* @param string &$isSourceExternal (referenced) Return value, will be set to TRUE if the image originated from a full URL.
* @param string $baseDir Default is "", meaning it is pointing to the document root.
* @param string $htmlDir The path to the parent HTML file's directory from the root of the archive.
- *
- * @return bool
*/
- protected function resolveImage($source, &$internalPath, &$internalSrc, &$isSourceExternal, $baseDir = "", $htmlDir = "")
+ protected function resolveImage(string $source, &$internalPath, &$internalSrc, &$isSourceExternal, string $baseDir = "", string $htmlDir = ""): bool
{
if ($this->isFinalized) {
return false;
@@ -566,33 +561,28 @@ protected function resolveImage($source, &$internalPath, &$internalSrc, &$isSour
if (preg_match('#^(http|ftp)s?://#i', $source) == 1) {
$urlinfo = parse_url($source);
-
if (str_contains($urlinfo['path'], $baseDir . "/")) {
$internalSrc = FileHelper::sanitizeFileName(urldecode(substr($urlinfo['path'], strpos($urlinfo['path'], $baseDir . "/") + strlen($baseDir) + 1)));
}
$internalPath = $urlinfo["scheme"] . "/" . $urlinfo["host"] . "/" . pathinfo($urlinfo["path"], PATHINFO_DIRNAME);
$isSourceExternal = true;
$imageData = ImageHelper::getImage($this, $source);
+ } elseif (str_starts_with($source, "/")) {
+ $internalPath = pathinfo($source, PATHINFO_DIRNAME);
+ $path = $source;
+ if (!file_exists($path)) {
+ $path = $this->docRoot . $path;
+ }
+ $imageData = ImageHelper::getImage($this, $path);
} else {
- if (str_starts_with($source, "/")) {
- $internalPath = pathinfo($source, PATHINFO_DIRNAME);
-
- $path = $source;
- if (!file_exists($path)) {
- $path = $this->docRoot . $path;
- }
+ $internalPath = $htmlDir . "/" . preg_replace('#^[/\.]+#', '', pathinfo($source, PATHINFO_DIRNAME));
- $imageData = ImageHelper::getImage($this, $path);
- } else {
- $internalPath = $htmlDir . "/" . preg_replace('#^[/\.]+#', '', pathinfo($source, PATHINFO_DIRNAME));
-
- $path = $baseDir . "/" . $source;
- if (!file_exists($path)) {
- $path = $this->docRoot . $path;
- }
-
- $imageData = ImageHelper::getImage($this, $path);
+ $path = $baseDir . "/" . $source;
+ if (!file_exists($path)) {
+ $path = $this->docRoot . $path;
}
+
+ $imageData = ImageHelper::getImage($this, $path);
}
if ($imageData !== false) {
$iSrcInfo = pathinfo((string) $internalSrc);
@@ -621,7 +611,7 @@ protected function resolveImage($source, &$internalPath, &$internalSrc, &$isSour
*
* @return bool $success
*/
- public function addFileToMETAINF($fileName, $fileData)
+ public function addFileToMETAINF($fileName, $fileData): bool
{
if ($this->isFinalized) {
return false;
@@ -646,7 +636,7 @@ public function addFileToMETAINF($fileName, $fileData)
*
* @return bool $success
*/
- public function addFile($fileName, $fileId, $fileData, $mimetype)
+ public function addFile($fileName, $fileId, $fileData, $mimetype): bool
{
if ($this->isFinalized || array_key_exists($fileName, $this->fileList)) {
return false;
@@ -677,7 +667,7 @@ public function addFile($fileName, $fileId, $fileData, $mimetype)
*
* @return bool FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
*/
- protected function processChapterLinks(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", $backPath = "")
+ protected function processChapterLinks(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, string $baseDir = "", $htmlDir = "", string $backPath = ""): bool
{
if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
return false;
@@ -696,18 +686,14 @@ protected function processChapterLinks(&$xmlDoc, $externalReferences = EPub::EXT
if (preg_match('#^(http|ftp)s?://#i', $source) == 1) {
$urlinfo = parse_url($source);
-
if (str_contains($urlinfo['path'], $baseDir . "/")) {
$internalSrc = substr($urlinfo['path'], strpos($urlinfo['path'], $baseDir . "/") + strlen($baseDir) + 1);
}
-
@$sourceData = FileHelper::getFileContents($source);
+ } elseif (str_starts_with($source, "/")) {
+ @$sourceData = file_get_contents($this->docRoot . $source);
} else {
- if (str_starts_with($source, "/")) {
- @$sourceData = file_get_contents($this->docRoot . $source);
- } else {
- @$sourceData = file_get_contents($this->docRoot . $baseDir . "/" . $source);
- }
+ @$sourceData = file_get_contents($this->docRoot . $baseDir . "/" . $source);
}
if (!empty($sourceData)) {
@@ -744,7 +730,7 @@ protected function processChapterLinks(&$xmlDoc, $externalReferences = EPub::EXT
*
* @return bool $success
*/
- public function addCSSFile($fileName, $fileId, $fileData, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = "")
+ public function addCSSFile($fileName, string $fileId, $fileData, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = ""): bool
{
if ($this->isFinalized || array_key_exists($fileName, $this->fileList)) {
return false;
@@ -779,7 +765,7 @@ public function addCSSFile($fileName, $fileId, $fileData, $externalReferences =
*
* @return bool FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
*/
- protected function processChapterImages(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", $backPath = "")
+ protected function processChapterImages(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", string $backPath = ""): bool
{
if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
return false;
@@ -795,30 +781,27 @@ protected function processChapterImages(&$xmlDoc, $externalReferences = EPub::EX
if ($externalReferences === EPub::EXTERNAL_REF_REMOVE_IMAGES) {
$postProcDomElememts[] = $img;
+ } elseif ($externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
+ $altNode = $img->attributes->getNamedItem("alt");
+ $alt = "image";
+ if ($altNode !== null && strlen($altNode->nodeValue) > 0) {
+ $alt = $altNode->nodeValue;
+ }
+ $postProcDomElememts[] = [$img, StringHelper::createDomFragment($xmlDoc, "[" . $alt . "] ")];
} else {
- if ($externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
- $altNode = $img->attributes->getNamedItem("alt");
- $alt = "image";
- if ($altNode !== null && strlen($altNode->nodeValue) > 0) {
- $alt = $altNode->nodeValue;
- }
- $postProcDomElememts[] = [$img, StringHelper::createDomFragment($xmlDoc, "[" . $alt . "] ")];
- } else {
- $source = $img->attributes->getNamedItem("src")->nodeValue;
+ $source = $img->attributes->getNamedItem("src")->nodeValue;
- $parsedSource = parse_url($source);
- $internalSrc = FileHelper::sanitizeFileName(urldecode(pathinfo($parsedSource['path'], PATHINFO_BASENAME)));
- $internalPath = "";
- $isSourceExternal = false;
+ $parsedSource = parse_url($source);
+ $internalSrc = FileHelper::sanitizeFileName(urldecode(pathinfo($parsedSource['path'], PATHINFO_BASENAME)));
+ $internalPath = "";
+ $isSourceExternal = false;
- if ($this->resolveImage($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $htmlDir)) {
- $img->setAttribute("src", $backPath . $internalPath);
- } else {
- if ($isSourceExternal) {
- $postProcDomElememts[] = $img; // External image is missing
- }
- } // else do nothing, if the image is local, and missing, assume it's been generated.
- }
+ if ($this->resolveImage($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $htmlDir)) {
+ $img->setAttribute("src", $backPath . $internalPath);
+ } elseif ($isSourceExternal) {
+ $postProcDomElememts[] = $img;
+ // External image is missing
+ } // else do nothing, if the image is local, and missing, assume it's been generated.
}
}
@@ -845,7 +828,7 @@ protected function processChapterImages(&$xmlDoc, $externalReferences = EPub::EX
*
* @return bool FALSE if uncuccessful (book is finalized or $externalReferences == EXTERNAL_REF_IGNORE).
*/
- protected function processChapterSources(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", $backPath = "")
+ protected function processChapterSources(&$xmlDoc, $externalReferences = EPub::EXTERNAL_REF_ADD, $baseDir = "", $htmlDir = "", string $backPath = ""): bool
{
if ($this->isFinalized || $externalReferences === EPub::EXTERNAL_REF_IGNORE) {
return false;
@@ -864,30 +847,27 @@ protected function processChapterSources(&$xmlDoc, $externalReferences = EPub::E
$img = $images->item($idx);
if ($externalReferences === EPub::EXTERNAL_REF_REMOVE_IMAGES) {
$postProcDomElememts[] = $img;
+ } elseif ($externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
+ $altNode = $img->attributes->getNamedItem("alt");
+ $alt = "image";
+ if ($altNode !== null && strlen($altNode->nodeValue) > 0) {
+ $alt = $altNode->nodeValue;
+ }
+ $postProcDomElememts[] = [$img, StringHelper::createDomFragment($xmlDoc, "[" . $alt . "]")];
} else {
- if ($externalReferences === EPub::EXTERNAL_REF_REPLACE_IMAGES) {
- $altNode = $img->attributes->getNamedItem("alt");
- $alt = "image";
- if ($altNode !== null && strlen($altNode->nodeValue) > 0) {
- $alt = $altNode->nodeValue;
- }
- $postProcDomElememts[] = [$img, StringHelper::createDomFragment($xmlDoc, "[" . $alt . "]")];
- } else {
- $source = $img->attributes->getNamedItem("src")->nodeValue;
+ $source = $img->attributes->getNamedItem("src")->nodeValue;
- $parsedSource = parse_url($source);
- $internalSrc = FileHelper::sanitizeFileName(urldecode(pathinfo($parsedSource['path'], PATHINFO_BASENAME)));
- $internalPath = "";
- $isSourceExternal = false;
+ $parsedSource = parse_url($source);
+ $internalSrc = FileHelper::sanitizeFileName(urldecode(pathinfo($parsedSource['path'], PATHINFO_BASENAME)));
+ $internalPath = "";
+ $isSourceExternal = false;
- if ($this->resolveMedia($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $htmlDir)) {
- $img->setAttribute("src", $backPath . $internalPath);
- } else {
- if ($isSourceExternal) {
- $postProcDomElememts[] = $img; // External image is missing
- }
- } // else do nothing, if the image is local, and missing, assume it's been generated.
- }
+ if ($this->resolveMedia($source, $internalPath, $internalSrc, $isSourceExternal, $baseDir, $htmlDir)) {
+ $img->setAttribute("src", $backPath . $internalPath);
+ } elseif ($isSourceExternal) {
+ $postProcDomElememts[] = $img;
+ // External image is missing
+ } // else do nothing, if the image is local, and missing, assume it's been generated.
}
}
@@ -903,10 +883,8 @@ protected function processChapterSources(&$xmlDoc, $externalReferences = EPub::E
* @param string $isSourceExternal (referenced) Return value, will be set to TRUE if the image originated from a full URL.
* @param string $baseDir Default is "", meaning it is pointing to the document root.
* @param string $htmlDir The path to the parent HTML file's directory from the root of the archive.
- *
- * @return bool
*/
- protected function resolveMedia($source, &$internalPath, &$internalSrc, &$isSourceExternal, $baseDir = "", $htmlDir = "")
+ protected function resolveMedia(string $source, &$internalPath, &$internalSrc, &$isSourceExternal, string $baseDir = "", string $htmlDir = ""): bool
{
if ($this->isFinalized) {
return false;
@@ -916,7 +894,6 @@ protected function resolveMedia($source, &$internalPath, &$internalSrc, &$isSour
if (preg_match('#^(http|ftp)s?://#i', $source) == 1) {
$urlInfo = parse_url($source);
-
if (str_contains($urlInfo['path'], $baseDir . "/")) {
$internalSrc = substr($urlInfo['path'], strpos($urlInfo['path'], $baseDir . "/") + strlen($baseDir) + 1);
}
@@ -924,21 +901,18 @@ protected function resolveMedia($source, &$internalPath, &$internalSrc, &$isSour
$isSourceExternal = true;
$mediaPath = FileHelper::getFileContents($source, true);
$tmpFile = $mediaPath;
+ } elseif (str_starts_with($source, "/")) {
+ $internalPath = pathinfo($source, PATHINFO_DIRNAME);
+ $mediaPath = $source;
+ if (!file_exists($mediaPath)) {
+ $mediaPath = $this->docRoot . $mediaPath;
+ }
} else {
- if (str_starts_with($source, "/")) {
- $internalPath = pathinfo($source, PATHINFO_DIRNAME);
-
- $mediaPath = $source;
- if (!file_exists($mediaPath)) {
- $mediaPath = $this->docRoot . $mediaPath;
- }
- } else {
- $internalPath = $htmlDir . "/" . preg_replace('#^[/\.]+#', '', pathinfo($source, PATHINFO_DIRNAME));
+ $internalPath = $htmlDir . "/" . preg_replace('#^[/\.]+#', '', pathinfo($source, PATHINFO_DIRNAME));
- $mediaPath = $baseDir . "/" . $source;
- if (!file_exists($mediaPath)) {
- $mediaPath = $this->docRoot . $mediaPath;
- }
+ $mediaPath = $baseDir . "/" . $source;
+ if (!file_exists($mediaPath)) {
+ $mediaPath = $this->docRoot . $mediaPath;
}
}
@@ -971,7 +945,7 @@ protected function resolveMedia($source, &$internalPath, &$internalSrc, &$isSour
*
* @return bool $success
*/
- public function addLargeFile($fileName, $fileId, $filePath, $mimetype)
+ public function addLargeFile($fileName, $fileId, $filePath, $mimetype): bool
{
if ($this->isFinalized || array_key_exists($fileName, $this->fileList)) {
return false;
@@ -994,12 +968,12 @@ public function addLargeFile($fileName, $fileId, $filePath, $mimetype)
/**
* initialize defaults.
*/
- private function initialize()
+ private function initialize(): void
{
if ($this->isInitialized) {
return;
}
- if (strlen((string) $this->bookRoot) != 0 && $this->bookRoot != 'OEBPS/') {
+ if (strlen($this->bookRoot) != 0 && $this->bookRoot != 'OEBPS/') {
$this->setBookRoot($this->bookRoot);
}
@@ -1032,7 +1006,7 @@ private function initialize()
*
* @param string $bookRoot
*/
- public function setBookRoot($bookRoot)
+ public function setBookRoot($bookRoot): void
{
if ($this->isInitialized) {
die("bookRoot can't be set after book initialization (first file added).");
@@ -1040,18 +1014,13 @@ public function setBookRoot($bookRoot)
$bookRoot = trim($bookRoot);
if (strlen($bookRoot) <= 1 || $bookRoot == '/') {
$bookRoot = '';
- } else {
- if (!BinStringStatic::endsWith($bookRoot, '/')) {
- $bookRoot .= '/';
- }
+ } elseif (!str_ends_with($bookRoot, '/')) {
+ $bookRoot .= '/';
}
$this->bookRoot = $bookRoot;
}
- /**
- * @return bool
- */
- public function isEPubVersion2()
+ public function isEPubVersion2(): bool
{
return $this->bookVersion === EPub::BOOK_VERSION_EPUB2;
}
@@ -1069,7 +1038,7 @@ public function isEPubVersion2()
*
* @return bool|NavPoint The new NavPoint for that level.
*/
- public function subLevel($navTitle = null, $navId = null, $navClass = null, $isNavHidden = false, $writingDirection = null)
+ public function subLevel($navTitle = null, $navId = null, $navClass = null, $isNavHidden = false, $writingDirection = null): \PHPePub\Core\Structure\NCX\NavPoint|bool
{
return $this->ncx->subLevel(StringHelper::decodeHtmlEntities($navTitle), $navId, $navClass, $isNavHidden, $writingDirection);
}
@@ -1079,7 +1048,7 @@ public function subLevel($navTitle = null, $navId = null, $navClass = null, $isN
*
* Subsequent chapters will be added to this chapters parent level.
*/
- public function backLevel()
+ public function backLevel(): void
{
$this->ncx->backLevel();
}
@@ -1089,7 +1058,7 @@ public function backLevel()
*
* Subsequent chapters will be added to the rooot NavMap.
*/
- public function rootLevel()
+ public function rootLevel(): void
{
$this->ncx->rootLevel();
}
@@ -1101,7 +1070,7 @@ public function rootLevel()
*
* @param int $newLevel
*/
- public function setCurrentLevel($newLevel)
+ public function setCurrentLevel($newLevel): void
{
$this->ncx->setCurrentLevel($newLevel);
}
@@ -1121,7 +1090,7 @@ public function getCurrentLevel()
* @param string $nsName
* @param string $nsURI
*/
- public function addCustomNamespace($nsName, $nsURI)
+ public function addCustomNamespace($nsName, $nsURI): void
{
if ($this->isFinalized) {
return;
@@ -1138,7 +1107,7 @@ public function addCustomNamespace($nsName, $nsURI)
* @param string $name
* @param string $URI
*/
- public function addCustomPrefix($name, $URI)
+ public function addCustomPrefix($name, $URI): void
{
if ($this->isFinalized) {
return;
@@ -1157,7 +1126,7 @@ public function addCustomPrefix($name, $URI)
*
* @param MetaValue $value
*/
- public function addCustomMetaValue($value)
+ public function addCustomMetaValue($value): void
{
if ($this->isFinalized) {
return;
@@ -1177,7 +1146,7 @@ public function addCustomMetaValue($value)
* @param string $name property name, including the namespace declaration, ie. "dcterms:modified"
* @param string $content
*/
- public function addCustomMetaProperty($name, $content)
+ public function addCustomMetaProperty($name, $content): void
{
if ($this->isFinalized) {
return;
@@ -1193,7 +1162,7 @@ public function addCustomMetaProperty($name, $content)
* @param string $name
* @param string $content
*/
- public function addCustomMetadata($name, $content)
+ public function addCustomMetadata($name, $content): void
{
if ($this->isFinalized) {
return;
@@ -1210,7 +1179,7 @@ public function addCustomMetadata($name, $content)
* @param string $dublinCoreConstant name
* @param string $value
*/
- public function addDublinCoreMetadata($dublinCoreConstant, $value)
+ public function addDublinCoreMetadata($dublinCoreConstant, $value): void
{
if ($this->isFinalized) {
return;
@@ -1231,7 +1200,7 @@ public function addDublinCoreMetadata($dublinCoreConstant, $value)
*
* @return bool $success
*/
- public function setCoverImage($fileName, $imageData = null, $mimetype = null)
+ public function setCoverImage($fileName, $imageData = null, $mimetype = null): bool
{
if ($this->isFinalized || $this->isCoverImageSet || array_key_exists("CoverPage.xhtml", $this->fileList)) {
return false;
@@ -1274,8 +1243,9 @@ public function setCoverImage($fileName, $imageData = null, $mimetype = null)
}
if ($this->isEPubVersion2()) {
- $coverPage = "\n"
- . "
+\n"
. "\n"
. "\t\n"
@@ -1305,12 +1275,15 @@ public function setCoverImage($fileName, $imageData = null, $mimetype = null)
. "\t\n"
. "\n";
}
- $coverPageCss = "@page, body, div, img {\n"
- . "\tpadding: 0pt;\n"
- . "\tmargin:0pt;\n"
- . "}\n\nbody {\n"
- . "\ttext-align: center;\n"
- . "}\n";
+ $coverPageCss = '@page, body, div, img {
+ padding: 0pt;
+ margin:0pt;
+}
+
+body {
+ text-align: center;
+}
+';
$this->addCSSFile("Styles/CoverPage.css", "CoverPageCss", $coverPageCss);
$this->addFile($imgPath, "CoverImage", $imageData, $mimetype);
@@ -1335,7 +1308,7 @@ public function setCoverImage($fileName, $imageData = null, $mimetype = null)
*
* @return bool $success
*/
- public function addReferencePage($pageName, $fileName, $pageData, $reference, $externalReferences = EPub::EXTERNAL_REF_IGNORE, $baseDir = "")
+ public function addReferencePage($pageName, $fileName, $pageData, string $reference, $externalReferences = EPub::EXTERNAL_REF_IGNORE, string $baseDir = ""): bool
{
if ($this->isFinalized) {
return false;
@@ -1380,7 +1353,7 @@ public function addReferencePage($pageName, $fileName, $pageData, $reference, $e
*
* @return string $content
*/
- private function wrapChapter($content)
+ private function wrapChapter(string $content): string
{
return $this->htmlContentHeader . "\n" . $content . "\n" . $this->htmlContentFooter;
}
@@ -1391,7 +1364,7 @@ private function wrapChapter($content)
* @access public
* @return number of chapters
*/
- public function getChapterCount()
+ public function getChapterCount(): int
{
return $this->chapterCount;
}
@@ -1402,7 +1375,7 @@ public function getChapterCount()
* @access public
* @return string $title
*/
- public function getTitle()
+ public function getTitle(): string
{
return $this->title;
}
@@ -1412,12 +1385,11 @@ public function getTitle()
*
* Used for the dc:title metadata parameter in the OPF file as well as the DocTitle attribute in the NCX file.
*
- * @param string $title
*
* @access public
* @return bool $success
*/
- public function setTitle($title)
+ public function setTitle(string $title): bool
{
if ($this->isFinalized) {
return false;
@@ -1433,7 +1405,7 @@ public function setTitle($title)
* @access public
* @return string $language
*/
- public function getLanguage()
+ public function getLanguage(): string
{
return $this->language;
}
@@ -1451,9 +1423,9 @@ public function getLanguage()
* @access public
* @return bool $success
*/
- public function setLanguage($language)
+ public function setLanguage($language): bool
{
- if ($this->isFinalized || 0 === preg_match('/^((?([A-Za-z]{2,3}(-(?[A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?)|[A-Za-z]{4}|[A-Za-z]{5,8})(-(?[A-Za-z]{2}|[0-9]{3}))?)$/', $language)) {
+ if ($this->isFinalized || 0 === preg_match('/^((?([A-Za-z]{2,3}(-(?[A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?)|[A-Za-z]{4}|[A-Za-z]{5,8})(-(?[A-Za-z]{2}|\d{3}))?)$/', $language)) {
return false;
}
$this->language = $language;
@@ -1467,7 +1439,7 @@ public function setLanguage($language)
* @access public
* @return string $identifier
*/
- public function getIdentifier()
+ public function getIdentifier(): string
{
return $this->identifier;
}
@@ -1489,13 +1461,12 @@ public function getIdentifier()
* EPub::IDENTIFIER_ISBN
* EPub::IDENTIFIER_UUID
*
- * @param string $identifier
* @param string $identifierType
*
* @access public
* @return bool $success
*/
- public function setIdentifier($identifier, $identifierType)
+ public function setIdentifier(string $identifier, $identifierType): bool
{
if ($this->isFinalized || ($identifierType !== EPub::IDENTIFIER_URI && $identifierType !== EPub::IDENTIFIER_ISBN && $identifierType !== EPub::IDENTIFIER_UUID)) {
return false;
@@ -1512,7 +1483,7 @@ public function setIdentifier($identifier, $identifierType)
* @access public
* @return string $identifierType
*/
- public function getIdentifierType()
+ public function getIdentifierType(): string
{
return $this->identifierType;
}
@@ -1523,7 +1494,7 @@ public function getIdentifierType()
* @access public
* @return string $description
*/
- public function getDescription()
+ public function getDescription(): string
{
return $this->description;
}
@@ -1539,12 +1510,11 @@ public function getDescription()
*
* Used for the dc:source metadata parameter in the OPF file
*
- * @param string $description
*
* @access public
* @return bool $success
*/
- public function setDescription($description)
+ public function setDescription(string $description): bool
{
if ($this->isFinalized) {
return false;
@@ -1560,7 +1530,7 @@ public function setDescription($description)
* @access public
* @return string $author
*/
- public function getAuthor()
+ public function getAuthor(): string
{
return $this->author;
}
@@ -1580,13 +1550,11 @@ public function getAuthor()
* docAuthor attribure in the NCX file.
* The sort key is used for the opf:file-as attribute in dc:creator.
*
- * @param string $author
- * @param string $authorSortKey
*
* @access public
* @return bool $success
*/
- public function setAuthor($author, $authorSortKey)
+ public function setAuthor(string $author, string $authorSortKey): bool
{
if ($this->isFinalized) {
return false;
@@ -1607,13 +1575,11 @@ public function setAuthor($author, $authorSortKey)
*
* Used for the dc:publisher and dc:relation metadata parameters in the OPF file.
*
- * @param string $publisherName
- * @param string $publisherURL
*
* @access public
* @return bool $success
*/
- public function setPublisher($publisherName, $publisherURL)
+ public function setPublisher(string $publisherName, string $publisherURL): bool
{
if ($this->isFinalized) {
return false;
@@ -1630,7 +1596,7 @@ public function setPublisher($publisherName, $publisherURL)
* @access public
* @return string $publisherName
*/
- public function getPublisherName()
+ public function getPublisherName(): string
{
return $this->publisherName;
}
@@ -1641,7 +1607,7 @@ public function getPublisherName()
* @access public
* @return string $publisherURL
*/
- public function getPublisherURL()
+ public function getPublisherURL(): string
{
return $this->publisherURL;
}
@@ -1652,7 +1618,7 @@ public function getPublisherURL()
* @access public
* @return string $date
*/
- public function getDate()
+ public function getDate(): int
{
return $this->date;
}
@@ -1670,12 +1636,11 @@ public function getDate()
*
* Used for the dc:date metadata parameter in the OPF file
*
- * @param int $timestamp
*
* @access public
* @return bool $success
*/
- public function setDate($timestamp)
+ public function setDate(int $timestamp): bool
{
if ($this->isFinalized) {
return false;
@@ -1692,7 +1657,7 @@ public function setDate($timestamp)
* @access public
* @return string $rights
*/
- public function getRights()
+ public function getRights(): string
{
return $this->rights;
}
@@ -1708,12 +1673,11 @@ public function getRights()
*
* Used for the dc:rights metadata parameter in the OPF file
*
- * @param string $rightsText
*
* @access public
* @return bool $success
*/
- public function setRights($rightsText)
+ public function setRights(string $rightsText): bool
{
if ($this->isFinalized) {
return false;
@@ -1735,7 +1699,7 @@ public function setRights($rightsText)
*
* @param string $subject
*/
- public function setSubject($subject)
+ public function setSubject($subject): void
{
if ($this->isFinalized) {
return;
@@ -1749,7 +1713,7 @@ public function setSubject($subject)
* @access public
* @return string $sourceURL
*/
- public function getSourceURL()
+ public function getSourceURL(): string
{
return $this->sourceURL;
}
@@ -1765,12 +1729,11 @@ public function getSourceURL()
*
* Used for the dc:source metadata parameter in the OPF file
*
- * @param string $sourceURL
*
* @access public
* @return bool $success
*/
- public function setSourceURL($sourceURL)
+ public function setSourceURL(string $sourceURL): bool
{
if ($this->isFinalized) {
return false;
@@ -1786,7 +1749,7 @@ public function setSourceURL($sourceURL)
* @access public
* @return string $coverage
*/
- public function getCoverage()
+ public function getCoverage(): string
{
return $this->coverage;
}
@@ -1810,12 +1773,11 @@ public function getCoverage()
*
* Same as ->addDublinCoreMetadata(DublinCore::COVERAGE, $coverage);
*
- * @param string $coverage
*
* @access public
* @return bool $success
*/
- public function setCoverage($coverage)
+ public function setCoverage(string $coverage): bool
{
if ($this->isFinalized) {
return false;
@@ -1830,7 +1792,7 @@ public function setCoverage($coverage)
*
* @return string The relation.
*/
- public function getRelation()
+ public function getRelation(): string
{
return $this->relation;
}
@@ -1842,10 +1804,8 @@ public function getRelation()
*
* Recommended best practice is to identify the related resource by means
* of a string conforming to a formal identification system.
- *
- * @param string $relation
*/
- public function setRelation($relation)
+ public function setRelation(string $relation): void
{
if ($this->isFinalized) {
return;
@@ -1858,7 +1818,7 @@ public function setRelation($relation)
*
* @return string The generator identity string.
*/
- public function getGenerator()
+ public function getGenerator(): string
{
return $this->generator;
}
@@ -1868,10 +1828,8 @@ public function getGenerator()
*
* The generator is a meta tag added to the ncx file, it is not visible
* from within the book, but is a kind of electronic watermark.
- *
- * @param string $generator
*/
- public function setGenerator($generator)
+ public function setGenerator(string $generator): void
{
if ($this->isFinalized) {
return;
@@ -1889,7 +1847,7 @@ public function setGenerator($generator)
* @access public
* @return bool $success
*/
- public function setShortDateFormat()
+ public function setShortDateFormat(): bool
{
if ($this->isFinalized) {
return false;
@@ -1905,10 +1863,8 @@ public function setShortDateFormat()
* @param string $referencesTitle
* @param string $referencesId
* @param string $referencesClass
- *
- * @return bool
*/
- public function setReferencesTitle($referencesTitle = "Guide", $referencesId = "", $referencesClass = "references")
+ public function setReferencesTitle($referencesTitle = "Guide", $referencesId = "", $referencesClass = "references"): bool
{
if ($this->isFinalized) {
return false;
@@ -1924,10 +1880,8 @@ public function setReferencesTitle($referencesTitle = "Guide", $referencesId = "
* Set the references title for the ePub 3 landmarks section
*
* @param bool $isReferencesAddedToToc
- *
- * @return bool
*/
- public function setisReferencesAddedToToc($isReferencesAddedToToc = true)
+ public function setisReferencesAddedToToc($isReferencesAddedToToc = true): bool
{
if ($this->isFinalized) {
return false;
@@ -1941,9 +1895,8 @@ public function setisReferencesAddedToToc($isReferencesAddedToToc = true)
* Get Book status.
*
* @access public
- * @return bool
*/
- public function isFinalized()
+ public function isFinalized(): bool
{
return $this->isFinalized;
}
@@ -1957,10 +1910,8 @@ public function isFinalized()
* @param bool $addReferences include reference pages in the TOC, using the $referencesOrder array to determine the order of the pages in the TOC. Default is TRUE.
* @param bool $addToIndex Add the TOC to the NCX index at the current leve/position. Default is FALSE
* @param string $tocFileName Change the default name of the TOC file. The default is "TOC.xhtml"
- *
- * @return bool
*/
- public function buildTOC($cssFileName = null, $tocCSSClass = "toc", $title = "Table of Contents", $addReferences = true, $addToIndex = false, $tocFileName = "TOC.xhtml")
+ public function buildTOC($cssFileName = null, $tocCSSClass = "toc", $title = "Table of Contents", bool $addReferences = true, $addToIndex = false, $tocFileName = "TOC.xhtml"): bool
{
if ($this->isFinalized) {
return false;
@@ -1992,12 +1943,10 @@ public function buildTOC($cssFileName = null, $tocCSSClass = "toc", $title = "Ta
/**
* Save the ePub file to local disk.
*
- * @param string $fileName
* @param string $baseDir If empty baseDir is absolute to server path, if omitted it's relative to script path
- *
* @return string The sent file name if successful, FALSE if it failed.
*/
- public function saveBook($fileName, $baseDir = '.')
+ public function saveBook(string $fileName, string $baseDir = '.'): string|bool
{
// Make fileName safe
@@ -2008,7 +1957,7 @@ public function saveBook($fileName, $baseDir = '.')
$this->finalize();
}
- if (!BinStringStatic::endsWith($fileName, ".epub")) {
+ if (!str_ends_with($fileName, ".epub")) {
$fileName .= ".epub";
}
@@ -2016,7 +1965,7 @@ public function saveBook($fileName, $baseDir = '.')
$fh = fopen($baseDir . '/' . $fileName, "w");
if ($fh) {
- fputs($fh, $this->getBook());
+ fwrite($fh, $this->getBook());
fclose($fh);
// if file is written return TRUE
@@ -2033,13 +1982,13 @@ public function saveBook($fileName, $baseDir = '.')
*
* @return bool $success
*/
- public function finalize()
+ public function finalize(): bool
{
- if ($this->isFinalized || $this->chapterCount == 0 || empty($this->title) || empty($this->language)) {
+ if ($this->isFinalized || $this->chapterCount == 0 || ($this->title === '' || $this->title === '0') || ($this->language === '' || $this->language === '0')) {
return false;
}
- if (empty($this->identifier) || empty($this->identifierType)) {
+ if ($this->identifier === '' || $this->identifier === '0' || ($this->identifierType === '' || $this->identifierType === '0')) {
$this->setIdentifier(StringHelper::createUUID(4), EPub::IDENTIFIER_UUID);
}
@@ -2047,11 +1996,11 @@ public function finalize()
$this->date = time();
}
- if (empty($this->sourceURL)) {
+ if ($this->sourceURL === '' || $this->sourceURL === '0') {
$this->sourceURL = URLHelper::getCurrentPageURL();
}
- if (empty($this->publisherURL)) {
+ if ($this->publisherURL === '' || $this->publisherURL === '0') {
$this->sourceURL = URLHelper::getCurrentServerURL();
}
@@ -2063,37 +2012,37 @@ public function finalize()
$DCdate->addOpfAttr("event", "publication");
$this->opf->metadata->addDublinCore($DCdate);
- if (!empty($this->description)) {
+ if ($this->description !== '' && $this->description !== '0') {
$this->opf->addDCMeta(DublinCore::DESCRIPTION, StringHelper::decodeHtmlEntities($this->description));
}
- if (!empty($this->publisherName)) {
+ if ($this->publisherName !== '' && $this->publisherName !== '0') {
$this->opf->addDCMeta(DublinCore::PUBLISHER, StringHelper::decodeHtmlEntities($this->publisherName));
}
- if (!empty($this->publisherURL)) {
+ if ($this->publisherURL !== '' && $this->publisherURL !== '0') {
$this->opf->addDCMeta(DublinCore::RELATION, StringHelper::decodeHtmlEntities($this->publisherURL));
}
- if (!empty($this->author)) {
+ if ($this->author !== '' && $this->author !== '0') {
$author = StringHelper::decodeHtmlEntities($this->author);
$this->opf->addCreator($author, StringHelper::decodeHtmlEntities($this->authorSortKey), MarcCode::AUTHOR);
$this->ncx->setDocAuthor($author);
}
- if (!empty($this->rights)) {
+ if ($this->rights !== '' && $this->rights !== '0') {
$this->opf->addDCMeta(DublinCore::RIGHTS, StringHelper::decodeHtmlEntities($this->rights));
}
- if (!empty($this->coverage)) {
+ if ($this->coverage !== '' && $this->coverage !== '0') {
$this->opf->addDCMeta(DublinCore::COVERAGE, StringHelper::decodeHtmlEntities($this->coverage));
}
- if (!empty($this->sourceURL)) {
+ if ($this->sourceURL !== '' && $this->sourceURL !== '0') {
$this->opf->addDCMeta(DublinCore::SOURCE, $this->sourceURL);
}
- if (!empty($this->relation)) {
+ if ($this->relation !== '' && $this->relation !== '0') {
$this->opf->addDCMeta(DublinCore::RELATION, StringHelper::decodeHtmlEntities($this->relation));
}
@@ -2101,7 +2050,7 @@ public function finalize()
$this->opf->addMeta("cover", "CoverImage");
}
- if (!empty($this->generator)) {
+ if ($this->generator !== '' && $this->generator !== '0') {
$gen = StringHelper::decodeHtmlEntities($this->generator);
$this->opf->addMeta("generator", $gen);
$this->ncx->addMetaEntry("dtb:generator", $gen);
@@ -2158,10 +2107,8 @@ public function finalize()
/**
* Finalize and build final ePub structures.
- *
- * @return bool
*/
- private function finalizeTOC()
+ private function finalizeTOC(): bool
{
if (!$this->buildTOC) {
return false;
@@ -2198,7 +2145,7 @@ private function finalizeTOC()
. $tocCssCls . ".level7 {text-indent: 12em;}\n"
. $tocCssCls . ".reference {}\n"
. "\n";
- if (!empty($this->tocCssFileName)) {
+ if ($this->tocCssFileName !== null && $this->tocCssFileName !== '' && $this->tocCssFileName !== '0') {
$tocData .= " tocCssFileName . "\" />\n";
}
@@ -2222,19 +2169,13 @@ private function finalizeTOC()
/* . str_repeat(" ", $level) . */
. "" . $chapterName . "
\n";
}
- } else {
- if ($this->tocAddReferences === true) {
- if (array_key_exists($item, $this->ncx->referencesList)) {
- $tocData .= "\tncx->referencesList[$item] . "\">" . $descriptive . "
\n";
- } else {
- if ($item === "toc") {
- $tocData .= "\t" . $this->tocTitle . "
\n";
- } else {
- if ($item === "cover" && $this->isCoverImageSet) {
- $tocData .= "\t" . $descriptive . "
\n";
- }
- }
- }
+ } elseif ($this->tocAddReferences) {
+ if (array_key_exists($item, $this->ncx->referencesList)) {
+ $tocData .= "\tncx->referencesList[$item] . "\">" . $descriptive . "
\n";
+ } elseif ($item === "toc") {
+ $tocData .= "\t" . $this->tocTitle . "
\n";
+ } elseif ($item === "cover" && $this->isCoverImageSet) {
+ $tocData .= "\t" . $descriptive . "
\n";
}
}
}
@@ -2248,10 +2189,8 @@ private function finalizeTOC()
/**
* @param string $fileName
* @param string $tocData
- *
- * @return bool
*/
- public function addEPub3TOC($fileName, $tocData)
+ public function addEPub3TOC($fileName, $tocData): bool
{
if ($this->isEPubVersion2() || $this->isFinalized || array_key_exists($fileName, $this->fileList)) {
return false;
@@ -2274,10 +2213,8 @@ public function addEPub3TOC($fileName, $tocData)
/**
* @param string $cssFileName
* @param string $title
- *
- * @return string
*/
- public function buildEPub3TOC($cssFileName = null, $title = "Table of Contents")
+ public function buildEPub3TOC($cssFileName = null, $title = "Table of Contents"): string
{
$this->ncx->referencesOrder = $this->referencesOrder;
$this->ncx->setDocTitle(StringHelper::decodeHtmlEntities($this->title));
@@ -2324,13 +2261,13 @@ public function getBookSize()
*
* @return string|bool The sent file name if successful, FALSE if it failed.
*/
- public function sendBook($fileName)
+ public function sendBook(string $fileName): string|bool
{
if (!$this->isFinalized) {
$this->finalize();
}
- if (!BinStringStatic::endsWith($fileName, ".epub")) {
+ if (!str_ends_with($fileName, ".epub")) {
$fileName .= ".epub";
}
@@ -2348,7 +2285,7 @@ public function sendBook($fileName)
*
* @return array file list
*/
- public function getFileList()
+ public function getFileList(): array
{
return $this->fileList;
}
@@ -2358,10 +2295,8 @@ public function getFileList()
* Default is 250000 bytes, and minimum is 10240 bytes.
*
* @param int $size segment size in bytes
- *
- * @return void
*/
- public function setSplitSize($size)
+ public function setSplitSize($size): void
{
$this->splitDefaultSize = (int)$size;
if ($size < 10240) {
@@ -2379,10 +2314,7 @@ public function getSplitSize()
return $this->splitDefaultSize;
}
- /**
- * @return string
- */
- public function getLog()
+ public function getLog(): string
{
return $this->log->getLog();
}
@@ -2396,7 +2328,7 @@ public function getLog()
* @param int|string $width integer for the width, or a string referencing an entry in the $viewportMap.
* @param int $height
*/
- public function setViewport($width = null, $height = null)
+ public function setViewport($width = null, $height = null): void
{
if ($width == null) {
unset($this->viewport);
@@ -2414,9 +2346,18 @@ public function setViewport($width = null, $height = null)
*
* @return string the meta data line, or an empty string if no viewport is defined.
*/
- public function getViewportMetaLine()
+ public function getViewportMetaLine(): string
{
- if (empty($this->viewport)) {
+ if (is_null($this->viewport)) {
+ return "";
+ }
+ if ($this->viewport === []) {
+ return "";
+ }
+ if (!array_key_exists("width", $this->viewport)) {
+ return "";
+ }
+ if (!array_key_exists("height", $this->viewport)) {
return "";
}
@@ -2431,7 +2372,7 @@ public function getViewportMetaLine()
*
* @param bool $dangermode
*/
- public function setDangermode($dangermode)
+ public function setDangermode($dangermode): void
{
$this->dangermode = $dangermode === true;
}
@@ -2441,7 +2382,7 @@ public function setDangermode($dangermode)
*
* @return null|Opf the Opf structure class.
*/
- public function DANGER_getOpf()
+ public function DANGER_getOpf(): ?\PHPePub\Core\Structure\Opf
{
return $this->dangermode ? $this->opf : null;
}
@@ -2451,7 +2392,7 @@ public function DANGER_getOpf()
*
* @return null|Ncx The Ncx Navigation class
*/
- public function DANGER_getNcx()
+ public function DANGER_getNcx(): ?\PHPePub\Core\Structure\Ncx
{
return $this->dangermode ? $this->ncx : null;
}
@@ -2465,7 +2406,7 @@ public function DANGER_getNcx()
*
* @return null|Zip The actual zip file.
*/
- public function DANGER_getZip()
+ public function DANGER_getZip(): ?\PHPZip\Zip\File\Zip
{
return $this->dangermode ? $this->zip : null;
}
diff --git a/src/PHPePub/Core/EPubChapterSplitter.php b/src/PHPePub/Core/EPubChapterSplitter.php
index 6d6164b..523e224 100644
--- a/src/PHPePub/Core/EPubChapterSplitter.php
+++ b/src/PHPePub/Core/EPubChapterSplitter.php
@@ -18,8 +18,8 @@
*/
class EPubChapterSplitter
{
- private $splitDefaultSize = 250000;
- private $bookVersion = EPub::BOOK_VERSION_EPUB2;
+ private int $splitDefaultSize = 250000;
+ private string $bookVersion = EPub::BOOK_VERSION_EPUB2;
private $htmlFormat = EPub::FORMAT_XHTML;
/**
@@ -38,7 +38,7 @@ public function __construct($htmlFormat = EPub::FORMAT_XHTML)
*
* @param string $bookVersion
*/
- public function setVersion($bookVersion)
+ public function setVersion($bookVersion): void
{
$this->bookVersion = is_string($bookVersion) ? trim($bookVersion) : EPub::BOOK_VERSION_EPUB2;
}
@@ -48,7 +48,7 @@ public function setVersion($bookVersion)
*
* @param string $htmlFormat
*/
- public function setHtmlFormat($htmlFormat)
+ public function setHtmlFormat($htmlFormat): void
{
$this->htmlFormat = in_array($htmlFormat, [EPub::FORMAT_XHTML, EPub::FORMAT_HTML5])
? $htmlFormat
@@ -60,10 +60,8 @@ public function setHtmlFormat($htmlFormat)
* Default is 250000 bytes, and minimum is 10240 bytes.
*
* @param int $size segment size in bytes
- *
- * @return void
*/
- public function setSplitSize($size)
+ public function setSplitSize($size): void
{
$this->splitDefaultSize = (int)$size;
if ($size < 10240) {
@@ -76,7 +74,7 @@ public function setSplitSize($size)
*
* @return int $size
*/
- public function getSplitSize()
+ public function getSplitSize(): int
{
return $this->splitDefaultSize;
}
@@ -93,7 +91,7 @@ public function getSplitSize()
*
* @return array with 1 or more parts
*/
- public function splitChapter($chapter, $splitOnSearchString = false, $searchString = '/^Chapter\\ /i')
+ public function splitChapter($chapter, $splitOnSearchString = false, $searchString = '/^Chapter\\ /i'): array
{
$chapterData = [];
$isSearchRegexp = $splitOnSearchString && (preg_match('#^(\D|\S|\W).+\1[imsxeADSUXJu]*$#m', $searchString) == 1);
@@ -201,14 +199,13 @@ public function splitChapter($chapter, $splitOnSearchString = false, $searchStri
}
} while ($node != null);
- $curFile = null;
-
$xml = new DOMDocument('1.0', $xmlDoc->xmlEncoding);
$xml->lookupPrefix("http://www.w3.org/1999/xhtml");
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
+ $counter = count($files);
- for ($idx = 0; $idx < count($files); $idx++) {
+ for ($idx = 0; $idx < $counter; $idx++) {
$xml2Doc = new DOMDocument('1.0', $xmlDoc->xmlEncoding);
$xml2Doc->lookupPrefix("http://www.w3.org/1999/xhtml");
$xml2Doc->loadXML($newXML);
diff --git a/src/PHPePub/Core/Logger.php b/src/PHPePub/Core/Logger.php
index 57d660d..67de9e3 100644
--- a/src/PHPePub/Core/Logger.php
+++ b/src/PHPePub/Core/Logger.php
@@ -11,11 +11,11 @@
*/
class Logger
{
- private $log = "";
- private $tStart;
+ private string $log = "";
+ private array|float|null $tStart = null;
private $tLast;
- private $name = null;
- private $isDebugging = false;
+ private ?string $name = null;
+ private bool $isDebugging = false;
/**
* Class constructor.
@@ -25,15 +25,11 @@ class Logger
*/
public function __construct($name = null, private $isLogging = false)
{
- if ($name === null) {
- $this->name = "";
- } else {
- $this->name = $name . " : ";
- }
+ $this->name = $name === null ? "" : $name . " : ";
$this->start();
}
- public function start()
+ public function start(): void
{
/* Prepare Logging. Just in case it's used. later */
if ($this->isLogging) {
@@ -44,7 +40,7 @@ public function start()
}
}
- public function logLine($line)
+ public function logLine(string $line): void
{
if ($this->isLogging) {
$tTemp = gettimeofday();
@@ -73,7 +69,7 @@ public function __destruct()
unset($this->log);
}
- public function dumpInstalledModules()
+ public function dumpInstalledModules(): void
{
if ($this->isLogging) {
$isCurlInstalled = extension_loaded('curl') && function_exists('curl_version');
@@ -90,17 +86,15 @@ public function dumpInstalledModules()
}
}
- public function getLog()
+ public function getLog(): string
{
return $this->log;
}
/**
* @param $isCurlInstalled
- *
- * @return string
*/
- public function boolYN($isCurlInstalled)
+ public function boolYN($isCurlInstalled): string
{
return ($isCurlInstalled ? "Yes" : "No");
}
diff --git a/src/PHPePub/Core/Structure/NCX/NavMap.php b/src/PHPePub/Core/Structure/NCX/NavMap.php
index eecbe2d..2486854 100644
--- a/src/PHPePub/Core/Structure/NCX/NavMap.php
+++ b/src/PHPePub/Core/Structure/NCX/NavMap.php
@@ -13,9 +13,9 @@ class NavMap extends AbstractNavEntry
{
final public const _VERSION = 3.30;
- private $navPoints = [];
- private $navLevels = 0;
- private $writingDirection = null;
+ private array $navPoints = [];
+ private int $navLevels = 0;
+ private ?string $writingDirection = null;
/**
* Class constructor.
@@ -37,7 +37,7 @@ public function __destruct()
unset($this->navPoints, $this->navLevels, $this->writingDirection);
}
- public function getWritingDirection()
+ public function getWritingDirection(): ?string
{
return $this->writingDirection;
}
@@ -47,7 +47,7 @@ public function getWritingDirection()
*
* @param string $writingDirection
*/
- public function setWritingDirection($writingDirection)
+ public function setWritingDirection($writingDirection): void
{
$this->writingDirection = isset($writingDirection) && is_string($writingDirection) ? trim($writingDirection) : null;
}
@@ -59,7 +59,7 @@ public function setWritingDirection($writingDirection)
*
* @return NavMap
*/
- public function addNavPoint($navPoint)
+ public function addNavPoint($navPoint): \PHPePub\Core\Structure\NCX\NavPoint|static
{
if ($navPoint != null && is_object($navPoint) && $navPoint instanceof NavPoint) {
$navPoint->setParent($this);
@@ -80,12 +80,12 @@ public function addNavPoint($navPoint)
*
* @return number
*/
- public function getNavLevels()
+ public function getNavLevels(): int|float
{
return $this->navLevels + 1;
}
- public function getLevel()
+ public function getLevel(): int
{
return 1;
}
@@ -93,7 +93,7 @@ public function getLevel()
/**
* @return AbstractNavEntry this
*/
- public function getParent()
+ public function getParent(): static
{
return $this;
}
@@ -102,13 +102,13 @@ public function getParent()
* Finalize the navMap, the final max depth for the "dtb:depth" meta attribute can be retrieved with getNavLevels after finalization
*
*/
- public function finalize()
+ public function finalize(): string
{
$playOrder = 0;
$this->navLevels = 0;
$nav = "\t\n";
- if (count($this->navPoints) > 0) {
+ if ($this->navPoints !== []) {
$this->navLevels++;
foreach ($this->navPoints as $navPoint) {
/** @var $navPoint NavPoint */
@@ -126,7 +126,7 @@ public function finalize()
* Finalize the navMap, the final max depth for the "dtb:depth" meta attribute can be retrieved with getNavLevels after finalization
*
*/
- public function finalizeEPub3()
+ public function finalizeEPub3(): string
{
$playOrder = 0;
$level = 0;
@@ -134,7 +134,7 @@ public function finalizeEPub3()
$nav = "\t\t\n";
- if (count($this->navPoints) > 0) {
+ if ($this->navPoints !== []) {
$this->navLevels++;
$nav .= str_repeat("\t", $level) . "\t\t\t\n";
diff --git a/src/PHPePub/Core/Structure/NCX/NavPoint.php b/src/PHPePub/Core/Structure/NCX/NavPoint.php
index bd22d67..a17df2d 100644
--- a/src/PHPePub/Core/Structure/NCX/NavPoint.php
+++ b/src/PHPePub/Core/Structure/NCX/NavPoint.php
@@ -15,15 +15,15 @@ class NavPoint extends AbstractNavEntry
{
final public const _VERSION = 3.30;
- private $label = null;
- private $contentSrc = null;
- private $id = null;
- private $navClass = null;
- private $isNavHidden = false;
- private $navPoints = [];
+ private ?string $label = null;
+ private ?string $contentSrc = null;
+ private ?string $id = null;
+ private ?string $navClass = null;
+ private bool $isNavHidden = false;
+ private array $navPoints = [];
/** @var $parent AbstractNavEntry */
- private $parent = null;
- private $writingDirection = EPub::DIRECTION_LEFT_TO_RIGHT;
+ private ?\PHPePub\Core\Structure\NCX\AbstractNavEntry $parent = null;
+ private ?string $writingDirection = EPub::DIRECTION_LEFT_TO_RIGHT;
/**
* Class constructor.
@@ -54,7 +54,7 @@ public function __construct($label, $contentSrc = null, $id = null, $navClass =
*
* @param string $id
*/
- public function setId($id)
+ public function setId($id): void
{
$this->id = is_string($id) ? trim($id) : null;
}
@@ -64,7 +64,7 @@ public function setId($id)
*
* @param string $navClass
*/
- public function setNavClass($navClass)
+ public function setNavClass($navClass): void
{
$this->navClass = isset($navClass) && is_string($navClass) ? trim($navClass) : null;
}
@@ -74,7 +74,7 @@ public function setNavClass($navClass)
*
* @param $isNavHidden
*/
- public function setNavHidden($isNavHidden)
+ public function setNavHidden($isNavHidden): void
{
$this->isNavHidden = $isNavHidden === true;
}
@@ -95,7 +95,7 @@ public function __destruct()
*
* @return string Label
*/
- public function getLabel()
+ public function getLabel(): ?string
{
return $this->label;
}
@@ -107,7 +107,7 @@ public function getLabel()
*
* @param string $label
*/
- public function setLabel($label)
+ public function setLabel($label): void
{
$this->label = is_string($label) ? trim($label) : null;
}
@@ -117,7 +117,7 @@ public function setLabel($label)
*
* @return string content src url.
*/
- public function getContentSrc()
+ public function getContentSrc(): ?string
{
return $this->contentSrc;
}
@@ -129,7 +129,7 @@ public function getContentSrc()
*
* @param string $contentSrc
*/
- public function setContentSrc($contentSrc)
+ public function setContentSrc($contentSrc): void
{
$this->contentSrc = isset($contentSrc) && is_string($contentSrc) ? trim($contentSrc) : null;
}
@@ -139,7 +139,7 @@ public function setContentSrc($contentSrc)
*
* @return AbstractNavEntry if the parent is the root.
*/
- public function getParent()
+ public function getParent(): ?\PHPePub\Core\Structure\NCX\AbstractNavEntry
{
return $this->parent;
}
@@ -149,11 +149,15 @@ public function getParent()
*
* @param NavPoint|NavMap $parent
*/
- public function setParent($parent)
+ public function setParent($parent): void
{
- if ($parent != null && is_object($parent) && $parent instanceof AbstractNavEntry) {
- $this->parent = $parent;
+ if ($parent == null) {
+ return;
}
+ if (!is_object($parent)) {
+ return;
+ }
+ $this->parent = $parent;
}
/**
@@ -161,9 +165,9 @@ public function setParent($parent)
*
* @return int level
*/
- public function getLevel()
+ public function getLevel(): int|float
{
- return $this->parent === null ? 1 : $this->parent->getLevel() + 1;
+ return $this->parent instanceof \PHPePub\Core\Structure\NCX\AbstractNavEntry ? $this->parent->getLevel() + 1 : 1;
}
/**
@@ -173,7 +177,7 @@ public function getLevel()
*
* @return $this
*/
- public function addNavPoint($navPoint)
+ public function addNavPoint($navPoint): static
{
if ($navPoint != null && is_object($navPoint) && $navPoint instanceof NavPoint) {
/** @var $navPoint NavPoint */
@@ -189,7 +193,7 @@ public function addNavPoint($navPoint)
return $this;
}
- public function getWritingDirection()
+ public function getWritingDirection(): ?string
{
return $this->writingDirection;
}
@@ -199,7 +203,7 @@ public function getWritingDirection()
*
* @param string $writingDirection
*/
- public function setWritingDirection($writingDirection)
+ public function setWritingDirection($writingDirection): void
{
$this->writingDirection = isset($writingDirection) && is_string($writingDirection) ? trim($writingDirection) : null;
}
@@ -208,13 +212,11 @@ public function setWritingDirection($writingDirection)
*
* Enter description here ...
*
- * @param string $nav
* @param int $playOrder
* @param int $level
- *
* @return int
*/
- public function finalize(&$nav = "", &$playOrder = 0, $level = 0)
+ public function finalize(string &$nav = "", &$playOrder = 0, $level = 0)
{
$maxLevel = $level;
$levelAdjust = 0;
@@ -223,7 +225,7 @@ public function finalize(&$nav = "", &$playOrder = 0, $level = 0)
return $maxLevel;
}
- if (isset($this->contentSrc)) {
+ if ($this->contentSrc !== null) {
$playOrder++;
if ($this->id == null) {
@@ -238,7 +240,7 @@ public function finalize(&$nav = "", &$playOrder = 0, $level = 0)
$levelAdjust++;
}
- if (count($this->navPoints) > 0) {
+ if ($this->navPoints !== []) {
$maxLevel++;
foreach ($this->navPoints as $navPoint) {
/** @var $navPoint NavPoint */
@@ -249,7 +251,7 @@ public function finalize(&$nav = "", &$playOrder = 0, $level = 0)
}
}
- if (isset($this->contentSrc)) {
+ if ($this->contentSrc !== null) {
$nav .= str_repeat("\t", $level) . "\t\t\n";
}
@@ -260,15 +262,13 @@ public function finalize(&$nav = "", &$playOrder = 0, $level = 0)
*
* Enter description here ...
*
- * @param string $nav
* @param int $playOrder
* @param int $level
* @param null $subLevelClass
* @param bool $subLevelHidden
- *
* @return int
*/
- public function finalizeEPub3(&$nav = "", &$playOrder = 0, $level = 0, $subLevelClass = null, $subLevelHidden = false)
+ public function finalizeEPub3(string &$nav = "", &$playOrder = 0, $level = 0, $subLevelClass = null, $subLevelHidden = false)
{
$maxLevel = $level;
@@ -277,20 +277,20 @@ public function finalizeEPub3(&$nav = "", &$playOrder = 0, $level = 0, $subLevel
}
$dir = "";
- if (isset($this->writingDirection)) {
+ if ($this->writingDirection !== null) {
$dir .= " dir=\"" . $this->writingDirection . "\"";
}
$indent = str_repeat("\t", $level) . "\t\t\t\t";
$nav .= $indent . "id . "\"" . $dir . ">\n";
- if (isset($this->contentSrc)) {
+ if ($this->contentSrc !== null) {
$nav .= $indent . "\tcontentSrc . "\"" . $dir . ">" . $this->label . " \n";
} else {
$nav .= $indent . "\t" . $this->label . " \n";
}
- if (count($this->navPoints) > 0) {
+ if ($this->navPoints !== []) {
$maxLevel++;
$nav .= $indent . "\tparentBook = $parentBook;
}
@@ -90,7 +90,7 @@ public function setBook($parentBook)
*
* @param string $bookVersion
*/
- public function setVersion($bookVersion)
+ public function setVersion($bookVersion): void
{
$this->bookVersion = is_string($bookVersion) ? trim($bookVersion) : EPub::BOOK_VERSION_EPUB2;
}
@@ -99,7 +99,7 @@ public function setVersion($bookVersion)
*
* @return bool TRUE if the book is set to type ePub 2
*/
- public function isEPubVersion2()
+ public function isEPubVersion2(): bool
{
return $this->bookVersion === EPub::BOOK_VERSION_EPUB2;
}
@@ -110,7 +110,7 @@ public function isEPubVersion2()
*
* @param string $uid
*/
- public function setUid($uid)
+ public function setUid($uid): void
{
$this->uid = is_string($uid) ? trim($uid) : null;
}
@@ -121,7 +121,7 @@ public function setUid($uid)
*
* @param string $docTitle
*/
- public function setDocTitle($docTitle)
+ public function setDocTitle($docTitle): void
{
$this->docTitle = is_string($docTitle) ? trim($docTitle) : null;
}
@@ -132,7 +132,7 @@ public function setDocTitle($docTitle)
*
* @param string $docAuthor
*/
- public function setDocAuthor($docAuthor)
+ public function setDocAuthor($docAuthor): void
{
$this->docAuthor = is_string($docAuthor) ? trim($docAuthor) : null;
}
@@ -143,7 +143,7 @@ public function setDocAuthor($docAuthor)
*
* @param string $languageCode
*/
- public function setLanguageCode($languageCode)
+ public function setLanguageCode($languageCode): void
{
$this->languageCode = is_string($languageCode) ? trim($languageCode) : "en";
}
@@ -154,7 +154,7 @@ public function setLanguageCode($languageCode)
*
* @param string $writingDirection
*/
- public function setWritingDirection($writingDirection)
+ public function setWritingDirection($writingDirection): void
{
$this->writingDirection = is_string($writingDirection) ? trim($writingDirection) : EPub::DIRECTION_LEFT_TO_RIGHT;
}
@@ -165,11 +165,15 @@ public function setWritingDirection($writingDirection)
*
* @param NavMap $navMap
*/
- public function setNavMap($navMap)
+ public function setNavMap($navMap): void
{
- if ($navMap != null && is_object($navMap) && $navMap instanceof NavMap) {
- $this->navMap = $navMap;
+ if ($navMap == null) {
+ return;
}
+ if (!is_object($navMap)) {
+ return;
+ }
+ $this->navMap = $navMap;
}
/**
@@ -182,10 +186,8 @@ public function setNavMap($navMap)
* @param string $navClass
* @param bool $isNavHidden
* @param null $writingDirection
- *
- * @return bool|NavPoint
*/
- public function subLevel($navTitle = null, $navId = null, $navClass = null, $isNavHidden = false, $writingDirection = null)
+ public function subLevel($navTitle = null, $navId = null, $navClass = null, $isNavHidden = false, $writingDirection = null): \PHPePub\Core\Structure\NCX\NavPoint|bool
{
$navPoint = false;
if (isset($navTitle) && isset($navClass)) {
@@ -204,7 +206,7 @@ public function subLevel($navTitle = null, $navId = null, $navClass = null, $isN
*
* Subsequent chapters will be added to this chapters parent level.
*/
- public function backLevel()
+ public function backLevel(): void
{
$this->lastLevel = $this->currentLevel;
$this->currentLevel = $this->currentLevel->getParent();
@@ -215,7 +217,7 @@ public function backLevel()
*
* Subsequent chapters will be added to the rooot NavMap.
*/
- public function rootLevel()
+ public function rootLevel(): void
{
$this->lastLevel = $this->currentLevel;
$this->currentLevel = $this->navMap;
@@ -228,7 +230,7 @@ public function rootLevel()
*
* @param int $newLevel
*/
- public function setCurrentLevel($newLevel)
+ public function setCurrentLevel($newLevel): void
{
if ($newLevel <= 1) {
$this->rootLevel();
@@ -255,7 +257,7 @@ public function getCurrentLevel()
*
* @param NavPoint $navPoint
*/
- public function addNavPoint($navPoint)
+ public function addNavPoint($navPoint): void
{
$this->lastLevel = $this->currentLevel->addNavPoint($navPoint);
}
@@ -266,7 +268,7 @@ public function addNavPoint($navPoint)
*
* @return NavMap
*/
- public function getNavMap()
+ public function getNavMap(): ?\PHPePub\Core\Structure\NCX\NavMap
{
return $this->navMap;
}
@@ -278,23 +280,24 @@ public function getNavMap()
* @param string $name
* @param string $content
*/
- public function addMetaEntry($name, $content)
+ public function addMetaEntry($name, $content): void
{
$name = is_string($name) ? trim($name) : null;
$content = is_string($content) ? trim($content) : null;
-
- if ($name != null && $content != null) {
- $this->meta[] = [$name => $content];
+ if ($name == null) {
+ return;
}
+ if ($content == null) {
+ return;
+ }
+ $this->meta[] = [$name => $content];
}
/**
*
* Enter description here ...
- *
- * @return string
*/
- public function finalize()
+ public function finalize(): string
{
$nav = $this->navMap->finalize();
@@ -310,12 +313,10 @@ public function finalize()
. "\t\t \n"
. "\t\t \n";
- if (count($this->meta)) {
- foreach ($this->meta as $metaEntry) {
- $content = reset($metaEntry);
- $name = key($metaEntry);
- $ncx .= "\t\t \n";
- }
+ foreach ($this->meta as $metaEntry) {
+ $content = reset($metaEntry);
+ $name = key($metaEntry);
+ $ncx .= "\t\t \n";
}
$ncx .= "\t\n\n\t\n\t\t"
@@ -330,15 +331,14 @@ public function finalize()
/**
*
- * @param string $title
* @param string $cssFileName
*
- * @return string
*/
- public function finalizeEPub3($title = "Table of Contents", $cssFileName = null)
+ public function finalizeEPub3(string $title = "Table of Contents", $cssFileName = null): string
{
- $end = "\n"
- . "
+languageCode . "\" lang=\"" . $this->languageCode . "\" dir=\"" . $this->writingDirection . "\">\n"
. "\t\n"
@@ -353,28 +353,24 @@ public function finalizeEPub3($title = "Table of Contents", $cssFileName = null)
$end .= "\t\t \n";
}
- $end .= "\t\n"
- . "\t\n"
- . "\t\t\n"
- . "\t\t\t" . $title . " \n"
+ return $end . ('
+
+
+ ' . $title . " \n"
. "\t\t \n"
. $this->navMap->finalizeEPub3()
. $this->finalizeEPub3Landmarks()
. "\t\n"
- . "\n";
-
- return $end;
+ . "\n");
}
/**
* Build the references for the ePub 2 toc.
* These are merely reference pages added to the end of the navMap though.
- *
- * @return string
*/
- public function finalizeReferences()
+ public function finalizeReferences(): void
{
- if (isset($this->referencesList) && count($this->referencesList) > 0) {
+ if ($this->referencesList !== null && count($this->referencesList) > 0) {
$this->rootLevel();
$this->subLevel($this->referencesTitle, $this->referencesId, $this->referencesClass);
$refId = 1;
@@ -390,15 +386,13 @@ public function finalizeReferences()
/**
* Build the landmarks for the ePub 3 toc.
- *
- * @return string
*/
- public function finalizeEPub3Landmarks()
+ public function finalizeEPub3Landmarks(): string
{
$lm = "";
- if (isset($this->referencesList) && count($this->referencesList) > 0) {
- $lm = "\t\t\t\n"
- . "\t\t\t\treferencesList !== null && count($this->referencesList) > 0) {
+ $lm = '
+ writingDirection === EPub::DIRECTION_RIGHT_TO_LEFT ? " dir=\"rtl\"" : "") . ">"
. $this->referencesTitle . " \n"
. "\t\t\t\t\n";
@@ -413,7 +407,7 @@ public function finalizeEPub3Landmarks()
. " \n";
}
}
- if (empty($li)) {
+ if ($li === '' || $li === '0') {
return "";
}
diff --git a/src/PHPePub/Core/Structure/OPF/DublinCore.php b/src/PHPePub/Core/Structure/OPF/DublinCore.php
index 7a3f0ab..151fb87 100644
--- a/src/PHPePub/Core/Structure/OPF/DublinCore.php
+++ b/src/PHPePub/Core/Structure/OPF/DublinCore.php
@@ -45,7 +45,7 @@ public function __construct($name, $value)
* @param string $name
* @param string $value
*/
- public function setDc($name, $value)
+ public function setDc($name, $value): void
{
if (is_string($name)) {
$this->setValue("dc:" . trim($name), $value);
diff --git a/src/PHPePub/Core/Structure/OPF/Guide.php b/src/PHPePub/Core/Structure/OPF/Guide.php
index b5a48c6..6a5971e 100644
--- a/src/PHPePub/Core/Structure/OPF/Guide.php
+++ b/src/PHPePub/Core/Structure/OPF/Guide.php
@@ -11,12 +11,7 @@
*/
class Guide
{
- private $references = [];
-
- /**
- * Class constructor.
- */
- public function __construct() {}
+ private array $references = [];
/**
* Class destructor
@@ -33,7 +28,7 @@ public function __destruct()
* Enter description here ...
*
*/
- public function length()
+ public function length(): int
{
return count($this->references);
}
@@ -44,23 +39,25 @@ public function length()
*
* @param Reference $reference
*/
- public function addReference($reference)
+ public function addReference($reference): void
{
- if ($reference != null && is_object($reference) && $reference instanceof Reference) {
- $this->references[] = $reference;
+ if ($reference == null) {
+ return;
}
+ if (!is_object($reference)) {
+ return;
+ }
+ $this->references[] = $reference;
}
/**
*
* Enter description here ...
- *
- * @return string
*/
- public function finalize()
+ public function finalize(): string
{
$ref = "";
- if (count($this->references) > 0) {
+ if ($this->references !== []) {
$ref = "\n\t\n";
foreach ($this->references as $reference) {
/** @var $reference Reference */
diff --git a/src/PHPePub/Core/Structure/OPF/Item.php b/src/PHPePub/Core/Structure/OPF/Item.php
index 7ca4510..1c8a9e5 100644
--- a/src/PHPePub/Core/Structure/OPF/Item.php
+++ b/src/PHPePub/Core/Structure/OPF/Item.php
@@ -13,16 +13,16 @@
*/
class Item
{
- private $id = null;
- private $href = null;
- private $mediaType = null;
- private $properties = null;
- private $requiredNamespace = null;
- private $requiredModules = null;
- private $fallback = null;
- private $fallbackStyle = null;
+ private ?string $id = null;
+ private ?string $href = null;
+ private ?string $mediaType = null;
+ private ?string $properties = null;
+ private ?string $requiredNamespace = null;
+ private ?string $requiredModules = null;
+ private ?string $fallback = null;
+ private ?string $fallbackStyle = null;
- private $indexPoints = [];
+ private array $indexPoints = [];
/**
* Class constructor.
@@ -46,7 +46,7 @@ public function __construct($id, $href, $mediaType, $properties = null)
*
* @param string $id
*/
- public function setId($id)
+ public function setId($id): void
{
$this->id = is_string($id) ? trim($id) : null;
}
@@ -57,7 +57,7 @@ public function setId($id)
*
* @param string $href
*/
- public function setHref($href)
+ public function setHref($href): void
{
$this->href = is_string($href) ? trim($href) : null;
}
@@ -68,7 +68,7 @@ public function setHref($href)
*
* @param string $mediaType
*/
- public function setMediaType($mediaType)
+ public function setMediaType($mediaType): void
{
$this->mediaType = is_string($mediaType) ? trim($mediaType) : null;
}
@@ -79,7 +79,7 @@ public function setMediaType($mediaType)
*
* @param string $properties
*/
- public function setProperties($properties)
+ public function setProperties($properties): void
{
$this->properties = is_string($properties) ? trim($properties) : null;
}
@@ -101,7 +101,7 @@ public function __destruct()
*
* @param string $requiredNamespace
*/
- public function setRequiredNamespace($requiredNamespace)
+ public function setRequiredNamespace($requiredNamespace): void
{
$this->requiredNamespace = is_string($requiredNamespace) ? trim($requiredNamespace) : null;
}
@@ -112,7 +112,7 @@ public function setRequiredNamespace($requiredNamespace)
*
* @param string $requiredModules
*/
- public function setRequiredModules($requiredModules)
+ public function setRequiredModules($requiredModules): void
{
$this->requiredModules = is_string($requiredModules) ? trim($requiredModules) : null;
}
@@ -123,7 +123,7 @@ public function setRequiredModules($requiredModules)
*
* @param string $fallback
*/
- public function setfallback($fallback)
+ public function setfallback($fallback): void
{
$this->fallback = is_string($fallback) ? trim($fallback) : null;
}
@@ -134,7 +134,7 @@ public function setfallback($fallback)
*
* @param string $fallbackStyle
*/
- public function setFallbackStyle($fallbackStyle)
+ public function setFallbackStyle($fallbackStyle): void
{
$this->fallbackStyle = is_string($fallbackStyle) ? trim($fallbackStyle) : null;
}
@@ -142,35 +142,30 @@ public function setFallbackStyle($fallbackStyle)
/**
*
* @param string $bookVersion
- *
- * @return string
*/
- public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2)
+ public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2): string
{
$item = "\t\t- id . "\" href=\"" . $this->href . "\" media-type=\"" . $this->mediaType . "\" ";
- if ($bookVersion === EPub::BOOK_VERSION_EPUB3 && isset($this->properties)) {
+ if ($bookVersion === EPub::BOOK_VERSION_EPUB3 && $this->properties !== null) {
$item .= "properties=\"" . $this->properties . "\" ";
}
- if (isset($this->requiredNamespace)) {
+ if ($this->requiredNamespace !== null) {
$item .= "\n\t\t\trequired-namespace=\"" . $this->requiredNamespace . "\" ";
- if (isset($this->requiredModules)) {
+ if ($this->requiredModules !== null) {
$item .= "required-modules=\"" . $this->requiredModules . "\" ";
}
}
- if (isset($this->fallback)) {
+ if ($this->fallback !== null) {
$item .= "\n\t\t\tfallback=\"" . $this->fallback . "\" ";
}
- if (isset($this->fallbackStyle)) {
+ if ($this->fallbackStyle !== null) {
$item .= "\n\t\t\tfallback-style=\"" . $this->fallbackStyle . "\" ";
}
return $item . "/>\n";
}
- /**
- * @return array
- */
- public function getIndexPoints()
+ public function getIndexPoints(): array
{
return $this->indexPoints;
}
@@ -178,32 +173,27 @@ public function getIndexPoints()
/**
* @param string $indexPoint
*/
- public function addIndexPoint($indexPoint)
+ public function addIndexPoint($indexPoint): void
{
$this->indexPoints[] = $indexPoint;
}
/**
* @param string $indexPoint
- * @return bool
*/
- public function hasIndexPoint($indexPoint)
+ public function hasIndexPoint($indexPoint): bool
{
return in_array($indexPoint, $this->indexPoints);
}
- /**
- * @return null
- */
- public function getId()
+
+ public function getId(): ?string
{
return $this->id;
}
- /**
- * @return null
- */
- public function getHref()
+
+ public function getHref(): ?string
{
return $this->href;
}
diff --git a/src/PHPePub/Core/Structure/OPF/Itemref.php b/src/PHPePub/Core/Structure/OPF/Itemref.php
index 500bee4..7b9380a 100644
--- a/src/PHPePub/Core/Structure/OPF/Itemref.php
+++ b/src/PHPePub/Core/Structure/OPF/Itemref.php
@@ -11,8 +11,8 @@
*/
class Itemref
{
- private $idref = null;
- private $linear = true;
+ private ?string $idref = null;
+ private bool $linear = true;
/**
* Class constructor.
@@ -32,7 +32,7 @@ public function __construct($idref, $linear = true)
*
* @param bool $linear
*/
- public function setLinear($linear = true)
+ public function setLinear($linear = true): void
{
$this->linear = $linear === true;
}
@@ -53,7 +53,7 @@ public function __destruct()
*
* @return string $idref
*/
- public function getIdref()
+ public function getIdref(): ?string
{
return $this->idref;
}
@@ -64,7 +64,7 @@ public function getIdref()
*
* @param string $idref
*/
- public function setIdref($idref)
+ public function setIdref($idref): void
{
$this->idref = is_string($idref) ? trim($idref) : null;
}
@@ -72,10 +72,8 @@ public function setIdref($idref)
/**
*
* Enter description here ...
- *
- * @return string
*/
- public function finalize()
+ public function finalize(): string
{
$itemref = "\t\t
idref . "\"";
diff --git a/src/PHPePub/Core/Structure/OPF/Manifest.php b/src/PHPePub/Core/Structure/OPF/Manifest.php
index 6eb4a84..3921e62 100644
--- a/src/PHPePub/Core/Structure/OPF/Manifest.php
+++ b/src/PHPePub/Core/Structure/OPF/Manifest.php
@@ -13,12 +13,7 @@
*/
class Manifest
{
- private $items = [];
-
- /**
- * Class constructor.
- */
- public function __construct() {}
+ private array $items = [];
/**
* Class destructor
@@ -36,20 +31,22 @@ public function __destruct()
*
* @param Item $item
*/
- public function addItem($item)
+ public function addItem($item): void
{
- if ($item != null && is_object($item) && $item instanceof Item) {
- $this->items[] = $item;
+ if ($item == null) {
+ return;
+ }
+ if (!is_object($item)) {
+ return;
}
+ $this->items[] = $item;
}
/**
*
* @param string $bookVersion
- *
- * @return string
*/
- public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2)
+ public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2): string
{
$manifest = "\n\t\n";
foreach ($this->items as $item) {
@@ -60,10 +57,7 @@ public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2)
return $manifest . "\t \n";
}
- /**
- * @return array
- */
- public function getItems()
+ public function getItems(): array
{
return $this->items;
}
diff --git a/src/PHPePub/Core/Structure/OPF/MetaValue.php b/src/PHPePub/Core/Structure/OPF/MetaValue.php
index 8cbb72d..61b0103 100644
--- a/src/PHPePub/Core/Structure/OPF/MetaValue.php
+++ b/src/PHPePub/Core/Structure/OPF/MetaValue.php
@@ -13,10 +13,10 @@
*/
class MetaValue
{
- private $tagName = null;
- private $tagValue = null;
- private $attr = [];
- private $opfAttr = [];
+ private ?string $tagName = null;
+ private ?string $tagValue = null;
+ private array $attr = [];
+ private array $opfAttr = [];
/**
* Class constructor.
@@ -36,13 +36,11 @@ public function __construct($name, $value)
* @param string $name
* @param string $value
*/
- public function setValue($name, $value)
+ public function setValue($name, $value): void
{
$this->tagName = is_string($name) ? trim($name) : null;
- if (isset($this->tagName)) {
- $this->tagValue = isset($value) ? (string)$value : null;
- }
- if (!isset($this->tagValue)) {
+ $this->tagValue = isset($value) ? (string)$value : null;
+ if ($this->tagValue === null) {
$this->tagName = null;
}
}
@@ -64,7 +62,7 @@ public function __destruct()
* @param string $attrName
* @param string $attrValue
*/
- public function addAttr($attrName, $attrValue)
+ public function addAttr($attrName, $attrValue): void
{
$attrName = is_string($attrName) ? trim($attrName) : null;
if (isset($attrName)) {
@@ -83,7 +81,7 @@ public function addAttr($attrName, $attrValue)
* @param string $opfAttrName
* @param string $opfAttrValue
*/
- public function addOpfAttr($opfAttrName, $opfAttrValue)
+ public function addOpfAttr($opfAttrName, $opfAttrValue): void
{
$opfAttrName = is_string($opfAttrName) ? trim($opfAttrName) : null;
if (isset($opfAttrName)) {
@@ -104,13 +102,11 @@ public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2)
{
$dc = "\t\t<" . $this->tagName;
- if (count($this->attr) > 0) {
- foreach ($this->attr as $name => $content) {
- $dc .= " " . $name . "=\"" . $content . "\"";
- }
+ foreach ($this->attr as $name => $content) {
+ $dc .= " " . $name . "=\"" . $content . "\"";
}
- if ($bookVersion === EPub::BOOK_VERSION_EPUB2 && count($this->opfAttr) > 0) {
+ if ($bookVersion === EPub::BOOK_VERSION_EPUB2 && $this->opfAttr !== []) {
foreach ($this->opfAttr as $name => $content) {
$dc .= " opf:" . $name . "=\"" . $content . "\"";
}
diff --git a/src/PHPePub/Core/Structure/OPF/Metadata.php b/src/PHPePub/Core/Structure/OPF/Metadata.php
index 9701437..aaccfea 100644
--- a/src/PHPePub/Core/Structure/OPF/Metadata.php
+++ b/src/PHPePub/Core/Structure/OPF/Metadata.php
@@ -14,16 +14,11 @@
*/
class Metadata
{
- private $dc = [];
- private $meta = [];
- private $metaProperties = [];
+ private array $dc = [];
+ private array $meta = [];
+ private array $metaProperties = [];
public $namespaces = [];
- /**
- * Class constructor.
- */
- public function __construct() {}
-
/**
* Class destructor
*
@@ -40,11 +35,15 @@ public function __destruct()
*
* @param MetaValue $dc
*/
- public function addDublinCore($dc)
+ public function addDublinCore($dc): void
{
- if ($dc != null && is_object($dc) && $dc instanceof MetaValue) {
- $this->dc[] = $dc;
+ if ($dc == null) {
+ return;
}
+ if (!is_object($dc)) {
+ return;
+ }
+ $this->dc[] = $dc;
}
/**
@@ -54,7 +53,7 @@ public function addDublinCore($dc)
* @param string $name
* @param string $content
*/
- public function addMeta($name, $content)
+ public function addMeta($name, $content): void
{
$name = is_string($name) ? trim($name) : null;
if (isset($name)) {
@@ -72,7 +71,7 @@ public function addMeta($name, $content)
* @param string $name
* @param string $content
*/
- public function addMetaProperty($name, $content)
+ public function addMetaProperty($name, $content): void
{
$name = is_string($name) ? trim($name) : null;
if (isset($name)) {
@@ -87,7 +86,7 @@ public function addMetaProperty($name, $content)
* @param string $nsName
* @param string $nsURI
*/
- public function addNamespace($nsName, $nsURI)
+ public function addNamespace($nsName, $nsURI): void
{
if (!array_key_exists($nsName, $this->namespaces)) {
$this->namespaces[$nsName] = $nsURI;
@@ -98,10 +97,8 @@ public function addNamespace($nsName, $nsURI)
*
* @param string $bookVersion
* @param int $date
- *
- * @return string
*/
- public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2, $date = null)
+ public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2, $date = null): string
{
if ($bookVersion === EPub::BOOK_VERSION_EPUB2) {
$this->addNamespace("opf", StaticData::$namespaces["opf"]);
@@ -113,7 +110,7 @@ public function finalize($bookVersion = EPub::BOOK_VERSION_EPUB2, $date = null)
$this->addMetaProperty("dcterms:modified", gmdate('Y-m-d\TH:i:s\Z', $date));
}
- if (count($this->dc) > 0) {
+ if ($this->dc !== []) {
$this->addNamespace("dc", StaticData::$namespaces["dc"]);
}
diff --git a/src/PHPePub/Core/Structure/OPF/Reference.php b/src/PHPePub/Core/Structure/OPF/Reference.php
index 3c39f6d..fb8c7ec 100644
--- a/src/PHPePub/Core/Structure/OPF/Reference.php
+++ b/src/PHPePub/Core/Structure/OPF/Reference.php
@@ -79,9 +79,9 @@ class Reference
/** Ancillary material occurring after the document body, such as indices, appendices, etc. */
final public const BACKMATTER = "backmatter";
- private $type = null;
- private $title = null;
- private $href = null;
+ private ?string $type = null;
+ private ?string $title = null;
+ private ?string $href = null;
/**
* Class constructor.
@@ -103,7 +103,7 @@ public function __construct($type, $title, $href)
*
* @param string $type
*/
- public function setType($type)
+ public function setType($type): void
{
$this->type = is_string($type) ? trim($type) : null;
}
@@ -114,7 +114,7 @@ public function setType($type)
*
* @param string $title
*/
- public function setTitle($title)
+ public function setTitle($title): void
{
$this->title = is_string($title) ? trim($title) : null;
}
@@ -125,7 +125,7 @@ public function setTitle($title)
*
* @param string $href
*/
- public function setHref($href)
+ public function setHref($href): void
{
$this->href = is_string($href) ? trim($href) : null;
}
@@ -143,10 +143,8 @@ public function __destruct()
/**
*
* Enter description here ...
- *
- * @return string
*/
- public function finalize()
+ public function finalize(): string
{
return "\t\ttype . "\" title=\"" . $this->title . "\" href=\"" . $this->href . "\" />\n";
}
diff --git a/src/PHPePub/Core/Structure/OPF/Spine.php b/src/PHPePub/Core/Structure/OPF/Spine.php
index feee325..7e6af9f 100644
--- a/src/PHPePub/Core/Structure/OPF/Spine.php
+++ b/src/PHPePub/Core/Structure/OPF/Spine.php
@@ -11,8 +11,8 @@
*/
class Spine
{
- private $itemrefs = [];
- private $toc = null;
+ private array $itemrefs = [];
+ private ?string $toc = null;
/**
* Class constructor.
@@ -30,7 +30,7 @@ public function __construct($toc = "ncx")
*
* @param string $toc
*/
- public function setToc($toc)
+ public function setToc($toc): void
{
$this->toc = is_string($toc) ? trim($toc) : null;
}
@@ -51,24 +51,25 @@ public function __destruct()
*
* @param Itemref $itemref
*/
- public function addItemref($itemref)
+ public function addItemref($itemref): void
{
- if ($itemref != null
- && is_object($itemref)
- && $itemref instanceof Itemref
- && !isset($this->itemrefs[$itemref->getIdref()])
- ) {
- $this->itemrefs[$itemref->getIdref()] = $itemref;
+ if ($itemref == null) {
+ return;
}
+ if (!is_object($itemref)) {
+ return;
+ }
+ if (isset($this->itemrefs[$itemref->getIdref()])) {
+ return;
+ }
+ $this->itemrefs[$itemref->getIdref()] = $itemref;
}
/**
*
* Enter description here ...
- *
- * @return string
*/
- public function finalize()
+ public function finalize(): string
{
$spine = "\n\ttoc . "\">\n";
foreach ($this->itemrefs as $itemref) {
diff --git a/src/PHPePub/Core/Structure/Opf.php b/src/PHPePub/Core/Structure/Opf.php
index 7e32af2..aac64bc 100644
--- a/src/PHPePub/Core/Structure/Opf.php
+++ b/src/PHPePub/Core/Structure/Opf.php
@@ -2,7 +2,6 @@
namespace PHPePub\Core\Structure;
-use com\grandt\BinStringStatic;
use PHPePub\Core\EPub;
use PHPePub\Core\Structure\OPF\DublinCore;
use PHPePub\Core\Structure\OPF\Guide;
@@ -39,19 +38,19 @@ class Opf
final public const TYPE_OEB1_CSS = "text/x-oeb1-css"; // Deprecated
final public const TYPE_NCX = "application/x-dtbncx+xml";
- private $bookVersion = EPub::BOOK_VERSION_EPUB2;
- private $ident = "BookId";
+ private string $bookVersion = EPub::BOOK_VERSION_EPUB2;
+ private string $ident = "BookId";
- public $date = null;
+ public $date;
/** @var $metadata Metadata */
- public $metadata = null;
+ public $metadata;
/** @var $manifest Manifest */
- public $manifest = null;
+ public $manifest;
/** @var $spine Spine */
- public $spine = null;
+ public $spine;
/** @var $guide Guide */
- public $guide = null;
+ public $guide;
public $namespaces = ["xsi" => "http://www.w3.org/2001/XMLSchema-instance"];
public $prefixes = [];
@@ -88,12 +87,12 @@ public function __destruct()
*
* @param $bookVersion
*/
- public function setVersion($bookVersion)
+ public function setVersion($bookVersion): void
{
$this->bookVersion = is_string($bookVersion) ? trim($bookVersion) : EPub::BOOK_VERSION_EPUB2;
}
- public function isEPubVersion2()
+ public function isEPubVersion2(): bool
{
return $this->bookVersion === EPub::BOOK_VERSION_EPUB2;
}
@@ -104,7 +103,7 @@ public function isEPubVersion2()
*
* @param string $ident
*/
- public function setIdent($ident = "BookId")
+ public function setIdent($ident = "BookId"): void
{
$this->ident = is_string($ident) ? trim($ident) : "BookId";
}
@@ -112,10 +111,8 @@ public function setIdent($ident = "BookId")
/**
*
* Enter description here ...
- *
- * @return string
*/
- public function finalize()
+ public function finalize(): string
{
$metadata = $this->metadata->finalize($this->bookVersion, $this->date);
@@ -123,8 +120,9 @@ public function finalize()
$this->addNamespace($ns, $nsuri);
}
- $opf = "\n"
- . "
+namespaces as $ns => $uri) {
$opf .= "\txmlns:$ns=\"$uri\"\n";
@@ -167,7 +165,7 @@ public function finalize()
* @param string $identifier
* @param string $identifierScheme
*/
- public function initialize($title, $language, $identifier, $identifierScheme)
+ public function initialize($title, $language, $identifier, $identifierScheme): void
{
$this->metadata->addDublinCore(new DublinCore("title", $title));
$this->metadata->addDublinCore(new DublinCore("language", $language));
@@ -182,7 +180,7 @@ public function initialize($title, $language, $identifier, $identifierScheme)
* @param string $nsName
* @param string $nsURI
*/
- public function addNamespace($nsName, $nsURI)
+ public function addNamespace($nsName, $nsURI): void
{
if (!array_key_exists($nsName, $this->namespaces)) {
$this->namespaces[$nsName] = $nsURI;
@@ -193,7 +191,7 @@ public function addNamespace($nsName, $nsURI)
* @param string $name
* @param string $URI
*/
- public function addPrefix($name, $URI)
+ public function addPrefix($name, $URI): void
{
if (!array_key_exists($name, $this->prefixes)) {
$this->prefixes[$name] = $URI;
@@ -209,7 +207,7 @@ public function addPrefix($name, $URI)
* @param string $mediaType
* @param string $properties
*/
- public function addItem($id, $href, $mediaType, $properties = null)
+ public function addItem($id, $href, $mediaType, $properties = null): void
{
$this->manifest->addItem(new Item($id, $href, $mediaType, $properties));
}
@@ -244,11 +242,16 @@ public function getItemByHref($href, $startsWith = false)
foreach ($this->manifest->getItems() as $item) {
if (!$startsWith && $item->getHref() == $href) {
return $item;
- } elseif($startsWith && BinStringStatic::startsWith($item->getHref(), $href)) {
- $rv[] = $item;
}
+ if (!$startsWith) {
+ continue;
+ }
+ if (!str_starts_with((string) $item->getHref(), $href)) {
+ continue;
+ }
+ $rv[] = $item;
}
- if (count($rv) > 0) {
+ if ($rv !== []) {
return $rv;
}
return false;
@@ -261,7 +264,7 @@ public function getItemByHref($href, $startsWith = false)
* @param string $idref
* @param bool $linear
*/
- public function addItemRef($idref, $linear = true)
+ public function addItemRef($idref, $linear = true): void
{
$this->spine->addItemref(new Itemref($idref, $linear));
}
@@ -274,7 +277,7 @@ public function addItemRef($idref, $linear = true)
* @param string $title
* @param string $href
*/
- public function addReference($type, $title, $href)
+ public function addReference($type, $title, $href): void
{
$this->guide->addReference(new Reference($type, $title, $href));
}
@@ -286,7 +289,7 @@ public function addReference($type, $title, $href)
* @param string $name
* @param string $value
*/
- public function addDCMeta($name, $value)
+ public function addDCMeta($name, $value): void
{
$this->addMetaValue(new DublinCore($name, $value));
}
@@ -295,7 +298,7 @@ public function addDCMeta($name, $value)
*
* @param MetaValue $value
*/
- public function addMetaValue($value)
+ public function addMetaValue($value): void
{
$this->metadata->addDublinCore($value);
}
@@ -309,7 +312,7 @@ public function addMetaValue($value)
* @param string $name
* @param string $content
*/
- public function addMeta($name, $content)
+ public function addMeta($name, $content): void
{
$this->metadata->addMeta($name, $content);
}
@@ -325,7 +328,7 @@ public function addMeta($name, $content)
* @param string $name property name, including the namespace declaration, ie. "dcterms:modified"
* @param string $content
*/
- public function addMetaProperty($name, $content)
+ public function addMetaProperty($name, $content): void
{
$this->metadata->addMetaProperty($name, $content);
}
@@ -338,7 +341,7 @@ public function addMetaProperty($name, $content)
* @param string $fileAs
* @param string $role Use the MarcCode constants
*/
- public function addCreator($name, $fileAs = null, $role = null)
+ public function addCreator($name, $fileAs = null, $role = null): void
{
$dc = new DublinCore(DublinCore::CREATOR, trim($name));
@@ -361,7 +364,7 @@ public function addCreator($name, $fileAs = null, $role = null)
* @param string $fileAs
* @param string $role Use the MarcCode constants
*/
- public function addColaborator($name, $fileAs = null, $role = null)
+ public function addColaborator($name, $fileAs = null, $role = null): void
{
$dc = new DublinCore(DublinCore::CONTRIBUTOR, trim($name));
diff --git a/src/PHPePub/Helpers/CalibreHelper.php b/src/PHPePub/Helpers/CalibreHelper.php
index 3c3827c..a4b079f 100644
--- a/src/PHPePub/Helpers/CalibreHelper.php
+++ b/src/PHPePub/Helpers/CalibreHelper.php
@@ -17,10 +17,9 @@ class CalibreHelper
/**
* @param EPub $book
* @param string $seriesName
- * @param string $seriesIndex
* @param string $sortTitle
*/
- public static function setCalibreMetadata($book, $seriesName, $seriesIndex, $sortTitle = null)
+ public static function setCalibreMetadata($book, $seriesName, string $seriesIndex, $sortTitle = null): void
{
$book->addCustomMetadata("calibre:series", $seriesName);
$book->addCustomMetadata("calibre:series_index", "" . $seriesIndex);
diff --git a/src/PHPePub/Helpers/Enum.php b/src/PHPePub/Helpers/Enum.php
index 946d59f..d1b0b20 100644
--- a/src/PHPePub/Helpers/Enum.php
+++ b/src/PHPePub/Helpers/Enum.php
@@ -13,7 +13,7 @@
*/
abstract class Enum
{
- private static $constantsCache = [];
+ private static array $constantsCache = [];
private $value;
public function __construct($value)
@@ -25,7 +25,7 @@ public function __construct($value)
$this->value = $value;
}
- public function is($value)
+ public function is($value): bool
{
return $this->value === $value;
}
@@ -35,7 +35,7 @@ public function value()
return $this->value;
}
- public static function has($value)
+ public static function has($value): bool
{
return in_array($value, self::toArray(), true);
}
diff --git a/src/PHPePub/Helpers/FileHelper.php b/src/PHPePub/Helpers/FileHelper.php
index 136d5da..a83f5e8 100644
--- a/src/PHPePub/Helpers/FileHelper.php
+++ b/src/PHPePub/Helpers/FileHelper.php
@@ -60,7 +60,7 @@ public static function getIsFileGetContentsExtInstalled()
*
* @return mixed|string
*/
- public static function sanitizeFileName($fileName)
+ public static function sanitizeFileName($fileName): string
{
$fileName1 = str_replace(StaticData::$forbiddenCharacters, '', $fileName);
$fileName2 = preg_replace('/[\s-]+/', '-', $fileName1);
@@ -147,7 +147,7 @@ public static function getFileContents($source, $toTempFile = false)
*
* @return string normalized filename
*/
- public static function normalizeFileName($fileName)
+ public static function normalizeFileName($fileName): ?string
{
return preg_replace('#^[/\.]+#i', "", RelativePath::getRelativePath($fileName));
}
diff --git a/src/PHPePub/Helpers/IBooksHelper.php b/src/PHPePub/Helpers/IBooksHelper.php
index 52a2306..204d650 100644
--- a/src/PHPePub/Helpers/IBooksHelper.php
+++ b/src/PHPePub/Helpers/IBooksHelper.php
@@ -129,7 +129,7 @@ class IBooksHelper
*
* @param EPub $book
*/
- public static function addPrefix($book)
+ public static function addPrefix($book): void
{
if (!$book->isEPubVersion2()) {
$book->addCustomPrefix(self::EPUB3_IBOOK_PREFIX_NAME, self::EPUB3_IBOOK_PREFIX_URI);
@@ -141,7 +141,7 @@ public static function addPrefix($book)
* @param string $property
* @param string $value
*/
- public static function addProperty($book, $property, $value)
+ public static function addProperty($book, $property, $value): void
{
if (!$book->isEPubVersion2()) {
$book->addCustomMetaProperty($property, $value);
@@ -152,7 +152,7 @@ public static function addProperty($book, $property, $value)
* @param EPub $book
* @param bool $value
*/
- public static function setFixedLayout($book, $value)
+ public static function setFixedLayout($book, $value): void
{
if (!$book->isEPubVersion2()) {
$book->addCustomMetaProperty(self::EPUB3_FIXED_LAYOUT, Boolean::getBoolean($value));
@@ -163,7 +163,7 @@ public static function setFixedLayout($book, $value)
* @param EPub $book
* @param string $value "portrait-only", "landscape-only"
*/
- public static function setIPhoneOrientationLock($book, $value)
+ public static function setIPhoneOrientationLock($book, $value): void
{
if (!$book->isEPubVersion2() && $value === self::ORIENTATION_PORTRAIT_ONLY || $value === self::ORIENTATION_LANDSCAPE_ONLY) {
$book->addCustomMetaProperty(self::EPUB3_IPHONE_ORIENTATION_LOCK, $value);
@@ -174,7 +174,7 @@ public static function setIPhoneOrientationLock($book, $value)
* @param EPub $book
* @param string $value "portrait-only", "landscape-only"
*/
- public static function setIPadOrientationLock($book, $value)
+ public static function setIPadOrientationLock($book, $value): void
{
if (!$book->isEPubVersion2() && $value === self::ORIENTATION_PORTRAIT_ONLY || $value === self::ORIENTATION_LANDSCAPE_ONLY) {
$book->addCustomMetaProperty(self::EPUB3_IPAD_ORIENTATION_LOCK, $value);
@@ -185,7 +185,7 @@ public static function setIPadOrientationLock($book, $value)
* @param EPub $book
* @param bool $value
*/
- public static function setSpecifiedFonts($book, $value)
+ public static function setSpecifiedFonts($book, $value): void
{
if (!$book->isEPubVersion2()) {
$book->addCustomMetaProperty(self::EPUB3_SPECIFIED_FONTS, Boolean::getBoolean($value));
@@ -196,7 +196,7 @@ public static function setSpecifiedFonts($book, $value)
* @param EPub $book
* @param bool $value
*/
- public static function setBinding($book, $value)
+ public static function setBinding($book, $value): void
{
if (!$book->isEPubVersion2()) {
$book->addCustomMetaProperty(self::EPUB3_BINDING, Boolean::getBoolean($value));
diff --git a/src/PHPePub/Helpers/ImageHelper.php b/src/PHPePub/Helpers/ImageHelper.php
index d51ca3a..7fb68d1 100644
--- a/src/PHPePub/Helpers/ImageHelper.php
+++ b/src/PHPePub/Helpers/ImageHelper.php
@@ -10,16 +10,15 @@
namespace PHPePub\Helpers;
-use com\grandt\BinStringStatic;
use grandt\ResizeGif\ResizeGif;
use PHPePub\Core\EPub;
use SimpleXMLElement;
class ImageHelper
{
- protected static $isGdInstalled = null;
- protected static $isExifInstalled = null;
- protected static $isAnimatedGifResizeInstalled = null;
+ protected static $isGdInstalled;
+ protected static $isExifInstalled;
+ protected static $isAnimatedGifResizeInstalled;
/**
* get mime type from image data
@@ -56,42 +55,37 @@ public static function getImageFileTypeFromBinary($binary)
*
* @param $maxImageWidth
* @param $maxImageHeight
- *
- * @return float
*/
- public static function getImageScale($width, $height, $maxImageWidth, $maxImageHeight)
+ public static function getImageScale($width, $height, $maxImageWidth, $maxImageHeight): int|float
{
- $ratio = 1;
if ($width > $maxImageWidth) {
- $ratio = $maxImageWidth / $width;
+ return $maxImageWidth / $width;
}
- if ($height * $ratio > $maxImageHeight) {
- $ratio = $maxImageHeight / $height;
-
- return $ratio;
+ if ($height > $maxImageHeight) {
+ return $maxImageHeight / $height;
}
- return $ratio;
+ return 1;
}
/**
* @param $attr
- * @param string $sep
*
* @return array
*/
- public static function splitCSV($attr, $sep = ',')
+ public static function splitCSV($attr, string $sep = ','): array|false
{
if (strpos((string) $attr, $sep) > 0) {
return preg_split('/\s*' . $sep . '\s*/', (string) $attr);
- } elseif ($sep !== ',' && strpos((string) $attr, ',') > 0) {
+ }
+ if ($sep !== ',' && strpos((string) $attr, ',') > 0) {
return preg_split('/\s*,\s*/', (string) $attr);
- } elseif (strpos((string) $attr, ';') > 0) {
+ }
+ if (strpos((string) $attr, ';') > 0) {
return preg_split('/\s*;\s*/', (string) $attr);
- } else {
- return preg_split('/\s+/', (string) $attr);
}
+ return preg_split('/\s+/', (string) $attr);
}
/**
@@ -100,10 +94,8 @@ public static function splitCSV($attr, $sep = ',')
*
* @param $length
* @param int $portSize
- *
- * @return float
*/
- public static function scaleSVGUnit($length, $portSize = 512)
+ public static function scaleSVGUnit($length, $portSize = 512): float
{
static $unitLength = [
'px' => 1.0,
@@ -120,25 +112,21 @@ public static function scaleSVGUnit($length, $portSize = 512)
];
$matches = [];
if (preg_match('/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', (string) $length, $matches)) {
- $length = floatval($matches[1]);
+ $length = (float) $matches[1];
$unit = $matches[2];
if ($unit == '%') {
return $length * 0.01 * $portSize;
- } else {
- return $length * $unitLength[$unit];
}
- } else {
- // Assume pixels
- return floatval($length);
+ return $length * $unitLength[$unit];
}
+ // Assume pixels
+ return (float) $length;
}
/**
* @param SimpleXMLElement $svg
- *
- * @return array
*/
- public static function handleSVGAttribs($svg)
+ public static function handleSVGAttribs($svg): array
{
$metadata = [];
$attr = $svg->attributes();
@@ -150,7 +138,7 @@ public static function handleSVGAttribs($svg)
$width = null;
$height = null;
- if ($attr->viewBox) {
+ if ($attr->viewBox !== null) {
// min-x min-y width height
$viewBoxAttr = trim($attr->viewBox);
@@ -164,20 +152,20 @@ public static function handleSVGAttribs($svg)
}
}
- if ($attr->x) {
+ if ($attr->x !== null) {
$x = self::scaleSVGUnit($attr->x, 0);
$metadata['originalX'] = "" . $attr->x;
}
- if ($attr->y) {
+ if ($attr->y !== null) {
$y = self::scaleSVGUnit($attr->y, 0);
$metadata['originalY'] = "" . $attr->y;
}
- if ($attr->width) {
+ if ($attr->width !== null) {
$width = self::scaleSVGUnit($attr->width, $viewWidth);
$metadata['originalWidth'] = "" . $attr->width;
}
- if ($attr->height) {
+ if ($attr->height !== null) {
$height = self::scaleSVGUnit($attr->height, $viewHeight);
$metadata['originalHeight'] = "" . $attr->height;
}
@@ -192,12 +180,12 @@ public static function handleSVGAttribs($svg)
}
if ($x > 0 && $y > 0) {
- $metadata['x'] = intval(round($x));
- $metadata['y'] = intval(round($y));
+ $metadata['x'] = (int) round($x);
+ $metadata['y'] = (int) round($y);
}
if ($width > 0 && $height > 0) {
- $metadata['width'] = intval(round($width));
- $metadata['height'] = intval(round($height));
+ $metadata['width'] = (int) round($width);
+ $metadata['height'] = (int) round($height);
$metadata['aspect'] = $aspect;
}
@@ -217,10 +205,9 @@ public static function handleSVGAttribs($svg)
* @param EPub $book
* @param string $imageSource path or url to file.
*
- * @return array|bool
* @throws \Exception
*/
- public static function getImage($book, $imageSource)
+ public static function getImage($book, $imageSource): bool|array
{
$width = -1;
$height = -1;
@@ -231,7 +218,7 @@ public static function getImage($book, $imageSource)
$ratio = 1;
if ($image !== false && strlen((string) $image) > 0) {
- if (BinStringStatic::startsWith(trim((string) $image), ' 0)) {
+ if (str_starts_with(trim((string) $image), ' 0)) {
// SVG image.
$xml = simplexml_load_string((string) $image);
$attr = $xml->attributes();
@@ -247,11 +234,13 @@ public static function getImage($book, $imageSource)
$ratio = ImageHelper::getImageScale($width, $height, $book->maxImageWidth, $book->maxImageHeight);
if ($ratio < 1) {
+
$attr->width = $width * $ratio;
$attr->height = $height * $ratio;
}
$image = $xml->asXML();
} else {
+
$imageFile = imagecreatefromstring($image);
if ($imageFile !== false) {
$width = ImageSX($imageFile);
@@ -283,45 +272,37 @@ public static function getImage($book, $imageSource)
if ($mime == "image/png" || ($book->isGifImagesEnabled === false && $mime == "image/gif")) {
$image_o = imagecreatefromstring($image);
$image_p = imagecreatetruecolor($width * $ratio, $height * $ratio);
-
imagealphablending($image_p, false);
imagesavealpha($image_p, true);
imagealphablending($image_o, true);
-
imagecopyresampled($image_p, $image_o, 0, 0, 0, 0, ($width * $ratio), ($height * $ratio), $width, $height);
ob_start();
imagepng($image_p, null, 9);
$image = ob_get_contents();
ob_end_clean();
-
imagedestroy($image_o);
imagedestroy($image_p);
-
$ext = "png";
+ } elseif ($book->isGifImagesEnabled !== false && $mime == "image/gif") {
+ $tFileD = tempnam("BewareOfGeeksBearingGifs", "grD");
+ ResizeGif::ResizeByRatio($imageSource, $tFileD, $ratio);
+ $image = file_get_contents($tFileD);
+ unlink($tFileD);
} else {
- if ($book->isGifImagesEnabled !== false && $mime == "image/gif") {
-
- $tFileD = tempnam("BewareOfGeeksBearingGifs", "grD");
-
- ResizeGif::ResizeByRatio($imageSource, $tFileD, $ratio);
- $image = file_get_contents($tFileD);
- unlink($tFileD);
- } else {
- $image_o = imagecreatefromstring($image);
- $image_p = imagecreatetruecolor($width * $ratio, $height * $ratio);
+ $image_o = imagecreatefromstring($image);
+ $image_p = imagecreatetruecolor($width * $ratio, $height * $ratio);
- imagecopyresampled($image_p, $image_o, 0, 0, 0, 0, ($width * $ratio), ($height * $ratio), $width, $height);
- ob_start();
- imagejpeg($image_p, null, 80);
- $image = ob_get_contents();
- ob_end_clean();
+ imagecopyresampled($image_p, $image_o, 0, 0, 0, 0, ($width * $ratio), ($height * $ratio), $width, $height);
+ ob_start();
+ imagejpeg($image_p, null, 80);
+ $image = ob_get_contents();
+ ob_end_clean();
- imagedestroy($image_o);
- imagedestroy($image_p);
+ imagedestroy($image_o);
+ imagedestroy($image_p);
- $mime = "image/jpeg";
- $ext = "jpg";
- }
+ $mime = "image/jpeg";
+ $ext = "jpg";
}
}
}
diff --git a/src/PHPePub/Helpers/Rendition/RenditionHelper.php b/src/PHPePub/Helpers/Rendition/RenditionHelper.php
index 6b94d53..eea3164 100644
--- a/src/PHPePub/Helpers/Rendition/RenditionHelper.php
+++ b/src/PHPePub/Helpers/Rendition/RenditionHelper.php
@@ -40,7 +40,7 @@ class RenditionHelper
*
* @param EPub $book
*/
- public static function addPrefix($book)
+ public static function addPrefix($book): void
{
if (!$book->isEPubVersion2()) {
$book->addCustomPrefix(self::RENDITION_PREFIX_NAME, self::RENDITION_PREFIX_URI);
@@ -51,7 +51,7 @@ public static function addPrefix($book)
* @param EPub $book
* @param string $value "reflowable", "pre-paginated"
*/
- public static function setLayout($book, $value)
+ public static function setLayout($book, $value): void
{
if (!$book->isEPubVersion2() && $value === self::LAYOUT_REFLOWABLE || $value === self::LAYOUT_PRE_PAGINATED) {
$book->addCustomMetaProperty(self::RENDITION_LAYOUT, $value);
@@ -62,7 +62,7 @@ public static function setLayout($book, $value)
* @param EPub $book
* @param string $value "landscape", "portrait" or "auto"
*/
- public static function setOrientation($book, $value)
+ public static function setOrientation($book, $value): void
{
if (!$book->isEPubVersion2() && $value === self::ORIENTATION_LANDSCAPE || $value === self::ORIENTATION_PORTRAIT || $value === self::ORIENTATION_AUTO) {
$book->addCustomMetaProperty(self::RENDITION_ORIENTATION, $value);
@@ -73,7 +73,7 @@ public static function setOrientation($book, $value)
* @param EPub $book
* @param string $value "landscape", "portrait" or "auto"
*/
- public static function setSpread($book, $value)
+ public static function setSpread($book, $value): void
{
if (!$book->isEPubVersion2() && $value === self::SPREAD_NONE || $value === self::SPREAD_LANDSCAPE || $value === self::SPREAD_PORTRAIT || $value === self::SPREAD_BOTH || $value === self::SPREAD_AUTO) {
$book->addCustomMetaProperty(self::RENDITION_SPREAD, $value);
diff --git a/src/PHPePub/Helpers/StringHelper.php b/src/PHPePub/Helpers/StringHelper.php
index 00661ac..33f622a 100644
--- a/src/PHPePub/Helpers/StringHelper.php
+++ b/src/PHPePub/Helpers/StringHelper.php
@@ -10,7 +10,6 @@
namespace PHPePub\Helpers;
-use com\grandt\BinStringStatic;
use DOMDocument;
use DOMNode;
use PHPePub\Core\StaticData;
@@ -32,9 +31,8 @@ public static function fixEncoding($in_str)
{
if (mb_detect_encoding($in_str) == "UTF-8" && mb_check_encoding($in_str, "UTF-8")) {
return $in_str;
- } else {
- return mb_convert_encoding($in_str, 'UTF-8', 'ISO-8859-1');
}
+ return mb_convert_encoding($in_str, 'UTF-8', 'ISO-8859-1');
}
/**
@@ -44,7 +42,7 @@ public static function fixEncoding($in_str)
*
* @return string
*/
- public static function html2text($string)
+ public static function html2text($string): ?string
{
return preg_replace('~<[^>]*>~', '', $string);
}
@@ -74,14 +72,10 @@ public static function createUUID($bookVersion = 4, $url = null)
* http://www.php.net/manual/en/function.htmlentities.php#90111
*
* @param string $string string to encode.
- *
- * @return string
*/
- public static function encodeHtml($string)
+ public static function encodeHtml($string): string
{
- $string = strtr($string, StaticData::$htmlEntities);
-
- return $string;
+ return strtr($string, StaticData::$htmlEntities);
}
/**
@@ -91,9 +85,9 @@ public static function encodeHtml($string)
*
* @return string with the stripped entities.
*/
- public static function decodeHtmlEntities($string)
+ public static function decodeHtmlEntities($string): string
{
- $string = preg_replace('~\s* \s*~i', "\n", $string);
+ $string = preg_replace('~\s* \s*~i', "\n", (string) $string);
$string = preg_replace('~\s*(p|div)\s*>\s*~i', "\n\n", $string);
$string = preg_replace('~<[^>]*>~', '', $string);
@@ -103,9 +97,8 @@ public static function decodeHtmlEntities($string)
$string = str_replace('&', '&', $string);
$string = preg_replace('~&(#x*[a-fA-F0-9]+;)~', '&\1', $string);
$string = str_replace('<', '<', $string);
- $string = str_replace('>', '>', $string);
- return $string;
+ return str_replace('>', '>', $string);
}
/**
@@ -131,11 +124,11 @@ public static function createDomFragment($dom, $markup)
*
* @return string
*/
- public static function removeComments($doc)
+ public static function removeComments($doc): string|array|null
{
$doc = preg_replace('~--\s+>~', '-->', (string) $doc);
$doc = preg_replace('~<\s*!\s*--~', '");
@@ -147,19 +140,19 @@ public static function removeComments($doc)
$lastEPos = $cPos;
$ePos = $cPos;
do {
- $ePos = BinStringStatic::_strpos($doc, "-->", $ePos + 1);
+ $ePos = mb_strpos($doc, "-->", $ePos + 1);
if ($ePos !== false) {
$lastEPos = $ePos;
- $comment = BinStringStatic::_substr($doc, $cPos, ($lastEPos + 3) - $cPos);
- $startCount = substr_count((string) $comment, "");
+ $comment = mb_substr($doc, $cPos, ($lastEPos + 3) - $cPos);
+ $startCount = substr_count($comment, "");
} elseif ($lastEPos == $cPos) {
- $lastEPos = BinStringStatic::_strlen($doc) - 3;
+ $lastEPos = mb_strlen($doc) - 3;
}
- } while ($startCount != $endCount && $ePos !== false);
+ } while ($startCount !== $endCount && $ePos !== false);
$doc = substr_replace($doc, "", $cPos, ($lastEPos + 3) - $cPos);
- $cPos = BinStringStatic::_strpos($doc, "', (string) $doc);
$doc = preg_replace('~<\s*!\s*--~', '