1<?php
2/**
3 * Zend Framework (http://framework.zend.com/)
4*
5* @link      http://github.com/zendframework/zf2 for the canonical source repository
6* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7* @license   http://framework.zend.com/license/new-bsd New BSD License
8*/
9
10namespace Zend\Log\Processor;
11
12class Backtrace implements ProcessorInterface
13{
14    /**
15     * Maximum stack level of backtrace (PHP > 5.4.0)
16     * @var int
17     */
18    protected $traceLimit = 10;
19
20    /**
21     * Classes within this namespace in the stack are ignored
22     * @var string
23     */
24    protected $ignoredNamespace = 'Zend\\Log';
25
26    /**
27     * Adds the origin of the log() call to the event extras
28     *
29     * @param array $event event data
30     * @return array event data
31    */
32    public function process(array $event)
33    {
34        $trace = $this->getBacktrace();
35
36        array_shift($trace); // ignore $this->getBacktrace();
37        array_shift($trace); // ignore $this->process()
38
39        $i = 0;
40        while (isset($trace[$i]['class'])
41               && false !== strpos($trace[$i]['class'], $this->ignoredNamespace)
42        ) {
43            $i++;
44        }
45
46        $origin = array(
47            'file'     => isset($trace[$i-1]['file'])   ? $trace[$i-1]['file']   : null,
48            'line'     => isset($trace[$i-1]['line'])   ? $trace[$i-1]['line']   : null,
49            'class'    => isset($trace[$i]['class'])    ? $trace[$i]['class']    : null,
50            'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null,
51        );
52
53        $extra = $origin;
54        if (isset($event['extra'])) {
55            $extra = array_merge($origin, $event['extra']);
56        }
57        $event['extra'] = $extra;
58
59        return $event;
60    }
61
62    /**
63     * Provide backtrace as slim as possible
64     *
65     * @return array[]
66     */
67    protected function getBacktrace()
68    {
69        if (PHP_VERSION_ID >= 50400) {
70            return debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $this->traceLimit);
71        }
72
73        return debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
74    }
75}
76