Total Complexity | 51 |
Total Lines | 459 |
Duplicated Lines | 0 % |
Changes | 5 | ||
Bugs | 0 | Features | 0 |
Complex classes like HTML often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use HTML, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
281 | class HTML |
||
282 | { |
||
283 | private bool $validate; |
||
284 | |||
285 | private array $conditions; |
||
286 | |||
287 | private array $buffer; |
||
288 | |||
289 | private array $stack; |
||
290 | |||
291 | |||
292 | /** |
||
293 | * Class constructor. |
||
294 | * |
||
295 | * @param bool $validate Whether to validate the HTML upon return/echo or not. |
||
296 | */ |
||
297 | public function __construct(bool $validate = true) |
||
303 | } |
||
304 | |||
305 | |||
306 | /** |
||
307 | * Creates a complete HTML element (opening and closing tags) constructed from the specified parameters and pass it to the buffer. |
||
308 | * |
||
309 | * @param string $name A name of an HTML tag. |
||
310 | * @param string|null $content [optional] The text or html content of the element, passing null will make it a self-closing tag. |
||
311 | * @param string[] $attributes [optional] An associative array of attributes. To indicate a boolean-attribute (no-value-attribute), simply provide a key with value `null` or provide only a value without a key with the name of the attribute. As a shortcut, setting the value as `false` will exclude the attribute. |
||
312 | * |
||
313 | * @return $this |
||
314 | * |
||
315 | * @throws \Exception If the supplied name is invalid. |
||
316 | */ |
||
317 | public function element(string $name, ?string $content = '', array $attributes = []): HTML |
||
318 | { |
||
319 | $this->agreeOrFail( |
||
320 | !strlen($name), |
||
321 | 'Invalid name supplied to %s::%s() in %s on line %s. Tag name cannot be an empty string' |
||
322 | ); |
||
323 | |||
324 | if ($this->isConditionTruthy()) { |
||
325 | $tag = $content !== null |
||
326 | ? '<{name}{attributes}>{content}</{name}>' |
||
327 | : '<{name}{attributes} />'; |
||
328 | $name = strtolower(trim($name)); |
||
329 | $attributes = $this->stringifyAttributes($attributes); |
||
330 | |||
331 | $this->buffer[] = $this->translateElement($tag, compact('name', 'content', 'attributes')); |
||
332 | } |
||
333 | |||
334 | return $this; |
||
335 | } |
||
336 | |||
337 | /** |
||
338 | * Creates an HTML entity from the specified name and pass it to the buffer. |
||
339 | * |
||
340 | * @param string $name The name of the HTML entity without `&` nor `;`. |
||
341 | * |
||
342 | * @return $this |
||
343 | * |
||
344 | * @throws \Exception If the supplied name is invalid. |
||
345 | */ |
||
346 | public function entity(string $name): HTML |
||
347 | { |
||
348 | $this->agreeOrFail( |
||
349 | !strlen($name), |
||
350 | 'Invalid name supplied to %s::%s() in %s on line %s. Entity name cannot be an empty string' |
||
351 | ); |
||
352 | |||
353 | if ($this->isConditionTruthy()) { |
||
354 | $entity = sprintf('&%s;', trim($name, '& ;')); |
||
355 | $this->buffer[] = $entity; |
||
356 | } |
||
357 | |||
358 | |||
359 | return $this; |
||
360 | } |
||
361 | |||
362 | /** |
||
363 | * Creates an HTML comment from the specified text and pass it to the buffer. |
||
364 | * |
||
365 | * @param string $comment The text content of the HTML comment without `<!--` and `-->`. |
||
366 | * |
||
367 | * @return $this |
||
368 | * |
||
369 | * @throws \Exception If the supplied text is invalid. |
||
370 | */ |
||
371 | public function comment(string $text): HTML |
||
372 | { |
||
373 | $this->agreeOrFail( |
||
374 | !strlen($text), |
||
375 | 'Invalid text supplied to %s::%s() in %s on line %s. Comment text cannot be an empty string' |
||
376 | ); |
||
377 | |||
378 | if ($this->isConditionTruthy()) { |
||
379 | $comment = sprintf('<!-- %s -->', trim($text)); |
||
380 | $this->buffer[] = $comment; |
||
381 | } |
||
382 | |||
383 | return $this; |
||
384 | } |
||
385 | |||
386 | /** |
||
387 | * Creates an arbitrary text-node from the specified text and pass it to the buffer (useful to add some special tags, "\<!DOCTYPE html>" for example). |
||
388 | * |
||
389 | * @param string $text The text to pass to the buffer. |
||
390 | * |
||
391 | * @return $this |
||
392 | * |
||
393 | * @throws \Exception If the supplied text is invalid. |
||
394 | */ |
||
395 | public function node(string $text): HTML |
||
408 | } |
||
409 | |||
410 | /** |
||
411 | * Creates an HTML opening tag from the specified parameters and pass it to the buffer. Works in conjunction with `self::close()`. |
||
412 | * |
||
413 | * @param string $name A name of an HTML tag. |
||
414 | * @param string[] $attributes [optional] An associative array of attributes. To indicate a boolean-attribute (no-value-attribute), simply provide a key with value `null`. Setting the value as `false` will exclude the attribute. |
||
415 | * |
||
416 | * @return $this |
||
417 | * |
||
418 | * @throws \Exception If the supplied name is invalid. |
||
419 | */ |
||
420 | public function open(string $name, array $attributes = []): HTML |
||
438 | } |
||
439 | |||
440 | /** |
||
441 | * Creates an HTML closing tag matching the last tag opened by `self::open()`. |
||
442 | * |
||
443 | * @return $this |
||
444 | * |
||
445 | * @throws \Exception If no tag has been opened. |
||
446 | */ |
||
447 | public function close(): HTML |
||
463 | } |
||
464 | |||
465 | /** |
||
466 | * Takes a callback and executes it after binding $this (HTML) to it, useful for example to execute any PHP code while creating the markup. |
||
467 | * |
||
468 | * @param callable $callback The callback to call and bind $this to, this callback will also be passed the instance it was called on as the first parameter. |
||
469 | * |
||
470 | * @return $this |
||
471 | */ |
||
472 | public function execute(callable $callback): HTML |
||
473 | { |
||
474 | if ($this->isConditionTruthy()) { |
||
475 | $boundClosure = \Closure::fromCallable($callback)->bindTo($this); |
||
476 | |||
477 | if ($boundClosure !== false) { |
||
478 | $boundClosure($this); |
||
479 | } else { |
||
480 | $callback($this); |
||
481 | } |
||
482 | } |
||
483 | |||
484 | return $this; |
||
485 | } |
||
486 | |||
487 | /** |
||
488 | * Takes a condition (some boolean value) to determine whether or not to create the very next element and pass it to the buffer. |
||
489 | * |
||
490 | * @param mixed $condition Any value that can be casted into a boolean. |
||
491 | * |
||
492 | * @return $this |
||
493 | */ |
||
494 | public function condition($condition): HTML |
||
499 | } |
||
500 | |||
501 | /** |
||
502 | * Determines whether or not the last set condition is truthy or falsy. |
||
503 | * |
||
504 | * @param int $parent [optional] A flag to indicate condition depth `[+1 = parentOpened, 0 = normal, -1 = parentClosed]`. |
||
505 | * |
||
506 | * @return bool The result of the current condition. |
||
507 | */ |
||
508 | private function isConditionTruthy(int $parent = 0): bool |
||
509 | { |
||
510 | static $parentConditions = []; |
||
511 | |||
512 | $result = true; |
||
513 | |||
514 | if (!empty($this->conditions) || !empty($parentConditions)) { |
||
515 | $actualCondition = $this->conditions[count($this->conditions) - 1] ?? $result; |
||
516 | $parentCondition = $parentConditions[count($parentConditions) - 1] ?? $result; |
||
517 | |||
518 | $condition = $parentCondition & $actualCondition; |
||
519 | if (!$condition) { |
||
520 | $result = false; |
||
521 | } |
||
522 | |||
523 | switch ($parent) { |
||
524 | case +1: |
||
525 | array_push($parentConditions, $condition); |
||
526 | break; |
||
527 | case -1: |
||
528 | array_pop($parentConditions); |
||
529 | break; |
||
530 | case 0: |
||
531 | // NORMAL! |
||
532 | break; |
||
533 | } |
||
534 | |||
535 | array_pop($this->conditions); |
||
536 | } |
||
537 | |||
538 | return $result; |
||
539 | } |
||
540 | |||
541 | /** |
||
542 | * Checks if the passed condition and throws exception if it's not truthy. |
||
543 | * The message that is passed to this function should contain four `%s` placeholders for the |
||
544 | * `class`, `function`, `file` and `line` of the previous caller (offset 2 of the backtrace) |
||
545 | * |
||
546 | * @param bool $condition |
||
547 | * @param string $message |
||
548 | * |
||
549 | * @return void |
||
550 | * |
||
551 | * @throws \Exception |
||
552 | */ |
||
553 | private function agreeOrFail(bool $condition, string $message): void |
||
554 | { |
||
555 | if ($condition) { |
||
556 | $variables = ['class', 'function', 'file', 'line']; |
||
557 | $backtrace = Misc::backtrace($variables, 2); |
||
558 | $backtrace = is_array($backtrace) ? $backtrace : array_map('strtoupper', $variables); |
||
559 | |||
560 | throw new \Exception(vsprintf($message, $backtrace)); |
||
561 | } |
||
562 | } |
||
563 | |||
564 | /** |
||
565 | * Returns an HTML attributes string from an associative array of attributes. |
||
566 | * |
||
567 | * @param array $attributes |
||
568 | * |
||
569 | * @return string |
||
570 | */ |
||
571 | private function stringifyAttributes(array $attributes): string |
||
572 | { |
||
573 | $attrStr = ''; |
||
574 | |||
575 | foreach ($attributes as $name => $value) { |
||
576 | if ($value === false) { |
||
577 | continue; |
||
578 | } |
||
579 | |||
580 | $attrStr .= is_string($name) && !is_null($value) |
||
581 | ? sprintf(' %s="%s"', $name, $value) |
||
582 | : sprintf(' %s', $value ?: $name); |
||
583 | } |
||
584 | |||
585 | return $attrStr; |
||
586 | } |
||
587 | |||
588 | /** |
||
589 | * Replaces variables in the passed string with values with matching key from the passed array. |
||
590 | * |
||
591 | * @param string $text A string like `{var} world!`. |
||
592 | * @param array $variables An array like `['var' => 'Hello']`. |
||
593 | * |
||
594 | * @return string A string like `Hello world!` |
||
595 | */ |
||
596 | private function translateElement(string $text, array $variables = []): string |
||
597 | { |
||
598 | $replacements = []; |
||
599 | |||
600 | foreach ($variables as $key => $value) { |
||
601 | $replacements[sprintf('{%s}', $key)] = $value; |
||
602 | } |
||
603 | |||
604 | return strtr($text, $replacements); |
||
605 | } |
||
606 | |||
607 | /** |
||
608 | * Asserts that the passed HTML is valid. |
||
609 | * |
||
610 | * @return void |
||
611 | * |
||
612 | * @throws \Exception If the passed html is invalid. |
||
613 | */ |
||
614 | private function validate(string $html): void |
||
615 | { |
||
616 | $html = !empty($html) ? $html : '<br/>'; |
||
617 | |||
618 | $xml = libxml_use_internal_errors(true); |
||
619 | |||
620 | $dom = new \DOMDocument(); |
||
621 | $dom->validateOnParse = true; |
||
622 | $dom->loadHTML($html); |
||
623 | // $dom->saveHTML(); |
||
624 | |||
625 | $ignoredCodes = [801]; |
||
626 | $errors = libxml_get_errors(); |
||
627 | libxml_clear_errors(); |
||
628 | |||
629 | if (!empty($errors) && !in_array($errors[0]->code, $ignoredCodes)) { |
||
630 | $file = Misc::backtrace('file', 3); |
||
631 | $file = is_string($file) ? $file : 'FILE'; |
||
632 | |||
633 | throw new \Exception( |
||
634 | vsprintf( |
||
635 | 'HTML is invalid in %s! Found %s problem(s). Last LibXMLError: [level:%s/code:%s] %s', |
||
636 | [$file, count($errors), $errors[0]->level, $errors[0]->code, $errors[0]->message] |
||
637 | ) |
||
638 | ); |
||
639 | } |
||
640 | |||
641 | libxml_use_internal_errors($xml); |
||
642 | } |
||
643 | |||
644 | /** |
||
645 | * Returns the created HTML elements found in the buffer and empties it. |
||
646 | * |
||
647 | * @return string |
||
648 | * |
||
649 | * @throws \Exception If not all open elements are closed or the generated html is invalid. |
||
650 | */ |
||
651 | public function return(): string |
||
652 | { |
||
653 | if (count($this->stack)) { |
||
654 | $file = Misc::backtrace('file', 2); |
||
655 | $file = is_string($file) ? $file : 'FILE'; |
||
656 | |||
657 | throw new \Exception( |
||
658 | sprintf( |
||
659 | "Cannot return HTML in %s. The following tag(s): '%s' has/have not been closed properly", |
||
660 | $file, |
||
661 | implode(', ', $this->stack) |
||
662 | ) |
||
663 | ); |
||
664 | } |
||
665 | |||
666 | $html = implode('', $this->buffer); |
||
667 | |||
668 | $this->buffer = []; |
||
669 | |||
670 | if ($this->validate) { |
||
671 | $this->validate($html); |
||
672 | } |
||
673 | |||
674 | return $html; |
||
675 | } |
||
676 | |||
677 | /** |
||
678 | * Echos the created HTML elements found in the buffer and empties it. |
||
679 | * |
||
680 | * @return void |
||
681 | * |
||
682 | * @throws \Exception If not all open elements are closed or the generated html is invalid. |
||
683 | */ |
||
684 | public function echo(): void |
||
685 | { |
||
686 | echo $this->return(); |
||
687 | } |
||
688 | |||
689 | /** |
||
690 | * Minifies HTML buffers by removing all unnecessary whitespaces and comments. |
||
691 | * |
||
692 | * @param string $html |
||
693 | * |
||
694 | * @return string |
||
695 | */ |
||
696 | public static function minify(string $html): string |
||
697 | { |
||
698 | $patterns = [ |
||
699 | '/(\s)+/s' => '$1', // shorten multiple whitespace sequences |
||
700 | '/>[^\S ]+/s' => '>', // remove spaces after tag, except one space |
||
701 | '/[^\S ]+</s' => '<', // remove spaces before tag, except one space |
||
702 | '/>[\s]+</' => '><', // remove spaces between tags, except one space |
||
703 | '/<(\s|\t|\r?\n)+/' => '<', // remove spaces, tabs, and new lines after start of the tag |
||
704 | '/(\s|\t|\r?\n)+>/' => '>', // remove spaces, tabs, and new lines before end of the tag |
||
705 | '/<!--(.|\s)*?-->/' => '', // remove comments |
||
706 | ]; |
||
707 | |||
708 | return preg_replace( |
||
709 | array_keys($patterns), |
||
710 | array_values($patterns), |
||
711 | $html |
||
712 | ); |
||
713 | } |
||
714 | |||
715 | |||
716 | /** |
||
717 | * Makes HTML tags available as methods on the class. |
||
718 | */ |
||
719 | public function __call(string $method, array $arguments) |
||
726 | } |
||
727 | |||
728 | /** |
||
729 | * Makes HTML tags available as static methods on the class. |
||
730 | */ |
||
731 | public static function __callStatic(string $method, array $arguments) |
||
740 | } |
||
741 | } |
||
742 |