OutputHelper   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 17
c 1
b 0
f 0
dl 0
loc 40
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A catchOutput() 0 19 3
A exceptionHandler() 0 5 3
1
<?php
2
3
namespace kdn\yii2;
4
5
/**
6
 * Class OutputHelper.
7
 * @package kdn\yii2
8
 */
9
class OutputHelper
10
{
11
    /**
12
     * Call a user function given with an array of parameters and catch its output.
13
     * @param callable $callback function to be called
14
     * @param array $arguments parameters to be passed to the function, as an indexed array
15
     * @return array array containing result returned by function and its output.
16
     * @throws \Exception|\Throwable
17
     */
18
    public static function catchOutput($callback, $arguments = [])
19
    {
20
        $obInitialLevel = ob_get_level();
21
        ob_start();
22
        ob_implicit_flush(0);
23
        try {
24
            return [
25
                'result' => call_user_func_array($callback, $arguments),
26
                'output' => ob_get_clean(),
27
            ];
28
        } catch (\Exception $e) {
29
            static::exceptionHandler($obInitialLevel);
30
31
            throw $e;
32
        } /* @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ catch (\Throwable $e) {
33
            // additional check for \Throwable introduced in PHP 7
34
            static::exceptionHandler($obInitialLevel);
35
36
            throw $e;
37
        }
38
    }
39
40
    /**
41
     * Closes the output buffer opened above if it has not been closed already.
42
     * @param int $obInitialLevel initial level of the output buffering mechanism
43
     */
44
    protected static function exceptionHandler($obInitialLevel)
45
    {
46
        while (ob_get_level() > $obInitialLevel) {
47
            if (!@ob_end_clean()) {
48
                ob_clean();
49
            }
50
        }
51
    }
52
}
53