1<?php
2
3declare(strict_types=1);
4
5/*
6 * This file is part of the league/commonmark package.
7 *
8 * (c) Colin O'Dell <colinodell@gmail.com>
9 *
10 * For the full copyright and license information, please view the LICENSE
11 * file that was distributed with this source code.
12 */
13
14namespace League\CommonMark\Normalizer;
15
16use League\Config\ConfigurationAwareInterface;
17use League\Config\ConfigurationInterface;
18
19/**
20 * Creates URL-friendly strings based on the given string input
21 */
22final class SlugNormalizer implements TextNormalizerInterface, ConfigurationAwareInterface
23{
24    /** @psalm-allow-private-mutation */
25    private int $defaultMaxLength = 255;
26
27    public function setConfiguration(ConfigurationInterface $configuration): void
28    {
29        $this->defaultMaxLength = $configuration->get('slug_normalizer/max_length');
30    }
31
32    /**
33     * {@inheritDoc}
34     *
35     * @psalm-immutable
36     */
37    public function normalize(string $text, array $context = []): string
38    {
39        // Add any requested prefix
40        $slug = ($context['prefix'] ?? '') . $text;
41        // Trim whitespace
42        $slug = \trim($slug);
43        // Convert to lowercase
44        $slug = \mb_strtolower($slug, 'UTF-8');
45        // Try replacing whitespace with a dash
46        $slug = \preg_replace('/\s+/u', '-', $slug) ?? $slug;
47        // Try removing characters other than letters, numbers, and marks.
48        $slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug) ?? $slug;
49        // Trim to requested length if given
50        if ($length = $context['length'] ?? $this->defaultMaxLength) {
51            $slug = \mb_substr($slug, 0, $length, 'UTF-8');
52        }
53
54        return $slug;
55    }
56}
57