PluginProbe
SimpleTOC – Table of Contents Block / 7.2.0
SimpleTOC – Table of Contents Block v7.2.0
7.2.0 7.3.0 7.1.1 7.1.0 7.0.10 7.0.9 7.0.8 7.0.7 7.0.6 7.0.4 7.0.5 5.0.21.1 5.0.22 5.0.23 5.0.24 5.0.25 5.0.25.1 5.0.27 5.0.28 5.0.29 5.0.3 5.0.30 5.0.31 5.0.32 5.0.33 All 159 releases
simpletoc / simpletoc-class-headline-ids.php

simpletoc-class-headline-ids.php in SimpleTOC – Table of Contents Block 7.2.0, at simpletoc-class-headline-ids.php

82 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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