SoapDispatcherCallHandler   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 150
rs 10
c 0
b 0
f 0
wmc 21
lcom 0
cbo 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
D __call() 0 119 20
1
<?php
2
3
// +---------------------------------------------------------------------------+
4
// | This file is part of the Agavi package.                                   |
5
// | Copyright (c) 2005-2011 the Agavi Project.                                |
6
// | Based on the Mojavi3 MVC Framework, Copyright (c) 2003-2005 Sean Kerr.    |
7
// |                                                                           |
8
// | For the full copyright and license information, please view the LICENSE   |
9
// | file that was distributed with this source code. You can also view the    |
10
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
11
// |   vi: set noexpandtab:                                                    |
12
// |   Local Variables:                                                        |
13
// |   indent-tabs-mode: t                                                     |
14
// |   End:                                                                    |
15
// +---------------------------------------------------------------------------+
16
17
/**
18
 * SoapDispatcherCallHandler has the __call overload for the PHP SOAP ext.
19
 *
20
 * @package    agavi
21
 * @subpackage Dispatcher
22
 *
23
 * @author     David Zülke <[email protected]>
24
 * @copyright  Authors
25
 * @copyright  The Agavi Project
26
 *
27
 * @since      0.11.0
28
 *
29
 * @version    $Id$
30
 */
31
32
namespace Agavi\Dispatcher;
33
34
use Agavi\Core\Context;
35
use Agavi\Request\SoapRequest;
36
37
class SoapDispatcherCallHandler
38
{
39
    /**
40
     * @var        Context The context.
41
     */
42
    protected $context;
43
    
44
    /**
45
     * Constructor.
46
     *
47
     * @param      Context $context  The current Context.
48
     *
49
     * @author     David Zülke <[email protected]>
50
     * @since      0.11.0
51
     */
52
    public function __construct(Context $context)
53
    {
54
        $this->context = $context;
55
    }
56
    
57
    /**
58
     * Call overload run by PHP's SoapServer while attempting to execute the
59
     * method called in the SOAP request.
60
     *
61
     * @param      string $name      The name of the SOAP method called.
62
     * @param      array  $arguments An array of parameters from the method call.
63
     *
64
     * @author     David Zülke <[email protected]>
65
     * @since      0.11.0
66
     */
67
    public function __call($name, $arguments)
68
    {
69
        /** @var SoapDispatcher $ct */
70
        $ct = $this->context->getDispatcher();
71
72
        /** @var SoapRequest $rq */
73
        $rq = $this->context->getRequest();
74
        
75
        // set the name of the method that was called
76
        // the request will also update the routing input
77
        $rq->setInvokedMethod($name);
78
        
79
        // then we grab the SoapClient with the WSDL (yes, SoapClient!)
80
        // and grab a list of functions. in SoapClient, that list contains the method signatures, including the parameter names. SoapServer's __getFunctions() doesn't...
81
        $functions = $ct->getSoapClient()->__getFunctions();
82
        foreach ($functions as $function) {
83
            // now we try to match the called method against the function signatures
84
            if (preg_match('/^(?:\S+|list\([^\)]*\))\s' . preg_quote($name, '/') . '\(([^\)]*)\)$/', $function, $matches)) {
85
                // we found something, so we can extract all method argument names
86
                preg_match_all('/\$([\w]+)/', $matches[1], $params);
87
                for ($i = 0; $i < count($params[1]); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
88
                    // and replace the numeric keys from our method call args with the actual parameter names as defined in the WSDL
89
                    $arguments[$params[1][$i]] = $arguments[$i];
90
                    unset($arguments[$i]);
91
                }
92
                // and while we're at it, please get us the name of the return value as well, we need it in document/literal wrapped WSDL styles
93
                $returnType = '';
94
                if (preg_match('/^(\w+) /', $function, $matches)) {
95
                    $returnType = $matches[1];
96
                }
97
                break;
98
            }
99
        }
100
        // all that was done because PHP's SOAP extension doesn't allow us to get information about the request. In SOAP, remote methods are always defined using named parameters, but that naming gets lost as PHP calls the respective function on the server directly, and PHP doesn't have named arguments. So all we know is the values that were given for the first, second, and so on parameter. But in Agavi, we want to access parameters by their names. We made it. With an ugly hack. Thank you, Zend.
101
        
102
        // for document/literal wrapped style services, unpack the complex type passed in by php, see http://bugs.php.net/bug.php?id=30302 - PHP produces an stdClass object with named members.
103
        if ($ct->getParameter('force_document_literal_wrapped_marshalling', false)) {
104
            $unpackedArguments = array();
105
            foreach ($arguments as $argument) {
106
                foreach ($argument as $name => $value) {
107
                    $unpackedArguments[$name] = $value;
108
                }
109
            }
110
            $arguments = $unpackedArguments;
111
        }
112
        
113
        // finally, we can populate the request with the final data and call the _real_ dispatch() method on the "normal" Dispatcher. We hand it the arguments we got in the SOAP request. Everyone's happy.
114
        $rd = $rq->getRequestData();
115
        
116
        $rd->setParameters($arguments);
117
        
118
        // call doDispatch on the Dispatcher
119
        $response = $ct->doDispatch();
120
        $responseContent = $response->getContent();
121
        
122
        // repack the document/literal wrapped content if required
123
        if ($ct->getParameter('force_document_literal_wrapped_marshalling', false)) {
124
            // the return type is a complex type with a single element, but what's the name of that element?
125
            // struct methodNameResponse {
126
            //   typeName returnValueName;
127
            // }
128
            // it may also be empty, depending on the definition (if the request/response has a void input/output):
129
            // struct deleteEverything {
130
            // }
131
            
132
            // do not wrap soap faults
133
            if (!($responseContent instanceof \SoapFault)) {
134
                $originalResponseContent = $responseContent;
135
                $wrapperFound = false;
136
                foreach ($ct->getSoapClient()->__getTypes() as $type) {
137
                    if ($originalResponseContent !== null && preg_match('/^struct ' . preg_quote($returnType, '/') . ' \{\s*(.+)\s*\}$/s', $type, $matches)) {
138
                        // next: extract all the return value part names (usually just one)
139
                        $returnPartCount = preg_match_all('/^\s*(?P<type>\w+) (?P<name>\w+);$/m', $matches[1], $returnParts);
140
                        
141
                        // we convert the response content to an array if it's exactly one return part
142
                        // so the code further down works without additional checks
143
                        // a check like !is_array() would be wrong as the return value might be an array itself already (e.g. for a list of objects)
144
                        if ($returnPartCount == 1) {
145
                            $originalResponseContent = array($originalResponseContent);
146
                        }
147
                        
148
                        $responseContent = new \stdClass();
149
                        
150
                        // it *should* be an array with return parts as keys, but doesn't have to be (first because PHP allows this, and second because we do this a couple of lines above)
151
                        // so we need to iterate by hand and check for named key first, numeric offset second
152
                        for ($i = 0; $i < $returnPartCount; $i++) {
153
                            $returnPartName = $returnParts['name'][$i];
154
                            
155
                            if (array_key_exists($returnPartName, $originalResponseContent)) {
156
                                $returnPartValue = $originalResponseContent[$returnPartName];
157
                            } elseif (array_key_exists($i, $originalResponseContent)) {
158
                                $returnPartValue = $originalResponseContent[$i];
159
                            } else {
160
                                // nothing found
161
                                // that means the response was invalid or something... we should bail out here, so $wrapperFound won't be true and the next type is tried
162
                                continue 2;
163
                            }
164
                            
165
                            $responseContent->$returnPartName = $returnPartValue;
166
                        }
167
                        
168
                        // we set $wrapperFound only now
169
                        $wrapperFound = true;
170
                        break;
171
                    } elseif ($originalResponseContent === null && preg_match('/^struct ' . preg_quote($returnType, '/') . ' \{\s*\}$/s', $type, $matches)) {
0 ignored issues
show
Bug introduced by
The variable $returnType does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
172
                        $wrapperFound = true;
173
                        $responseContent = new \stdClass();
174
                        break;
175
                    }
176
                }
177
                if (!$wrapperFound) {
178
                    $responseContent = new \SoapFault('Server', 'Failed to marshal document/literal wrapped response: no suitable type found.');
179
                }
180
            }
181
        }
182
        
183
        // return the content. that's an array, or a float, or whatever, and PHP's SOAP extension will handle the response envelope creation, sending etc for us
184
        return $responseContent;
185
    }
186
}
187