Completed
Pull Request — master (#52)
by Alexander
03:31
created

Spaceless::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
rs 10
ccs 4
cts 4
cp 1
cc 1
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Yiisoft\Widget;
5
6
/**
7
 * Spaceless widget removes whitespace characters between HTML tags. Whitespaces within HTML tags or in a plain text are
8
 * always left untouched.
9
 *
10
 * Usage example:
11
 *
12
 * ```php
13
 * <body>
14
 *     <?php Spaceless::begin(); ?>
15
 *         <div class="nav-bar">
16
 *             <!-- tags -->
17
 *         </div>
18
 *         <div class="content">
19
 *             <!-- tags -->
20
 *         </div>
21
 *     <?php Spaceless::end(); ?>
22
 * </body>
23
 * ```
24
 *
25
 * This example will generate the following HTML:
26
 *
27
 * ```html
28
 * <body>
29
 *     <div class="nav-bar"><!-- tags --></div><div class="content"><!-- tags --></div></body>
30
 * ```
31
 *
32
 * This method is not designed for content compression (you should use `gzip` output compression to achieve it). Main
33
 * intention is to strip out extra whitespace characters between HTML tags in order to avoid browser rendering quirks
34
 * in some circumstances (e.g. newlines between inline-block elements).
35
 *
36
 * Note, never use this method with `pre` or `textarea` tags. It's not that trivial to deal with such tags as it may
37
 * seem at first sight. For this case you should consider using [HTML Tidy Project](http://tidy.sourceforge.net/)
38
 * instead.
39
 *
40
 * @see http://tidy.sourceforge.net/
41
 */
42
class Spaceless extends Widget
43
{
44
    /**
45
     * Starts capturing an output to be cleaned from whitespace characters between HTML tags.
46
     */
47 2
    public function init(): void
48
    {
49 2
        parent::init();
50
51 2
        ob_start();
52 2
        ob_implicit_flush(0);
53
    }
54
55
    /**
56
     * Marks the end of content to be cleaned from whitespace characters between HTML tags.
57
     * Stops capturing an output and returns cleaned result.
58
     *
59
     * @return string the result of widget execution to be outputted.
60
     */
61 2
    public function run(): string
62
    {
63 2
        return trim(preg_replace('/>\s+</', '><', ob_get_clean()));
64
    }
65
}
66