HtmlBuilder: change all return error to Throw, update Element/StrinReplace

We do not return old style bool on error, we throw Exceptions: HtmlBuilderExcpetion

Element has more classes to set tag, id, etc with basic checks for valid data

String Replace to set strings is one array with key -> value entries

Errors thrown on index for element/replace blocks
This commit is contained in:
Clemens Schwaighofer
2023-06-28 14:16:44 +09:00
parent 3c37899a48
commit 1754ecf2ee
12 changed files with 316 additions and 118 deletions

View File

@@ -22,6 +22,13 @@ final class CoreLibsTemplateHtmlBuilderBlockTest extends TestCase
Block::buildHtml($el) Block::buildHtml($el)
); );
} }
// ael
// aelx|addSub
// resetSub
// acssel/rcssel/scssel
// buildHtml
// buildHtmlFromList|printHtmlFromArray
} }
// __END__ // __END__

View File

@@ -7,6 +7,7 @@ namespace tests;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use CoreLibs\Template\HtmlBuilder\Element; use CoreLibs\Template\HtmlBuilder\Element;
use CoreLibs\Template\HtmlBuilder\General\Error; use CoreLibs\Template\HtmlBuilder\General\Error;
use CoreLibs\Template\HtmlBuilder\General\HtmlBuilderExcpetion;
/** /**
* Test class for Template\HtmlBuilder\Element * Test class for Template\HtmlBuilder\Element
@@ -204,6 +205,8 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
'nested build failed' 'nested build failed'
); );
// this would create a loop, throws error // this would create a loop, throws error
$this->expectException(HtmlBuilderExcpetion::class);
$this->expectExceptionMessage("Cannot assign Element to itself, this would create an infinite loop");
$el_sub->addSub($el_sub); $el_sub->addSub($el_sub);
$this->assertEquals( $this->assertEquals(
'<div id="sub-1"></div>', '<div id="sub-1"></div>',
@@ -218,7 +221,7 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
[[ [[
'level' => 'Error', 'level' => 'Error',
'id' => '100', 'id' => '100',
'message' => 'Cannot assign Element, this would create a loop', 'message' => 'Cannot assign Element to itself, this would create an infinite loop',
'context' => ['tag' => 'div', 'id' => 'sub-1'] 'context' => ['tag' => 'div', 'id' => 'sub-1']
]], ]],
Error::getMessages(), Error::getMessages(),
@@ -287,11 +290,11 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
/** /**
* Undocumented function * Undocumented function
* *
* @testdox test change content * @testdox test change tag/id/content
* *
* @return void * @return void
*/ */
public function testChangeContent(): void public function testChangeElementData(): void
{ {
$el = new Element('div', 'id', 'Content'); $el = new Element('div', 'id', 'Content');
// content change // content change
@@ -306,6 +309,30 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
$el->getContent(), $el->getContent(),
'changed content' 'changed content'
); );
$this->assertEquals(
'div',
$el->getTag(),
'set tag'
);
$el->setTag('span');
$this->assertEquals(
'span',
$el->getTag(),
'changed tag'
);
$this->assertEquals(
'id',
$el->getId(),
'set id'
);
$el->setId('id-2');
$this->assertEquals(
'id-2',
$el->getId(),
'changed id'
);
} }
/** /**
@@ -349,7 +376,15 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
// build output // build output
// build from array list // build from array list
public function testBuildHtml(): void
/**
* Undocumented function
*
* @testdox build element tree from object
*
* @return void
*/
public function testBuildHtmlObject(): void
{ {
// build a simple block // build a simple block
// div -> div -> button // div -> div -> button
@@ -399,13 +434,36 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
/** /**
* Undocumented function * Undocumented function
* *
* @testdox check for invalid tag detection * @testdox build elements from array list
*
* @return void
*/
public function testbuildHtmlArray(): void
{
$this->assertEquals(
'<div id="id-1">A</div>'
. '<div id="id-2">B</div>'
. '<div id="id-3">C</div>',
Element::buildHtmlFromList([
new Element('div', 'id-1', 'A'),
new Element('div', 'id-2', 'B'),
new Element('div', 'id-3', 'C'),
])
);
}
/**
* Undocumented function
*
* @testdox check for invalid tag detection, possible invalid id, possible invalid css
* *
* @return void * @return void
*/ */
public function testInvalidElement(): void public function testInvalidElement(): void
{ {
Error::resetMessages(); Error::resetMessages();
$this->expectException(HtmlBuilderExcpetion::class);
$this->expectExceptionMessage("Could not create Element");
$el = new Element(''); $el = new Element('');
$this->assertTrue( $this->assertTrue(
Error::hasError(), Error::hasError(),
@@ -422,6 +480,27 @@ final class CoreLibsTemplateHtmlBuilderElementTest extends TestCase
'check error message failed' 'check error message failed'
); );
// if we set invalid tag
$el = new Element('div');
$this->expectException(HtmlBuilderExcpetion::class);
$this->expectExceptionMessage("Invalid or empty tag");
$el->setTag('123123');
$this->assertTrue(
Error::hasError(),
'failed to set error invalid tag detection'
);
$this->assertEquals(
[[
'level' => 'Error',
'id' => '201',
'message' => 'invalid or empty tag',
'context' => ['tag' => '']
]],
Error::getMessages(),
'check error message failed'
);
// invalid id (warning) // invalid id (warning)
Error::resetMessages(); Error::resetMessages();
$el = new Element('div', '-$a15'); $el = new Element('div', '-$a15');

View File

@@ -39,15 +39,27 @@ HTML,
StringReplace::replaceData( StringReplace::replaceData(
$html_block, $html_block,
[ [
'ID', 'CSS', '{CONTENT}' 'ID' => 'block-id',
], 'CSS' => join(',', ['blue', 'red']),
[ '{CONTENT}' => 'Some content here<br>with bla bla inside',
'block-id', join(',', ['blue', 'red']),
'Some content here<br>with bla bla inside'
] ]
) )
); );
} }
/**
* Undocumented function
*
* @testdox replaceData error
*
* @return void
*/
/* public function testReplaceDataErrors(): void
{
$this->expectException(HtmlBuilderExcpetion::class);
$this->expectExceptionMessage("Replace and content array count differ");
StringReplace::replaceData('<span>{FOO}</span>', ['{FOO}', '{BAR}'], ['foo']);
} */
} }
// __END__ // __END__

View File

@@ -20,6 +20,7 @@ ob_end_flush();
use CoreLibs\Template\HtmlBuilder\Element; use CoreLibs\Template\HtmlBuilder\Element;
use CoreLibs\Template\HtmlBuilder\General\Error; use CoreLibs\Template\HtmlBuilder\General\Error;
use CoreLibs\Template\HtmlBuilder\General\HtmlBuilderExcpetion;
use CoreLibs\Debug\Support; use CoreLibs\Debug\Support;
$log = new CoreLibs\Logging\Logging([ $log = new CoreLibs\Logging\Logging([
@@ -83,7 +84,11 @@ echo "<hr>";
// self loop // self loop
$el_s = new Element('div', 'id-s', 'Self'); $el_s = new Element('div', 'id-s', 'Self');
$el_s->addSub($el_s, new Element('span', '', 'Span')); try {
$el_s->addSub($el_s, new Element('span', '', 'Span'));
} catch (HtmlBuilderExcpetion $e) {
print "E: " . $e->getMessage() . " | " . $e->getTraceAsString() . "<br>";
}
// var_dump($el_s); // var_dump($el_s);
print "el_s, buildHtml(): <pre>" . htmlentities($el_s->buildHtml()) . "</pre>"; print "el_s, buildHtml(): <pre>" . htmlentities($el_s->buildHtml()) . "</pre>";
@@ -95,8 +100,12 @@ $el_s_2->addSub(
); );
$el_s_3 = new Element('div', 'id-3', 'ID 3'); $el_s_3 = new Element('div', 'id-3', 'ID 3');
$el_s_3->addSub($el_s_2); try {
$el_s_2->addSub($el_s_2); $el_s_3->addSub($el_s_2);
$el_s_2->addSub($el_s_2);
} catch (HtmlBuilderExcpetion $e) {
print "E: " . $e->getMessage() . " | " . $e->getTraceAsString() . "<br>";
}
// print "<pre>" . var_export($el_s_3, true) . "</pre>"; // print "<pre>" . var_export($el_s_3, true) . "</pre>";
@@ -104,12 +113,22 @@ print "el_s_3, buildHtml(): <pre>" . htmlentities($el_s_3->buildHtml()) . "</pre
echo "<hr>"; echo "<hr>";
Error::resetMessages(); Error::resetMessages();
$el_er = new Element(''); try {
$el_er = new Element('');
} catch (HtmlBuilderExcpetion $e) {
print "E: " . $e->getMessage() . " | " . $e->getTraceAsString() . "<br>";
print "E: " . $e->getPrevious()->getMessage() . " | " . $e->getPrevious()->getTraceAsString() . "<br>";
}
print "Errors: <pre>" . print_r(Error::getMessages(), true) . "</pre>"; print "Errors: <pre>" . print_r(Error::getMessages(), true) . "</pre>";
print "Warning: " . Support::printToString(Error::hasWarning()) . "<br>"; print "Warning: " . Support::printToString(Error::hasWarning()) . "<br>";
print "Error: " . Support::printToString(Error::hasError()) . "<br>"; print "Error: " . Support::printToString(Error::hasError()) . "<br>";
Error::resetMessages(); Error::resetMessages();
$el_er = new Element('123123'); try {
$el_er = new Element('123123');
} catch (HtmlBuilderExcpetion $e) {
print "E: " . $e->getMessage() . " | " . $e->getTraceAsString() . "<br>";
print "E: " . $e->getPrevious()->getMessage() . " | " . $e->getPrevious()->getTraceAsString() . "<br>";
}
print "Errors: <pre>" . print_r(Error::getMessages(), true) . "</pre>"; print "Errors: <pre>" . print_r(Error::getMessages(), true) . "</pre>";
print "Warning: " . Support::printToString(Error::hasWarning()) . "<br>"; print "Warning: " . Support::printToString(Error::hasWarning()) . "<br>";
print "Error: " . Support::printToString(Error::hasError()) . "<br>"; print "Error: " . Support::printToString(Error::hasError()) . "<br>";

View File

@@ -44,11 +44,9 @@ HTML;
print "<pre>" . htmlentities(StringReplace::replaceData( print "<pre>" . htmlentities(StringReplace::replaceData(
$html_block, $html_block,
[ [
'ID', 'CSS', '{CONTENT}' 'ID' => 'block-id',
], 'CSS' => join(',', ['blue', 'red']),
[ '{CONTENT}' => 'Some content here<br>with bla bla inside'
'block-id', join(',', ['blue', 'red']),
'Some content here<br>with bla bla inside'
] ]
)) . "</pre>"; )) . "</pre>";
@@ -63,14 +61,18 @@ print "Get: <pre>" . htmlentities(StringReplace::getElement('bar') ?: '') . '</p
print "Build element: <pre>" . htmlentities(StringReplace::buildElement( print "Build element: <pre>" . htmlentities(StringReplace::buildElement(
'bar', 'bar',
['ID}', '{CONTENT'], [
['new-id', 'Test cow 日本語'] 'ID}' => 'new-id',
'{CONTENT' => 'Test cow 日本語'
]
)) . '</pre>' ; )) . '</pre>' ;
print "Build element as replace: <pre>" . htmlentities(StringReplace::buildElement( print "Build element as replace: <pre>" . htmlentities(StringReplace::buildElement(
'bar', 'bar',
['ID}', '{CONTENT'], ['
['diff-id', 'Test cow 日本語. More text plus'], ID}' => 'diff-id',
'{CONTENT' => 'Test cow 日本語. More text plus'
],
'rpl-1' 'rpl-1'
)) . '</pre>' ; )) . '</pre>' ;

View File

@@ -83,7 +83,7 @@ $test_files = [
'class_test.html.php' => 'Class Test: HTML/ELEMENTS', 'class_test.html.php' => 'Class Test: HTML/ELEMENTS',
'class_test.html_build.element.php' => 'Class Test: HTML BUILDER: ELEMENT', 'class_test.html_build.element.php' => 'Class Test: HTML BUILDER: ELEMENT',
'class_test.html_build.block.php' => 'Class Test: HTML BUILDER: BLOCK', 'class_test.html_build.block.php' => 'Class Test: HTML BUILDER: BLOCK',
'class_test.html_build.replace.php' => 'Class Test: HTML BUILDER: REPLACE', 'class_test.html_build.replace.php' => 'Class Test: HTML BUILDER: STRING REPLACE',
'class_test.email.php' => 'Class Test: EMAIL', 'class_test.email.php' => 'Class Test: EMAIL',
'class_test.create_email.php' => 'Class Test: CREATE EMAIL', 'class_test.create_email.php' => 'Class Test: CREATE EMAIL',
'class_test.uids.php' => 'Class Test: UIDS', 'class_test.uids.php' => 'Class Test: UIDS',

View File

@@ -6,11 +6,15 @@
* DESCRIPTION: * DESCRIPTION:
* html builder: array * html builder: array
* static build for array lists (not objects) * static build for array lists (not objects)
*
* Recommended to use the Object one or for speed the String Replace
*/ */
namespace CoreLibs\Template\HtmlBuilder; namespace CoreLibs\Template\HtmlBuilder;
use CoreLibs\Template\HtmlBuilder\General\Settings; use CoreLibs\Template\HtmlBuilder\General\Settings;
use CoreLibs\Template\HtmlBuilder\General\Error;
use CoreLibs\Template\HtmlBuilder\General\HtmlBuilderExcpetion;
class Block class Block
{ {
@@ -22,6 +26,7 @@ class Block
* @param string $content * @param string $content
* @param array<string> $css, * @param array<string> $css,
* @param array<string,string> $options * @param array<string,string> $options
* @throws HtmlBuilderExcpetion
*/ */
public static function cel( public static function cel(
string $tag, string $tag,
@@ -30,6 +35,14 @@ class Block
array $css = [], array $css = [],
array $options = [] array $options = []
): array { ): array {
if (!preg_match("/^[A-Za-z]+$/", $tag)) {
Error::setError(
'201',
'invalid or empty tag',
['tag' => $tag]
);
throw new HtmlBuilderExcpetion('Invalid or empty tag');
}
return [ return [
'tag' => $tag, 'tag' => $tag,
'id' => $id, 'id' => $id,

View File

@@ -14,6 +14,7 @@ namespace CoreLibs\Template\HtmlBuilder;
use CoreLibs\Template\HtmlBuilder\General\Settings; use CoreLibs\Template\HtmlBuilder\General\Settings;
use CoreLibs\Template\HtmlBuilder\General\Error; use CoreLibs\Template\HtmlBuilder\General\Error;
use CoreLibs\Template\HtmlBuilder\General\HtmlBuilderExcpetion;
class Element class Element
{ {
@@ -46,6 +47,7 @@ class Element
* eg: onClick => 'something();' * eg: onClick => 'something();'
* id, css are skipped * id, css are skipped
* name only set on input/button * name only set on input/button
* @throws HtmlBuilderExcpetion
*/ */
public function __construct( public function __construct(
string $tag, string $tag,
@@ -54,6 +56,28 @@ class Element
array $css = [], array $css = [],
array $options = [] array $options = []
) { ) {
// exit if not valid tag
try {
$this->setTag($tag);
} catch (HtmlBuilderExcpetion $e) {
throw new HtmlBuilderExcpetion('Could not create Element', 0, $e);
}
$this->setId($id);
$this->setName($options['name'] ?? '');
$this->setContent($content);
$this->addCss(...$css);
$this->setOptions($options);
}
/**
* set tag
*
* @param string $tag
* @return void
* @throws HtmlBuilderExcpetion
*/
public function setTag(string $tag): void
{
// tag must be letters only // tag must be letters only
if (!preg_match("/^[A-Za-z]+$/", $tag)) { if (!preg_match("/^[A-Za-z]+$/", $tag)) {
Error::setError( Error::setError(
@@ -61,9 +85,29 @@ class Element
'invalid or empty tag', 'invalid or empty tag',
['tag' => $tag] ['tag' => $tag]
); );
return; throw new HtmlBuilderExcpetion('Invalid or empty tag');
} }
$this->tag = $tag; $this->tag = $tag;
}
/**
* get the tag name
*
* @return string HTML element tag
*/
public function getTag(): string
{
return $this->tag;
}
/**
* set the element id
*
* @param string $id
* @return void
*/
public function setId(string $id): void
{
// invalid id and name check too // invalid id and name check too
// be strict: [a-zA-Z0-9], -, _ // be strict: [a-zA-Z0-9], -, _
// cannot start with digit, two hyphens or a hyphen with a digit: // cannot start with digit, two hyphens or a hyphen with a digit:
@@ -77,63 +121,11 @@ class Element
Error::setWarning( Error::setWarning(
'202', '202',
'possible invalid id', 'possible invalid id',
['id' => $id, 'tag' => $this->tag] ['id' => $id, 'tag' => $this->getTag()]
); );
// TODO: shoud throw error
} }
$this->id = $id; $this->id = $id;
if (
!empty($options['name']) &&
!preg_match("/^[A-Za-z][\w-]*$/", $options['name'])
) {
Error::setWarning(
'203',
'possible invalid name',
['name' => $options['name'], 'id' => $this->id, 'tag' => $this->tag]
);
}
// same as id
$this->name = $options['name'] ?? '';
// anything allowed
$this->content = $content;
// should do check for empty/invalid css
foreach ($css as $_css) {
if (empty($_css)) {
Error::setError(
'204',
'cannot have empty css string',
);
continue;
}
// -?[_A-Za-z][_A-Za-z0-9-]*
if (!preg_match("/^-?[_A-Za-z][_A-Za-z0-9-]*$/", $_css)) {
Error::setWarning(
'205',
'possible invalid css string',
['css' => $_css, 'id' => $this->id, 'tag' => $this->tag]
);
}
$this->css[] = $_css;
}
// some basic options check
foreach ($options as $key => $value) {
if (empty($key)) {
Error::setError(
'110',
'Cannot set option with empty key',
['id' => $this->id, 'tag' => $this->tag]
);
continue;
}
if ($value === null) {
Error::setError(
'210',
'Cannot set option with null value',
['id' => $this->id, 'tag' => $this->tag]
);
continue;
}
$this->options[$key] = $value;
}
} }
/** /**
@@ -147,13 +139,26 @@ class Element
} }
/** /**
* get the tag name * Set name for elements
* only for elements that need it (input/button/form)
* *
* @return string HTML element tag * @param string $name
* @return void
*/ */
public function getTag(): string public function setName(string $name): void
{ {
return $this->tag; if (
!empty($name) &&
!preg_match("/^[A-Za-z][\w-]*$/", $name)
) {
Error::setWarning(
'203',
'possible invalid name',
['name' => $name, 'id' => $this->getId(), 'tag' => $this->getTag()]
);
// TODO: shoud throw error
}
$this->name = $name;
} }
/** /**
@@ -202,11 +207,21 @@ class Element
'Cannot set option with empty key', 'Cannot set option with empty key',
['id' => $this->getId(), 'tag' => $this->getTag()] ['id' => $this->getId(), 'tag' => $this->getTag()]
); );
// TODO: shoud throw error
continue; continue;
} }
// if data is null // if data is null
if ($value === null) { if ($value === null) {
unset($this->options[$key]); if (isset($this->options[$key])) {
unset($this->options[$key]);
} else {
Error::setError(
'210',
'Cannot set option with null value',
['id' => $this->getId(), 'tag' => $this->getTag()]
);
}
// TODO: shoud throw error
continue; continue;
} }
$this->options[$key] = $value; $this->options[$key] = $value;
@@ -243,6 +258,7 @@ class Element
* *
* @param Element $sub One or many elements to add * @param Element $sub One or many elements to add
* @return void * @return void
* @throws HtmlBuilderExcpetion
*/ */
public function addSub(Element ...$sub): void public function addSub(Element ...$sub): void
{ {
@@ -252,10 +268,10 @@ class Element
if ($_sub == $this) { if ($_sub == $this) {
Error::setError( Error::setError(
'100', '100',
'Cannot assign Element, this would create a loop', 'Cannot assign Element to itself, this would create an infinite loop',
['id' => $this->getId(), 'tag' => $this->getTag()] ['id' => $this->getId(), 'tag' => $this->getTag()]
); );
continue; throw new HtmlBuilderExcpetion('Cannot assign Element to itself, this would create an infinite loop');
} }
array_push($this->sub, $_sub); array_push($this->sub, $_sub);
} }
@@ -319,7 +335,29 @@ class Element
*/ */
public function addCss(string ...$css): Element public function addCss(string ...$css): Element
{ {
$this->css = array_unique(array_merge($this->css, $css)); // should do check for empty/invalid css
$_set_css = [];
foreach ($css as $_css) {
if (empty($_css)) {
Error::setError(
'204',
'cannot have empty css string',
);
// TODO: shoud throw error
continue;
}
// -?[_A-Za-z][_A-Za-z0-9-]*
if (!preg_match("/^-?[_A-Za-z][_A-Za-z0-9-]*$/", $_css)) {
Error::setWarning(
'205',
'possible invalid css string',
['css' => $_css, 'id' => $this->id, 'tag' => $this->tag]
);
// TODO: shoud throw error
}
$_set_css[] = $_css;
}
$this->css = array_unique(array_merge($this->css, $_set_css));
return $this; return $this;
} }

View File

@@ -0,0 +1,21 @@
<?php
/**
* AUTOR: Clemens Schwaighofer
* CREATED: 2023/6/28
* DESCRIPTION:
* Exception class for the HtmlBuilder blocks
*/
declare(strict_types=1);
namespace CoreLibs\Template\HtmlBuilder\General;
/**
* Exception class for HtmlBuilder
*/
class HtmlBuilderExcpetion extends \Exception
{
}
// __END__

View File

@@ -12,12 +12,13 @@ declare(strict_types=1);
namespace CoreLibs\Template\HtmlBuilder; namespace CoreLibs\Template\HtmlBuilder;
use CoreLibs\Template\HtmlBuilder\General\Error; use CoreLibs\Template\HtmlBuilder\General\Error;
use CoreLibs\Template\HtmlBuilder\General\HtmlBuilderExcpetion;
class StringReplace class StringReplace
{ {
/** @var array<string,string> */ /** @var array<string,string> */
private static array $elements = []; private static array $elements = [];
/** @var array<string,array<string,string>> */ /** @var array<string,string> */
private static array $replace = []; private static array $replace = [];
/** /**
@@ -28,16 +29,14 @@ class StringReplace
* if same index is tried twice it will set an error and skip * if same index is tried twice it will set an error and skip
* *
* @param array<string,string> ...$element Elements to load * @param array<string,string> ...$element Elements to load
* @return bool False if double index or other error * @return void
* True on ok * @throws HtmlBuilderExcpetion
*/ */
public static function loadElements(array ...$element): bool public static function loadElements(array ...$element): void
{ {
$error = false;
foreach ($element as $el) { foreach ($element as $el) {
$index = $el[0] ?? ''; $index = $el[0] ?? '';
if (empty($index)) { if (empty($index)) {
$error = true;
Error::setError( Error::setError(
'310', '310',
'Index cannot be an empty string', 'Index cannot be an empty string',
@@ -45,9 +44,9 @@ class StringReplace
'element' => $index 'element' => $index
] ]
); );
throw new HtmlBuilderExcpetion('Index cannot be an empty string');
} }
if (isset(self::$elements[$index])) { if (isset(self::$elements[$index])) {
$error = true;
Error::setError( Error::setError(
'311', '311',
'Index already exists', 'Index already exists',
@@ -55,11 +54,11 @@ class StringReplace
'element' => $index 'element' => $index
] ]
); );
throw new HtmlBuilderExcpetion('Index already exists: ' . $index);
} }
// content check? // content check?
self::$elements[$index] = $el[1]; self::$elements[$index] = $el[1];
} }
return $error;
} }
/** /**
@@ -80,7 +79,7 @@ class StringReplace
'element' => $index 'element' => $index
] ]
); );
return; throw new HtmlBuilderExcpetion('Index does not exists: ' . $index);
} }
// allow empty reset // allow empty reset
self::$elements[$index] = $element; self::$elements[$index] = $element;
@@ -91,13 +90,14 @@ class StringReplace
* if not found will return false * if not found will return false
* *
* @param string $index * @param string $index
* @return string|false * @return string
* @throws HtmlBuilderExcpetion
*/ */
public static function getElement(string $index): string|bool public static function getElement(string $index): string
{ {
if (!isset(self::$elements[$index])) { if (!isset(self::$elements[$index])) {
Error::setError('321', 'Index not found in elements', ['element' => $index]); Error::setError('321', 'Index not found in elements', ['element' => $index]);
return false; throw new HtmlBuilderExcpetion('Index not found in elements array: ' . $index);
} }
return self::$elements[$index]; return self::$elements[$index];
} }
@@ -120,12 +120,13 @@ class StringReplace
* *
* @param string $index * @param string $index
* @return string * @return string
* @throws HtmlBuilderExcpetion
*/ */
public static function getReplaceBlock(string $index): string public static function getReplaceBlock(string $index): string
{ {
if (!isset(self::$replace[$index])) { if (!isset(self::$replace[$index])) {
Error::setError('331', 'Index not found in replace block', ['replace' => $index]); Error::setError('331', 'Index not found in replace block', ['replace' => $index]);
return ''; throw new HtmlBuilderExcpetion('Index not found in replace block array: ' . $index);
} }
return self::$replace[$index]; return self::$replace[$index];
} }
@@ -136,14 +137,12 @@ class StringReplace
* if index not found in relement list will return false * if index not found in relement list will return false
* *
* @param string $index index of set element * @param string $index index of set element
* @param array<string> $replace array of text to search for * @param array<string,string> $replace array of text to search (key) and replace (value) for
* @param array<string> $content content data to be set for replace
* @return string|false * @return string|false
*/ */
public static function buildElement( public static function buildElement(
string $index, string $index,
array $replace, array $replace,
array $content,
string $replace_index = '' string $replace_index = ''
): string|bool { ): string|bool {
if (self::getElement($index) === false) { if (self::getElement($index) === false) {
@@ -152,11 +151,19 @@ class StringReplace
if ($replace_index) { if ($replace_index) {
self::setReplaceBlock( self::setReplaceBlock(
$replace_index, $replace_index,
self::replaceData(self::$elements[$index], $replace, $content) self::replaceData(
self::$elements[$index],
array_keys($replace),
array_values($replace)
)
); );
return self::getReplaceBlock($replace_index); return self::getReplaceBlock($replace_index);
} else { } else {
return self::replaceData(self::$elements[$index], $replace, $content); return self::replaceData(
self::$elements[$index],
array_keys($replace),
array_values($replace)
);
} }
} }
@@ -166,17 +173,14 @@ class StringReplace
* replace array they will be added. * replace array they will be added.
* if the replace and content count is not the same then an error will be thrown * if the replace and content count is not the same then an error will be thrown
* *
* @param string $data * @param string $data
* @param array<string> $replace * @param array<string,string> $replace
* @param array<string> $content * @return string
* @return string|bool * @throws HtmlBuilderExcpetion
*/ */
public static function replaceData(string $data, array $replace, array $content): string|bool public static function replaceData(string $data, array $replace): string
{ {
if (count($replace) != count($content)) { $replace = array_keys($replace);
Error::setError('340', 'Replace and content count differ');
return false;
}
// all replace data must have {} around // all replace data must have {} around
array_walk($replace, function (&$entry) { array_walk($replace, function (&$entry) {
if (!str_starts_with($entry, '{')) { if (!str_starts_with($entry, '{')) {
@@ -185,9 +189,10 @@ class StringReplace
if (!str_ends_with($entry, '}')) { if (!str_ends_with($entry, '}')) {
$entry .= '}'; $entry .= '}';
} }
// do some validation?
}); });
// replace content // replace content
return str_replace($replace, $content, $data); return str_replace($replace, array_values($replace), $data);
} }
} }

View File

@@ -80,8 +80,9 @@ return array(
'CoreLibs\\Template\\HtmlBuilder\\Block' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/Block.php', 'CoreLibs\\Template\\HtmlBuilder\\Block' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/Block.php',
'CoreLibs\\Template\\HtmlBuilder\\Element' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/Element.php', 'CoreLibs\\Template\\HtmlBuilder\\Element' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/Element.php',
'CoreLibs\\Template\\HtmlBuilder\\General\\Error' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/General/Error.php', 'CoreLibs\\Template\\HtmlBuilder\\General\\Error' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/General/Error.php',
'CoreLibs\\Template\\HtmlBuilder\\General\\HtmlBuilderExcpetion' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/General/HtmlBuilderExcpetion.php',
'CoreLibs\\Template\\HtmlBuilder\\General\\Settings' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/General/Settings.php', 'CoreLibs\\Template\\HtmlBuilder\\General\\Settings' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/General/Settings.php',
'CoreLibs\\Template\\HtmlBuilder\\Replace' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/Replace.php', 'CoreLibs\\Template\\HtmlBuilder\\StringReplace' => $baseDir . '/lib/CoreLibs/Template/HtmlBuilder/StringReplace.php',
'CoreLibs\\Template\\SmartyExtend' => $baseDir . '/lib/CoreLibs/Template/SmartyExtend.php', 'CoreLibs\\Template\\SmartyExtend' => $baseDir . '/lib/CoreLibs/Template/SmartyExtend.php',
'FileUpload\\Core\\qqUploadedFile' => $baseDir . '/lib/FileUpload/Core/qqUploadedFile.php', 'FileUpload\\Core\\qqUploadedFile' => $baseDir . '/lib/FileUpload/Core/qqUploadedFile.php',
'FileUpload\\Core\\qqUploadedFileForm' => $baseDir . '/lib/FileUpload/Core/qqUploadedFileForm.php', 'FileUpload\\Core\\qqUploadedFileForm' => $baseDir . '/lib/FileUpload/Core/qqUploadedFileForm.php',

View File

@@ -131,8 +131,9 @@ class ComposerStaticInit10fe8fe2ec4017b8644d2b64bcf398b9
'CoreLibs\\Template\\HtmlBuilder\\Block' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/Block.php', 'CoreLibs\\Template\\HtmlBuilder\\Block' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/Block.php',
'CoreLibs\\Template\\HtmlBuilder\\Element' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/Element.php', 'CoreLibs\\Template\\HtmlBuilder\\Element' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/Element.php',
'CoreLibs\\Template\\HtmlBuilder\\General\\Error' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/General/Error.php', 'CoreLibs\\Template\\HtmlBuilder\\General\\Error' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/General/Error.php',
'CoreLibs\\Template\\HtmlBuilder\\General\\HtmlBuilderExcpetion' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/General/HtmlBuilderExcpetion.php',
'CoreLibs\\Template\\HtmlBuilder\\General\\Settings' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/General/Settings.php', 'CoreLibs\\Template\\HtmlBuilder\\General\\Settings' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/General/Settings.php',
'CoreLibs\\Template\\HtmlBuilder\\Replace' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/Replace.php', 'CoreLibs\\Template\\HtmlBuilder\\StringReplace' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/HtmlBuilder/StringReplace.php',
'CoreLibs\\Template\\SmartyExtend' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/SmartyExtend.php', 'CoreLibs\\Template\\SmartyExtend' => __DIR__ . '/../..' . '/lib/CoreLibs/Template/SmartyExtend.php',
'FileUpload\\Core\\qqUploadedFile' => __DIR__ . '/../..' . '/lib/FileUpload/Core/qqUploadedFile.php', 'FileUpload\\Core\\qqUploadedFile' => __DIR__ . '/../..' . '/lib/FileUpload/Core/qqUploadedFile.php',
'FileUpload\\Core\\qqUploadedFileForm' => __DIR__ . '/../..' . '/lib/FileUpload/Core/qqUploadedFileForm.php', 'FileUpload\\Core\\qqUploadedFileForm' => __DIR__ . '/../..' . '/lib/FileUpload/Core/qqUploadedFileForm.php',