Skip to content

Commit

Permalink
Merge pull request #10 from yaquawa/inject_slugify
Browse files Browse the repository at this point in the history
Make sluggifier injectable; thanks for your contribution @yaquawa!  I will be releasing a new version with this change in the next day or two.
  • Loading branch information
caseyamcl committed Jul 15, 2020
2 parents 27edd0d + 1bcb989 commit d0ede3f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
16 changes: 11 additions & 5 deletions src/MarkupFixer.php
Expand Up @@ -21,6 +21,7 @@

use Masterminds\HTML5;
use RuntimeException;
use Cocur\Slugify\SlugifyInterface;

/**
* TOC Markup Fixer adds `id` attributes to all H1...H6 tags where they do not
Expand All @@ -37,14 +38,21 @@ class MarkupFixer
*/
private $htmlParser;

/**
* @var SlugifyInterface
*/
private $sluggifier;

/**
* Constructor
*
* @param HTML5 $htmlParser
* @param SlugifyInterface $sluggifier
*/
public function __construct(HTML5 $htmlParser = null)
public function __construct(HTML5 $htmlParser = null, SlugifyInterface $sluggifier = null)
{
$this->htmlParser = $htmlParser ?: new HTML5();
$this->htmlParser = $htmlParser ?? new HTML5();
$this->sluggifier = $sluggifier ?? new UniqueSluggifier();
}

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

$sluggifier = new UniqueSluggifier();

/** @var \DOMElement $node */
foreach ($this->traverseHeaderTags($domDocument, $topLevel, $depth) as $node) {
if ($node->getAttribute('id')) {
continue;
}

$node->setAttribute('id', $sluggifier->slugify($node->getAttribute('title') ?: $node->textContent));
$node->setAttribute('id', $this->sluggifier->slugify($node->getAttribute('title') ?: $node->textContent));
}

return $this->htmlParser->saveHTML(
Expand Down
8 changes: 5 additions & 3 deletions src/UniqueSluggifier.php
Expand Up @@ -21,13 +21,14 @@
namespace TOC;

use Cocur\Slugify\Slugify;
use Cocur\Slugify\SlugifyInterface;

/**
* UniqueSluggifier creates slugs from text without repeating the same slug twice per instance
*
* @author Casey McLaughlin <caseyamcl@gmail.com>
*/
class UniqueSluggifier
class UniqueSluggifier implements SlugifyInterface
{
/**
* @var Slugify
Expand All @@ -54,11 +55,12 @@ public function __construct(Slugify $slugify = null)
* Slugify
*
* @param string $text
* @param null $options
* @return string
*/
public function slugify(string $text): string
public function slugify($text, $options = null): string
{
$slugged = $this->slugify->slugify($text);
$slugged = $this->slugify->slugify($text, $options);

$count = 1;
$orig = $slugged;
Expand Down

0 comments on commit d0ede3f

Please sign in to comment.