CallableMessageHandler::handle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 5 Features 0
Metric Value
c 6
b 5
f 0
dl 0
loc 11
rs 9.4285
cc 3
eloc 7
nc 3
nop 3
1
<?php
2
3
namespace PEIP\Message;
4
5
/*
6
 * This file is part of the PEIP package.
7
 * (c) 2009-2016 Timo Michna <timomichna/yahoo.de>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
/**
14
 * CallableMessageHandler.
15
 *
16
 * @author Timo Michna <timomichna/yahoo.de>
17
 * @implements \PEIP\INF\Handler\Handler
18
 */
19
class CallableMessageHandler implements \PEIP\INF\Handler\Handler
20
{
21
    protected $callable,
22
        $requiredParameters;
23
24
    /**
25
     * @param $callable
26
     *
27
     * @return
28
     */
29
    public function __construct($callable)
30
    {
31
        $this->callable = $callable;
32
        $this->examineCallabe();
33
    }
34
35
    /**
36
     * @return
37
     */
38
    protected function examineCallabe()
39
    {
40
        if (is_callable($this->callable)) {
41
            if (is_array($this->callable)) {
42
                list($class, $method) = $this->callable;
43
                $static = !is_object($class);
44
                $class = is_object($class) ? get_class($class) : (string) $class;
45
                $reflectionClass = new \ReflectionClass($class);
46
                $reflectionFunc = $reflectionClass->getMethod($method);
47
                if ($static && !$reflectionFunc->isStatic()) {
48
                    throw new \InvalidArgumentException('Argument 1 passed to CallableMessageHandler::__construct is not an Callable: Method "'.$method.'" of class '.$class.' is not static.');
49
                }
50
            } else {
51
                $reflectionFunc = new \ReflectionFunction($this->callable);
52
            }
53
            $this->requiredParameters = $reflectionFunc->getNumberOfRequiredParameters();
54
        } else {
55
            throw new \InvalidArgumentException('Argument 1 passed to CallableMessageHandler::__construct is not a Callable');
56
        }
57
    }
58
59
    /**
60
     * @param $message
61
     * @param $channel
62
     * @param $sent
63
     *
64
     * @return
65
     */
66
    public function handle($message, $channel = false, $sent = false)
67
    {
68
        if (!is_object($message)) {
69
            throw new \InvalidArgumentException('Argument 1 passed to CallableMessageHandler::handle is not a Object');
70
        }
71
        try {
72
            return call_user_func_array($this->callable, [$message, $channel, $sent]);
73
        } catch (\Exception $e) {
74
            throw new \RuntimeException('Unable to call Callable: '.$e->getMessage());
75
        }
76
    }
77
}
78