| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class to manage headline IDs. |
| 4 |
* |
| 5 |
* Ensures a unique anchor for each headline. |
| 6 |
* |
| 7 |
* @package simpletoc |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace MToensing\SimpleTOC; |
| 11 |
|
| 12 |
/** |
| 13 |
* Class to manage headline IDs. |
| 14 |
* |
| 15 |
* Ensures a unique anchor for each headline. |
| 16 |
*/ |
| 17 |
class SimpleTOC_Headline_Ids { |
| 18 |
/** |
| 19 |
* Array of headlines and their counts. |
| 20 |
* |
| 21 |
* @var array |
| 22 |
*/ |
| 23 |
private $headlines = array(); |
| 24 |
|
| 25 |
/** |
| 26 |
* Add a headline to the array |
| 27 |
* |
| 28 |
* @param string $headline_slug The slug of the headline. |
| 29 |
*/ |
| 30 |
private function add_headline( $headline_slug ) { |
| 31 |
if ( empty( $headline_slug ) ) { |
| 32 |
return; |
| 33 |
} |
| 34 |
|
| 35 |
if ( ! isset( $this->headlines[ $headline_slug ] ) ) { |
| 36 |
$this->headlines[ $headline_slug ] = 1; |
| 37 |
} else { |
| 38 |
$this->headlines[ $headline_slug ] = $this->get_headline_count( $headline_slug ) + 1; |
| 39 |
} |
| 40 |
if ( $this->headlines[ $headline_slug ] > 1 ) { |
| 41 |
$new_headline_slug = $headline_slug . '-' . $this->headlines[ $headline_slug ]; |
| 42 |
if ( isset( $this->headlines[ $new_headline_slug ] ) ) { |
| 43 |
$new_headline_slug = $this->add_headline( $new_headline_slug ); |
| 44 |
} |
| 45 |
$new_headline_count = $this->get_headline_count( $new_headline_slug ); |
| 46 |
if ( 0 === $new_headline_count ) { |
| 47 |
$new_headline_count = 1; |
| 48 |
} |
| 49 |
$this->headlines[ $new_headline_slug ] = $new_headline_count; |
| 50 |
return $new_headline_slug; |
| 51 |
} |
| 52 |
return $headline_slug; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Get the anchor for a headline |
| 57 |
* |
| 58 |
* @param string $headline The headline. |
| 59 |
* @return string The anchor for the headline |
| 60 |
*/ |
| 61 |
public function get_headline_anchor( $headline ) { |
| 62 |
if ( empty( $headline ) ) { |
| 63 |
return ''; |
| 64 |
} |
| 65 |
|
| 66 |
$headline_slug = simpletoc_sanitize_string( $headline ); |
| 67 |
|
| 68 |
$headline_slug = $this->add_headline( $headline_slug ); |
| 69 |
return $headline_slug; |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Get the count of a headline slug. |
| 74 |
* |
| 75 |
* @param string $headline_slug The slug of the headline. |
| 76 |
* @return mixed The count of the headline slug. |
| 77 |
*/ |
| 78 |
private function get_headline_count( $headline_slug = '' ) { |
| 79 |
return $this->headlines[ $headline_slug ] ?? 0; |
| 80 |
} |
| 81 |
} |
| 82 |
|