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

ContentDecorator::run()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 1
    public function init(): void
50
    {
51 1
        parent::init();
52
53
        // Starts recording a clip.
54 1
        ob_start();
55 1
        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 1
    public function run(): string
65
    {
66 1
        $params = $this->params;
67 1
        $params['content'] = ob_get_clean();
68
69
        // render under the existing context
70
71 1
        return $this->getView()->renderFile($this->viewFile, $params);
72
    }
73
74 1
    public function params(array $value): self
75
    {
76 1
        $this->params = $value;
77
78 1
        return $this;
79
    }
80
81 1
    public function viewFile(string $value): self
82
    {
83 1
        $this->viewFile = $value;
84
85 1
        return $this;
86
    }
87
}
88