Completed
Push — master ( 6a7454...e111d0 )
by Dmitry
04:41
created

OutputHelper::exceptionHandler()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
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(false);
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
            throw $e;
31
        } catch (\Throwable $e) { // before PHP 7, \Exception did not implement the \Throwable interface
1 ignored issue
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
32
            static::exceptionHandler($obInitialLevel);
33
            throw $e;
34
        }
35
    }
36
37
    /**
38
     * Closes the output buffer opened above if it has not been closed already.
39
     * @param int $obInitialLevel initial level of the output buffering mechanism
40
     */
41
    protected static function exceptionHandler($obInitialLevel)
42
    {
43
        while (ob_get_level() > $obInitialLevel) {
44
            if (!@ob_end_clean()) {
45
                ob_clean();
46
            }
47
        }
48
    }
49
}
50