Skip to content

Commit

Permalink
Updated code to PHP 8
Browse files Browse the repository at this point in the history
  • Loading branch information
caseyamcl committed Dec 8, 2024
1 parent abecbce commit 4aba03d
Show file tree
Hide file tree
Showing 15 changed files with 112 additions and 156 deletions.
7 changes: 7 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## Slug creation changes

* Added `TOC\SluggerInterface` class
* Methods: `makeSlug` and `reset`
* Renamed `TOC\UniqueSlugify` to `TOC\UniqueSlugger`
* Replaced `cocur/slugify` with `symfony/string`

19 changes: 9 additions & 10 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,25 @@
}
},
"require": {
"php": "^7.2|^8.0",
"php": "^8.2",
"ext-dom": "*",
"masterminds/html5": "^2.1",
"cocur/slugify": "~4.4.0|^4.6",
"symfony/string": "^5.4|^6.0|^7.0",
"symfony/translation-contracts": "^2.5|^3.0",
"knplabs/knp-menu": "^3.2"
"masterminds/html5": "^2.9",
"symfony/string": "^6.0|^7.0",
"symfony/translation-contracts": "^3.0",
"knplabs/knp-menu": "^3.5"
},
"require-dev": {
"twig/twig": "^2.4|^3.0",
"phpunit/phpunit": "^7.5|^8.0|^9.0",
"twig/twig": "^3.0",
"phpunit/phpunit": "^11.0",
"squizlabs/php_codesniffer": "^3.5",
"phpstan/phpstan": "^1.4",
"phpstan/phpstan": "^2.0",
"jaschilz/php-coverage-badger": "^2.0"
},
"scripts": {
"test": " XDEBUG_MODE=coverage vendor/bin/phpunit; vendor/bin/php-coverage-badger build/logs/clover.xml ./coverage.svg",
"check-style": "phpcs -p --standard=PSR12 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests",
"fix-style": "phpcbf -p --standard=PSR12 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests",
"phpstan": "vendor/bin/phpstan analyse -l 5 src tests"
"phpstan": "vendor/bin/phpstan analyse -l 7 src tests"
},
"config": {
"sort-packages": true
Expand Down
4 changes: 2 additions & 2 deletions coverage.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 23 additions & 36 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,38 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
>
<coverage>
<include>
<directory>./</directory>
</include>
<exclude>
<directory>./tests</directory>
<directory>./vendor</directory>
</exclude>
<report>
<clover outputFile="build/logs/clover.xml"/>
<html outputDirectory="build/coverage"/>
<text outputFile="build/coverage.txt"/>
</report>
</coverage>
<testsuites>
<testsuite name="PHP TOC Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<logging>
<junit outputFile="build/report.junit.xml"/>
</logging>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
shortenArraysForExportThreshold="10"
beStrictAboutOutputDuringTests="true"
displayDetailsOnPhpunitDeprecations="true"
failOnPhpunitDeprecation="true"
failOnRisky="true"
displayDetailsOnSkippedTests="true"
failOnWarning="true">
<testsuites>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>

<source ignoreIndirectDeprecations="true" restrictNotices="true" restrictWarnings="true">
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
44 changes: 20 additions & 24 deletions src/HtmlHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,21 @@

use ArrayIterator;
use DOMDocument;
use DomElement;
use DOMElement;
use DOMXPath;

/**
* Trait that helps with HTML-related operations
*
* @package TOC
*/
trait HtmlHelper
{
/**
* Convert a topLevel and depth to H1...H6 tags array
*
* @param int $topLevel
* @param int $depth
* @return array|string[] Array of header tags; ex: ['h1', 'h2', 'h3']
*/
protected function determineHeaderTags(int $topLevel, int $depth): array
{
$desired = range($topLevel, $topLevel + ($depth - 1));
$allowed = [1, 2, 3, 4, 5, 6];

return array_map(function ($val) {
return 'h' . $val;
}, array_intersect($desired, $allowed));
}



/**
* Traverse Header Tags in DOM Document
*
* @param DOMDocument $domDocument
* @param int $topLevel
* @param int $depth
* @return ArrayIterator<int,\DOMElement>
* @return ArrayIterator<int,DOMElement>
*/
protected function traverseHeaderTags(DOMDocument $domDocument, int $topLevel, int $depth): ArrayIterator
{
Expand Down Expand Up @@ -85,6 +64,23 @@ protected function traverseHeaderTags(DOMDocument $domDocument, int $topLevel, i
}
}

/**
* Convert a topLevel and depth to H1...H6 tags array
*
* @param int $topLevel
* @param int $depth
* @return array|string[] Array of header tags; ex: ['h1', 'h2', 'h3']
*/
protected function determineHeaderTags(int $topLevel, int $depth): array
{
$desired = range($topLevel, $topLevel + ($depth - 1));
$allowed = [1, 2, 3, 4, 5, 6];

return array_map(function ($val) {
return 'h' . $val;
}, array_intersect($desired, $allowed));
}

/**
* Is this a full HTML document
*
Expand All @@ -95,6 +91,6 @@ protected function traverseHeaderTags(DOMDocument $domDocument, int $topLevel, i
*/
protected function isFullHtmlDocument(string $markup): bool
{
return (strpos($markup, "<body") !== false && strpos($markup, "</body>") !== false);
return (str_contains($markup, "<body") && str_contains($markup, "</body>"));
}
}
19 changes: 6 additions & 13 deletions src/MarkupFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,8 @@ class MarkupFixer
{
use HtmlHelper;

/**
* @var HTML5
*/
private $htmlParser;

/**
* @var SluggerInterface
*/
private $slugger;
private HTML5 $htmlParser;
private SluggerInterface $slugger;

/**
* Constructor
Expand All @@ -52,7 +45,7 @@ class MarkupFixer
public function __construct(?HTML5 $htmlParser = null, ?SluggerInterface $slugger = null)
{
$this->htmlParser = $htmlParser ?? new HTML5();
$this->slugger = $slugger ?? new UniqueSlugify();
$this->slugger = $slugger ?? new UniqueSlugger();
}

/**
Expand All @@ -74,16 +67,16 @@ public function fix(string $markup, int $topLevel = 1, int $depth = 6): string
$domDocument = $this->htmlParser->loadHTML($markup);
$domDocument->preserveWhiteSpace = true; // do not clobber whitespace

// If using the default slugger, ensure that a unique instance of the class
$slugger = $this->slugger instanceof UniqueSlugify ? new UniqueSlugify() : $this->slugger;
// Reset the slugger state
$this->slugger->reset();

/** @var DOMElement $node */
foreach ($this->traverseHeaderTags($domDocument, $topLevel, $depth) as $node) {
// If no id is found, try the title attribute
$id = $node->getAttribute('id') ?: $node->getAttribute('title');

// If no title attribute, use the text content
$id = $slugger->makeSlug($id ?: $node->textContent);
$id = $this->slugger->makeSlug($id ?: $node->textContent);

// If the first character begins with a numeric, prepend 'toc-' on it.
if (ctype_digit(substr($id, 0, 1))) {
Expand Down
6 changes: 3 additions & 3 deletions src/OrderedListRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
class OrderedListRenderer extends ListRenderer
{
/**
* @param ItemInterface $item
* @param array<string> $attributes
* @param array $options
* @param ItemInterface $item
* @param array<string> $attributes
* @param array<string,mixed> $options
* @return string
*/
protected function renderList(ItemInterface $item, array $attributes, array $options): string
Expand Down
2 changes: 2 additions & 0 deletions src/SluggerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@
interface SluggerInterface
{
public function makeSlug(string $string): string;

public function reset(): void;
}
22 changes: 6 additions & 16 deletions src/TocGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,8 @@ class TocGenerator

private const DEFAULT_NAME = 'TOC';

/**
* @var HTML5
*/
private $domParser;

/**
* @var MenuFactory
*/
private $menuFactory;
private HTML5 $domParser;
private MenuFactory $menuFactory;

/**
* Constructor
Expand Down Expand Up @@ -75,28 +68,28 @@ public function getMenu(string $markup, int $topLevel = 1, int $depth = 6): Item
// Set up an empty menu object
$menu = $this->menuFactory->createItem(self::DEFAULT_NAME);

// Empty? Return empty menu item
// Empty markup? Bail and return empty menu item
if (trim($markup) == '') {
return $menu;
}

// Parse HTML
$tagsToMatch = $this->determineHeaderTags($topLevel, $depth);

// Initial settings
// Initial state
$lastElem = $menu;

// Do it...
$domDocument = $this->domParser->loadHTML($markup);
foreach ($this->traverseHeaderTags($domDocument, $topLevel, $depth) as $node) {
// Skip items without IDs
// Skip items without 'id' attributes
if (! $node->hasAttribute('id')) {
continue;
}

// Get the TagName and the level
$tagName = $node->tagName;
$level = array_search(strtolower($tagName), $tagsToMatch) + 1;
$level = (int) (array_search(strtolower($tagName), $tagsToMatch)) + 1;

// Determine parent item which to add child
/** @var MenuItem $parent */
Expand Down Expand Up @@ -130,9 +123,6 @@ public function getMenu(string $markup, int $topLevel = 1, int $depth = 6): Item

/**
* Trim empty items from the menu
*
* @param ItemInterface $menuItem
* @return ItemInterface
*/
protected function trimMenu(ItemInterface $menuItem): ItemInterface
{
Expand Down
11 changes: 2 additions & 9 deletions src/TocTwigExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,8 @@
*/
class TocTwigExtension extends AbstractExtension
{
/**
* @var TocGenerator
*/
private $generator;

/**
* @var MarkupFixer
*/
private $fixer;
private TocGenerator $generator;
private MarkupFixer $fixer;

/**
* Constructor
Expand Down
23 changes: 9 additions & 14 deletions src/UniqueSlugify.php → src/UniqueSlugger.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

namespace TOC;

use Cocur\Slugify\SlugifyInterface;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\String\Slugger\SluggerInterface as SymfonyStringSluggerInterface;

Expand All @@ -29,17 +28,14 @@
*
* @author Casey McLaughlin <caseyamcl@gmail.com>
*/
class UniqueSlugify implements SluggerInterface, SlugifyInterface
class UniqueSlugger implements SluggerInterface
{
/**
* @var SymfonyStringSluggerInterface
*/
private $slugger;
private SymfonyStringSluggerInterface $slugger;

/**
* @var array
* @var array<string>
*/
private $used;
private array $used = [];

/**
* Constructor
Expand All @@ -48,15 +44,9 @@ class UniqueSlugify implements SluggerInterface, SlugifyInterface
*/
public function __construct(?SymfonyStringSluggerInterface $slugger = null)
{
$this->used = array();
$this->slugger = $slugger ?: new AsciiSlugger();
}

public function slugify(string $string, $options = null): string
{
return $this->makeSlug($string);
}

/**
* Slugify
*
Expand All @@ -77,4 +67,9 @@ public function makeSlug(string $string): string
$this->used[] = $slugged;
return $slugged;
}

public function reset(): void
{
$this->used = [];
}
}
Loading

0 comments on commit 4aba03d

Please sign in to comment.