| Total Complexity | 57 |
| Total Lines | 444 |
| Duplicated Lines | 0 % |
| Changes | 3 | ||
| 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) |
||
| 298 | { |
||
| 299 | $this->validate = $validate; |
||
| 300 | $this->buffer = []; |
||
| 301 | $this->stack = []; |
||
| 302 | $this->conditions = []; |
||
| 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 | if (!strlen(trim($name))) { |
||
| 320 | $variables = ['class', 'function', 'file', 'line']; |
||
| 321 | $backtrace = Misc::backtrace($variables, 1); |
||
| 322 | $backtrace = is_array($backtrace) ? $backtrace : array_map('strtoupper', $variables); |
||
| 323 | |||
| 324 | throw new \Exception( |
||
| 325 | vsprintf('Invalid name supplied to %s::%s() in %s on line %s. Tag name cannot be an empty string', $backtrace) |
||
| 326 | ); |
||
| 327 | } |
||
| 328 | |||
| 329 | if ($this->isConditionTruthy()) { |
||
| 330 | $tag = $content !== null |
||
| 331 | ? '<{name}{attributes}>{content}</{name}>' |
||
| 332 | : '<{name}{attributes} />'; |
||
| 333 | $name = strtolower(trim($name)); |
||
| 334 | $attributes = $this->stringifyAttributes($attributes); |
||
| 335 | |||
| 336 | $this->buffer[] = $this->translateElement($tag, compact('name', 'content', 'attributes')); |
||
| 337 | } |
||
| 338 | |||
| 339 | return $this; |
||
| 340 | } |
||
| 341 | |||
| 342 | /** |
||
| 343 | * Creates an HTML entity from the specified name and pass it to the buffer. |
||
| 344 | * |
||
| 345 | * @param string $name The name of the HTML entity without `&` nor `;`. |
||
| 346 | * |
||
| 347 | * @return $this |
||
| 348 | * |
||
| 349 | * @throws \Exception If the supplied name is invalid. |
||
| 350 | */ |
||
| 351 | public function entity(string $name): HTML |
||
| 352 | { |
||
| 353 | if (!strlen(trim($name))) { |
||
| 354 | $variables = ['class', 'function', 'file', 'line']; |
||
| 355 | $backtrace = Misc::backtrace($variables, 1); |
||
| 356 | $backtrace = is_array($backtrace) ? $backtrace : array_map('strtoupper', $variables); |
||
| 357 | |||
| 358 | throw new \Exception( |
||
| 359 | vsprintf('Invalid name supplied to %s::%s() in %s on line %s. Entity name cannot be an empty string', $backtrace) |
||
| 360 | ); |
||
| 361 | } |
||
| 362 | |||
| 363 | if ($this->isConditionTruthy()) { |
||
| 364 | $entity = sprintf('&%s;', trim($name, '& ;')); |
||
| 365 | $this->buffer[] = $entity; |
||
| 366 | } |
||
| 367 | |||
| 368 | |||
| 369 | return $this; |
||
| 370 | } |
||
| 371 | |||
| 372 | /** |
||
| 373 | * Creates an HTML comment from the specified text and pass it to the buffer. |
||
| 374 | * |
||
| 375 | * @param string $comment The text content of the HTML comment without `<!--` and `-->`. |
||
| 376 | * |
||
| 377 | * @return $this |
||
| 378 | */ |
||
| 379 | public function comment(string $text): HTML |
||
| 380 | { |
||
| 381 | if ($this->isConditionTruthy()) { |
||
| 382 | $comment = sprintf('<!-- %s -->', trim($text)); |
||
| 383 | $this->buffer[] = $comment; |
||
| 384 | } |
||
| 385 | |||
| 386 | return $this; |
||
| 387 | } |
||
| 388 | |||
| 389 | /** |
||
| 390 | * 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). |
||
| 391 | * |
||
| 392 | * @param string $text The text to pass to the buffer. |
||
| 393 | * |
||
| 394 | * @return $this |
||
| 395 | */ |
||
| 396 | public function node(string $text): HTML |
||
| 404 | } |
||
| 405 | |||
| 406 | /** |
||
| 407 | * Creates an HTML opening tag from the specified parameters and pass it to the buffer. Works in conjunction with `self::close()`. |
||
| 408 | * |
||
| 409 | * @param string $name A name of an HTML tag. |
||
| 410 | * @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. |
||
| 411 | * |
||
| 412 | * @return $this |
||
| 413 | * |
||
| 414 | * @throws \Exception If the supplied name is invalid. |
||
| 415 | */ |
||
| 416 | public function open(string $name, array $attributes = []): HTML |
||
| 439 | } |
||
| 440 | |||
| 441 | /** |
||
| 442 | * Creates an HTML closing tag matching the last tag opened by `self::open()`. |
||
| 443 | * |
||
| 444 | * @return $this |
||
| 445 | * |
||
| 446 | * @throws \Exception If no tag has been opened. |
||
| 447 | */ |
||
| 448 | public function close(): HTML |
||
| 449 | { |
||
| 450 | if (!count($this->stack)) { |
||
| 451 | $variables = ['class', 'function', 'file', 'line']; |
||
| 452 | $backtrace = Misc::backtrace($variables, 1); |
||
| 453 | $backtrace = is_array($backtrace) ? $backtrace : array_map('strtoupper', $variables); |
||
| 454 | |||
| 455 | throw new \Exception( |
||
| 456 | vsprintf('Not in a context to close a tag! Call to %s::%s() in %s on line %s is superfluous', $backtrace) |
||
| 457 | ); |
||
| 458 | } |
||
| 459 | |||
| 460 | if ($this->isConditionTruthy(-1)) { |
||
| 461 | $tag = '</{name}>'; |
||
| 462 | |||
| 463 | $name = array_pop($this->stack); |
||
| 464 | |||
| 465 | $this->buffer[] = $this->translateElement($tag, compact('name')); |
||
| 466 | } |
||
| 467 | |||
| 468 | return $this; |
||
| 469 | } |
||
| 470 | |||
| 471 | /** |
||
| 472 | * Takes a callback and executes it after binding $this (HTML) to it, useful for example to execute any PHP code while creating the markup. |
||
| 473 | * |
||
| 474 | * @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. |
||
| 475 | * |
||
| 476 | * @return $this |
||
| 477 | */ |
||
| 478 | public function execute(callable $callback): HTML |
||
| 479 | { |
||
| 480 | if ($this->isConditionTruthy()) { |
||
| 481 | $boundClosure = \Closure::fromCallable($callback)->bindTo($this); |
||
| 482 | |||
| 483 | if ($boundClosure !== false) { |
||
| 484 | $boundClosure($this); |
||
| 485 | } else { |
||
| 486 | $callback($this); |
||
| 487 | } |
||
| 488 | } |
||
| 489 | |||
| 490 | return $this; |
||
| 491 | } |
||
| 492 | |||
| 493 | /** |
||
| 494 | * Takes a condition (some boolean value) to determine whether or not to create the very next element and pass it to the buffer. |
||
| 495 | * |
||
| 496 | * @param mixed $condition Any value that can be casted into a boolean. |
||
| 497 | * |
||
| 498 | * @return $this |
||
| 499 | */ |
||
| 500 | public function condition($condition): HTML |
||
| 501 | { |
||
| 502 | $this->conditions[] = (bool)($condition); |
||
| 503 | |||
| 504 | return $this; |
||
| 505 | } |
||
| 506 | |||
| 507 | /** |
||
| 508 | * Determines whether or not the last set condition is truthy or falsy. |
||
| 509 | * |
||
| 510 | * @param int $parent [optional] A flag to indicate condition depth `[+1 = parentOpened, 0 = normal, -1 = parentClosed]`. |
||
| 511 | * |
||
| 512 | * @return bool|null The result of the condition, or null if the passed `$parent` is not in `[-1, 0, +1]`. |
||
| 513 | */ |
||
| 514 | private function isConditionTruthy(int $parent = 0): ?bool |
||
| 515 | { |
||
| 516 | static $parentConditions = []; |
||
| 517 | |||
| 518 | $result = true; |
||
| 519 | |||
| 520 | if (!empty($this->conditions) || !empty($parentConditions)) { |
||
| 521 | $actualCondition = $this->conditions[count($this->conditions) - 1] ?? $result; |
||
| 522 | $parentCondition = $parentConditions[count($parentConditions) - 1] ?? $result; |
||
| 523 | |||
| 524 | $condition = $parentCondition & $actualCondition; |
||
| 525 | if (!$condition) { |
||
| 526 | $result = false; |
||
| 527 | } |
||
| 528 | |||
| 529 | switch ($parent) { |
||
| 530 | case +1: |
||
| 531 | array_push($parentConditions, $condition); |
||
| 532 | break; |
||
| 533 | case -1: |
||
| 534 | array_pop($parentConditions); |
||
| 535 | break; |
||
| 536 | case 0: |
||
| 537 | // NORMAL! |
||
| 538 | break; |
||
| 539 | default: |
||
| 540 | return null; |
||
| 541 | } |
||
| 542 | |||
| 543 | array_pop($this->conditions); |
||
| 544 | } |
||
| 545 | |||
| 546 | return $result; |
||
| 547 | } |
||
| 548 | |||
| 549 | /** |
||
| 550 | * Returns an HTML attributes string from an associative array of attributes. |
||
| 551 | * |
||
| 552 | * @param array $attributes |
||
| 553 | * |
||
| 554 | * @return string |
||
| 555 | */ |
||
| 556 | private function stringifyAttributes(array $attributes): string |
||
| 557 | { |
||
| 558 | $attrStr = ''; |
||
| 559 | |||
| 560 | foreach ($attributes as $name => $value) { |
||
| 561 | if ($value === false) { |
||
| 562 | continue; |
||
| 563 | } |
||
| 564 | |||
| 565 | $attrStr .= is_string($name) && !is_null($value) |
||
| 566 | ? sprintf(' %s="%s"', $name, $value) |
||
| 567 | : sprintf(' %s', ($value ?: $name ?: '')); |
||
| 568 | } |
||
| 569 | |||
| 570 | return $attrStr; |
||
| 571 | } |
||
| 572 | |||
| 573 | /** |
||
| 574 | * Replaces variables in the passed string with values with matching key from the passed array. |
||
| 575 | * |
||
| 576 | * @param string $text A string like `{var} world!`. |
||
| 577 | * @param array $variables An array like `['var' => 'Hello']`. |
||
| 578 | * |
||
| 579 | * @return string A string like `Hello world!` |
||
| 580 | */ |
||
| 581 | private function translateElement(string $text, array $variables = []): string |
||
| 582 | { |
||
| 583 | $replacements = []; |
||
| 584 | |||
| 585 | foreach ($variables as $key => $value) { |
||
| 586 | $replacements[sprintf('{%s}', $key)] = $value; |
||
| 587 | } |
||
| 588 | |||
| 589 | return strtr($text, $replacements); |
||
| 590 | } |
||
| 591 | |||
| 592 | /** |
||
| 593 | * Asserts that the passed HTML is valid. |
||
| 594 | * |
||
| 595 | * @return void |
||
| 596 | * |
||
| 597 | * @throws \Exception If the passed html is invalid. |
||
| 598 | */ |
||
| 599 | private function validate(string $html): void |
||
| 600 | { |
||
| 601 | $html = !empty($html) ? $html : '<br/>'; |
||
| 602 | |||
| 603 | $xml = libxml_use_internal_errors(true); |
||
| 604 | |||
| 605 | $dom = new \DOMDocument(); |
||
| 606 | $dom->validateOnParse = true; |
||
| 607 | $dom->loadHTML($html); |
||
| 608 | // $dom->saveHTML(); |
||
| 609 | |||
| 610 | $ignoredCodes = [801]; |
||
| 611 | $errors = libxml_get_errors(); |
||
| 612 | libxml_clear_errors(); |
||
| 613 | |||
| 614 | if (!empty($errors) && !in_array($errors[0]->code, $ignoredCodes)) { |
||
| 615 | $file = Misc::backtrace('file', 3); |
||
| 616 | $file = is_string($file) ? $file : 'FILE'; |
||
| 617 | |||
| 618 | throw new \Exception( |
||
| 619 | vsprintf( |
||
| 620 | 'HTML is invalid in %s! Found %s problem(s). Last LibXMLError: [level:%s/code:%s] %s', |
||
| 621 | [$file, count($errors), $errors[0]->level, $errors[0]->code, $errors[0]->message] |
||
| 622 | ) |
||
| 623 | ); |
||
| 624 | } |
||
| 625 | |||
| 626 | libxml_use_internal_errors($xml); |
||
| 627 | } |
||
| 628 | |||
| 629 | /** |
||
| 630 | * Returns the created HTML elements found in the buffer and empties it. |
||
| 631 | * |
||
| 632 | * @return string |
||
| 633 | * |
||
| 634 | * @throws \Exception If not all open elements are closed or the generated html is invalid. |
||
| 635 | */ |
||
| 636 | public function return(): string |
||
| 637 | { |
||
| 638 | if (count($this->stack)) { |
||
| 639 | $file = Misc::backtrace('file', 2); |
||
| 640 | $file = is_string($file) ? $file : 'FILE'; |
||
| 641 | |||
| 642 | throw new \Exception( |
||
| 643 | sprintf( |
||
| 644 | "Cannot return HTML in %s. The following tag(s): '%s' has/have not been closed properly", |
||
| 645 | $file, |
||
| 646 | implode(', ', $this->stack) |
||
| 647 | ) |
||
| 648 | ); |
||
| 649 | } |
||
| 650 | |||
| 651 | $html = implode('', $this->buffer); |
||
| 652 | |||
| 653 | $this->buffer = []; |
||
| 654 | |||
| 655 | if ($this->validate) { |
||
| 656 | $this->validate($html); |
||
| 657 | } |
||
| 658 | |||
| 659 | return $html; |
||
| 660 | } |
||
| 661 | |||
| 662 | /** |
||
| 663 | * Echos the created HTML elements found in the buffer and empties it. |
||
| 664 | * |
||
| 665 | * @return void |
||
| 666 | * |
||
| 667 | * @throws \Exception If not all open elements are closed or the generated html is invalid. |
||
| 668 | */ |
||
| 669 | public function echo(): void |
||
| 670 | { |
||
| 671 | echo $this->return(); |
||
| 672 | } |
||
| 673 | |||
| 674 | /** |
||
| 675 | * Minifies HTML buffers by removing all unnecessary whitespaces and comments. |
||
| 676 | * |
||
| 677 | * @param string $html |
||
| 678 | * |
||
| 679 | * @return string |
||
| 680 | */ |
||
| 681 | public static function minify(string $html): string |
||
| 682 | { |
||
| 683 | $patterns = [ |
||
| 684 | '/(\s)+/s' => '$1', // shorten multiple whitespace sequences |
||
| 685 | '/>[^\S ]+/s' => '>', // remove spaces after tag, except one space |
||
| 686 | '/[^\S ]+</s' => '<', // remove spaces before tag, except one space |
||
| 687 | '/>[\s]+</' => '><', // remove spaces between tags, except one space |
||
| 688 | '/<(\s|\t|\r?\n)+/' => '<', // remove spaces, tabs, and new lines after start of the tag |
||
| 689 | '/(\s|\t|\r?\n)+>/' => '>', // remove spaces, tabs, and new lines before end of the tag |
||
| 690 | '/<!--(.|\s)*?-->/' => '', // remove comments |
||
| 691 | ]; |
||
| 692 | |||
| 693 | return preg_replace( |
||
| 694 | array_keys($patterns), |
||
| 695 | array_values($patterns), |
||
| 696 | $html |
||
| 697 | ); |
||
| 698 | } |
||
| 699 | |||
| 700 | |||
| 701 | /** |
||
| 702 | * Makes HTML tags available as methods on the class. |
||
| 703 | */ |
||
| 704 | public function __call(string $method, array $arguments) |
||
| 711 | } |
||
| 712 | |||
| 713 | /** |
||
| 714 | * Makes HTML tags available as static methods on the class. |
||
| 715 | */ |
||
| 716 | public static function __callStatic(string $method, array $arguments) |
||
| 725 | } |
||
| 726 | } |
||
| 727 |