Completed
Push — master ( 14809f...d3f21c )
by Mikael
03:26
created

CTextFilter::syntaxHighlightJs()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
cc 3
eloc 6
nc 2
nop 2
crap 3
1
<?php
2
3
namespace Mos\TextFilter;
4
5
/**
6
 * Filter and format content.
7
 *
8
 */
9
class CTextFilter
10
{
11
    use TTextUtilities,
12
        TShortcode;
13
14
15
16
    /**
17
     * Supported filters.
18
     */
19
    private $filters = [
20
        "jsonfrontmatter",
21
        "yamlfrontmatter",
22
        "bbcode",
23
        "clickable",
24
        "shortcode",
25
        "markdown",
26
        "geshi",
27
        "nl2br",
28
        "htmlentities",
29
        "purify",
30
        "titlefromh1",
31
        "titlefromheader",
32
        "anchor4Header",
33
     ];
34
35
36
37
     /**
38
      * Current document parsed.
39
      */
40
    private $current;
41
42
43
44
    /**
45
     * Hold meta information for filters to use.
46
     */
47
    private $meta = [];
48
49
50
51
    /**
52
     * Call each filter.
53
     *
54
     * @deprecated deprecated since version 1.2 in favour of parse().
55
     *
56
     * @param string       $text    the text to filter.
57
     * @param string|array $filters as comma separated list of filter,
58
     *                              or filters sent in as array.
59
     *
60
     * @return string the formatted text.
61
     */
62
    public function doFilter($text, $filters)
63
    {
64
        // Define all valid filters with their callback function.
65
        $callbacks = [
66
            'bbcode'    => 'bbcode2html',
67
            'clickable' => 'makeClickable',
68
            'shortcode' => 'shortCode',
69
            'markdown'  => 'markdown',
70
            'nl2br'     => 'nl2br',
71
            'purify'    => 'purify',
72
        ];
73
74
        // Make an array of the comma separated string $filters
75
        if (is_array($filters)) {
76
            $filter = $filters;
77
        } else {
78
            $filters = strtolower($filters);
79
            $filter = preg_replace('/\s/', '', explode(',', $filters));
80
        }
81
82
        // For each filter, call its function with the $text as parameter.
83
        foreach ($filter as $key) {
84
            if (!isset($callbacks[$key])) {
85
                throw new Exception("The filter '$filters' is not a valid filter string due to '$key'.");
86
            }
87
            $text = call_user_func_array([$this, $callbacks[$key]], [$text]);
88
        }
89
90
        return $text;
91
    }
92
93
94
95
    /**
96
     * Set meta information that some filters can use.
97
     *
98
     * @param array $meta values for filters to use.
99
     *
100
     * @return void
101
     */
102
    public function setMeta($meta)
103
    {
104
        return $this->meta = $meta;
105
    }
106
107
108
109
    /**
110
     * Return an array of all filters supported.
111
     *
112
     * @return array with strings of filters supported.
113
     */
114 1
    public function getFilters()
115
    {
116 1
        return $this->filters;
117 1
    }
118
119
120
121
    /**
122
     * Check if filter is supported.
123
     *
124
     * @param string $filter to use.
125
     *
126
     * @throws mos/TextFilter/Exception  when filter does not exists.
127
     *
128
     * @return boolean true if filter exists, false othwerwise.
129
     */
130 2
    public function hasFilter($filter)
131
    {
132 2
        return in_array($filter, $this->filters);
133
    }
134
135
136
137
    /**
138
     * Add array items to frontmatter.
139
     *
140
     * @param array|null $matter key value array with items to add
141
     *                           or null if empty.
142
     *
143
     * @return $this
144
     */
145 3
    private function addToFrontmatter($matter)
146
    {
147 3
        if (empty($matter) || !is_array($matter)) {
148 2
            return $this;
149
        }
150
151 2
        if (is_null($this->current->frontmatter)) {
152
            $this->current->frontmatter = [];
153 1
        }
154
155 3
        $this->current->frontmatter = array_merge($this->current->frontmatter, $matter);
156 3
        return $this;
157
    }
158
159
160
161
    /**
162
     * Call a specific filter and store its details.
163
     *
164
     * @param string $filter to use.
165
     *
166
     * @throws mos/TextFilter/Exception when filter does not exists.
167
     *
168
     * @return string the formatted text.
169
     */
170 6
    private function parseFactory($filter)
171
    {
172
        // Define single tasks filter with a callback.
173
        $callbacks = [
174 6
            "bbcode"    => "bbcode2html",
175 6
            "clickable" => "makeClickable",
176 6
            "shortcode" => "shortCode",
177 6
            "markdown"  => "markdown",
178 6
            "geshi"     => "syntaxHighlightGeSHi",
179 6
            "nl2br"     => "nl2br",
180 6
            "htmlentities" => "htmlentities",
181 6
            "purify"    => "purify",
182 6
            'anchor4Header' => 'createAnchor4Header',
183 6
        ];
184
185
        // Do the specific filter
186 6
        $text = $this->current->text;
187
        switch ($filter) {
188 6
            case "jsonfrontmatter":
189 3
                $res = $this->jsonFrontMatter($text);
190 3
                $this->current->text = $res["text"];
191 3
                $this->addToFrontmatter($res["frontmatter"]);
192 3
                break;
193
194 4
            case "yamlfrontmatter":
195
                $res = $this->yamlFrontMatter($text);
196
                $this->current->text = $res["text"];
197
                $this->addToFrontmatter($res["frontmatter"]);
198
                break;
199
200 4 View Code Duplication
            case "titlefromh1":
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
201 1
                $title = $this->getTitleFromFirstH1($text);
202 1
                $this->current->text = $text;
203 1
                if (!isset($this->current->frontmatter["title"])) {
204 1
                    $this->addToFrontmatter(["title" => $title]);
205 1
                }
206 1
                break;
207
208 4 View Code Duplication
            case "titlefromheader":
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
209
                $title = $this->getTitleFromFirstHeader($text);
210
                $this->current->text = $text;
211
                if (!isset($this->current->frontmatter["title"])) {
212
                    $this->addToFrontmatter(["title" => $title]);
213
                }
214
                break;
215
216 4
            case "bbcode":
217 4
            case "clickable":
218 4
            case "shortcode":
219 4
            case "markdown":
220 4
            case "geshi":
221 4
            case "nl2br":
222 4
            case "htmlentities":
223 4
            case "purify":
224 4
            case "anchor4Header":
225 4
                $this->current->text = call_user_func_array(
226 4
                    [$this, $callbacks[$filter]],
227 4
                    [$text]
228 4
                );
229 4
                break;
230
231
            default:
232
                throw new Exception("The filter '$filter' is not a valid filter     string.");
233
        }
234 6
    }
235
236
237
238
    /**
239
     * Call each filter and return array with details of the formatted content.
240
     *
241
     * @param string $text   the text to filter.
242
     * @param array  $filter array of filters to use.
243
     *
244
     * @throws mos/TextFilter/Exception  when filterd does not exists.
245
     *
246
     * @return array with the formatted text and additional details.
247
     */
248 8
    public function parse($text, $filter)
249
    {
250 8
        $this->current = new \stdClass();
251 8
        $this->current->frontmatter = [];
252 8
        $this->current->text = $text;
253
254 8
        foreach ($filter as $key) {
255 6
            $this->parseFactory($key);
256 8
        }
257
258 8
        $this->current->text = $this->getUntilStop($this->current->text);
259
260 8
        return $this->current;
261
    }
262
263
264
265
    /**
266
     * Add excerpt as short version of text if available.
267
     *
268
     * @param object &$current same structure as returned by parse().
269
     *
270
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
271
     */
272 2
    public function addExcerpt($current)
273
    {
274 2
        list($excerpt, $hasMore) = $this->getUntilMore($current->text);
275 2
        $current->excerpt = $excerpt;
276 2
        $current->hasMore = $hasMore;
277 2
    }
278
279
280
281
    /**
282
     * Extract front matter from text.
283
     *
284
     * @param string $text       the text to be parsed.
285
     * @param string $startToken the start token.
286
     * @param string $stopToken  the stop token.
287
     *
288
     * @return array with the formatted text and the front matter.
289
     */
290 3
    private function extractFrontMatter($text, $startToken, $stopToken)
291
    {
292 3
        $tokenLength = strlen($startToken);
293
294 3
        $start = strpos($text, $startToken);
295
        // Is a valid start?
296 3
        if ($start !== false && $start !== 0) {
297
            if ($text[$start - 1] !== "\n") {
298
                $start = false;
299
            }
300
        }
301
302 3
        $frontmatter = null;
303 3
        if ($start !== false) {
304 3
            $stop = strpos($text, $stopToken, $tokenLength - 1);
305
306 3
            if ($stop !== false && $text[$stop - 1] === "\n") {
307 2
                $length = $stop - ($start + $tokenLength);
308
309 2
                $frontmatter = substr($text, $start + $tokenLength, $length);
310 2
                $textStart = substr($text, 0, $start);
311 2
                $text = $textStart . substr($text, $stop + $tokenLength);
312 2
            }
313 3
        }
314
315 3
        return [$text, $frontmatter];
316
    }
317
318
319
320
    /**
321
     * Extract JSON front matter from text.
322
     *
323
     * @param string $text the text to be parsed.
324
     *
325
     * @return array with the formatted text and the front matter.
326
     */
327 3 View Code Duplication
    public function jsonFrontMatter($text)
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...
328
    {
329 3
        list($text, $frontmatter) = $this->extractFrontMatter($text, "{{{\n", "}}}\n");
330
331 3
        if (!empty($frontmatter)) {
332 2
            $frontmatter = json_decode($frontmatter, true);
333
334 2
            if (is_null($frontmatter)) {
335
                throw new Exception("Failed parsing JSON frontmatter.");
336
            }
337 2
        }
338
339
        return [
340 3
            "text" => $text,
341
            "frontmatter" => $frontmatter
342 3
        ];
343
    }
344
345
346
347
    /**
348
     * Extract YAML front matter from text.
349
     *
350
     * @param string $text the text to be parsed.
351
     *
352
     * @return array with the formatted text and the front matter.
353
     */
354 View Code Duplication
    public function yamlFrontMatter($text)
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...
355
    {
356
        list($text, $frontmatter) = $this->extractFrontMatter($text, "---\n", "...\n");
357
358
        if (function_exists("yaml_parse") && !empty($frontmatter)) {
359
            $frontmatter = yaml_parse("---\n$frontmatter...\n");
360
361
            if ($frontmatter === false) {
362
                throw new Exception("Failed parsing YAML frontmatter.");
363
            }
364
        }
365
366
        return [
367
            "text" => $text,
368
            "frontmatter" => $frontmatter
369
        ];
370
    }
371
372
373
374
    /**
375
     * Get the title from the first H1.
376
     *
377
     * @param string $text the text to be parsed.
378
     *
379
     * @return string|null with the title, if its found.
380
     */
381 1 View Code Duplication
    public function getTitleFromFirstH1($text)
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...
382
    {
383 1
        $matches = [];
384 1
        $title = null;
385
386 1
        if (preg_match("#<h1.*?>(.*)</h1>#", $text, $matches)) {
387 1
            $title = strip_tags($matches[1]);
388 1
        }
389
390 1
        return $title;
391
    }
392
393
394
395
    /**
396
     * Get the title from the first header.
397
     *
398
     * @param string $text the text to be parsed.
399
     *
400
     * @return string|null with the title, if its found.
401
     */
402 View Code Duplication
    public function getTitleFromFirstHeader($text)
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...
403
    {
404
        $matches = [];
405
        $title = null;
406
407
        if (preg_match("#<h[1-6].*?>(.*)</h[1-6]>#", $text, $matches)) {
408
            $title = strip_tags($matches[1]);
409
        }
410
411
        return $title;
412
    }
413
414
415
416
    /**
417
     * Helper, BBCode formatting converting to HTML.
418
     *
419
     * @param string $text The text to be converted.
420
     *
421
     * @return string the formatted text.
422
     *
423
     * @link http://dbwebb.se/coachen/reguljara-uttryck-i-php-ger-bbcode-formattering
424
     */
425 3
    public function bbcode2html($text)
426
    {
427
        $search = [
428 3
            '/\[b\](.*?)\[\/b\]/is',
429 3
            '/\[i\](.*?)\[\/i\]/is',
430 3
            '/\[u\](.*?)\[\/u\]/is',
431 3
            '/\[img\](https?.*?)\[\/img\]/is',
432 3
            '/\[url\](https?.*?)\[\/url\]/is',
433
            '/\[url=(https?.*?)\](.*?)\[\/url\]/is'
434 3
        ];
435
436
        $replace = [
437 3
            '<strong>$1</strong>',
438 3
            '<em>$1</em>',
439 3
            '<u>$1</u>',
440 3
            '<img src="$1" />',
441 3
            '<a href="$1">$1</a>',
442
            '<a href="$1">$2</a>'
443 3
        ];
444
445 3
        return preg_replace($search, $replace, $text);
446
    }
447
448
449
450
    /**
451
     * Make clickable links from URLs in text.
452
     *
453
     * @param string $text the text that should be formatted.
454
     *
455
     * @return string with formatted anchors.
456
     *
457
     * @link http://dbwebb.se/coachen/lat-php-funktion-make-clickable-automatiskt-skapa-klickbara-lankar
458
     */
459 1
    public function makeClickable($text)
460
    {
461 1
        return preg_replace_callback(
462 1
            '#\b(?<![href|src]=[\'"])https?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#',
463 1
            function ($matches) {
464 1
                return "<a href='{$matches[0]}'>{$matches[0]}</a>";
465 1
            },
466
            $text
467 1
        );
468
    }
469
470
471
472
    /**
473
     * Syntax highlighter using GeSHi http://qbnz.com/highlighter/.
474
     *
475
     * @param string $text     text to be converted.
476
     * @param string $language which language to use for highlighting syntax.
477
     *
478
     * @return string the formatted text.
479
     */
480 1
    public function syntaxHighlightGeSHi($text, $language = "text")
481
    {
482 1
        $language = $language ?: "text";
483
        //$language = ($language === 'html') ? 'html4strict' : $language;
484 1
        $language = ($language === 'html') ? 'html5' : $language;
485
486 1
        $geshi = new \GeSHi($text, $language);
487 1
        $geshi->set_overall_class('geshi');
488 1
        $geshi->enable_classes('geshi');
0 ignored issues
show
Documentation introduced by
'geshi' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
489
        //$geshi->set_header_type(GESHI_HEADER_PRE_VALID);
490
        //$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
491 1
        $code = $geshi->parse_code();
492
493
        //echo "<pre>$language\n$code\n", $geshi->get_stylesheet(false) , "</pre>"; exit;
494
495
        // Replace last &nbsp;</pre>, -strlen("&nbsp;</pre>") == 12
496 1
        $length = strlen("&nbsp;</pre>");
497 1
        if (substr($code, -$length) == "&nbsp;</pre>") {
498 1
            $code = substr_replace($code, "</pre>", -$length);
499 1
        }
500
501 1
        return $code;
502
    }
503
504
505
506
    /**
507
     * Syntax highlighter using highlight.php, a port of highlight.js
508
     * https://packagist.org/packages/scrivo/highlight.php.
509
     *
510
     * @param string $text     text to be converted.
511
     * @param string $language which language to use for highlighting syntax.
512
     *
513
     * @return string the formatted text.
514
     */
515 1
    public function syntaxHighlightJs($text, $language = "text")
516
    {
517 1
        if ($language === "text" || empty($language)) {
518 1
            return "<pre>$text</pre>";
519
        }
520
521 1
        $highlight = new \Highlight\Highlighter();
522 1
        $res = $highlight->highlight($language, $text);
523
524 1
        return "<pre class=\"hljs\">$res->value</pre>";
525
    }
526
527
528
529
    /**
530
     * Format text according to HTML Purifier.
531
     *
532
     * @param string $text that should be formatted.
533
     *
534
     * @return string as the formatted html-text.
535
     */
536 1
    public function purify($text)
537
    {
538 1
        $config   = \HTMLPurifier_Config::createDefault();
539 1
        $config->set("Cache.DefinitionImpl", null);
540
        //$config->set('Cache.SerializerPath', '/home/user/absolute/path');
541
542 1
        $purifier = new \HTMLPurifier($config);
543
    
544 1
        return $purifier->purify($text);
545
    }
546
547
548
549
    /**
550
     * Format text according to Markdown syntax.
551
     *
552
     * @param string $text the text that should be formatted.
553
     *
554
     * @return string as the formatted html-text.
555
     */
556 8
    public function markdown($text)
557
    {
558 8
        $text = \Michelf\MarkdownExtra::defaultTransform($text);
559 8
        $text = \Michelf\SmartyPantsTypographer::defaultTransform(
560 8
            $text,
561
            \Michelf\SMARTYPANTS_ATTR_LONG_EM_DASH_SHORT_EN
562 8
        );
563 8
        return $text;
564
    }
565
566
567
568
    /**
569
     * For convenience access to nl2br
570
     *
571
     * @param string $text text to be converted.
572
     *
573
     * @return string the formatted text.
574
     */
575 1
    public function nl2br($text)
576
    {
577 1
        return nl2br($text);
578
    }
579
580
581
582
    /**
583
     * For convenience access to htmlentities
584
     *
585
     * @param string $text text to be converted.
586
     *
587
     * @return string the formatted text.
588
     */
589
    public function htmlentities($text)
590
    {
591
        return htmlentities($text);
592
    }
593
594
595
596
    /**
597
     * Support SmartyPants for better typography.
598
     *
599
     * @param string text text to be converted.
600
     * @return string the formatted text.
601
     */
602
/*     public static function SmartyPants($text) {   
603
      require_once(__DIR__.'/php_smartypants_1.5.1e/smartypants.php');
604
      return SmartyPants($text);
605
    }
606
*/
607
608
609
    /**
610
     * Support enhanced SmartyPants/Typographer for better typography.
611
     *
612
     * @param string text text to be converted.
613
     * @return string the formatted text.
614
     */
615
/*     public static function Typographer($text) {   
616
      require_once(__DIR__.'/php_smartypants_typographer_1.0/smartypants.php');
617
      $ret = SmartyPants($text);
618
      return $ret;
619
    }
620
*/
621
}
622