summaryrefslogtreecommitdiff
path: root/zend/exception_handler.cpp
blob: 66034e260124e3512135c0ed585d77d86a7c46da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
 *  Exception_handler.cpp
 *
 *  Set the exception handler
 *
 *  @author Toon Schoenmakers <toon.schoenmakers@copernica.com>
 */

/**
 *  Dependencies
 */
#include "includes.h"

/**
 *  Open the PHP namespace
 */
namespace Php {

/**
 *  Set a std::function as a php exception handler
 */
Value set_exception_handler(const std::function<Value(Parameters &params)> &handler)
{
    // we need the tsrm_ls variable
    TSRMLS_FETCH();

    // create a functor which wraps our callback
    Function functor(handler);

    // initialize our output value
    Value output;

    // turn our user_exception_handler into a Value so we can return the original one later on
    if (!Z_ISNULL(EG(user_exception_handler))) output = &EG(user_exception_handler);

    // detach so we have the zval
    auto value = functor.detach(true);

    // copy our zval into the user_exception_handler
    ZVAL_COPY(value, &EG(user_exception_handler));

    // return the original handler
    return output;
}

/**
 *  Set a std::function as a php error handler
 */
Value set_error_handler(const std::function<Value(Parameters &params)> &handler, Error error)
{
    // we need the tsrm_ls variable
    TSRMLS_FETCH();

    // create the functor which wraps our callback
    Function functor(handler);

    // initialize our output value
    Value output;

    // turn our user_error_handler into a Value if we have one, just so we can return it later on
    if (!Z_ISNULL(EG(user_error_handler))) output = &EG(user_error_handler);

    // detach so we have the zval
    auto value = functor.detach(true);

    // copy our zval into the user_error_handler
    ZVAL_COPY(value, &EG(user_error_handler));
    EG(user_error_handler_error_reporting) = (int) error;

    // return the original handler
    return output;
}

/**
 *  Modify the error reporting level, will return the old error reporting level.
 */
Value error_reporting(Error error)
{
    // we need the tsrm_ls variable
    TSRMLS_FETCH();

    // store the old error reporting value
    Value output(EG(error_reporting));

    // create a small temporary buffer
    char str[21];

    // write the level into this buffer
    int size = sprintf(str, "%d", (int) error);

    // if we failed for some reason we bail out
    if (size < 0) return false;

    // alter the ini on the fly
    zend_alter_ini_entry(zend_string_init("error_reporting", sizeof("error_reporting"), 1), zend_string_init(str, size, 1), ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);

    // return the output
    return output;
}

/**
 *  End of namespace
 */
}