Pool::unwrap()   C
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 13.2607

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 34
ccs 13
cts 23
cp 0.5652
rs 5.3846
cc 8
eloc 20
nc 6
nop 0
crap 13.2607
1
<?php
2
/**
3
 * Created by Maciej Paprocki for Bureau-VA.
4
 * Date: 23/02/2016
5
 * Project Name: MaciekPaprocki\WordpressGuzzle
6
 * Time: 17:38.
7
 */
8
namespace BureauVa\WordpressGuzzle;
9
10
use Guzzle\Http\Message\Response;
11
use GuzzleHttp\Promise\Promise;
12
use GuzzleHttp\Client;
13
use GuzzleHttp\Exception\RequestException;
14
use Cache\Adapter\Common\AbstractCachePool;
15
16
/**
17
 * Class Pool.
18
 */
19
class Pool {
20
	/**
21
	 * @var array
22
	 */
23
	private $queries = [ ];
24
	/**
25
	 * @var array
26
	 */
27
	private $promises = [ ];
28
	/**
29
	 * @var array
30
	 */
31
	private $transformers = [ ];
32
	/**
33
	 * @var AbstractCachePool
34
	 */
35
	private $cachePool = null;
36
	/**
37
	 * @var Client
38
	 */
39
	protected $client = null;
40
	/**
41
	 * @var bool|string
42
	 */
43
	private $cacheKey = false;
44
	/**
45
	 * @var array
46
	 */
47
	private $cacheData = [ ];
48
	/**
49
	 * This will be mostly used for testing.
50
	 * It also gives quite good informations on life of object for debugging.
51
	 *
52
	 * @var array
53
	 */
54
	public $debug = [
55
		'attachedqueries'          => 0,
56
		'attachedpromises'         => 0,
57
		'executedqueries'          => 0,
58
		'executedpromises'         => 0, //will include also queries
59
		'queriesrestoredfromcache' => 0,
60
	];
61
62
	/**
63
	 * Pool constructor.
64
	 */
65 2
	public function __construct() {
66 2
		$this->cachePool = new Helper\EmptyCache();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \BureauVa\WordpressGuzzle\Helper\EmptyCache() of type object<BureauVa\Wordpres...zzle\Helper\EmptyCache> is incompatible with the declared type object<Cache\Adapter\Common\AbstractCachePool> of property $cachePool.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
67 2
	}
68
69
	/**
70
	 * let us keep reference to our client.
71
	 *
72
	 * @return mixed
73
	 */
74 2
	public function getClient() {
75 2
		return $this->client;
76
	}
77
78
	/**
79
	 * Awaits all the requests attaching callbacks before.
80
	 *
81
	 * @return mixed
82
	 */
83 2
	public function unwrap() {
84
		//Deals with whole pool cache
85 2
		if ( $this->getCachePool() &&
86 2
		     $this->getCacheKey() &&
87 2
		     ( $cacheItem = $this->getCachePool()->getItem( $this->getCacheKey() ) ) &&
0 ignored issues
show
Bug introduced by
It seems like $this->getCacheKey() targeting BureauVa\WordpressGuzzle\Pool::getCacheKey() can also be of type boolean; however, Cache\Adapter\Common\AbstractCachePool::getItem() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
88 1
		     $cacheItem->isHit()
89 1
		) {
90
			return $cacheItem->get();
91
		}
92
93 2
		$promises = $this->flushPromises();
94
95 2
		if ( empty( $promises ) ) {
96 2
			return [ ];
97
		}
98
99 2
		foreach ( $promises as $key => $promise ) {
100 2
			$promises[ $key ] = $this->attachTransforms( $promise );
101 1
		}
102
103 2
		$res = \GuzzleHttp\Promise\unwrap( $promises );
104
		$res = array_merge( $this->cacheData, $res );
105
		//saves pool cache
106
		if ( $this->getCacheKey() ) {
107
			$cacheItem = $this->getCachePool()->getItem( $this->getCacheKey() );
0 ignored issues
show
Bug introduced by
It seems like $this->getCacheKey() targeting BureauVa\WordpressGuzzle\Pool::getCacheKey() can also be of type boolean; however, Cache\Adapter\Common\AbstractCachePool::getItem() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
108
			$cacheItem->set( $res );
109
		}
110
		// clearing so the pool can be reused.
111
		$this->promises  = [ ];
112
		$this->cacheData = [ ];
113
		$this->queries   = [ ];
114
115
		return $res;
116
	}
117
118
	/**
119
	 * @return array
120
	 */
121 2
	private function flushPromises() {
122 2
		foreach ( $this->queries as $key => $query ) {
123 2
			$cacheKey = $query->getCacheKey();
124
			// checks if cache exists for the requests. if not pass it to promise.
125 2
			if ( ! ( $cacheKey &&
126 2
			         ( $cacheItem = $this->getCachePool()->getItem( $cacheKey ) ) &&
127 1
			         $cacheItem->isHit() )
128 1
			) {
129 2
				++ $this->debug['executedqueries'];
130 2
				$this->promises[ $key ] = $this->client->getAsync( (string) $query );
131 1
			} elseif ( $cacheKey ) {
132
				$this->cacheData[ $key ] = $cacheItem->get();
0 ignored issues
show
Bug introduced by
The variable $cacheItem 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...
133
			}
134
135 2
			unset( $this->queries[ $key ] );
136 1
		}
137
138 2
		return $this->promises;
139
	}
140
141
	/**
142
	 * @param Promise $req
143
	 *
144
	 * @return Promise Promise with attached transformers
145
	 */
146 2
	private function attachTransforms( Promise $req ) {
147 2
		$transformers = $this->getTransformers();
148
149
		return $req->then( function ( Response $res ) use ( $transformers ) {
150
151
			$data = \json_decode( (string) $res->getBody() );
152
153
			if ( is_object( $data ) ) {
154
				foreach ( $transformers as $transformer ) {
155
					$data = \call_user_func( $transformer, $data );
156
				}
157
			} elseif ( is_array( $data ) ) {
158
				foreach ( $data as $key => $val ) {
159
					foreach ( $transformers as $transformer ) {
160
						$data[ $key ] = \call_user_func( $transformer, $val );
161
					}
162
				}
163
			}
164
165
			return $data;
166 2
		}, function ( RequestException $e ) {
0 ignored issues
show
Unused Code introduced by
The parameter $e is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
167
168 2
		} );
169
	}
170
171
	/**
172
	 * GETTERS AND SETTERS.
173
	 */
174
	/**
175
	 * @param $query
176
	 *
177
	 * @return $this
178
	 */
179 2
	public function addQuery( $key, $query ) {
180 2
		++ $this->debug['attachedqueries'];
181 2
		$this->queries[ $key ] = $query;
182
183 2
		return $this;
184
	}
185
186
	/**
187
	 * @param Promise $promise
188
	 */
189 2
	public function addPromise( $name, Promise $promise ) {
190 2
		++ $this->debug['attachedpromises'];
191 2
		$this->promises[ $name ] = $promise;
192 2
	}
193
194
	/**
195
	 * @return array
196
	 */
197 2
	public function getTransformers() {
198 2
		return $this->transformers;
199
	}
200
201
	/**
202
	 * Adds another transformer to collection of transformers.
203
	 *
204
	 * @param callable $transformer
205
	 *
206
	 * @return $this
207
	 */
208 2
	public function addTransformer( callable $transformer ) {
209 2
		$this->transformers[] = $transformer;
210
211 2
		return $this;
212
	}
213
214
	/**
215
	 * Cache pool getter.
216
	 */
217 2
	public function getCachePool() {
218 2
		return $this->cachePool;
219
	}
220
221
	/**
222
	 * @param null $cachePool
223
	 */
224
	public function setCachePool( $cachePool ) {
225
		$this->cachePool = $cachePool;
226
227
		return $this;
228
	}
229
230
	/**
231
	 * Let us set our client reference taken from transaction.
232
	 *
233
	 * @param $client
234
	 *
235
	 * @return Client
236
	 */
237 2
	public function setClient( Client $client ) {
238 2
		$this->client = $client;
239
240 2
		return $this;
241
	}
242
243
	/**
244
	 * @param bool|string $cacheKey
245
	 *
246
	 * @return Pool
247
	 */
248
	public function setCacheKey( $cacheKey ) {
249
		$this->cacheKey = $cacheKey;
250
251
		return $this;
252
	}
253
254
	/**
255
	 * Cache key getter.
256
	 *
257
	 * @return bool|string
258
	 */
259 2
	public function getCacheKey() {
260 2
		return $this->cacheKey;
261
	}
262
}
263