Completed
Pull Request — master (#56)
by
unknown
02:00
created

ContentDecorator::params()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Yiisoft\Widget;
5
6
/**
7
 * ContentDecorator records all output between {@see begin()} and {@see end()]} calls, passes it to the given view file
8
 * as `$content` and then echoes rendering result.
9
 *
10
 * ```php
11
 * <?php ContentDecorator::begin()
12
 *     ->viewFile('@app/views/layouts/base.php'),
13
 *     ->params([]),
14
 *     ->view($this),
15
 * ]) ?>
16
 *
17
 * some content here
18
 *
19
 * <?php ContentDecorator::end() ?>
20
 * ```
21
 *
22
 * There are {@see \Yiisoft\View\View::beginContent()} and {@see \Yiisoft\View\View::endContent()} wrapper methods in
23
 * the {@see \Yiisoft\View\View} component to make syntax more friendly. In the view these could be used as follows:
24
 *
25
 * ```php
26
 * <?php $this->beginContent('@app/views/layouts/base.php') ?>
27
 *
28
 * some content here
29
 *
30
 * <?php $this->endContent() ?>
31
 * ```
32
 *
33
 * @method static ContentDecorator begin()
34
 * @method static ContentDecorator end()
35
 */
36
class ContentDecorator extends Widget
37
{
38
    /**
39
     * @var array the parameters (name => value) to be extracted and made available in the decorative view.
40
     */
41
    private $params = [];
42
43
    /**
44
     * @var string the view file that will be used to decorate the content enclosed by this widget. This can be
45
     *             specified as either the view file path or alias path.
46
     */
47
    private $viewFile;
48
49
    public function init(): void
50
    {
51
        parent::init();
52
53
        // Starts recording a clip.
54
        ob_start();
55
        ob_implicit_flush(0);
56
    }
57
58
    /**
59
     * Ends recording a clip.
60
     * This method stops output buffering and saves the rendering result as a named clip in the controller.
61
     *
62
     * @return string the result of widget execution to be outputted.
63
     */
64
    public function run(): string
65
    {
66
        $params = $this->params;
67
        $params['content'] = ob_get_clean();
68
69
        // render under the existing context
70
71
        return $this->getView()->renderFile($this->viewFile, $params);
72
    }
73
74
    public function params(array $value): self
75
    {
76
        $this->params = $value;
77
78
        return $this;
79
    }
80
81
    public function viewFile(string $value): self
82
    {
83
        $this->viewFile = $value;
84
85
        return $this;
86
    }
87
}
88