TTextUtilities   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 286
Duplicated Lines 9.09 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 32.31%

Importance

Changes 0
Metric Value
wmc 17
lcom 0
cbo 0
dl 26
loc 286
ccs 21
cts 65
cp 0.3231
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getUntilStop() 0 8 2
A getUntilMore() 0 9 2
A wrapElementWithStartEnd() 0 9 1
A wrapElementContentWithStartEnd() 0 9 1
A createToc() 0 23 5
A createAnchor4Header() 0 11 1
A addBaseurlToRelativeLinks() 13 13 1
A addBaseurlToImageSource() 13 13 1
A addRevisionHistory() 0 22 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Mos\TextFilter;
4
5
/**
6
 * Utilities when working with text.
7
 *
8
 */
9
trait TTextUtilities
10
{
11
    /**
12
     * Get text until <!--stop--> or all text.
13
     *
14
     * @param string $text with content
15
     *
16
     * @return string with text
17
     */
18 6
    public function getUntilStop($text)
19
    {
20 6
        $pos = stripos($text, "<!--stop-->");
21 6
        if ($pos) {
22 2
            $text = substr($text, 0, $pos);
23 2
        }
24 6
        return $text;
25
    }
26
27
28
29
    /**
30
     * Get text until <!--more--> or all text.
31
     *
32
     * @param string $text with content
33
     *
34
     * @return array with text and boolean if more was detected.
35
     */
36 2
    public function getUntilMore($text)
37
    {
38 2
        $pos = stripos($text, "<!--more-->");
39 2
        $hasMore = $pos;
40 2
        if ($pos) {
41 1
            $text = substr($text, 0, $pos);
42 1
        }
43 2
        return [$text, $hasMore];
44
    }
45
46
47
48
    /**
49
     * Wrap HTML element with with start and end.
50
     *
51
     * @param string  $text  with content
52
     * @param string  $tag   HTML tag to search for
53
     * @param string  $start wrap start part
54
     * @param string  $end   wrap end part
55
     * @param number  $count hits to search for
56
     *
57
     * @return array with text and boolean if more was detected.
58
     */
59
    public function wrapElementWithStartEnd($text, $tag, $start, $end, $count)
60
    {
61
        return preg_replace(
62
            "#(<$tag>)(.*?)(</$tag>)#",
63
            "$start$1$2$3$end</a>",
64
            $text,
65
            $count
66
        );
67
    }
68
69
70
71
    /**
72
    * Wrap content of a HTML element with start and end.
73
     *
74
     * @param string  $text  with content
75
     * @param string  $tag   HTML tag to search for
76
     * @param string  $start wrap start part
77
     * @param string  $end   wrap end part
78
     * @param number  $count hits to search for
79
     *
80
     * @return array with text and boolean if more was detected.
81
     */
82
    public function wrapElementContentWithStartEnd($text, $tag, $start, $end, $count)
83
    {
84
        return preg_replace(
85
            "#(<$tag>)(.*?)(</$tag>)#",
86
            "$1$start$2$end$3",
87
            $text,
88
            $count
89
        );
90
    }
91
92
93
94
    /**
95
     * Create a TOC of HTML headings from and to a certain level.
96
     *
97
     * @param string  $text  with content
98
     * @param integer $start level of headings to use for toc.
99
     * @param integer $stop  level of headings to use for toc.
100
     *
101
     * @return array with entries to generate a TOC.
102
     */
103
    public function createToc($text, $start = 2, $stop = 4)
104
    {
105
        $level = "$start-$stop";
106
        $pattern = "#<(h[$level])([^>]*)>(.*)</h[$level]>#";
107
        preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
108
109
        $toc = [];
110
        foreach ($matches as $val) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
111
            preg_match("#id=['\"]([^>\"']+)#", $val[2], $id);
112
            $id = isset($id[1]) ? $id[1] : null;
113
            $toc[] = [
114
                "level" => isset($val[1])
115
                    ? $val[1]
116
                    : null,
117
                "title" => isset($val[3])
118
                    ? ltrim(strip_tags($val[3]), "#")
119
                    : null,
120
                "id" => $id,
121
            ];
122
        }
123
124
        return $toc;
125
    }
126
127
128
129
    /**
130
     * Create a anchor for each header having an id.
131
     *
132
     * @param string  $text  with content
133
     * @param integer $start level of headings to use.
134
     * @param integer $stop  level of headings to use.
135
     *
136
     * @return string with modified text.
137
     */
138
    public function createAnchor4Header($text, $start = 1, $stop = 4)
139
    {
140
        $level = "$start-$stop";
141
        $pattern = "#(<h[$level] id=\"([\w\-_]+)\">)(.+)(</h[$level]>)#";
142
143
        return preg_replace(
144
            $pattern,
145
            "$1<a class=\"header-anchor\" href=\"#$2\">#</a>$3$4",
146
            $text
147
        );
148
    }
149
150
151
152
    /**
153
     * Add baseurl to all relative links.
154
     *
155
     * @param string   $text     with content.
156
     * @param string   $baseurl  as string to prepend relative link.
157
     * @param callable $callback Use to create url from route.
158
     *
159
     * @return string with modified text.
160
     */
161 2 View Code Duplication
    public function addBaseurlToRelativeLinks($text, $baseurl, $callback)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163 2
        $pattern = "#<a(.+?)href=\"([^\"]*)\"([.^>]*)>#";
164
165 2
        return preg_replace_callback(
166 2
            $pattern,
167 2
            function ($matches) use ($baseurl, $callback) {
168 2
                $url = $callback($matches[2], $baseurl);
169 2
                return "<a${matches[1]}href=\"$url\"${matches[3]}>";
170
            },
171
            $text
172 2
        );
173
    }
174
175
176
177
    /**
178
     * Add baseurl to all relative links in image source.
179
     *
180
     * @param string   $text     with content.
181
     * @param string   $baseurl  as string to prepend relative link.
182
     * @param callable $callback Use to create url from route.
183
     *
184
     * @return string with modified text.
185
     */
186 View Code Duplication
    public function addBaseurlToImageSource($text, $baseurl, $callback)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
    {
188
        $pattern = "#<img(.+?)src=\"([^\"]*)\"(.*?)>#";
189
        
190
        return preg_replace_callback(
191
            $pattern,
192
            function ($matches) use ($baseurl, $callback) {
193
                $url = $callback($matches[2], $baseurl);
194
                return "<img${matches[1]}src=\"$url\"${matches[3]}>";
195
            },
196
            $text
197
        );
198
    }
199
200
201
202
    /**
203
     * Generate revision history and add to the end of content.
204
     *
205
     * @param string $text     with content.
206
     * @param array  $revision with all revisions.
207
     * @param string $start    start wrap with this.
208
     * @param string $end      end wrap with this.
209
     * @param string $class    to add to ul element.
210
     * @param string $source   optional url to document source.
211
     *
212
     * @return string with text and optionally added revision history.
213
     */
214
    public function addRevisionHistory($text, $revision, $start, $end, $class, $source = null)
215
    {
216
        
217
        $text  = $text . $start;
218
        $text .= "<ul class=\"$class\">\n";
219
        
220
        foreach ($revision as $date => $info) {
221
            $text .= "<li>$date: $info</li>\n";
222
        }
223
224
        $text .= "</ul>\n";
225
226
        if ($source) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $source of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
227
            $text .= "<p><a class=\"$class\" href=\"$source\">"
228
            . t("Document source")
229
            . "</a>.</p>\n";
230
        }
231
232
        $text .= $end;
233
234
        return $text;
235
    }
236
237
238
239
    /**
240
     * Get content as pure text.
241
     *
242
     * @return string with the pure text.
243
     */
244
/*    public function GetPureText() {
245
      return preg_replace('/\s+/', ' ', strip_tags($this->GetFilteredData()));
246
    }
247
*/
248
249
250
251
    /**
252
     * Returns the excerpt of the text with at most the specified amount of characters.
253
     *
254
     * @param int $chars the number of characters to return.
255
     * @param boolean $hard do a hard break at exactly $chars characters or find closest space.
256
     * @return string as the excerpt.
257
     */
258
/*    public function GetExcerpt($chars=139, $hard=false) {
259
      if(!isset($this->data['data_filtered'])) {
260
        return null;
261
      }
262
      $excerpt = strip_tags($this->data['data_filtered']);
263
264
      if(strlen($excerpt) > $chars) {
265
        $excerpt   = substr($excerpt, 0, $chars-1);
266
      }
267
268
      if(!$hard) {
269
        $lastSpace = strrpos($excerpt, ' ');
270
        $excerpt   = substr($excerpt, 0, $lastSpace);
271
      }
272
273
      return $excerpt;
274
    }
275
    
276
    
277
    /**
278
     * Returns the first paragraph ot the text.
279
     * 
280
     * @return string as the first paragraph.
281
     */
282
/*    public function GetFirstParagraph() {
283
      if(!isset($this->data['data_filtered'])) {
284
        return null;
285
      }
286
      $excerpt = $this->data['data_filtered'];
287
288
      $firstPara = strpos($excerpt, '</p>');
289
      $excerpt   = substr($excerpt, 0, $firstPara + 4);
290
291
      return $excerpt;
292
    }
293
*/
294
}
295