Completed
Push — master ( b1b8c7...b37043 )
by Timo
06:43
created

Apache_Solr_Response::_parseData()   C

Complexity

Conditions 12
Paths 3

Size

Total Lines 41
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 18
nc 3
nop 0
dl 0
loc 41
rs 5.1612
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Copyright (c) 2007-2011, Servigistics, Inc.
4
 * All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions are met:
8
 *
9
 *  - Redistributions of source code must retain the above copyright notice,
10
 *    this list of conditions and the following disclaimer.
11
 *  - Redistributions in binary form must reproduce the above copyright
12
 *    notice, this list of conditions and the following disclaimer in the
13
 *    documentation and/or other materials provided with the distribution.
14
 *  - Neither the name of Servigistics, Inc. nor the names of
15
 *    its contributors may be used to endorse or promote products derived from
16
 *    this software without specific prior written permission.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
 * POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * @copyright Copyright 2007-2011 Servigistics, Inc. (http://servigistics.com)
31
 * @license http://solr-php-client.googlecode.com/svn/trunk/COPYING New BSD
32
 * @version $Id$
33
 *
34
 * @package Apache
35
 * @subpackage Solr
36
 * @author Donovan Jimenez <[email protected]>
37
 */
38
39
require_once(dirname(__FILE__) . '/ParserException.php');
40
41
/**
42
 * Represents a Solr response.  Parses the raw response into a set of stdClass objects
43
 * and associative arrays for easy access.
44
 *
45
 * Currently requires json_decode which is bundled with PHP >= 5.2.0, Alternatively can be
46
 * installed with PECL.  Zend Framework also includes a purely PHP solution.
47
 */
48
class Apache_Solr_Response
49
{
50
    /**
51
     * SVN Revision meta data for this class
52
     */
53
    const SVN_REVISION = '$Revision$';
54
55
    /**
56
     * SVN ID meta data for this class
57
     */
58
    const SVN_ID = '$Id$';
59
60
    /**
61
     * Holds the raw response used in construction
62
     *
63
     * @var Apache_Solr_HttpTransport_Response HTTP response
64
     */
65
    protected $_response;
66
67
    /**
68
     * Whether the raw response has been parsed
69
     *
70
     * @var boolean
71
     */
72
    protected $_isParsed = false;
73
74
    /**
75
     * Parsed representation of the data
76
     *
77
     * @var mixed
78
     */
79
    protected $_parsedData;
80
81
    /**
82
     * Data parsing flags.  Determines what extra processing should be done
83
     * after the data is initially converted to a data structure.
84
     *
85
     * @var boolean
86
     */
87
    protected $_createDocuments = true,
88
        $_collapseSingleValueArrays = true;
89
90
    /**
91
     * Constructor. Takes the raw HTTP response body and the exploded HTTP headers
92
     *
93
     * @return Apache_Solr_HttpTransport_Response HTTP response
94
     * @param boolean $createDocuments Whether to convert the documents json_decoded as stdClass instances to Apache_Solr_Document instances
95
     * @param boolean $collapseSingleValueArrays Whether to make multivalued fields appear as single values
96
     */
97
    public function __construct(
98
        Apache_Solr_HttpTransport_Response $response,
99
        $createDocuments = true,
100
        $collapseSingleValueArrays = true
101
    ) {
102
        $this->_response = $response;
103
        $this->_createDocuments = (bool)$createDocuments;
104
        $this->_collapseSingleValueArrays = (bool)$collapseSingleValueArrays;
105
    }
106
107
    /**
108
     * Get the HTTP status code
109
     *
110
     * @return integer
111
     */
112
    public function getHttpStatus()
113
    {
114
        return $this->_response->getStatusCode();
115
    }
116
117
    /**
118
     * Get the HTTP status message of the response
119
     *
120
     * @return string
121
     */
122
    public function getHttpStatusMessage()
123
    {
124
        return $this->_response->getStatusMessage();
125
    }
126
127
    /**
128
     * Get content type of this Solr response
129
     *
130
     * @return string
131
     */
132
    public function getType()
133
    {
134
        return $this->_response->getMimeType();
135
    }
136
137
    /**
138
     * Get character encoding of this response. Should usually be utf-8, but just in case
139
     *
140
     * @return string
141
     */
142
    public function getEncoding()
143
    {
144
        return $this->_response->getEncoding();
145
    }
146
147
    /**
148
     * Get the raw response as it was given to this object
149
     *
150
     * @return string
151
     */
152
    public function getRawResponse()
153
    {
154
        return $this->_response->getBody();
155
    }
156
157
    /**
158
     * Magic get to expose the parsed data and to lazily load it
159
     *
160
     * @param string $key
161
     * @return mixed
162
     */
163
    public function __get($key)
164
    {
165
        if (!$this->_isParsed) {
166
            $this->_parseData();
167
            $this->_isParsed = true;
168
        }
169
170
        if (isset($this->_parsedData->$key)) {
171
            return $this->_parsedData->$key;
172
        }
173
174
        return null;
175
    }
176
177
    /**
178
     * Parse the raw response into the parsed_data array for access
179
     *
180
     * @throws Apache_Solr_ParserException If the data could not be parsed
181
     */
182
    protected function _parseData()
183
    {
184
        //An alternative would be to use Zend_Json::decode(...)
185
        $data = json_decode($this->_response->getBody());
186
187
        // check that we receive a valid JSON response - we should never receive a null
188
        if ($data === null) {
189
            throw new Apache_Solr_ParserException('Solr response does not appear to be valid JSON, please examine the raw response with getRawResponse() method');
190
        }
191
192
        //if we're configured to collapse single valued arrays or to convert them to Apache_Solr_Document objects
193
        //and we have response documents, then try to collapse the values and / or convert them now
194
        if (($this->_createDocuments || $this->_collapseSingleValueArrays) && isset($data->response) && is_array($data->response->docs)) {
195
            $documents = array();
196
197
            foreach ($data->response->docs as $originalDocument) {
198
                if ($this->_createDocuments) {
199
                    $document = new Apache_Solr_Document();
200
                } else {
201
                    $document = $originalDocument;
202
                }
203
204
                foreach ($originalDocument as $key => $value) {
205
                    //If a result is an array with only a single
206
                    //value then its nice to be able to access
207
                    //it as if it were always a single value
208
                    if ($this->_collapseSingleValueArrays && is_array($value) && count($value) <= 1) {
209
                        $value = array_shift($value);
210
                    }
211
212
                    $document->$key = $value;
213
                }
214
215
                $documents[] = $document;
216
            }
217
218
            $data->response->docs = $documents;
219
        }
220
221
        $this->_parsedData = $data;
222
    }
223
224
    /**
225
     * Magic function for isset function on parsed data
226
     *
227
     * @param string $key
228
     * @return boolean
229
     */
230
    public function __isset($key)
231
    {
232
        if (!$this->_isParsed) {
233
            $this->_parseData();
234
            $this->_isParsed = true;
235
        }
236
237
        return isset($this->_parsedData->$key);
238
    }
239
}
240