Completed
Pull Request — master (#378)
by Darren
19:13
created
core/services/container/CoffeeShop.php 2 patches
Indentation   +565 added lines, -565 removed lines patch added patch discarded remove patch
@@ -30,569 +30,569 @@
 block discarded – undo
30 30
 {
31 31
 
32 32
 
33
-    /**
34
-     * This was the best coffee related name I could think of to represent class name "aliases"
35
-     * So classes can be found via an alias identifier,
36
-     * that is revealed when it is run through... the filters... eh? get it?
37
-     *
38
-     * @var array $filters
39
-     */
40
-    private $filters;
41
-
42
-    /**
43
-     * These are the classes that will actually build the objects (to order of course)
44
-     *
45
-     * @var array $coffee_makers
46
-     */
47
-    private $coffee_makers;
48
-
49
-    /**
50
-     * where the instantiated "singleton" objects are stored
51
-     *
52
-     * @var CollectionInterface $carafe
53
-     */
54
-    private $carafe;
55
-
56
-    /**
57
-     * collection of Recipes that instruct us how to brew objects
58
-     *
59
-     * @var CollectionInterface $recipes
60
-     */
61
-    private $recipes;
62
-
63
-    /**
64
-     * collection of closures for brewing objects
65
-     *
66
-     * @var CollectionInterface $reservoir
67
-     */
68
-    private $reservoir;
69
-
70
-
71
-    /**
72
-     * CoffeeShop constructor
73
-     *
74
-     * @throws InvalidInterfaceException
75
-     */
76
-    public function __construct()
77
-    {
78
-        // array for storing class aliases
79
-        $this->filters = array();
80
-        // create collection for storing shared services
81
-        $this->carafe = new LooseCollection('');
82
-        // create collection for storing recipes that tell us how to build services and entities
83
-        $this->recipes = new Collection('EventEspresso\core\services\container\RecipeInterface');
84
-        // create collection for storing closures for constructing new entities
85
-        $this->reservoir = new Collection('Closure');
86
-        // create collection for storing the generators that build our services and entity closures
87
-        $this->coffee_makers = new Collection('EventEspresso\core\services\container\CoffeeMakerInterface');
88
-    }
89
-
90
-
91
-    /**
92
-     * Returns true if the container can return an entry for the given identifier.
93
-     * Returns false otherwise.
94
-     * `has($identifier)` returning true does not mean that `get($identifier)` will not throw an exception.
95
-     * It does however mean that `get($identifier)` will not throw a `ServiceNotFoundException`.
96
-     *
97
-     * @param string $identifier  Identifier of the entry to look for.
98
-     *                            Typically a Fully Qualified Class Name
99
-     * @return boolean
100
-     * @throws InvalidIdentifierException
101
-     */
102
-    public function has($identifier)
103
-    {
104
-        $identifier = $this->filterIdentifier($identifier);
105
-        return $this->carafe->has($identifier);
106
-    }
107
-
108
-
109
-    /**
110
-     * finds a previously brewed (SHARED) service and returns it
111
-     *
112
-     * @param  string $identifier Identifier for the entity class to be constructed.
113
-     *                            Typically a Fully Qualified Class Name
114
-     * @return mixed
115
-     * @throws InvalidIdentifierException
116
-     * @throws ServiceNotFoundException No service was found for this identifier.
117
-     */
118
-    public function get($identifier)
119
-    {
120
-        $identifier = $this->filterIdentifier($identifier);
121
-        if ($this->carafe->has($identifier)) {
122
-            return $this->carafe->get($identifier);
123
-        }
124
-        throw new ServiceNotFoundException($identifier);
125
-    }
126
-
127
-
128
-    /**
129
-     * returns an instance of the requested entity type using the supplied arguments.
130
-     * If a shared service is requested and an instance is already in the carafe, then it will be returned.
131
-     * If it is not already in the carafe, then the service will be constructed, added to the carafe, and returned
132
-     * If the request is for a new entity and a closure exists in the reservoir for creating it,
133
-     * then a new entity will be instantiated from the closure and returned.
134
-     * If a closure does not exist, then one will be built and added to the reservoir
135
-     * before instantiating the requested entity.
136
-     *
137
-     * @param  string $identifier Identifier for the entity class to be constructed.
138
-     *                            Typically a Fully Qualified Class Name
139
-     * @param array   $arguments  an array of arguments to be passed to the entity constructor
140
-     * @param string  $type
141
-     * @return mixed
142
-     * @throws OutOfBoundsException
143
-     * @throws InstantiationException
144
-     * @throws InvalidDataTypeException
145
-     * @throws InvalidClassException
146
-     * @throws InvalidIdentifierException
147
-     * @throws ServiceExistsException
148
-     * @throws ServiceNotFoundException No service was found for this identifier.
149
-     */
150
-    public function brew($identifier, $arguments = array(), $type = '')
151
-    {
152
-        // resolve any class aliases that may exist
153
-        $identifier = $this->filterIdentifier($identifier);
154
-        // is a shared service being requested and already exists in the carafe?
155
-        $brewed = $this->getShared($identifier, $type);
156
-        // then return whatever was found
157
-        if ($brewed !== false) {
158
-            return $brewed;
159
-        }
160
-        // if the reservoir doesn't have a closure already for the requested identifier,
161
-        // then neither a shared service nor a closure for making entities has been built yet
162
-        if (! $this->reservoir->has($identifier)) {
163
-            // so let's brew something up and add it to the proper collection
164
-            $brewed = $this->makeCoffee($identifier, $arguments, $type);
165
-        }
166
-        // did the requested class only require loading, and if so, was that successful?
167
-        if ($this->brewedLoadOnly($brewed, $identifier, $type) === true) {
168
-            return true;
169
-        }
170
-        // was the brewed item a callable factory function ?
171
-        if (is_callable($brewed)) {
172
-            // then instantiate a new entity from the cached closure
173
-            return $brewed($arguments);
174
-        }
175
-        if ($brewed) {
176
-            // requested object was a shared entity, so attempt to get it from the carafe again
177
-            // because if it wasn't there before, then it should have just been brewed and added,
178
-            // but if it still isn't there, then this time the thrown ServiceNotFoundException will not be caught
179
-            return $this->get($identifier);
180
-        }
181
-        // if identifier is for a non-shared entity,
182
-        // then either a cached closure already existed, or was just brewed
183
-        return $this->brewedClosure($identifier, $arguments);
184
-    }
185
-
186
-
187
-    /**
188
-     * @param string $identifier
189
-     * @param string $type
190
-     * @return bool|mixed
191
-     * @throws InvalidIdentifierException
192
-     */
193
-    protected function getShared($identifier, $type)
194
-    {
195
-        try {
196
-            if (empty($type) || $type === CoffeeMaker::BREW_SHARED) {
197
-                // if a shared service was requested and an instance is in the carafe, then return it
198
-                return $this->get($identifier);
199
-            }
200
-        } catch (ServiceNotFoundException $e) {
201
-            // if not then we'll just catch the ServiceNotFoundException but not do anything just yet,
202
-            // and instead, attempt to build whatever was requested
203
-        }
204
-        return false;
205
-    }
206
-
207
-
208
-    /**
209
-     * @param mixed  $brewed
210
-     * @param string $identifier
211
-     * @param string $type
212
-     * @return bool
213
-     * @throws InvalidClassException
214
-     * @throws InvalidDataTypeException
215
-     * @throws InvalidIdentifierException
216
-     * @throws OutOfBoundsException
217
-     * @throws ServiceExistsException
218
-     * @throws ServiceNotFoundException
219
-     */
220
-    protected function brewedLoadOnly($brewed, $identifier, $type)
221
-    {
222
-        if ($type === CoffeeMaker::BREW_LOAD_ONLY) {
223
-            if ($brewed !== true) {
224
-                throw new ServiceNotFoundException(
225
-                    sprintf(
226
-                        esc_html__(
227
-                            'The "%1$s" class could not be loaded.',
228
-                            'event_espresso'
229
-                        ),
230
-                        $identifier
231
-                    )
232
-                );
233
-            }
234
-            return true;
235
-        }
236
-        return false;
237
-    }
238
-
239
-
240
-    /**
241
-     * @param string $identifier
242
-     * @param array  $arguments
243
-     * @return mixed
244
-     * @throws InstantiationException
245
-     */
246
-    protected function brewedClosure($identifier, array $arguments)
247
-    {
248
-        $closure = $this->reservoir->get($identifier);
249
-        if (empty($closure)) {
250
-            throw new InstantiationException(
251
-                sprintf(
252
-                    esc_html__(
253
-                        'Could not brew an instance of "%1$s".',
254
-                        'event_espresso'
255
-                    ),
256
-                    $identifier
257
-                )
258
-            );
259
-        }
260
-        return $closure($arguments);
261
-    }
262
-
263
-
264
-    /**
265
-     * @param CoffeeMakerInterface $coffee_maker
266
-     * @param string               $type
267
-     * @return bool
268
-     * @throws InvalidIdentifierException
269
-     * @throws InvalidEntityException
270
-     */
271
-    public function addCoffeeMaker(CoffeeMakerInterface $coffee_maker, $type)
272
-    {
273
-        $type = CoffeeMaker::validateType($type);
274
-        return $this->coffee_makers->add($coffee_maker, $type);
275
-    }
276
-
277
-
278
-    /**
279
-     * @param string   $identifier
280
-     * @param callable $closure
281
-     * @return callable|null
282
-     * @throws InvalidIdentifierException
283
-     * @throws InvalidDataTypeException
284
-     */
285
-    public function addClosure($identifier, $closure)
286
-    {
287
-        if (! is_callable($closure)) {
288
-            throw new InvalidDataTypeException('$closure', $closure, 'Closure');
289
-        }
290
-        $identifier = $this->processIdentifier($identifier);
291
-        if ($this->reservoir->add($closure, $identifier)) {
292
-            return $closure;
293
-        }
294
-        return null;
295
-    }
296
-
297
-
298
-    /**
299
-     * @param string $identifier
300
-     * @return boolean
301
-     * @throws InvalidIdentifierException
302
-     */
303
-    public function removeClosure($identifier)
304
-    {
305
-        $identifier = $this->processIdentifier($identifier);
306
-        if ($this->reservoir->has($identifier)) {
307
-            return $this->reservoir->remove($this->reservoir->get($identifier));
308
-        }
309
-        return false;
310
-    }
311
-
312
-
313
-    /**
314
-     * @param  string $identifier Identifier for the entity class that the service applies to
315
-     *                            Typically a Fully Qualified Class Name
316
-     * @param mixed   $service
317
-     * @return bool
318
-     * @throws \EventEspresso\core\services\container\exceptions\InvalidServiceException
319
-     * @throws InvalidIdentifierException
320
-     */
321
-    public function addService($identifier, $service)
322
-    {
323
-        $identifier = $this->processIdentifier($identifier);
324
-        $service = $this->validateService($identifier, $service);
325
-        return $this->carafe->add($service, $identifier);
326
-    }
327
-
328
-
329
-    /**
330
-     * @param string $identifier
331
-     * @return boolean
332
-     * @throws InvalidIdentifierException
333
-     */
334
-    public function removeService($identifier)
335
-    {
336
-        $identifier = $this->processIdentifier($identifier);
337
-        if ($this->carafe->has($identifier)) {
338
-            return $this->carafe->remove($this->carafe->get($identifier));
339
-        }
340
-        return false;
341
-    }
342
-
343
-
344
-    /**
345
-     * Adds instructions on how to brew objects
346
-     *
347
-     * @param RecipeInterface $recipe
348
-     * @return mixed
349
-     * @throws InvalidIdentifierException
350
-     */
351
-    public function addRecipe(RecipeInterface $recipe)
352
-    {
353
-        $this->addAliases($recipe->identifier(), $recipe->filters());
354
-        $identifier = $this->processIdentifier($recipe->identifier());
355
-        return $this->recipes->add($recipe, $identifier);
356
-    }
357
-
358
-
359
-    /**
360
-     * @param string $identifier The Recipe's identifier
361
-     * @return boolean
362
-     * @throws InvalidIdentifierException
363
-     */
364
-    public function removeRecipe($identifier)
365
-    {
366
-        $identifier = $this->processIdentifier($identifier);
367
-        if ($this->recipes->has($identifier)) {
368
-            return $this->recipes->remove($this->recipes->get($identifier));
369
-        }
370
-        return false;
371
-    }
372
-
373
-
374
-    /**
375
-     * Get instructions on how to brew objects
376
-     *
377
-     * @param  string $identifier Identifier for the entity class that the recipe applies to
378
-     *                            Typically a Fully Qualified Class Name
379
-     * @param string  $type
380
-     * @return RecipeInterface
381
-     * @throws OutOfBoundsException
382
-     * @throws InvalidIdentifierException
383
-     */
384
-    public function getRecipe($identifier, $type = '')
385
-    {
386
-        $identifier = $this->processIdentifier($identifier);
387
-        if ($this->recipes->has($identifier)) {
388
-            return $this->recipes->get($identifier);
389
-        }
390
-        $default_recipes = $this->getDefaultRecipes();
391
-        $matches = array();
392
-        foreach ($default_recipes as $wildcard => $default_recipe) {
393
-            // is the wildcard recipe prefix in the identifier ?
394
-            if (strpos($identifier, $wildcard) !== false) {
395
-                // track matches and use the number of wildcard characters matched for the key
396
-                $matches[strlen($wildcard)] = $default_recipe;
397
-            }
398
-        }
399
-        if (count($matches) > 0) {
400
-            // sort our recipes by the number of wildcard characters matched
401
-            ksort($matches);
402
-            // then grab the last recipe form the list, since it had the most matching characters
403
-            $match = array_pop($matches);
404
-            // since we are using a default recipe, we need to set it's identifier and fqcn
405
-            return $this->copyDefaultRecipe($match, $identifier, $type);
406
-        }
407
-        if ($this->recipes->has(Recipe::DEFAULT_ID)) {
408
-            // since we are using a default recipe, we need to set it's identifier and fqcn
409
-            return $this->copyDefaultRecipe($this->recipes->get(Recipe::DEFAULT_ID), $identifier, $type);
410
-        }
411
-        throw new OutOfBoundsException(
412
-            sprintf(
413
-                __('Could not brew coffee because no recipes were found for class "%1$s".', 'event_espresso'),
414
-                $identifier
415
-            )
416
-        );
417
-    }
418
-
419
-
420
-    /**
421
-     * adds class name aliases to list of filters
422
-     *
423
-     * @param  string       $identifier Identifier for the entity class that the alias applies to
424
-     *                                  Typically a Fully Qualified Class Name
425
-     * @param  array|string $aliases
426
-     * @return void
427
-     * @throws InvalidIdentifierException
428
-     */
429
-    public function addAliases($identifier, $aliases)
430
-    {
431
-        if (empty($aliases)) {
432
-            return;
433
-        }
434
-        $identifier = $this->processIdentifier($identifier);
435
-        foreach ((array)$aliases as $alias) {
436
-            $this->filters[$this->processIdentifier($alias)] = $identifier;
437
-        }
438
-    }
439
-
440
-
441
-    /**
442
-     * Adds a service to one of the internal collections
443
-     *
444
-     * @param        $identifier
445
-     * @param array  $arguments
446
-     * @param string $type
447
-     * @return mixed
448
-     * @throws InvalidDataTypeException
449
-     * @throws InvalidClassException
450
-     * @throws OutOfBoundsException
451
-     * @throws InvalidIdentifierException
452
-     * @throws ServiceExistsException
453
-     */
454
-    private function makeCoffee($identifier, $arguments = array(), $type = '')
455
-    {
456
-        if ((empty($type) || $type === CoffeeMaker::BREW_SHARED) && $this->has($identifier)) {
457
-            throw new ServiceExistsException($identifier);
458
-        }
459
-        $identifier = $this->filterIdentifier($identifier);
460
-        $recipe = $this->getRecipe($identifier, $type);
461
-        $type = ! empty($type) ? $type : $recipe->type();
462
-        $coffee_maker = $this->getCoffeeMaker($type);
463
-        return $coffee_maker->brew($recipe, $arguments);
464
-    }
465
-
466
-
467
-    /**
468
-     * filters alias identifiers to find the real class name
469
-     *
470
-     * @param  string $identifier Identifier for the entity class that the filter applies to
471
-     *                            Typically a Fully Qualified Class Name
472
-     * @return string
473
-     * @throws InvalidIdentifierException
474
-     */
475
-    private function filterIdentifier($identifier)
476
-    {
477
-        $identifier = $this->processIdentifier($identifier);
478
-        return isset($this->filters[$identifier]) && ! empty($this->filters[$identifier])
479
-            ? $this->filters[$identifier]
480
-            : $identifier;
481
-    }
482
-
483
-
484
-    /**
485
-     * verifies and standardizes identifiers
486
-     *
487
-     * @param  string $identifier Identifier for the entity class
488
-     *                            Typically a Fully Qualified Class Name
489
-     * @return string
490
-     * @throws InvalidIdentifierException
491
-     */
492
-    private function processIdentifier($identifier)
493
-    {
494
-        if (! is_string($identifier)) {
495
-            throw new InvalidIdentifierException(
496
-                is_object($identifier) ? get_class($identifier) : gettype($identifier),
497
-                '\Fully\Qualified\ClassName'
498
-            );
499
-        }
500
-        return ltrim($identifier, '\\');
501
-    }
502
-
503
-
504
-    /**
505
-     * @param string $type
506
-     * @return CoffeeMakerInterface
507
-     * @throws OutOfBoundsException
508
-     * @throws InvalidDataTypeException
509
-     * @throws InvalidClassException
510
-     */
511
-    private function getCoffeeMaker($type)
512
-    {
513
-        if (! $this->coffee_makers->has($type)) {
514
-            throw new OutOfBoundsException(
515
-                __('The requested coffee maker is either missing or invalid.', 'event_espresso')
516
-            );
517
-        }
518
-        return $this->coffee_makers->get($type);
519
-    }
520
-
521
-
522
-    /**
523
-     * Retrieves all recipes that use a wildcard "*" in their identifier
524
-     * This allows recipes to be set up for handling
525
-     * legacy classes that do not support PSR-4 autoloading.
526
-     * for example:
527
-     * using "EEM_*" for a recipe identifier would target all legacy models like EEM_Attendee
528
-     *
529
-     * @return array
530
-     */
531
-    private function getDefaultRecipes()
532
-    {
533
-        $default_recipes = array();
534
-        $this->recipes->rewind();
535
-        while ($this->recipes->valid()) {
536
-            $identifier = $this->recipes->getInfo();
537
-            // does this recipe use a wildcard ? (but is NOT the global default)
538
-            if ($identifier !== Recipe::DEFAULT_ID && strpos($identifier, '*') !== false) {
539
-                // strip the wildcard and use identifier as key
540
-                $default_recipes[str_replace('*', '', $identifier)] = $this->recipes->current();
541
-            }
542
-            $this->recipes->next();
543
-        }
544
-        return $default_recipes;
545
-    }
546
-
547
-
548
-    /**
549
-     * clones a default recipe and then copies details
550
-     * from the incoming request to it so that it can be used
551
-     *
552
-     * @param RecipeInterface $default_recipe
553
-     * @param string          $identifier
554
-     * @param string          $type
555
-     * @return RecipeInterface
556
-     */
557
-    private function copyDefaultRecipe(RecipeInterface $default_recipe, $identifier, $type = '')
558
-    {
559
-        $recipe = clone $default_recipe;
560
-        if (! empty($type)) {
561
-            $recipe->setType($type);
562
-        }
563
-        // is this the base default recipe ?
564
-        if ($default_recipe->identifier() === Recipe::DEFAULT_ID) {
565
-            $recipe->setIdentifier($identifier);
566
-            $recipe->setFqcn($identifier);
567
-            return $recipe;
568
-        }
569
-        $recipe->setIdentifier($identifier);
570
-        foreach ($default_recipe->paths() as $path) {
571
-            $path = str_replace('*', $identifier, $path);
572
-            if (is_readable($path)) {
573
-                $recipe->setPaths($path);
574
-            }
575
-        }
576
-        $recipe->setFqcn($identifier);
577
-        return $recipe;
578
-    }
579
-
580
-
581
-    /**
582
-     * @param  string $identifier Identifier for the entity class that the service applies to
583
-     *                            Typically a Fully Qualified Class Name
584
-     * @param mixed   $service
585
-     * @return mixed
586
-     * @throws InvalidServiceException
587
-     */
588
-    private function validateService($identifier, $service)
589
-    {
590
-        if (! is_object($service)) {
591
-            throw new InvalidServiceException(
592
-                $identifier,
593
-                $service
594
-            );
595
-        }
596
-        return $service;
597
-    }
33
+	/**
34
+	 * This was the best coffee related name I could think of to represent class name "aliases"
35
+	 * So classes can be found via an alias identifier,
36
+	 * that is revealed when it is run through... the filters... eh? get it?
37
+	 *
38
+	 * @var array $filters
39
+	 */
40
+	private $filters;
41
+
42
+	/**
43
+	 * These are the classes that will actually build the objects (to order of course)
44
+	 *
45
+	 * @var array $coffee_makers
46
+	 */
47
+	private $coffee_makers;
48
+
49
+	/**
50
+	 * where the instantiated "singleton" objects are stored
51
+	 *
52
+	 * @var CollectionInterface $carafe
53
+	 */
54
+	private $carafe;
55
+
56
+	/**
57
+	 * collection of Recipes that instruct us how to brew objects
58
+	 *
59
+	 * @var CollectionInterface $recipes
60
+	 */
61
+	private $recipes;
62
+
63
+	/**
64
+	 * collection of closures for brewing objects
65
+	 *
66
+	 * @var CollectionInterface $reservoir
67
+	 */
68
+	private $reservoir;
69
+
70
+
71
+	/**
72
+	 * CoffeeShop constructor
73
+	 *
74
+	 * @throws InvalidInterfaceException
75
+	 */
76
+	public function __construct()
77
+	{
78
+		// array for storing class aliases
79
+		$this->filters = array();
80
+		// create collection for storing shared services
81
+		$this->carafe = new LooseCollection('');
82
+		// create collection for storing recipes that tell us how to build services and entities
83
+		$this->recipes = new Collection('EventEspresso\core\services\container\RecipeInterface');
84
+		// create collection for storing closures for constructing new entities
85
+		$this->reservoir = new Collection('Closure');
86
+		// create collection for storing the generators that build our services and entity closures
87
+		$this->coffee_makers = new Collection('EventEspresso\core\services\container\CoffeeMakerInterface');
88
+	}
89
+
90
+
91
+	/**
92
+	 * Returns true if the container can return an entry for the given identifier.
93
+	 * Returns false otherwise.
94
+	 * `has($identifier)` returning true does not mean that `get($identifier)` will not throw an exception.
95
+	 * It does however mean that `get($identifier)` will not throw a `ServiceNotFoundException`.
96
+	 *
97
+	 * @param string $identifier  Identifier of the entry to look for.
98
+	 *                            Typically a Fully Qualified Class Name
99
+	 * @return boolean
100
+	 * @throws InvalidIdentifierException
101
+	 */
102
+	public function has($identifier)
103
+	{
104
+		$identifier = $this->filterIdentifier($identifier);
105
+		return $this->carafe->has($identifier);
106
+	}
107
+
108
+
109
+	/**
110
+	 * finds a previously brewed (SHARED) service and returns it
111
+	 *
112
+	 * @param  string $identifier Identifier for the entity class to be constructed.
113
+	 *                            Typically a Fully Qualified Class Name
114
+	 * @return mixed
115
+	 * @throws InvalidIdentifierException
116
+	 * @throws ServiceNotFoundException No service was found for this identifier.
117
+	 */
118
+	public function get($identifier)
119
+	{
120
+		$identifier = $this->filterIdentifier($identifier);
121
+		if ($this->carafe->has($identifier)) {
122
+			return $this->carafe->get($identifier);
123
+		}
124
+		throw new ServiceNotFoundException($identifier);
125
+	}
126
+
127
+
128
+	/**
129
+	 * returns an instance of the requested entity type using the supplied arguments.
130
+	 * If a shared service is requested and an instance is already in the carafe, then it will be returned.
131
+	 * If it is not already in the carafe, then the service will be constructed, added to the carafe, and returned
132
+	 * If the request is for a new entity and a closure exists in the reservoir for creating it,
133
+	 * then a new entity will be instantiated from the closure and returned.
134
+	 * If a closure does not exist, then one will be built and added to the reservoir
135
+	 * before instantiating the requested entity.
136
+	 *
137
+	 * @param  string $identifier Identifier for the entity class to be constructed.
138
+	 *                            Typically a Fully Qualified Class Name
139
+	 * @param array   $arguments  an array of arguments to be passed to the entity constructor
140
+	 * @param string  $type
141
+	 * @return mixed
142
+	 * @throws OutOfBoundsException
143
+	 * @throws InstantiationException
144
+	 * @throws InvalidDataTypeException
145
+	 * @throws InvalidClassException
146
+	 * @throws InvalidIdentifierException
147
+	 * @throws ServiceExistsException
148
+	 * @throws ServiceNotFoundException No service was found for this identifier.
149
+	 */
150
+	public function brew($identifier, $arguments = array(), $type = '')
151
+	{
152
+		// resolve any class aliases that may exist
153
+		$identifier = $this->filterIdentifier($identifier);
154
+		// is a shared service being requested and already exists in the carafe?
155
+		$brewed = $this->getShared($identifier, $type);
156
+		// then return whatever was found
157
+		if ($brewed !== false) {
158
+			return $brewed;
159
+		}
160
+		// if the reservoir doesn't have a closure already for the requested identifier,
161
+		// then neither a shared service nor a closure for making entities has been built yet
162
+		if (! $this->reservoir->has($identifier)) {
163
+			// so let's brew something up and add it to the proper collection
164
+			$brewed = $this->makeCoffee($identifier, $arguments, $type);
165
+		}
166
+		// did the requested class only require loading, and if so, was that successful?
167
+		if ($this->brewedLoadOnly($brewed, $identifier, $type) === true) {
168
+			return true;
169
+		}
170
+		// was the brewed item a callable factory function ?
171
+		if (is_callable($brewed)) {
172
+			// then instantiate a new entity from the cached closure
173
+			return $brewed($arguments);
174
+		}
175
+		if ($brewed) {
176
+			// requested object was a shared entity, so attempt to get it from the carafe again
177
+			// because if it wasn't there before, then it should have just been brewed and added,
178
+			// but if it still isn't there, then this time the thrown ServiceNotFoundException will not be caught
179
+			return $this->get($identifier);
180
+		}
181
+		// if identifier is for a non-shared entity,
182
+		// then either a cached closure already existed, or was just brewed
183
+		return $this->brewedClosure($identifier, $arguments);
184
+	}
185
+
186
+
187
+	/**
188
+	 * @param string $identifier
189
+	 * @param string $type
190
+	 * @return bool|mixed
191
+	 * @throws InvalidIdentifierException
192
+	 */
193
+	protected function getShared($identifier, $type)
194
+	{
195
+		try {
196
+			if (empty($type) || $type === CoffeeMaker::BREW_SHARED) {
197
+				// if a shared service was requested and an instance is in the carafe, then return it
198
+				return $this->get($identifier);
199
+			}
200
+		} catch (ServiceNotFoundException $e) {
201
+			// if not then we'll just catch the ServiceNotFoundException but not do anything just yet,
202
+			// and instead, attempt to build whatever was requested
203
+		}
204
+		return false;
205
+	}
206
+
207
+
208
+	/**
209
+	 * @param mixed  $brewed
210
+	 * @param string $identifier
211
+	 * @param string $type
212
+	 * @return bool
213
+	 * @throws InvalidClassException
214
+	 * @throws InvalidDataTypeException
215
+	 * @throws InvalidIdentifierException
216
+	 * @throws OutOfBoundsException
217
+	 * @throws ServiceExistsException
218
+	 * @throws ServiceNotFoundException
219
+	 */
220
+	protected function brewedLoadOnly($brewed, $identifier, $type)
221
+	{
222
+		if ($type === CoffeeMaker::BREW_LOAD_ONLY) {
223
+			if ($brewed !== true) {
224
+				throw new ServiceNotFoundException(
225
+					sprintf(
226
+						esc_html__(
227
+							'The "%1$s" class could not be loaded.',
228
+							'event_espresso'
229
+						),
230
+						$identifier
231
+					)
232
+				);
233
+			}
234
+			return true;
235
+		}
236
+		return false;
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param string $identifier
242
+	 * @param array  $arguments
243
+	 * @return mixed
244
+	 * @throws InstantiationException
245
+	 */
246
+	protected function brewedClosure($identifier, array $arguments)
247
+	{
248
+		$closure = $this->reservoir->get($identifier);
249
+		if (empty($closure)) {
250
+			throw new InstantiationException(
251
+				sprintf(
252
+					esc_html__(
253
+						'Could not brew an instance of "%1$s".',
254
+						'event_espresso'
255
+					),
256
+					$identifier
257
+				)
258
+			);
259
+		}
260
+		return $closure($arguments);
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param CoffeeMakerInterface $coffee_maker
266
+	 * @param string               $type
267
+	 * @return bool
268
+	 * @throws InvalidIdentifierException
269
+	 * @throws InvalidEntityException
270
+	 */
271
+	public function addCoffeeMaker(CoffeeMakerInterface $coffee_maker, $type)
272
+	{
273
+		$type = CoffeeMaker::validateType($type);
274
+		return $this->coffee_makers->add($coffee_maker, $type);
275
+	}
276
+
277
+
278
+	/**
279
+	 * @param string   $identifier
280
+	 * @param callable $closure
281
+	 * @return callable|null
282
+	 * @throws InvalidIdentifierException
283
+	 * @throws InvalidDataTypeException
284
+	 */
285
+	public function addClosure($identifier, $closure)
286
+	{
287
+		if (! is_callable($closure)) {
288
+			throw new InvalidDataTypeException('$closure', $closure, 'Closure');
289
+		}
290
+		$identifier = $this->processIdentifier($identifier);
291
+		if ($this->reservoir->add($closure, $identifier)) {
292
+			return $closure;
293
+		}
294
+		return null;
295
+	}
296
+
297
+
298
+	/**
299
+	 * @param string $identifier
300
+	 * @return boolean
301
+	 * @throws InvalidIdentifierException
302
+	 */
303
+	public function removeClosure($identifier)
304
+	{
305
+		$identifier = $this->processIdentifier($identifier);
306
+		if ($this->reservoir->has($identifier)) {
307
+			return $this->reservoir->remove($this->reservoir->get($identifier));
308
+		}
309
+		return false;
310
+	}
311
+
312
+
313
+	/**
314
+	 * @param  string $identifier Identifier for the entity class that the service applies to
315
+	 *                            Typically a Fully Qualified Class Name
316
+	 * @param mixed   $service
317
+	 * @return bool
318
+	 * @throws \EventEspresso\core\services\container\exceptions\InvalidServiceException
319
+	 * @throws InvalidIdentifierException
320
+	 */
321
+	public function addService($identifier, $service)
322
+	{
323
+		$identifier = $this->processIdentifier($identifier);
324
+		$service = $this->validateService($identifier, $service);
325
+		return $this->carafe->add($service, $identifier);
326
+	}
327
+
328
+
329
+	/**
330
+	 * @param string $identifier
331
+	 * @return boolean
332
+	 * @throws InvalidIdentifierException
333
+	 */
334
+	public function removeService($identifier)
335
+	{
336
+		$identifier = $this->processIdentifier($identifier);
337
+		if ($this->carafe->has($identifier)) {
338
+			return $this->carafe->remove($this->carafe->get($identifier));
339
+		}
340
+		return false;
341
+	}
342
+
343
+
344
+	/**
345
+	 * Adds instructions on how to brew objects
346
+	 *
347
+	 * @param RecipeInterface $recipe
348
+	 * @return mixed
349
+	 * @throws InvalidIdentifierException
350
+	 */
351
+	public function addRecipe(RecipeInterface $recipe)
352
+	{
353
+		$this->addAliases($recipe->identifier(), $recipe->filters());
354
+		$identifier = $this->processIdentifier($recipe->identifier());
355
+		return $this->recipes->add($recipe, $identifier);
356
+	}
357
+
358
+
359
+	/**
360
+	 * @param string $identifier The Recipe's identifier
361
+	 * @return boolean
362
+	 * @throws InvalidIdentifierException
363
+	 */
364
+	public function removeRecipe($identifier)
365
+	{
366
+		$identifier = $this->processIdentifier($identifier);
367
+		if ($this->recipes->has($identifier)) {
368
+			return $this->recipes->remove($this->recipes->get($identifier));
369
+		}
370
+		return false;
371
+	}
372
+
373
+
374
+	/**
375
+	 * Get instructions on how to brew objects
376
+	 *
377
+	 * @param  string $identifier Identifier for the entity class that the recipe applies to
378
+	 *                            Typically a Fully Qualified Class Name
379
+	 * @param string  $type
380
+	 * @return RecipeInterface
381
+	 * @throws OutOfBoundsException
382
+	 * @throws InvalidIdentifierException
383
+	 */
384
+	public function getRecipe($identifier, $type = '')
385
+	{
386
+		$identifier = $this->processIdentifier($identifier);
387
+		if ($this->recipes->has($identifier)) {
388
+			return $this->recipes->get($identifier);
389
+		}
390
+		$default_recipes = $this->getDefaultRecipes();
391
+		$matches = array();
392
+		foreach ($default_recipes as $wildcard => $default_recipe) {
393
+			// is the wildcard recipe prefix in the identifier ?
394
+			if (strpos($identifier, $wildcard) !== false) {
395
+				// track matches and use the number of wildcard characters matched for the key
396
+				$matches[strlen($wildcard)] = $default_recipe;
397
+			}
398
+		}
399
+		if (count($matches) > 0) {
400
+			// sort our recipes by the number of wildcard characters matched
401
+			ksort($matches);
402
+			// then grab the last recipe form the list, since it had the most matching characters
403
+			$match = array_pop($matches);
404
+			// since we are using a default recipe, we need to set it's identifier and fqcn
405
+			return $this->copyDefaultRecipe($match, $identifier, $type);
406
+		}
407
+		if ($this->recipes->has(Recipe::DEFAULT_ID)) {
408
+			// since we are using a default recipe, we need to set it's identifier and fqcn
409
+			return $this->copyDefaultRecipe($this->recipes->get(Recipe::DEFAULT_ID), $identifier, $type);
410
+		}
411
+		throw new OutOfBoundsException(
412
+			sprintf(
413
+				__('Could not brew coffee because no recipes were found for class "%1$s".', 'event_espresso'),
414
+				$identifier
415
+			)
416
+		);
417
+	}
418
+
419
+
420
+	/**
421
+	 * adds class name aliases to list of filters
422
+	 *
423
+	 * @param  string       $identifier Identifier for the entity class that the alias applies to
424
+	 *                                  Typically a Fully Qualified Class Name
425
+	 * @param  array|string $aliases
426
+	 * @return void
427
+	 * @throws InvalidIdentifierException
428
+	 */
429
+	public function addAliases($identifier, $aliases)
430
+	{
431
+		if (empty($aliases)) {
432
+			return;
433
+		}
434
+		$identifier = $this->processIdentifier($identifier);
435
+		foreach ((array)$aliases as $alias) {
436
+			$this->filters[$this->processIdentifier($alias)] = $identifier;
437
+		}
438
+	}
439
+
440
+
441
+	/**
442
+	 * Adds a service to one of the internal collections
443
+	 *
444
+	 * @param        $identifier
445
+	 * @param array  $arguments
446
+	 * @param string $type
447
+	 * @return mixed
448
+	 * @throws InvalidDataTypeException
449
+	 * @throws InvalidClassException
450
+	 * @throws OutOfBoundsException
451
+	 * @throws InvalidIdentifierException
452
+	 * @throws ServiceExistsException
453
+	 */
454
+	private function makeCoffee($identifier, $arguments = array(), $type = '')
455
+	{
456
+		if ((empty($type) || $type === CoffeeMaker::BREW_SHARED) && $this->has($identifier)) {
457
+			throw new ServiceExistsException($identifier);
458
+		}
459
+		$identifier = $this->filterIdentifier($identifier);
460
+		$recipe = $this->getRecipe($identifier, $type);
461
+		$type = ! empty($type) ? $type : $recipe->type();
462
+		$coffee_maker = $this->getCoffeeMaker($type);
463
+		return $coffee_maker->brew($recipe, $arguments);
464
+	}
465
+
466
+
467
+	/**
468
+	 * filters alias identifiers to find the real class name
469
+	 *
470
+	 * @param  string $identifier Identifier for the entity class that the filter applies to
471
+	 *                            Typically a Fully Qualified Class Name
472
+	 * @return string
473
+	 * @throws InvalidIdentifierException
474
+	 */
475
+	private function filterIdentifier($identifier)
476
+	{
477
+		$identifier = $this->processIdentifier($identifier);
478
+		return isset($this->filters[$identifier]) && ! empty($this->filters[$identifier])
479
+			? $this->filters[$identifier]
480
+			: $identifier;
481
+	}
482
+
483
+
484
+	/**
485
+	 * verifies and standardizes identifiers
486
+	 *
487
+	 * @param  string $identifier Identifier for the entity class
488
+	 *                            Typically a Fully Qualified Class Name
489
+	 * @return string
490
+	 * @throws InvalidIdentifierException
491
+	 */
492
+	private function processIdentifier($identifier)
493
+	{
494
+		if (! is_string($identifier)) {
495
+			throw new InvalidIdentifierException(
496
+				is_object($identifier) ? get_class($identifier) : gettype($identifier),
497
+				'\Fully\Qualified\ClassName'
498
+			);
499
+		}
500
+		return ltrim($identifier, '\\');
501
+	}
502
+
503
+
504
+	/**
505
+	 * @param string $type
506
+	 * @return CoffeeMakerInterface
507
+	 * @throws OutOfBoundsException
508
+	 * @throws InvalidDataTypeException
509
+	 * @throws InvalidClassException
510
+	 */
511
+	private function getCoffeeMaker($type)
512
+	{
513
+		if (! $this->coffee_makers->has($type)) {
514
+			throw new OutOfBoundsException(
515
+				__('The requested coffee maker is either missing or invalid.', 'event_espresso')
516
+			);
517
+		}
518
+		return $this->coffee_makers->get($type);
519
+	}
520
+
521
+
522
+	/**
523
+	 * Retrieves all recipes that use a wildcard "*" in their identifier
524
+	 * This allows recipes to be set up for handling
525
+	 * legacy classes that do not support PSR-4 autoloading.
526
+	 * for example:
527
+	 * using "EEM_*" for a recipe identifier would target all legacy models like EEM_Attendee
528
+	 *
529
+	 * @return array
530
+	 */
531
+	private function getDefaultRecipes()
532
+	{
533
+		$default_recipes = array();
534
+		$this->recipes->rewind();
535
+		while ($this->recipes->valid()) {
536
+			$identifier = $this->recipes->getInfo();
537
+			// does this recipe use a wildcard ? (but is NOT the global default)
538
+			if ($identifier !== Recipe::DEFAULT_ID && strpos($identifier, '*') !== false) {
539
+				// strip the wildcard and use identifier as key
540
+				$default_recipes[str_replace('*', '', $identifier)] = $this->recipes->current();
541
+			}
542
+			$this->recipes->next();
543
+		}
544
+		return $default_recipes;
545
+	}
546
+
547
+
548
+	/**
549
+	 * clones a default recipe and then copies details
550
+	 * from the incoming request to it so that it can be used
551
+	 *
552
+	 * @param RecipeInterface $default_recipe
553
+	 * @param string          $identifier
554
+	 * @param string          $type
555
+	 * @return RecipeInterface
556
+	 */
557
+	private function copyDefaultRecipe(RecipeInterface $default_recipe, $identifier, $type = '')
558
+	{
559
+		$recipe = clone $default_recipe;
560
+		if (! empty($type)) {
561
+			$recipe->setType($type);
562
+		}
563
+		// is this the base default recipe ?
564
+		if ($default_recipe->identifier() === Recipe::DEFAULT_ID) {
565
+			$recipe->setIdentifier($identifier);
566
+			$recipe->setFqcn($identifier);
567
+			return $recipe;
568
+		}
569
+		$recipe->setIdentifier($identifier);
570
+		foreach ($default_recipe->paths() as $path) {
571
+			$path = str_replace('*', $identifier, $path);
572
+			if (is_readable($path)) {
573
+				$recipe->setPaths($path);
574
+			}
575
+		}
576
+		$recipe->setFqcn($identifier);
577
+		return $recipe;
578
+	}
579
+
580
+
581
+	/**
582
+	 * @param  string $identifier Identifier for the entity class that the service applies to
583
+	 *                            Typically a Fully Qualified Class Name
584
+	 * @param mixed   $service
585
+	 * @return mixed
586
+	 * @throws InvalidServiceException
587
+	 */
588
+	private function validateService($identifier, $service)
589
+	{
590
+		if (! is_object($service)) {
591
+			throw new InvalidServiceException(
592
+				$identifier,
593
+				$service
594
+			);
595
+		}
596
+		return $service;
597
+	}
598 598
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
         }
160 160
         // if the reservoir doesn't have a closure already for the requested identifier,
161 161
         // then neither a shared service nor a closure for making entities has been built yet
162
-        if (! $this->reservoir->has($identifier)) {
162
+        if ( ! $this->reservoir->has($identifier)) {
163 163
             // so let's brew something up and add it to the proper collection
164 164
             $brewed = $this->makeCoffee($identifier, $arguments, $type);
165 165
         }
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
      */
285 285
     public function addClosure($identifier, $closure)
286 286
     {
287
-        if (! is_callable($closure)) {
287
+        if ( ! is_callable($closure)) {
288 288
             throw new InvalidDataTypeException('$closure', $closure, 'Closure');
289 289
         }
290 290
         $identifier = $this->processIdentifier($identifier);
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
             return;
433 433
         }
434 434
         $identifier = $this->processIdentifier($identifier);
435
-        foreach ((array)$aliases as $alias) {
435
+        foreach ((array) $aliases as $alias) {
436 436
             $this->filters[$this->processIdentifier($alias)] = $identifier;
437 437
         }
438 438
     }
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
      */
492 492
     private function processIdentifier($identifier)
493 493
     {
494
-        if (! is_string($identifier)) {
494
+        if ( ! is_string($identifier)) {
495 495
             throw new InvalidIdentifierException(
496 496
                 is_object($identifier) ? get_class($identifier) : gettype($identifier),
497 497
                 '\Fully\Qualified\ClassName'
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
      */
511 511
     private function getCoffeeMaker($type)
512 512
     {
513
-        if (! $this->coffee_makers->has($type)) {
513
+        if ( ! $this->coffee_makers->has($type)) {
514 514
             throw new OutOfBoundsException(
515 515
                 __('The requested coffee maker is either missing or invalid.', 'event_espresso')
516 516
             );
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
     private function copyDefaultRecipe(RecipeInterface $default_recipe, $identifier, $type = '')
558 558
     {
559 559
         $recipe = clone $default_recipe;
560
-        if (! empty($type)) {
560
+        if ( ! empty($type)) {
561 561
             $recipe->setType($type);
562 562
         }
563 563
         // is this the base default recipe ?
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
      */
588 588
     private function validateService($identifier, $service)
589 589
     {
590
-        if (! is_object($service)) {
590
+        if ( ! is_object($service)) {
591 591
             throw new InvalidServiceException(
592 592
                 $identifier,
593 593
                 $service
Please login to merge, or discard this patch.
core/services/container/DependencyInjector.php 2 patches
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -21,209 +21,209 @@
 block discarded – undo
21 21
 class DependencyInjector implements InjectorInterface
22 22
 {
23 23
 
24
-    /**
25
-     * @var CoffeePotInterface $coffee_pot
26
-     */
27
-    private $coffee_pot;
28
-
29
-    /**
30
-     * @var EEH_Array $array_helper
31
-     */
32
-    private $array_helper;
33
-
34
-    /**
35
-     * @var ReflectionClass[] $reflectors
36
-     */
37
-    private $reflectors;
38
-
39
-    /**
40
-     * @var ReflectionMethod[] $constructors
41
-     */
42
-    private $constructors;
43
-
44
-    /**
45
-     * @var ReflectionParameter[] $parameters
46
-     */
47
-    private $parameters;
48
-
49
-
50
-    /**
51
-     * DependencyInjector constructor
52
-     *
53
-     * @param CoffeePotInterface $coffee_pot
54
-     * @param EEH_Array          $array_helper
55
-     */
56
-    public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
57
-    {
58
-        $this->coffee_pot = $coffee_pot;
59
-        $this->array_helper = $array_helper;
60
-    }
61
-
62
-
63
-    /**
64
-     * getReflectionClass
65
-     * checks if a ReflectionClass object has already been generated for a class
66
-     * and returns that instead of creating a new one
67
-     *
68
-     * @param string $class_name
69
-     * @return ReflectionClass
70
-     */
71
-    public function getReflectionClass($class_name)
72
-    {
73
-        if (! isset($this->reflectors[$class_name])
74
-            || ! $this->reflectors[$class_name] instanceof ReflectionClass
75
-        ) {
76
-            $this->reflectors[$class_name] = new ReflectionClass($class_name);
77
-        }
78
-        return $this->reflectors[$class_name];
79
-    }
80
-
81
-
82
-    /**
83
-     * getConstructor
84
-     * checks if a ReflectionMethod object has already been generated for the class constructor
85
-     * and returns that instead of creating a new one
86
-     *
87
-     * @param ReflectionClass $reflector
88
-     * @return ReflectionMethod
89
-     */
90
-    protected function getConstructor(ReflectionClass $reflector)
91
-    {
92
-        if (! isset($this->constructors[$reflector->getName()])
93
-            || ! $this->constructors[$reflector->getName()] instanceof ReflectionMethod
94
-        ) {
95
-            $this->constructors[$reflector->getName()] = $reflector->getConstructor();
96
-        }
97
-        return $this->constructors[$reflector->getName()];
98
-    }
99
-
100
-
101
-    /**
102
-     * getParameters
103
-     * checks if an array of ReflectionParameter objects has already been generated for the class constructor
104
-     * and returns that instead of creating a new one
105
-     *
106
-     * @param ReflectionMethod $constructor
107
-     * @return ReflectionParameter[]
108
-     */
109
-    protected function getParameters(ReflectionMethod $constructor)
110
-    {
111
-        if (! isset($this->parameters[$constructor->class])) {
112
-            $this->parameters[$constructor->class] = $constructor->getParameters();
113
-        }
114
-        return $this->parameters[$constructor->class];
115
-    }
116
-
117
-
118
-    /**
119
-     * resolveDependencies
120
-     * examines the constructor for the requested class to determine
121
-     * if any dependencies exist, and if they can be injected.
122
-     * If so, then those classes will be added to the array of arguments passed to the constructor
123
-     * PLZ NOTE: this is achieved by type hinting the constructor params
124
-     * For example:
125
-     *        if attempting to load a class "Foo" with the following constructor:
126
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
127
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
128
-     *        but only IF they are NOT already present in the incoming arguments array,
129
-     *        and the correct classes can be loaded
130
-     *
131
-     * @param RecipeInterface $recipe
132
-     * @param ReflectionClass $reflector
133
-     * @param array           $arguments
134
-     * @return array
135
-     * @throws UnexpectedValueException
136
-     */
137
-    public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
138
-    {
139
-        // if arguments array is numerically and sequentially indexed, then we want it to remain as is,
140
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
141
-        $arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
142
-            ? $arguments
143
-            : array($arguments);
144
-        $resolved_parameters = array();
145
-        // let's examine the constructor
146
-        // let's examine the constructor
147
-        $constructor = $this->getConstructor($reflector);
148
-        // whu? huh? nothing?
149
-        if (! $constructor) {
150
-            return $arguments;
151
-        }
152
-        // get constructor parameters
153
-        $params = $this->getParameters($constructor);
154
-        if (empty($params)) {
155
-            return $resolved_parameters;
156
-        }
157
-        $ingredients = $recipe->ingredients();
158
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
159
-        $argument_keys = array_keys($arguments);
160
-        // now loop thru all of the constructors expected parameters
161
-        foreach ($params as $index => $param) {
162
-            if (! $param instanceof ReflectionParameter) {
163
-                continue;
164
-            }
165
-            // is this a dependency for a specific class ?
166
-            $param_class = $param->getClass() ? $param->getClass()->name : '';
167
-            $param_name = $param->getName() ? $param->getName() : '';
168
-            if (// param is not a class but is specified in the list of ingredients for this Recipe
169
-                is_string($param_name) && isset($ingredients[$param_name])
170
-            ) {
171
-                // attempt to inject the dependency
172
-                $resolved_parameters[$index] = $ingredients[$param_name];
173
-            } else if (// param is specified in the list of ingredients for this Recipe
174
-                        isset($ingredients[$param_class])
175
-            ) { // attempt to inject the dependency
176
-                $resolved_parameters[$index] = $this->injectDependency($reflector, $ingredients[$param_class]);
177
-            } else if (// param is not even a class
178
-                        empty($param_class)
179
-                        // and something already exists in the incoming arguments for this param
180
-                        && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
181
-            ) {
182
-                // add parameter from incoming arguments
183
-                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
184
-            } else if (// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
185
-                ! empty($param_class)
186
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
187
-                && $arguments[$argument_keys[$index]] instanceof $param_class
188
-            ) {
189
-                // add parameter from incoming arguments
190
-                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
191
-            } else if (// parameter is type hinted as a class, and should be injected
192
-                       ! empty($param_class)
193
-            ) {
194
-                // attempt to inject the dependency
195
-                $resolved_parameters[$index] = $this->injectDependency($reflector, $param_class);
196
-            } else if ($param->isOptional()) {
197
-                $resolved_parameters[$index] = $param->getDefaultValue();
198
-            } else {
199
-                $resolved_parameters[$index] = null;
200
-            }
201
-        }
202
-        return $resolved_parameters;
203
-    }
204
-
205
-
206
-    /**
207
-     * @param ReflectionClass $reflector
208
-     * @param string          $param_class
209
-     * @return mixed
210
-     * @throws UnexpectedValueException
211
-     */
212
-    private function injectDependency(ReflectionClass $reflector, $param_class)
213
-    {
214
-        $dependency = $this->coffee_pot->brew($param_class);
215
-        if (! $dependency instanceof $param_class) {
216
-            throw new UnexpectedValueException(
217
-                sprintf(
218
-                    esc_html__(
219
-                        'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
220
-                        'event_espresso'
221
-                    ),
222
-                    $param_class,
223
-                    $reflector->getName()
224
-                )
225
-            );
226
-        }
227
-        return $dependency;
228
-    }
24
+	/**
25
+	 * @var CoffeePotInterface $coffee_pot
26
+	 */
27
+	private $coffee_pot;
28
+
29
+	/**
30
+	 * @var EEH_Array $array_helper
31
+	 */
32
+	private $array_helper;
33
+
34
+	/**
35
+	 * @var ReflectionClass[] $reflectors
36
+	 */
37
+	private $reflectors;
38
+
39
+	/**
40
+	 * @var ReflectionMethod[] $constructors
41
+	 */
42
+	private $constructors;
43
+
44
+	/**
45
+	 * @var ReflectionParameter[] $parameters
46
+	 */
47
+	private $parameters;
48
+
49
+
50
+	/**
51
+	 * DependencyInjector constructor
52
+	 *
53
+	 * @param CoffeePotInterface $coffee_pot
54
+	 * @param EEH_Array          $array_helper
55
+	 */
56
+	public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
57
+	{
58
+		$this->coffee_pot = $coffee_pot;
59
+		$this->array_helper = $array_helper;
60
+	}
61
+
62
+
63
+	/**
64
+	 * getReflectionClass
65
+	 * checks if a ReflectionClass object has already been generated for a class
66
+	 * and returns that instead of creating a new one
67
+	 *
68
+	 * @param string $class_name
69
+	 * @return ReflectionClass
70
+	 */
71
+	public function getReflectionClass($class_name)
72
+	{
73
+		if (! isset($this->reflectors[$class_name])
74
+			|| ! $this->reflectors[$class_name] instanceof ReflectionClass
75
+		) {
76
+			$this->reflectors[$class_name] = new ReflectionClass($class_name);
77
+		}
78
+		return $this->reflectors[$class_name];
79
+	}
80
+
81
+
82
+	/**
83
+	 * getConstructor
84
+	 * checks if a ReflectionMethod object has already been generated for the class constructor
85
+	 * and returns that instead of creating a new one
86
+	 *
87
+	 * @param ReflectionClass $reflector
88
+	 * @return ReflectionMethod
89
+	 */
90
+	protected function getConstructor(ReflectionClass $reflector)
91
+	{
92
+		if (! isset($this->constructors[$reflector->getName()])
93
+			|| ! $this->constructors[$reflector->getName()] instanceof ReflectionMethod
94
+		) {
95
+			$this->constructors[$reflector->getName()] = $reflector->getConstructor();
96
+		}
97
+		return $this->constructors[$reflector->getName()];
98
+	}
99
+
100
+
101
+	/**
102
+	 * getParameters
103
+	 * checks if an array of ReflectionParameter objects has already been generated for the class constructor
104
+	 * and returns that instead of creating a new one
105
+	 *
106
+	 * @param ReflectionMethod $constructor
107
+	 * @return ReflectionParameter[]
108
+	 */
109
+	protected function getParameters(ReflectionMethod $constructor)
110
+	{
111
+		if (! isset($this->parameters[$constructor->class])) {
112
+			$this->parameters[$constructor->class] = $constructor->getParameters();
113
+		}
114
+		return $this->parameters[$constructor->class];
115
+	}
116
+
117
+
118
+	/**
119
+	 * resolveDependencies
120
+	 * examines the constructor for the requested class to determine
121
+	 * if any dependencies exist, and if they can be injected.
122
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
123
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
124
+	 * For example:
125
+	 *        if attempting to load a class "Foo" with the following constructor:
126
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
127
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
128
+	 *        but only IF they are NOT already present in the incoming arguments array,
129
+	 *        and the correct classes can be loaded
130
+	 *
131
+	 * @param RecipeInterface $recipe
132
+	 * @param ReflectionClass $reflector
133
+	 * @param array           $arguments
134
+	 * @return array
135
+	 * @throws UnexpectedValueException
136
+	 */
137
+	public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
138
+	{
139
+		// if arguments array is numerically and sequentially indexed, then we want it to remain as is,
140
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
141
+		$arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
142
+			? $arguments
143
+			: array($arguments);
144
+		$resolved_parameters = array();
145
+		// let's examine the constructor
146
+		// let's examine the constructor
147
+		$constructor = $this->getConstructor($reflector);
148
+		// whu? huh? nothing?
149
+		if (! $constructor) {
150
+			return $arguments;
151
+		}
152
+		// get constructor parameters
153
+		$params = $this->getParameters($constructor);
154
+		if (empty($params)) {
155
+			return $resolved_parameters;
156
+		}
157
+		$ingredients = $recipe->ingredients();
158
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
159
+		$argument_keys = array_keys($arguments);
160
+		// now loop thru all of the constructors expected parameters
161
+		foreach ($params as $index => $param) {
162
+			if (! $param instanceof ReflectionParameter) {
163
+				continue;
164
+			}
165
+			// is this a dependency for a specific class ?
166
+			$param_class = $param->getClass() ? $param->getClass()->name : '';
167
+			$param_name = $param->getName() ? $param->getName() : '';
168
+			if (// param is not a class but is specified in the list of ingredients for this Recipe
169
+				is_string($param_name) && isset($ingredients[$param_name])
170
+			) {
171
+				// attempt to inject the dependency
172
+				$resolved_parameters[$index] = $ingredients[$param_name];
173
+			} else if (// param is specified in the list of ingredients for this Recipe
174
+						isset($ingredients[$param_class])
175
+			) { // attempt to inject the dependency
176
+				$resolved_parameters[$index] = $this->injectDependency($reflector, $ingredients[$param_class]);
177
+			} else if (// param is not even a class
178
+						empty($param_class)
179
+						// and something already exists in the incoming arguments for this param
180
+						&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
181
+			) {
182
+				// add parameter from incoming arguments
183
+				$resolved_parameters[$index] = $arguments[$argument_keys[$index]];
184
+			} else if (// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
185
+				! empty($param_class)
186
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
187
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
188
+			) {
189
+				// add parameter from incoming arguments
190
+				$resolved_parameters[$index] = $arguments[$argument_keys[$index]];
191
+			} else if (// parameter is type hinted as a class, and should be injected
192
+					   ! empty($param_class)
193
+			) {
194
+				// attempt to inject the dependency
195
+				$resolved_parameters[$index] = $this->injectDependency($reflector, $param_class);
196
+			} else if ($param->isOptional()) {
197
+				$resolved_parameters[$index] = $param->getDefaultValue();
198
+			} else {
199
+				$resolved_parameters[$index] = null;
200
+			}
201
+		}
202
+		return $resolved_parameters;
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param ReflectionClass $reflector
208
+	 * @param string          $param_class
209
+	 * @return mixed
210
+	 * @throws UnexpectedValueException
211
+	 */
212
+	private function injectDependency(ReflectionClass $reflector, $param_class)
213
+	{
214
+		$dependency = $this->coffee_pot->brew($param_class);
215
+		if (! $dependency instanceof $param_class) {
216
+			throw new UnexpectedValueException(
217
+				sprintf(
218
+					esc_html__(
219
+						'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
220
+						'event_espresso'
221
+					),
222
+					$param_class,
223
+					$reflector->getName()
224
+				)
225
+			);
226
+		}
227
+		return $dependency;
228
+	}
229 229
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
      */
71 71
     public function getReflectionClass($class_name)
72 72
     {
73
-        if (! isset($this->reflectors[$class_name])
73
+        if ( ! isset($this->reflectors[$class_name])
74 74
             || ! $this->reflectors[$class_name] instanceof ReflectionClass
75 75
         ) {
76 76
             $this->reflectors[$class_name] = new ReflectionClass($class_name);
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
      */
90 90
     protected function getConstructor(ReflectionClass $reflector)
91 91
     {
92
-        if (! isset($this->constructors[$reflector->getName()])
92
+        if ( ! isset($this->constructors[$reflector->getName()])
93 93
             || ! $this->constructors[$reflector->getName()] instanceof ReflectionMethod
94 94
         ) {
95 95
             $this->constructors[$reflector->getName()] = $reflector->getConstructor();
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
      */
109 109
     protected function getParameters(ReflectionMethod $constructor)
110 110
     {
111
-        if (! isset($this->parameters[$constructor->class])) {
111
+        if ( ! isset($this->parameters[$constructor->class])) {
112 112
             $this->parameters[$constructor->class] = $constructor->getParameters();
113 113
         }
114 114
         return $this->parameters[$constructor->class];
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         // let's examine the constructor
147 147
         $constructor = $this->getConstructor($reflector);
148 148
         // whu? huh? nothing?
149
-        if (! $constructor) {
149
+        if ( ! $constructor) {
150 150
             return $arguments;
151 151
         }
152 152
         // get constructor parameters
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
         $argument_keys = array_keys($arguments);
160 160
         // now loop thru all of the constructors expected parameters
161 161
         foreach ($params as $index => $param) {
162
-            if (! $param instanceof ReflectionParameter) {
162
+            if ( ! $param instanceof ReflectionParameter) {
163 163
                 continue;
164 164
             }
165 165
             // is this a dependency for a specific class ?
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
     private function injectDependency(ReflectionClass $reflector, $param_class)
213 213
     {
214 214
         $dependency = $this->coffee_pot->brew($param_class);
215
-        if (! $dependency instanceof $param_class) {
215
+        if ( ! $dependency instanceof $param_class) {
216 216
             throw new UnexpectedValueException(
217 217
                 sprintf(
218 218
                     esc_html__(
Please login to merge, or discard this patch.
core/services/payment_methods/gateways/GatewayDataFormatter.php 1 patch
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -14,115 +14,115 @@
 block discarded – undo
14 14
 class GatewayDataFormatter implements GatewayDataFormatterInterface
15 15
 {
16 16
 
17
-    /**
18
-     * Gets the text to use for a gateway's line item name when this is a partial payment
19
-     *
20
-     * @param \EEI_Payment $payment
21
-     * @return string
22
-     */
23
-    public function formatPartialPaymentLineItemName(\EEI_Payment $payment)
24
-    {
25
-        return apply_filters(
26
-            'EEG_Paypal_Pro__do_direct_payment__partial_amount_line_item_name',
27
-            $payment->get_first_event_name(),
28
-            $this,
29
-            $payment
30
-        );
31
-    }
17
+	/**
18
+	 * Gets the text to use for a gateway's line item name when this is a partial payment
19
+	 *
20
+	 * @param \EEI_Payment $payment
21
+	 * @return string
22
+	 */
23
+	public function formatPartialPaymentLineItemName(\EEI_Payment $payment)
24
+	{
25
+		return apply_filters(
26
+			'EEG_Paypal_Pro__do_direct_payment__partial_amount_line_item_name',
27
+			$payment->get_first_event_name(),
28
+			$this,
29
+			$payment
30
+		);
31
+	}
32 32
 
33 33
 
34
-    /**
35
-     * Gets the text to use for a gateway's line item description when this is a partial payment
36
-     *
37
-     * @param \EEI_Payment $payment
38
-     * @return string
39
-     */
40
-    public function formatPartialPaymentLineItemDesc(\EEI_Payment $payment)
41
-    {
42
-        return apply_filters(
43
-            'FHEE__EE_Gateway___partial_payment_desc',
44
-            sprintf(
45
-                __('Payment of %1$s for %2$s', "event_espresso"),
46
-                $payment->get_pretty('PAY_amount', 'no_currency_code'),
47
-                $payment->get_first_event_name()
48
-            ),
49
-            $this,
50
-            $payment
51
-        );
52
-    }
34
+	/**
35
+	 * Gets the text to use for a gateway's line item description when this is a partial payment
36
+	 *
37
+	 * @param \EEI_Payment $payment
38
+	 * @return string
39
+	 */
40
+	public function formatPartialPaymentLineItemDesc(\EEI_Payment $payment)
41
+	{
42
+		return apply_filters(
43
+			'FHEE__EE_Gateway___partial_payment_desc',
44
+			sprintf(
45
+				__('Payment of %1$s for %2$s', "event_espresso"),
46
+				$payment->get_pretty('PAY_amount', 'no_currency_code'),
47
+				$payment->get_first_event_name()
48
+			),
49
+			$this,
50
+			$payment
51
+		);
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * Gets the name to use for a line item when sending line items to the gateway
57
-     *
58
-     * @param \EEI_Line_Item $line_item
59
-     * @param \EEI_Payment   $payment
60
-     * @return string
61
-     */
62
-    public function formatLineItemName(\EEI_Line_Item $line_item, \EEI_Payment $payment)
63
-    {
64
-        return apply_filters(
65
-            'FHEE__EE_gateway___line_item_name',
66
-            sprintf(
67
-                _x('%1$s for %2$s', 'Ticket for Event', 'event_espresso'),
68
-                $line_item->name(),
69
-                $line_item->ticket_event_name()
70
-            ),
71
-            $this,
72
-            $line_item,
73
-            $payment
74
-        );
75
-    }
55
+	/**
56
+	 * Gets the name to use for a line item when sending line items to the gateway
57
+	 *
58
+	 * @param \EEI_Line_Item $line_item
59
+	 * @param \EEI_Payment   $payment
60
+	 * @return string
61
+	 */
62
+	public function formatLineItemName(\EEI_Line_Item $line_item, \EEI_Payment $payment)
63
+	{
64
+		return apply_filters(
65
+			'FHEE__EE_gateway___line_item_name',
66
+			sprintf(
67
+				_x('%1$s for %2$s', 'Ticket for Event', 'event_espresso'),
68
+				$line_item->name(),
69
+				$line_item->ticket_event_name()
70
+			),
71
+			$this,
72
+			$line_item,
73
+			$payment
74
+		);
75
+	}
76 76
 
77 77
 
78
-    /**
79
-     * Gets the description to use for a line item when sending line items to the gateway
80
-     *
81
-     * @param \EEI_Line_Item $line_item
82
-     * @param \EEI_Payment   $payment
83
-     * @return string
84
-     */
85
-    public function formatLineItemDesc(\EEI_Line_Item $line_item, \EEI_Payment $payment)
86
-    {
87
-        return apply_filters(
88
-            'FHEE__EE_Gateway___line_item_desc',
89
-            $line_item->desc(),
90
-            $this,
91
-            $line_item,
92
-            $payment
93
-        );
94
-    }
78
+	/**
79
+	 * Gets the description to use for a line item when sending line items to the gateway
80
+	 *
81
+	 * @param \EEI_Line_Item $line_item
82
+	 * @param \EEI_Payment   $payment
83
+	 * @return string
84
+	 */
85
+	public function formatLineItemDesc(\EEI_Line_Item $line_item, \EEI_Payment $payment)
86
+	{
87
+		return apply_filters(
88
+			'FHEE__EE_Gateway___line_item_desc',
89
+			$line_item->desc(),
90
+			$this,
91
+			$line_item,
92
+			$payment
93
+		);
94
+	}
95 95
 
96 96
 
97
-    /**
98
-     * Gets the order description that should generally be sent to gateways
99
-     *
100
-     * @param \EEI_Payment $payment
101
-     * @return string
102
-     */
103
-    public function formatOrderDescription(\EEI_Payment $payment)
104
-    {
105
-        return apply_filters(
106
-            'FHEE__EE_Gateway___order_description',
107
-            sprintf(
108
-                __('Event Registrations from %1$s for %2$s', "event_espresso"),
109
-                wp_specialchars_decode(get_bloginfo(), ENT_QUOTES),
110
-                $payment->get_first_event_name()
111
-            ),
112
-            $this,
113
-            $payment
114
-        );
115
-    }
97
+	/**
98
+	 * Gets the order description that should generally be sent to gateways
99
+	 *
100
+	 * @param \EEI_Payment $payment
101
+	 * @return string
102
+	 */
103
+	public function formatOrderDescription(\EEI_Payment $payment)
104
+	{
105
+		return apply_filters(
106
+			'FHEE__EE_Gateway___order_description',
107
+			sprintf(
108
+				__('Event Registrations from %1$s for %2$s', "event_espresso"),
109
+				wp_specialchars_decode(get_bloginfo(), ENT_QUOTES),
110
+				$payment->get_first_event_name()
111
+			),
112
+			$this,
113
+			$payment
114
+		);
115
+	}
116 116
 
117 117
 
118
-    /**
119
-     * Formats the amount so it can generally be sent to gateways
120
-     *
121
-     * @param float $amount
122
-     * @return string
123
-     */
124
-    public function formatCurrency($amount)
125
-    {
126
-        return number_format($amount, 2, '.', '');
127
-    }
118
+	/**
119
+	 * Formats the amount so it can generally be sent to gateways
120
+	 *
121
+	 * @param float $amount
122
+	 * @return string
123
+	 */
124
+	public function formatCurrency($amount)
125
+	{
126
+		return number_format($amount, 2, '.', '');
127
+	}
128 128
 }
Please login to merge, or discard this patch.
core/services/database/TableManager.php 2 patches
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -13,248 +13,248 @@
 block discarded – undo
13 13
 class TableManager extends \EE_Base
14 14
 {
15 15
 
16
-    /**
17
-     * @var TableAnalysis $table_analysis
18
-     */
19
-    private $table_analysis;
16
+	/**
17
+	 * @var TableAnalysis $table_analysis
18
+	 */
19
+	private $table_analysis;
20 20
 
21 21
 
22
-    /**
23
-     * TableManager constructor.
24
-     *
25
-     * @param TableAnalysis $TableAnalysis
26
-     */
27
-    public function __construct(TableAnalysis $TableAnalysis)
28
-    {
29
-        $this->table_analysis = $TableAnalysis;
30
-    }
22
+	/**
23
+	 * TableManager constructor.
24
+	 *
25
+	 * @param TableAnalysis $TableAnalysis
26
+	 */
27
+	public function __construct(TableAnalysis $TableAnalysis)
28
+	{
29
+		$this->table_analysis = $TableAnalysis;
30
+	}
31 31
 
32 32
 
33
-    /**
34
-     * Gets the injected table analyzer, or throws an exception
35
-     *
36
-     * @return TableAnalysis
37
-     * @throws \EE_Error
38
-     */
39
-    protected function getTableAnalysis()
40
-    {
41
-        if ($this->table_analysis instanceof TableAnalysis) {
42
-            return $this->table_analysis;
43
-        } else {
44
-            throw new \EE_Error(
45
-                sprintf(
46
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
47
-                    get_class($this)
48
-                )
49
-            );
50
-        }
51
-    }
33
+	/**
34
+	 * Gets the injected table analyzer, or throws an exception
35
+	 *
36
+	 * @return TableAnalysis
37
+	 * @throws \EE_Error
38
+	 */
39
+	protected function getTableAnalysis()
40
+	{
41
+		if ($this->table_analysis instanceof TableAnalysis) {
42
+			return $this->table_analysis;
43
+		} else {
44
+			throw new \EE_Error(
45
+				sprintf(
46
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
47
+					get_class($this)
48
+				)
49
+			);
50
+		}
51
+	}
52 52
 
53 53
 
54
-    /**
55
-     * @param string $table_name which can optionally start with $wpdb->prefix or not
56
-     * @param string $column_name
57
-     * @param string $column_info
58
-     * @return bool|false|int
59
-     */
60
-    public function addColumn($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
61
-    {
62
-        if (apply_filters('FHEE__EEH_Activation__add_column_if_it_doesnt_exist__short_circuit', false)) {
63
-            return false;
64
-        }
65
-        global $wpdb;
66
-        $full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
67
-        $columns = $this->getTableColumns($table_name);
68
-        if (! in_array($column_name, $columns)) {
69
-            $alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
70
-            return $wpdb->query($alter_query);
71
-        }
72
-        return true;
73
-    }
54
+	/**
55
+	 * @param string $table_name which can optionally start with $wpdb->prefix or not
56
+	 * @param string $column_name
57
+	 * @param string $column_info
58
+	 * @return bool|false|int
59
+	 */
60
+	public function addColumn($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
61
+	{
62
+		if (apply_filters('FHEE__EEH_Activation__add_column_if_it_doesnt_exist__short_circuit', false)) {
63
+			return false;
64
+		}
65
+		global $wpdb;
66
+		$full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
67
+		$columns = $this->getTableColumns($table_name);
68
+		if (! in_array($column_name, $columns)) {
69
+			$alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
70
+			return $wpdb->query($alter_query);
71
+		}
72
+		return true;
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * Gets the name of all columns on the  table. $table_name can
78
-     * optionally start with $wpdb->prefix or not
79
-     *
80
-     * @global \wpdb $wpdb
81
-     * @param string $table_name
82
-     * @return array
83
-     */
84
-    public function getTableColumns($table_name)
85
-    {
86
-        global $wpdb;
87
-        $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
-        $field_array = array();
89
-        if (! empty($table_name)) {
90
-            $columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
91
-            if ($columns !== false) {
92
-                foreach ($columns as $column) {
93
-                    $field_array[] = $column->Field;
94
-                }
95
-            }
96
-        }
97
-        return $field_array;
98
-    }
76
+	/**
77
+	 * Gets the name of all columns on the  table. $table_name can
78
+	 * optionally start with $wpdb->prefix or not
79
+	 *
80
+	 * @global \wpdb $wpdb
81
+	 * @param string $table_name
82
+	 * @return array
83
+	 */
84
+	public function getTableColumns($table_name)
85
+	{
86
+		global $wpdb;
87
+		$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
+		$field_array = array();
89
+		if (! empty($table_name)) {
90
+			$columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
91
+			if ($columns !== false) {
92
+				foreach ($columns as $column) {
93
+					$field_array[] = $column->Field;
94
+				}
95
+			}
96
+		}
97
+		return $field_array;
98
+	}
99 99
 
100 100
 
101
-    /**
102
-     * Drops the specified table from the database. $table_name can
103
-     * optionally start with $wpdb->prefix or not
104
-     *
105
-     * @global \wpdb $wpdb
106
-     * @param string $table_name
107
-     * @return int
108
-     */
109
-    public function dropTable($table_name)
110
-    {
111
-        global $wpdb;
112
-        if ($this->getTableAnalysis()->tableExists($table_name)) {
113
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
114
-            return $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
115
-        }
116
-        return 0;
117
-    }
101
+	/**
102
+	 * Drops the specified table from the database. $table_name can
103
+	 * optionally start with $wpdb->prefix or not
104
+	 *
105
+	 * @global \wpdb $wpdb
106
+	 * @param string $table_name
107
+	 * @return int
108
+	 */
109
+	public function dropTable($table_name)
110
+	{
111
+		global $wpdb;
112
+		if ($this->getTableAnalysis()->tableExists($table_name)) {
113
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
114
+			return $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
115
+		}
116
+		return 0;
117
+	}
118 118
 
119 119
 
120
-    /**
121
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
122
-     * each table name provided has a wpdb prefix attached, and that it exists.
123
-     * Returns the list actually deleted
124
-     *
125
-     * @global WPDB $wpdb
126
-     * @param array $table_names
127
-     * @return array of table names which we deleted
128
-     */
129
-    public function dropTables($table_names)
130
-    {
131
-        $tables_to_delete = array();
132
-        foreach ($table_names as $table_name) {
133
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
134
-            if ($this->getTableAnalysis()->tableExists($table_name)) {
135
-                $tables_to_delete[$table_name] = $table_name;
136
-            }
137
-        }
138
-        if (! empty($tables_to_delete)) {
139
-            global $wpdb;
140
-            // make sure we only have a unique strings in the array.
141
-            $tables_to_delete = array_unique($tables_to_delete);
142
-            $wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
143
-        }
144
-        return $tables_to_delete;
145
-    }
120
+	/**
121
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
122
+	 * each table name provided has a wpdb prefix attached, and that it exists.
123
+	 * Returns the list actually deleted
124
+	 *
125
+	 * @global WPDB $wpdb
126
+	 * @param array $table_names
127
+	 * @return array of table names which we deleted
128
+	 */
129
+	public function dropTables($table_names)
130
+	{
131
+		$tables_to_delete = array();
132
+		foreach ($table_names as $table_name) {
133
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
134
+			if ($this->getTableAnalysis()->tableExists($table_name)) {
135
+				$tables_to_delete[$table_name] = $table_name;
136
+			}
137
+		}
138
+		if (! empty($tables_to_delete)) {
139
+			global $wpdb;
140
+			// make sure we only have a unique strings in the array.
141
+			$tables_to_delete = array_unique($tables_to_delete);
142
+			$wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
143
+		}
144
+		return $tables_to_delete;
145
+	}
146 146
 
147 147
 
148
-    /**
149
-     * Drops the specified index from the specified table. $table_name can
150
-     * optionally start with $wpdb->prefix or not
151
-     *
152
-     * @global \wpdb $wpdb
153
-     * @param string $table_name
154
-     * @param string $index_name
155
-     * @return int the number of indexes dropped. False if there was a datbase error
156
-     */
157
-    public function dropIndex($table_name, $index_name)
158
-    {
159
-        if (apply_filters('FHEE__EEH_Activation__drop_index__short_circuit', false)) {
160
-            return 0;
161
-        }
162
-        global $wpdb;
163
-        $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
164
-        $index_exists_query = "SHOW INDEX FROM {$table_name} WHERE key_name = '{$index_name}'";
165
-        if ($this->getTableAnalysis()->tableExists($table_name)
166
-            && $wpdb->get_var($index_exists_query)
167
-               === $table_name // using get_var with the $index_exists_query returns the table's name
168
-        ) {
169
-            return $wpdb->query("ALTER TABLE {$table_name} DROP INDEX {$index_name}");
170
-        }
171
-        return 0;
172
-    }
148
+	/**
149
+	 * Drops the specified index from the specified table. $table_name can
150
+	 * optionally start with $wpdb->prefix or not
151
+	 *
152
+	 * @global \wpdb $wpdb
153
+	 * @param string $table_name
154
+	 * @param string $index_name
155
+	 * @return int the number of indexes dropped. False if there was a datbase error
156
+	 */
157
+	public function dropIndex($table_name, $index_name)
158
+	{
159
+		if (apply_filters('FHEE__EEH_Activation__drop_index__short_circuit', false)) {
160
+			return 0;
161
+		}
162
+		global $wpdb;
163
+		$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
164
+		$index_exists_query = "SHOW INDEX FROM {$table_name} WHERE key_name = '{$index_name}'";
165
+		if ($this->getTableAnalysis()->tableExists($table_name)
166
+			&& $wpdb->get_var($index_exists_query)
167
+			   === $table_name // using get_var with the $index_exists_query returns the table's name
168
+		) {
169
+			return $wpdb->query("ALTER TABLE {$table_name} DROP INDEX {$index_name}");
170
+		}
171
+		return 0;
172
+	}
173 173
 
174 174
 
175
-    /**
176
-     * Just creates the requested table. $table_name can
177
-     * optionally start with $wpdb->prefix or not
178
-     *
179
-     * @param string $table_name
180
-     * @param string $create_sql defining the table's columns and indexes
181
-     * @param string $engine     (no need to specify "ENGINE=", that's implied)
182
-     * @return void
183
-     * @throws \EE_Error
184
-     */
185
-    public function createTable($table_name, $create_sql, $engine = 'MyISAM')
186
-    {
187
-        // does $sql contain valid column information? ( LPT: https://regex101.com/ is great for working out regex patterns )
188
-        if (preg_match('((((.*?))(,\s))+)', $create_sql, $valid_column_data)) {
189
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
190
-            /** @var \wpdb $wpdb */
191
-            global $wpdb;
192
-            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
175
+	/**
176
+	 * Just creates the requested table. $table_name can
177
+	 * optionally start with $wpdb->prefix or not
178
+	 *
179
+	 * @param string $table_name
180
+	 * @param string $create_sql defining the table's columns and indexes
181
+	 * @param string $engine     (no need to specify "ENGINE=", that's implied)
182
+	 * @return void
183
+	 * @throws \EE_Error
184
+	 */
185
+	public function createTable($table_name, $create_sql, $engine = 'MyISAM')
186
+	{
187
+		// does $sql contain valid column information? ( LPT: https://regex101.com/ is great for working out regex patterns )
188
+		if (preg_match('((((.*?))(,\s))+)', $create_sql, $valid_column_data)) {
189
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
190
+			/** @var \wpdb $wpdb */
191
+			global $wpdb;
192
+			$SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
193 193
 
194
-            // get $wpdb to echo errors, but buffer them. This way at least WE know an error
195
-            // happened. And then we can choose to tell the end user
196
-            $old_show_errors_policy = $wpdb->show_errors(true);
197
-            $old_error_suppression_policy = $wpdb->suppress_errors(false);
198
-            ob_start();
199
-            dbDelta($SQL);
200
-            $output = ob_get_contents();
201
-            ob_end_clean();
202
-            $wpdb->show_errors($old_show_errors_policy);
203
-            $wpdb->suppress_errors($old_error_suppression_policy);
204
-            if (! empty($output)) {
205
-                throw new \EE_Error($output);
206
-            }
207
-        } else {
208
-            throw new \EE_Error(
209
-                sprintf(
210
-                    __(
211
-                        'The following table creation SQL does not contain valid information about the table columns: %1$s %2$s',
212
-                        'event_espresso'
213
-                    ),
214
-                    '<br />',
215
-                    $create_sql
216
-                )
217
-            );
218
-        }
219
-    }
194
+			// get $wpdb to echo errors, but buffer them. This way at least WE know an error
195
+			// happened. And then we can choose to tell the end user
196
+			$old_show_errors_policy = $wpdb->show_errors(true);
197
+			$old_error_suppression_policy = $wpdb->suppress_errors(false);
198
+			ob_start();
199
+			dbDelta($SQL);
200
+			$output = ob_get_contents();
201
+			ob_end_clean();
202
+			$wpdb->show_errors($old_show_errors_policy);
203
+			$wpdb->suppress_errors($old_error_suppression_policy);
204
+			if (! empty($output)) {
205
+				throw new \EE_Error($output);
206
+			}
207
+		} else {
208
+			throw new \EE_Error(
209
+				sprintf(
210
+					__(
211
+						'The following table creation SQL does not contain valid information about the table columns: %1$s %2$s',
212
+						'event_espresso'
213
+					),
214
+					'<br />',
215
+					$create_sql
216
+				)
217
+			);
218
+		}
219
+	}
220 220
 
221 221
 
222
-    /**
223
-     * Drops the specified index if it's size differs from $desired_index_size.
224
-     * WordPress' dbdelta method doesn't automatically change index sizes, so this
225
-     * method can be used to only drop the index if needed, and afterwards dbdelta can be used as normal.
226
-     * If the table doesn't exist, or it exists but the index does not, or returns false
227
-     *
228
-     * @param string     $table_name
229
-     * @param string     $index_name
230
-     * @param string     $column_name        if none is provided, we assume the column name matches the index (often
231
-     *                                       true in EE)
232
-     * @param string|int $desired_index_size defaults to TableAnalysis::index_col_size, the max for utf8mb4.
233
-     * @return bool whether an index was dropped or not
234
-     * @throws /EE_Error if table analysis object isn't defined
235
-     */
236
-    public function dropIndexIfSizeNot(
237
-        $table_name,
238
-        $index_name,
239
-        $column_name = null,
240
-        $desired_index_size = TableAnalysis::INDEX_COLUMN_SIZE
241
-    ) {
242
-        if ($column_name === null) {
243
-            $column_name = $index_name;
244
-        }
245
-        if (! $this->getTableAnalysis()->tableExists($table_name)) {
246
-            return false;
247
-        }
248
-        $index_entries = $this->getTableAnalysis()->showIndexes($table_name, $index_name);
249
-        if (empty($index_entries)) {
250
-            return false;
251
-        }
252
-        foreach ($index_entries as $index_entry) {
253
-            if ($column_name === $index_entry->Column_name
254
-                && (string)$desired_index_size !== $index_entry->Sub_part) {
255
-                return $this->dropIndex($table_name, $index_name);
256
-            }
257
-        }
258
-        return false;
259
-    }
222
+	/**
223
+	 * Drops the specified index if it's size differs from $desired_index_size.
224
+	 * WordPress' dbdelta method doesn't automatically change index sizes, so this
225
+	 * method can be used to only drop the index if needed, and afterwards dbdelta can be used as normal.
226
+	 * If the table doesn't exist, or it exists but the index does not, or returns false
227
+	 *
228
+	 * @param string     $table_name
229
+	 * @param string     $index_name
230
+	 * @param string     $column_name        if none is provided, we assume the column name matches the index (often
231
+	 *                                       true in EE)
232
+	 * @param string|int $desired_index_size defaults to TableAnalysis::index_col_size, the max for utf8mb4.
233
+	 * @return bool whether an index was dropped or not
234
+	 * @throws /EE_Error if table analysis object isn't defined
235
+	 */
236
+	public function dropIndexIfSizeNot(
237
+		$table_name,
238
+		$index_name,
239
+		$column_name = null,
240
+		$desired_index_size = TableAnalysis::INDEX_COLUMN_SIZE
241
+	) {
242
+		if ($column_name === null) {
243
+			$column_name = $index_name;
244
+		}
245
+		if (! $this->getTableAnalysis()->tableExists($table_name)) {
246
+			return false;
247
+		}
248
+		$index_entries = $this->getTableAnalysis()->showIndexes($table_name, $index_name);
249
+		if (empty($index_entries)) {
250
+			return false;
251
+		}
252
+		foreach ($index_entries as $index_entry) {
253
+			if ($column_name === $index_entry->Column_name
254
+				&& (string)$desired_index_size !== $index_entry->Sub_part) {
255
+				return $this->dropIndex($table_name, $index_name);
256
+			}
257
+		}
258
+		return false;
259
+	}
260 260
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
         global $wpdb;
66 66
         $full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
67 67
         $columns = $this->getTableColumns($table_name);
68
-        if (! in_array($column_name, $columns)) {
68
+        if ( ! in_array($column_name, $columns)) {
69 69
             $alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
70 70
             return $wpdb->query($alter_query);
71 71
         }
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
         global $wpdb;
87 87
         $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88 88
         $field_array = array();
89
-        if (! empty($table_name)) {
89
+        if ( ! empty($table_name)) {
90 90
             $columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
91 91
             if ($columns !== false) {
92 92
                 foreach ($columns as $column) {
@@ -135,11 +135,11 @@  discard block
 block discarded – undo
135 135
                 $tables_to_delete[$table_name] = $table_name;
136 136
             }
137 137
         }
138
-        if (! empty($tables_to_delete)) {
138
+        if ( ! empty($tables_to_delete)) {
139 139
             global $wpdb;
140 140
             // make sure we only have a unique strings in the array.
141 141
             $tables_to_delete = array_unique($tables_to_delete);
142
-            $wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
142
+            $wpdb->query('DROP TABLE '.implode(', ', $tables_to_delete));
143 143
         }
144 144
         return $tables_to_delete;
145 145
     }
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
             $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
190 190
             /** @var \wpdb $wpdb */
191 191
             global $wpdb;
192
-            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
192
+            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} ".$wpdb->get_charset_collate();
193 193
 
194 194
             // get $wpdb to echo errors, but buffer them. This way at least WE know an error
195 195
             // happened. And then we can choose to tell the end user
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
             ob_end_clean();
202 202
             $wpdb->show_errors($old_show_errors_policy);
203 203
             $wpdb->suppress_errors($old_error_suppression_policy);
204
-            if (! empty($output)) {
204
+            if ( ! empty($output)) {
205 205
                 throw new \EE_Error($output);
206 206
             }
207 207
         } else {
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
         if ($column_name === null) {
243 243
             $column_name = $index_name;
244 244
         }
245
-        if (! $this->getTableAnalysis()->tableExists($table_name)) {
245
+        if ( ! $this->getTableAnalysis()->tableExists($table_name)) {
246 246
             return false;
247 247
         }
248 248
         $index_entries = $this->getTableAnalysis()->showIndexes($table_name, $index_name);
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
         }
252 252
         foreach ($index_entries as $index_entry) {
253 253
             if ($column_name === $index_entry->Column_name
254
-                && (string)$desired_index_size !== $index_entry->Sub_part) {
254
+                && (string) $desired_index_size !== $index_entry->Sub_part) {
255 255
                 return $this->dropIndex($table_name, $index_name);
256 256
             }
257 257
         }
Please login to merge, or discard this patch.
core/services/database/TableAnalysis.php 2 patches
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -14,131 +14,131 @@
 block discarded – undo
14 14
 class TableAnalysis extends \EE_Base
15 15
 {
16 16
 
17
-    /**
18
-     * The maximum number of characters that can be indexed on a column using utf8mb4 collation,
19
-     * see https://events.codebasehq.com/redirect?https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/
20
-     */
21
-    const INDEX_COLUMN_SIZE = 191;
17
+	/**
18
+	 * The maximum number of characters that can be indexed on a column using utf8mb4 collation,
19
+	 * see https://events.codebasehq.com/redirect?https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/
20
+	 */
21
+	const INDEX_COLUMN_SIZE = 191;
22 22
 
23
-    /**
24
-     * Returns the table name which will definitely have the wpdb prefix on the front,
25
-     * except if it currently has the wpdb->base_prefix on the front, in which case
26
-     * it will have the wpdb->base_prefix on it
27
-     *
28
-     * @global \wpdb $wpdb
29
-     * @param string $table_name
30
-     * @return string $tableName, having ensured it has the wpdb prefix on the front
31
-     */
32
-    public function ensureTableNameHasPrefix($table_name)
33
-    {
34
-        global $wpdb;
35
-        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
36
-    }
23
+	/**
24
+	 * Returns the table name which will definitely have the wpdb prefix on the front,
25
+	 * except if it currently has the wpdb->base_prefix on the front, in which case
26
+	 * it will have the wpdb->base_prefix on it
27
+	 *
28
+	 * @global \wpdb $wpdb
29
+	 * @param string $table_name
30
+	 * @return string $tableName, having ensured it has the wpdb prefix on the front
31
+	 */
32
+	public function ensureTableNameHasPrefix($table_name)
33
+	{
34
+		global $wpdb;
35
+		return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * Indicates whether or not the table has any entries. $table_name can
41
-     * optionally start with $wpdb->prefix or not
42
-     *
43
-     * @global \wpdb $wpdb
44
-     * @param string $table_name
45
-     * @return bool
46
-     */
47
-    public function tableIsEmpty($table_name)
48
-    {
49
-        global $wpdb;
50
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
51
-        if ($this->tableExists($table_name)) {
52
-            $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
53
-            return absint($count) === 0 ? true : false;
54
-        }
55
-        return false;
56
-    }
39
+	/**
40
+	 * Indicates whether or not the table has any entries. $table_name can
41
+	 * optionally start with $wpdb->prefix or not
42
+	 *
43
+	 * @global \wpdb $wpdb
44
+	 * @param string $table_name
45
+	 * @return bool
46
+	 */
47
+	public function tableIsEmpty($table_name)
48
+	{
49
+		global $wpdb;
50
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
51
+		if ($this->tableExists($table_name)) {
52
+			$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
53
+			return absint($count) === 0 ? true : false;
54
+		}
55
+		return false;
56
+	}
57 57
 
58 58
 
59
-    /**
60
-     * Indicates whether or not the table exists. $table_name can optionally
61
-     * have the $wpdb->prefix on the beginning, or not.
62
-     *
63
-     * @global \wpdb $wpdb
64
-     * @global array EZSQL_Error
65
-     * @param        $table_name
66
-     * @return bool
67
-     */
68
-    public function tableExists($table_name)
69
-    {
70
-        global $wpdb, $EZSQL_ERROR;
71
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
72
-        // ignore if this causes an sql error
73
-        $old_error = $wpdb->last_error;
74
-        $old_suppress_errors = $wpdb->suppress_errors();
75
-        $old_show_errors_value = $wpdb->show_errors(false);
76
-        $ezsql_error_cache = $EZSQL_ERROR;
77
-        $wpdb->get_results("SELECT * from $table_name LIMIT 1");
78
-        $wpdb->show_errors($old_show_errors_value);
79
-        $wpdb->suppress_errors($old_suppress_errors);
80
-        $new_error = $wpdb->last_error;
81
-        $wpdb->last_error = $old_error;
82
-        $EZSQL_ERROR = $ezsql_error_cache;
83
-        // if there was a table doesn't exist error
84
-        if (! empty($new_error)) {
85
-            if (in_array(
86
-                \EEH_Activation::last_wpdb_error_code(),
87
-                array(
88
-                    1051, // bad table
89
-                    1109, // unknown table
90
-                    117, // no such table
91
-                )
92
-            )
93
-                ||
94
-                preg_match(
95
-                    '~^Table .* doesn\'t exist~',
96
-                    $new_error
97
-                ) // in case not using mysql and error codes aren't reliable, just check for this error string
98
-            ) {
99
-                return false;
100
-            } else {
101
-                // log this because that's weird. Just use the normal PHP error log
102
-                error_log(
103
-                    sprintf(
104
-                        __(
105
-                            'Event Espresso error detected when checking if table existed: %1$s (it wasn\'t just that the table didn\'t exist either)',
106
-                            'event_espresso'
107
-                        ),
108
-                        $new_error
109
-                    )
110
-                );
111
-            }
112
-        }
113
-        return true;
114
-    }
59
+	/**
60
+	 * Indicates whether or not the table exists. $table_name can optionally
61
+	 * have the $wpdb->prefix on the beginning, or not.
62
+	 *
63
+	 * @global \wpdb $wpdb
64
+	 * @global array EZSQL_Error
65
+	 * @param        $table_name
66
+	 * @return bool
67
+	 */
68
+	public function tableExists($table_name)
69
+	{
70
+		global $wpdb, $EZSQL_ERROR;
71
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
72
+		// ignore if this causes an sql error
73
+		$old_error = $wpdb->last_error;
74
+		$old_suppress_errors = $wpdb->suppress_errors();
75
+		$old_show_errors_value = $wpdb->show_errors(false);
76
+		$ezsql_error_cache = $EZSQL_ERROR;
77
+		$wpdb->get_results("SELECT * from $table_name LIMIT 1");
78
+		$wpdb->show_errors($old_show_errors_value);
79
+		$wpdb->suppress_errors($old_suppress_errors);
80
+		$new_error = $wpdb->last_error;
81
+		$wpdb->last_error = $old_error;
82
+		$EZSQL_ERROR = $ezsql_error_cache;
83
+		// if there was a table doesn't exist error
84
+		if (! empty($new_error)) {
85
+			if (in_array(
86
+				\EEH_Activation::last_wpdb_error_code(),
87
+				array(
88
+					1051, // bad table
89
+					1109, // unknown table
90
+					117, // no such table
91
+				)
92
+			)
93
+				||
94
+				preg_match(
95
+					'~^Table .* doesn\'t exist~',
96
+					$new_error
97
+				) // in case not using mysql and error codes aren't reliable, just check for this error string
98
+			) {
99
+				return false;
100
+			} else {
101
+				// log this because that's weird. Just use the normal PHP error log
102
+				error_log(
103
+					sprintf(
104
+						__(
105
+							'Event Espresso error detected when checking if table existed: %1$s (it wasn\'t just that the table didn\'t exist either)',
106
+							'event_espresso'
107
+						),
108
+						$new_error
109
+					)
110
+				);
111
+			}
112
+		}
113
+		return true;
114
+	}
115 115
 
116 116
 
117
-    /**
118
-     * @param $table_name
119
-     * @param $index_name
120
-     * @return array of columns used on that index, Each entry is an object with the following properties {
121
-     * @type string Table
122
-     * @type string Non_unique "0" or "1"
123
-     * @type string Key_name
124
-     * @type string Seq_in_index
125
-     * @type string Column_name
126
-     * @type string Collation
127
-     * @type string Cardinality
128
-     * @type string Sub_part on a column, usually this is just the number of characters from this column to use in
129
-     *       indexing
130
-     * @type string|null Packed
131
-     * @type string Null
132
-     * @type string Index_type
133
-     * @type string Comment
134
-     * @type string Index_comment
135
-     * }
136
-     */
137
-    public function showIndexes($table_name, $index_name)
138
-    {
139
-        global $wpdb;
140
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
141
-        $index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
142
-        return $wpdb->get_results($index_exists_query);
143
-    }
117
+	/**
118
+	 * @param $table_name
119
+	 * @param $index_name
120
+	 * @return array of columns used on that index, Each entry is an object with the following properties {
121
+	 * @type string Table
122
+	 * @type string Non_unique "0" or "1"
123
+	 * @type string Key_name
124
+	 * @type string Seq_in_index
125
+	 * @type string Column_name
126
+	 * @type string Collation
127
+	 * @type string Cardinality
128
+	 * @type string Sub_part on a column, usually this is just the number of characters from this column to use in
129
+	 *       indexing
130
+	 * @type string|null Packed
131
+	 * @type string Null
132
+	 * @type string Index_type
133
+	 * @type string Comment
134
+	 * @type string Index_comment
135
+	 * }
136
+	 */
137
+	public function showIndexes($table_name, $index_name)
138
+	{
139
+		global $wpdb;
140
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
141
+		$index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
142
+		return $wpdb->get_results($index_exists_query);
143
+	}
144 144
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
     public function ensureTableNameHasPrefix($table_name)
33 33
     {
34 34
         global $wpdb;
35
-        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
35
+        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix.$table_name;
36 36
     }
37 37
 
38 38
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
         $wpdb->last_error = $old_error;
82 82
         $EZSQL_ERROR = $ezsql_error_cache;
83 83
         // if there was a table doesn't exist error
84
-        if (! empty($new_error)) {
84
+        if ( ! empty($new_error)) {
85 85
             if (in_array(
86 86
                 \EEH_Activation::last_wpdb_error_code(),
87 87
                 array(
Please login to merge, or discard this patch.
display_strategies/number_bubbles/NumberBubblesProgressStepsDisplay.php 2 patches
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -16,29 +16,29 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * used for setting up css and js required for the display strategy
21
-     *
22
-     * @return void
23
-     */
24
-    public function enqueueStylesAndScripts()
25
-    {
26
-        // core/services/progress_steps/display_strategies/number_bubbles/number_bubbles.css
27
-        wp_enqueue_style(
28
-            'ee_progress_steps_display_number_bubbles',
29
-            plugin_dir_url(__FILE__) . 'number_bubbles.css'
30
-        );
31
-    }
19
+	/**
20
+	 * used for setting up css and js required for the display strategy
21
+	 *
22
+	 * @return void
23
+	 */
24
+	public function enqueueStylesAndScripts()
25
+	{
26
+		// core/services/progress_steps/display_strategies/number_bubbles/number_bubbles.css
27
+		wp_enqueue_style(
28
+			'ee_progress_steps_display_number_bubbles',
29
+			plugin_dir_url(__FILE__) . 'number_bubbles.css'
30
+		);
31
+	}
32 32
 
33 33
 
34
-    /**
35
-     * loads and returns a full server path to the template used for the display strategy
36
-     *
37
-     * @return string
38
-     */
39
-    public function getTemplate()
40
-    {
41
-        // return plugin_dir_path( __FILE__ ) . 'number_bubbles.template.php';
42
-        return __DIR__ . DS . 'number_bubbles.template.php';
43
-    }
34
+	/**
35
+	 * loads and returns a full server path to the template used for the display strategy
36
+	 *
37
+	 * @return string
38
+	 */
39
+	public function getTemplate()
40
+	{
41
+		// return plugin_dir_path( __FILE__ ) . 'number_bubbles.template.php';
42
+		return __DIR__ . DS . 'number_bubbles.template.php';
43
+	}
44 44
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
         // core/services/progress_steps/display_strategies/number_bubbles/number_bubbles.css
27 27
         wp_enqueue_style(
28 28
             'ee_progress_steps_display_number_bubbles',
29
-            plugin_dir_url(__FILE__) . 'number_bubbles.css'
29
+            plugin_dir_url(__FILE__).'number_bubbles.css'
30 30
         );
31 31
     }
32 32
 
@@ -39,6 +39,6 @@  discard block
 block discarded – undo
39 39
     public function getTemplate()
40 40
     {
41 41
         // return plugin_dir_path( __FILE__ ) . 'number_bubbles.template.php';
42
-        return __DIR__ . DS . 'number_bubbles.template.php';
42
+        return __DIR__.DS.'number_bubbles.template.php';
43 43
     }
44 44
 }
Please login to merge, or discard this patch.
core/services/progress_steps/ProgressStep.php 2 patches
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -18,190 +18,190 @@
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * @var boolean $current
23
-     */
24
-    private $current = false;
25
-
26
-
27
-    /**
28
-     * @var boolean $completed
29
-     */
30
-    private $completed = false;
31
-
32
-
33
-    /**
34
-     * @var string $html_class
35
-     */
36
-    private $html_class;
37
-
38
-    /**
39
-     * @var string $id
40
-     */
41
-    private $id = '';
42
-
43
-    /**
44
-     * @var int $order
45
-     */
46
-    private $order = 0;
47
-
48
-    /**
49
-     * @var string $text
50
-     */
51
-    private $text = '';
52
-
53
-
54
-    /**
55
-     * ProgressStep constructor
56
-     *
57
-     * @param int    $order
58
-     * @param string $id
59
-     * @param string $html_class
60
-     * @param string $text
61
-     * @throws InvalidDataTypeException
62
-     */
63
-    public function __construct($order, $id, $html_class, $text)
64
-    {
65
-        $this->setOrder($order);
66
-        $this->setId($id);
67
-        $this->setHtmlClass($html_class);
68
-        $this->setText($text);
69
-    }
70
-
71
-
72
-    /**
73
-     * @return boolean
74
-     */
75
-    public function isCurrent()
76
-    {
77
-        return $this->current;
78
-    }
79
-
80
-
81
-    /**
82
-     * @param boolean $current
83
-     */
84
-    public function setIsCurrent($current = true)
85
-    {
86
-        $this->current = filter_var($current, FILTER_VALIDATE_BOOLEAN);
87
-    }
88
-
89
-
90
-    /**
91
-     * @return boolean
92
-     */
93
-    public function isCompleted()
94
-    {
95
-        return $this->completed;
96
-    }
97
-
98
-
99
-    /**
100
-     * @param boolean $completed
101
-     */
102
-    public function setIsCompleted($completed = true)
103
-    {
104
-        $this->completed = filter_var($completed, FILTER_VALIDATE_BOOLEAN);
105
-    }
106
-
107
-
108
-    /**
109
-     * @return string
110
-     */
111
-    public function id()
112
-    {
113
-        return $this->id;
114
-    }
115
-
116
-
117
-    /**
118
-     * @access protected
119
-     * @param string $id
120
-     * @throws InvalidDataTypeException
121
-     */
122
-    protected function setId($id = '')
123
-    {
124
-        if (! is_string($id)) {
125
-            throw new InvalidDataTypeException('$id', $id, 'string');
126
-        }
127
-        $this->id = $id;
128
-    }
129
-
130
-
131
-    /**
132
-     * @return int
133
-     */
134
-    public function order()
135
-    {
136
-        return $this->order;
137
-    }
138
-
139
-
140
-    /**
141
-     * @access protected
142
-     * @param int $order
143
-     * @throws InvalidDataTypeException
144
-     */
145
-    protected function setOrder($order = 0)
146
-    {
147
-        if (! is_int($order)) {
148
-            throw new InvalidDataTypeException('$order', $order, 'integer');
149
-        }
150
-        $this->order = $order;
151
-    }
152
-
153
-
154
-    /**
155
-     * @return string
156
-     */
157
-    public function htmlClass()
158
-    {
159
-        $html_class = $this->html_class;
160
-        if ($this->isCurrent()) {
161
-            $html_class .= ' progress-step-active';
162
-        } else if ($this->isCompleted()) {
163
-            $html_class .= ' progress-step-completed';
164
-        }
165
-        return $html_class;
166
-    }
167
-
168
-
169
-    /**
170
-     * @access protected
171
-     * @param string $html_class
172
-     * @throws InvalidDataTypeException
173
-     */
174
-    protected function setHtmlClass($html_class)
175
-    {
176
-        if (! is_string($html_class)) {
177
-            throw new InvalidDataTypeException('$html_class', $html_class, 'string');
178
-        }
179
-        if (strpos($html_class, 'progress-step-') === false) {
180
-            $html_class = 'progress-step-' . $html_class;
181
-        }
182
-        $this->html_class = $html_class;
183
-    }
184
-
185
-
186
-    /**
187
-     * @return string
188
-     */
189
-    public function text()
190
-    {
191
-        return $this->text;
192
-    }
193
-
194
-
195
-    /**
196
-     * @access protected
197
-     * @param string $text
198
-     * @throws InvalidDataTypeException
199
-     */
200
-    protected function setText($text)
201
-    {
202
-        if (! is_string($text)) {
203
-            throw new InvalidDataTypeException('$text', $text, 'string');
204
-        }
205
-        $this->text = $text;
206
-    }
21
+	/**
22
+	 * @var boolean $current
23
+	 */
24
+	private $current = false;
25
+
26
+
27
+	/**
28
+	 * @var boolean $completed
29
+	 */
30
+	private $completed = false;
31
+
32
+
33
+	/**
34
+	 * @var string $html_class
35
+	 */
36
+	private $html_class;
37
+
38
+	/**
39
+	 * @var string $id
40
+	 */
41
+	private $id = '';
42
+
43
+	/**
44
+	 * @var int $order
45
+	 */
46
+	private $order = 0;
47
+
48
+	/**
49
+	 * @var string $text
50
+	 */
51
+	private $text = '';
52
+
53
+
54
+	/**
55
+	 * ProgressStep constructor
56
+	 *
57
+	 * @param int    $order
58
+	 * @param string $id
59
+	 * @param string $html_class
60
+	 * @param string $text
61
+	 * @throws InvalidDataTypeException
62
+	 */
63
+	public function __construct($order, $id, $html_class, $text)
64
+	{
65
+		$this->setOrder($order);
66
+		$this->setId($id);
67
+		$this->setHtmlClass($html_class);
68
+		$this->setText($text);
69
+	}
70
+
71
+
72
+	/**
73
+	 * @return boolean
74
+	 */
75
+	public function isCurrent()
76
+	{
77
+		return $this->current;
78
+	}
79
+
80
+
81
+	/**
82
+	 * @param boolean $current
83
+	 */
84
+	public function setIsCurrent($current = true)
85
+	{
86
+		$this->current = filter_var($current, FILTER_VALIDATE_BOOLEAN);
87
+	}
88
+
89
+
90
+	/**
91
+	 * @return boolean
92
+	 */
93
+	public function isCompleted()
94
+	{
95
+		return $this->completed;
96
+	}
97
+
98
+
99
+	/**
100
+	 * @param boolean $completed
101
+	 */
102
+	public function setIsCompleted($completed = true)
103
+	{
104
+		$this->completed = filter_var($completed, FILTER_VALIDATE_BOOLEAN);
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return string
110
+	 */
111
+	public function id()
112
+	{
113
+		return $this->id;
114
+	}
115
+
116
+
117
+	/**
118
+	 * @access protected
119
+	 * @param string $id
120
+	 * @throws InvalidDataTypeException
121
+	 */
122
+	protected function setId($id = '')
123
+	{
124
+		if (! is_string($id)) {
125
+			throw new InvalidDataTypeException('$id', $id, 'string');
126
+		}
127
+		$this->id = $id;
128
+	}
129
+
130
+
131
+	/**
132
+	 * @return int
133
+	 */
134
+	public function order()
135
+	{
136
+		return $this->order;
137
+	}
138
+
139
+
140
+	/**
141
+	 * @access protected
142
+	 * @param int $order
143
+	 * @throws InvalidDataTypeException
144
+	 */
145
+	protected function setOrder($order = 0)
146
+	{
147
+		if (! is_int($order)) {
148
+			throw new InvalidDataTypeException('$order', $order, 'integer');
149
+		}
150
+		$this->order = $order;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @return string
156
+	 */
157
+	public function htmlClass()
158
+	{
159
+		$html_class = $this->html_class;
160
+		if ($this->isCurrent()) {
161
+			$html_class .= ' progress-step-active';
162
+		} else if ($this->isCompleted()) {
163
+			$html_class .= ' progress-step-completed';
164
+		}
165
+		return $html_class;
166
+	}
167
+
168
+
169
+	/**
170
+	 * @access protected
171
+	 * @param string $html_class
172
+	 * @throws InvalidDataTypeException
173
+	 */
174
+	protected function setHtmlClass($html_class)
175
+	{
176
+		if (! is_string($html_class)) {
177
+			throw new InvalidDataTypeException('$html_class', $html_class, 'string');
178
+		}
179
+		if (strpos($html_class, 'progress-step-') === false) {
180
+			$html_class = 'progress-step-' . $html_class;
181
+		}
182
+		$this->html_class = $html_class;
183
+	}
184
+
185
+
186
+	/**
187
+	 * @return string
188
+	 */
189
+	public function text()
190
+	{
191
+		return $this->text;
192
+	}
193
+
194
+
195
+	/**
196
+	 * @access protected
197
+	 * @param string $text
198
+	 * @throws InvalidDataTypeException
199
+	 */
200
+	protected function setText($text)
201
+	{
202
+		if (! is_string($text)) {
203
+			throw new InvalidDataTypeException('$text', $text, 'string');
204
+		}
205
+		$this->text = $text;
206
+	}
207 207
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
      */
122 122
     protected function setId($id = '')
123 123
     {
124
-        if (! is_string($id)) {
124
+        if ( ! is_string($id)) {
125 125
             throw new InvalidDataTypeException('$id', $id, 'string');
126 126
         }
127 127
         $this->id = $id;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
      */
145 145
     protected function setOrder($order = 0)
146 146
     {
147
-        if (! is_int($order)) {
147
+        if ( ! is_int($order)) {
148 148
             throw new InvalidDataTypeException('$order', $order, 'integer');
149 149
         }
150 150
         $this->order = $order;
@@ -173,11 +173,11 @@  discard block
 block discarded – undo
173 173
      */
174 174
     protected function setHtmlClass($html_class)
175 175
     {
176
-        if (! is_string($html_class)) {
176
+        if ( ! is_string($html_class)) {
177 177
             throw new InvalidDataTypeException('$html_class', $html_class, 'string');
178 178
         }
179 179
         if (strpos($html_class, 'progress-step-') === false) {
180
-            $html_class = 'progress-step-' . $html_class;
180
+            $html_class = 'progress-step-'.$html_class;
181 181
         }
182 182
         $this->html_class = $html_class;
183 183
     }
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
      */
200 200
     protected function setText($text)
201 201
     {
202
-        if (! is_string($text)) {
202
+        if ( ! is_string($text)) {
203 203
             throw new InvalidDataTypeException('$text', $text, 'string');
204 204
         }
205 205
         $this->text = $text;
Please login to merge, or discard this patch.
core/services/progress_steps/ProgressStepCollection.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -17,13 +17,13 @@
 block discarded – undo
17 17
 class ProgressStepCollection extends Collection
18 18
 {
19 19
 
20
-    /**
21
-     * ProgressStepCollection constructor.
22
-     *
23
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
24
-     */
25
-    public function __construct()
26
-    {
27
-        parent::__construct('\EventEspresso\core\services\progress_steps\ProgressStepInterface');
28
-    }
20
+	/**
21
+	 * ProgressStepCollection constructor.
22
+	 *
23
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
24
+	 */
25
+	public function __construct()
26
+	{
27
+		parent::__construct('\EventEspresso\core\services\progress_steps\ProgressStepInterface');
28
+	}
29 29
 }
Please login to merge, or discard this patch.
core/services/progress_steps/ProgressStepManager.php 2 patches
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -26,227 +26,227 @@
 block discarded – undo
26 26
 class ProgressStepManager
27 27
 {
28 28
 
29
-    /**
30
-     * @var ProgressStepInterface[] $collection
31
-     */
32
-    private $collection;
33
-
34
-    /**
35
-     * @var string $default_step
36
-     */
37
-    private $default_step;
38
-
39
-    /**
40
-     * the key used for the URL param that denotes the current form step
41
-     * defaults to 'ee-form-step'
42
-     *
43
-     * @var string $form_step_url_key
44
-     */
45
-    private $form_step_url_key = '';
46
-
47
-    /**
48
-     * @var ProgressStepsDisplayInterface $display_strategy
49
-     */
50
-    private $display_strategy;
51
-
52
-    /**
53
-     * @var EE_Request $request
54
-     */
55
-    private $request;
56
-
57
-
58
-    /**
59
-     * ProgressStepManager constructor
60
-     *
61
-     * @param string              $display_strategy_name
62
-     * @param string              $default_step
63
-     * @param string              $form_step_url_key
64
-     * @param CollectionInterface $collection
65
-     * @param \EE_Request         $request
66
-     * @throws InvalidClassException
67
-     * @throws InvalidDataTypeException
68
-     * @throws InvalidInterfaceException
69
-     */
70
-    public function __construct(
71
-        $display_strategy_name = 'number_bubbles',
72
-        $default_step = '',
73
-        $form_step_url_key = '',
74
-        CollectionInterface $collection = null,
75
-        EE_Request $request = null
76
-    ) {
77
-        $this->setDisplayStrategy($display_strategy_name);
78
-        $this->setDefaultStep($default_step);
79
-        $this->setFormStepUrlKey($form_step_url_key);
80
-        if (! $collection instanceof CollectionInterface) {
81
-            $collection = new Collection('\EventEspresso\core\services\progress_steps\ProgressStepInterface');
82
-        }
83
-        $this->collection = $collection;
84
-        if (! $request instanceof EE_Request) {
85
-            $request = \EE_Registry::instance()->load_core('Request');
86
-        }
87
-        $this->request = $request;
88
-    }
89
-
90
-
91
-    /**
92
-     * @param string $display_strategy_name
93
-     * @throws InvalidDataTypeException
94
-     * @throws InvalidClassException
95
-     */
96
-    protected function setDisplayStrategy($display_strategy_name = 'number_bubbles')
97
-    {
98
-        if (! is_string($display_strategy_name)) {
99
-            throw new InvalidDataTypeException('$display_strategy_name', $display_strategy_name, 'string');
100
-        }
101
-        // build up FQCN from incoming display strategy folder name
102
-        $display_strategy_class = 'EventEspresso\core\services\progress_steps\display_strategies\\';
103
-        $display_strategy_class .= $display_strategy_name . '\\';
104
-        $display_strategy_class .= str_replace(' ', '', ucwords(str_replace('_', ' ', $display_strategy_name)));
105
-        $display_strategy_class .= 'ProgressStepsDisplay';
106
-        $display_strategy_class = apply_filters(
107
-            'FHEE__ProgressStepManager__setDisplayStrategy__display_strategy_class',
108
-            $display_strategy_class
109
-        );
110
-        if (! class_exists($display_strategy_class)) {
111
-            throw new InvalidClassException($display_strategy_class);
112
-        }
113
-        $display_strategy = new $display_strategy_class();
114
-        if (! $display_strategy instanceof ProgressStepsDisplayInterface) {
115
-            throw new InvalidClassException(
116
-                $display_strategy_class,
117
-                sprintf(
118
-                    __('The "%1$s" Class needs to be an implementation of the "%1$s" Interface.', 'event_espresso'),
119
-                    $display_strategy_class,
120
-                    '\EventEspresso\core\services\progress_steps\display_strategies\ProgressStepsDisplayInterface'
121
-                )
122
-            );
123
-        }
124
-        $this->display_strategy = $display_strategy;
125
-    }
126
-
127
-
128
-    /**
129
-     * @param string $default_step
130
-     * @throws InvalidDataTypeException
131
-     */
132
-    public function setDefaultStep($default_step)
133
-    {
134
-        if (! is_string($default_step)) {
135
-            throw new InvalidDataTypeException('$default_step', $default_step, 'string');
136
-        }
137
-        $this->default_step = $default_step;
138
-    }
139
-
140
-
141
-    /**
142
-     * @param string $form_step_url_key
143
-     * @throws InvalidDataTypeException
144
-     */
145
-    public function setFormStepUrlKey($form_step_url_key = 'ee-form-step')
146
-    {
147
-        if (! is_string($form_step_url_key)) {
148
-            throw new InvalidDataTypeException('$form_step_key', $form_step_url_key, 'string');
149
-        }
150
-        $this->form_step_url_key = ! empty($form_step_url_key) ? $form_step_url_key : 'ee-form-step';
151
-    }
152
-
153
-
154
-    /**
155
-     * @param string $step
156
-     * @throws InvalidIdentifierException
157
-     */
158
-    public function setCurrentStep($step = '')
159
-    {
160
-        // use incoming value if it's set, otherwise use request param if it's set, otherwise use default
161
-        $step = ! empty($step)
162
-            ? $step
163
-            : $this->request->get($this->form_step_url_key, $this->default_step);
164
-        // grab the step previously known as current, in case we need to revert
165
-        $current_current_step = $this->collection->current();
166
-        // verify that requested step exists
167
-        if (! $this->collection->has($step)) {
168
-            throw new InvalidIdentifierException($step, $this->default_step);
169
-        }
170
-        if ($this->collection->setCurrent($step)) {
171
-            // if the old boss is the same as the new boss, then nothing changes
172
-            if ($this->collection->current() !== $current_current_step) {
173
-                $current_current_step->setIsCurrent(false);
174
-            }
175
-            $this->collection->current()->setIsCurrent();
176
-        } else {
177
-            $this->collection->setCurrent($current_current_step->id());
178
-            $current_current_step->setIsCurrent(true);
179
-        }
180
-    }
181
-
182
-
183
-    /**
184
-     * setPreviousStepsCompleted
185
-     */
186
-    public function setPreviousStepsCompleted()
187
-    {
188
-        $current_current_step = $this->collection->current();
189
-        $this->collection->rewind();
190
-        while ($this->collection->valid()) {
191
-            if ($this->collection->current() === $current_current_step) {
192
-                break;
193
-            }
194
-            $this->setCurrentStepCompleted();
195
-            $this->collection->next();
196
-        }
197
-        $this->collection->setCurrentUsingObject($current_current_step);
198
-        return false;
199
-    }
200
-
201
-
202
-    /**
203
-     * @return ProgressStepInterface
204
-     */
205
-    public function currentStep()
206
-    {
207
-        return $this->collection->current();
208
-    }
209
-
210
-
211
-    /**
212
-     * @return ProgressStepInterface
213
-     */
214
-    public function nextStep()
215
-    {
216
-        return $this->collection->next();
217
-    }
218
-
219
-
220
-    /**
221
-     * @return void
222
-     */
223
-    public function enqueueStylesAndScripts()
224
-    {
225
-        $this->display_strategy->enqueueStylesAndScripts();
226
-    }
227
-
228
-
229
-    /**
230
-     * echos out HTML
231
-     *
232
-     * @return string
233
-     */
234
-    public function displaySteps()
235
-    {
236
-        return \EEH_Template::display_template(
237
-            $this->display_strategy->getTemplate(),
238
-            array('progress_steps' => $this->collection),
239
-            true
240
-        );
241
-    }
242
-
243
-
244
-    /**
245
-     * @param bool $completed
246
-     * @return \EventEspresso\core\services\progress_steps\ProgressStepInterface
247
-     */
248
-    public function setCurrentStepCompleted($completed = true)
249
-    {
250
-        return $this->collection->current()->setIsCompleted($completed);
251
-    }
29
+	/**
30
+	 * @var ProgressStepInterface[] $collection
31
+	 */
32
+	private $collection;
33
+
34
+	/**
35
+	 * @var string $default_step
36
+	 */
37
+	private $default_step;
38
+
39
+	/**
40
+	 * the key used for the URL param that denotes the current form step
41
+	 * defaults to 'ee-form-step'
42
+	 *
43
+	 * @var string $form_step_url_key
44
+	 */
45
+	private $form_step_url_key = '';
46
+
47
+	/**
48
+	 * @var ProgressStepsDisplayInterface $display_strategy
49
+	 */
50
+	private $display_strategy;
51
+
52
+	/**
53
+	 * @var EE_Request $request
54
+	 */
55
+	private $request;
56
+
57
+
58
+	/**
59
+	 * ProgressStepManager constructor
60
+	 *
61
+	 * @param string              $display_strategy_name
62
+	 * @param string              $default_step
63
+	 * @param string              $form_step_url_key
64
+	 * @param CollectionInterface $collection
65
+	 * @param \EE_Request         $request
66
+	 * @throws InvalidClassException
67
+	 * @throws InvalidDataTypeException
68
+	 * @throws InvalidInterfaceException
69
+	 */
70
+	public function __construct(
71
+		$display_strategy_name = 'number_bubbles',
72
+		$default_step = '',
73
+		$form_step_url_key = '',
74
+		CollectionInterface $collection = null,
75
+		EE_Request $request = null
76
+	) {
77
+		$this->setDisplayStrategy($display_strategy_name);
78
+		$this->setDefaultStep($default_step);
79
+		$this->setFormStepUrlKey($form_step_url_key);
80
+		if (! $collection instanceof CollectionInterface) {
81
+			$collection = new Collection('\EventEspresso\core\services\progress_steps\ProgressStepInterface');
82
+		}
83
+		$this->collection = $collection;
84
+		if (! $request instanceof EE_Request) {
85
+			$request = \EE_Registry::instance()->load_core('Request');
86
+		}
87
+		$this->request = $request;
88
+	}
89
+
90
+
91
+	/**
92
+	 * @param string $display_strategy_name
93
+	 * @throws InvalidDataTypeException
94
+	 * @throws InvalidClassException
95
+	 */
96
+	protected function setDisplayStrategy($display_strategy_name = 'number_bubbles')
97
+	{
98
+		if (! is_string($display_strategy_name)) {
99
+			throw new InvalidDataTypeException('$display_strategy_name', $display_strategy_name, 'string');
100
+		}
101
+		// build up FQCN from incoming display strategy folder name
102
+		$display_strategy_class = 'EventEspresso\core\services\progress_steps\display_strategies\\';
103
+		$display_strategy_class .= $display_strategy_name . '\\';
104
+		$display_strategy_class .= str_replace(' ', '', ucwords(str_replace('_', ' ', $display_strategy_name)));
105
+		$display_strategy_class .= 'ProgressStepsDisplay';
106
+		$display_strategy_class = apply_filters(
107
+			'FHEE__ProgressStepManager__setDisplayStrategy__display_strategy_class',
108
+			$display_strategy_class
109
+		);
110
+		if (! class_exists($display_strategy_class)) {
111
+			throw new InvalidClassException($display_strategy_class);
112
+		}
113
+		$display_strategy = new $display_strategy_class();
114
+		if (! $display_strategy instanceof ProgressStepsDisplayInterface) {
115
+			throw new InvalidClassException(
116
+				$display_strategy_class,
117
+				sprintf(
118
+					__('The "%1$s" Class needs to be an implementation of the "%1$s" Interface.', 'event_espresso'),
119
+					$display_strategy_class,
120
+					'\EventEspresso\core\services\progress_steps\display_strategies\ProgressStepsDisplayInterface'
121
+				)
122
+			);
123
+		}
124
+		$this->display_strategy = $display_strategy;
125
+	}
126
+
127
+
128
+	/**
129
+	 * @param string $default_step
130
+	 * @throws InvalidDataTypeException
131
+	 */
132
+	public function setDefaultStep($default_step)
133
+	{
134
+		if (! is_string($default_step)) {
135
+			throw new InvalidDataTypeException('$default_step', $default_step, 'string');
136
+		}
137
+		$this->default_step = $default_step;
138
+	}
139
+
140
+
141
+	/**
142
+	 * @param string $form_step_url_key
143
+	 * @throws InvalidDataTypeException
144
+	 */
145
+	public function setFormStepUrlKey($form_step_url_key = 'ee-form-step')
146
+	{
147
+		if (! is_string($form_step_url_key)) {
148
+			throw new InvalidDataTypeException('$form_step_key', $form_step_url_key, 'string');
149
+		}
150
+		$this->form_step_url_key = ! empty($form_step_url_key) ? $form_step_url_key : 'ee-form-step';
151
+	}
152
+
153
+
154
+	/**
155
+	 * @param string $step
156
+	 * @throws InvalidIdentifierException
157
+	 */
158
+	public function setCurrentStep($step = '')
159
+	{
160
+		// use incoming value if it's set, otherwise use request param if it's set, otherwise use default
161
+		$step = ! empty($step)
162
+			? $step
163
+			: $this->request->get($this->form_step_url_key, $this->default_step);
164
+		// grab the step previously known as current, in case we need to revert
165
+		$current_current_step = $this->collection->current();
166
+		// verify that requested step exists
167
+		if (! $this->collection->has($step)) {
168
+			throw new InvalidIdentifierException($step, $this->default_step);
169
+		}
170
+		if ($this->collection->setCurrent($step)) {
171
+			// if the old boss is the same as the new boss, then nothing changes
172
+			if ($this->collection->current() !== $current_current_step) {
173
+				$current_current_step->setIsCurrent(false);
174
+			}
175
+			$this->collection->current()->setIsCurrent();
176
+		} else {
177
+			$this->collection->setCurrent($current_current_step->id());
178
+			$current_current_step->setIsCurrent(true);
179
+		}
180
+	}
181
+
182
+
183
+	/**
184
+	 * setPreviousStepsCompleted
185
+	 */
186
+	public function setPreviousStepsCompleted()
187
+	{
188
+		$current_current_step = $this->collection->current();
189
+		$this->collection->rewind();
190
+		while ($this->collection->valid()) {
191
+			if ($this->collection->current() === $current_current_step) {
192
+				break;
193
+			}
194
+			$this->setCurrentStepCompleted();
195
+			$this->collection->next();
196
+		}
197
+		$this->collection->setCurrentUsingObject($current_current_step);
198
+		return false;
199
+	}
200
+
201
+
202
+	/**
203
+	 * @return ProgressStepInterface
204
+	 */
205
+	public function currentStep()
206
+	{
207
+		return $this->collection->current();
208
+	}
209
+
210
+
211
+	/**
212
+	 * @return ProgressStepInterface
213
+	 */
214
+	public function nextStep()
215
+	{
216
+		return $this->collection->next();
217
+	}
218
+
219
+
220
+	/**
221
+	 * @return void
222
+	 */
223
+	public function enqueueStylesAndScripts()
224
+	{
225
+		$this->display_strategy->enqueueStylesAndScripts();
226
+	}
227
+
228
+
229
+	/**
230
+	 * echos out HTML
231
+	 *
232
+	 * @return string
233
+	 */
234
+	public function displaySteps()
235
+	{
236
+		return \EEH_Template::display_template(
237
+			$this->display_strategy->getTemplate(),
238
+			array('progress_steps' => $this->collection),
239
+			true
240
+		);
241
+	}
242
+
243
+
244
+	/**
245
+	 * @param bool $completed
246
+	 * @return \EventEspresso\core\services\progress_steps\ProgressStepInterface
247
+	 */
248
+	public function setCurrentStepCompleted($completed = true)
249
+	{
250
+		return $this->collection->current()->setIsCompleted($completed);
251
+	}
252 252
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -77,11 +77,11 @@  discard block
 block discarded – undo
77 77
         $this->setDisplayStrategy($display_strategy_name);
78 78
         $this->setDefaultStep($default_step);
79 79
         $this->setFormStepUrlKey($form_step_url_key);
80
-        if (! $collection instanceof CollectionInterface) {
80
+        if ( ! $collection instanceof CollectionInterface) {
81 81
             $collection = new Collection('\EventEspresso\core\services\progress_steps\ProgressStepInterface');
82 82
         }
83 83
         $this->collection = $collection;
84
-        if (! $request instanceof EE_Request) {
84
+        if ( ! $request instanceof EE_Request) {
85 85
             $request = \EE_Registry::instance()->load_core('Request');
86 86
         }
87 87
         $this->request = $request;
@@ -95,23 +95,23 @@  discard block
 block discarded – undo
95 95
      */
96 96
     protected function setDisplayStrategy($display_strategy_name = 'number_bubbles')
97 97
     {
98
-        if (! is_string($display_strategy_name)) {
98
+        if ( ! is_string($display_strategy_name)) {
99 99
             throw new InvalidDataTypeException('$display_strategy_name', $display_strategy_name, 'string');
100 100
         }
101 101
         // build up FQCN from incoming display strategy folder name
102 102
         $display_strategy_class = 'EventEspresso\core\services\progress_steps\display_strategies\\';
103
-        $display_strategy_class .= $display_strategy_name . '\\';
103
+        $display_strategy_class .= $display_strategy_name.'\\';
104 104
         $display_strategy_class .= str_replace(' ', '', ucwords(str_replace('_', ' ', $display_strategy_name)));
105 105
         $display_strategy_class .= 'ProgressStepsDisplay';
106 106
         $display_strategy_class = apply_filters(
107 107
             'FHEE__ProgressStepManager__setDisplayStrategy__display_strategy_class',
108 108
             $display_strategy_class
109 109
         );
110
-        if (! class_exists($display_strategy_class)) {
110
+        if ( ! class_exists($display_strategy_class)) {
111 111
             throw new InvalidClassException($display_strategy_class);
112 112
         }
113 113
         $display_strategy = new $display_strategy_class();
114
-        if (! $display_strategy instanceof ProgressStepsDisplayInterface) {
114
+        if ( ! $display_strategy instanceof ProgressStepsDisplayInterface) {
115 115
             throw new InvalidClassException(
116 116
                 $display_strategy_class,
117 117
                 sprintf(
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     public function setDefaultStep($default_step)
133 133
     {
134
-        if (! is_string($default_step)) {
134
+        if ( ! is_string($default_step)) {
135 135
             throw new InvalidDataTypeException('$default_step', $default_step, 'string');
136 136
         }
137 137
         $this->default_step = $default_step;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
      */
145 145
     public function setFormStepUrlKey($form_step_url_key = 'ee-form-step')
146 146
     {
147
-        if (! is_string($form_step_url_key)) {
147
+        if ( ! is_string($form_step_url_key)) {
148 148
             throw new InvalidDataTypeException('$form_step_key', $form_step_url_key, 'string');
149 149
         }
150 150
         $this->form_step_url_key = ! empty($form_step_url_key) ? $form_step_url_key : 'ee-form-step';
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
         // grab the step previously known as current, in case we need to revert
165 165
         $current_current_step = $this->collection->current();
166 166
         // verify that requested step exists
167
-        if (! $this->collection->has($step)) {
167
+        if ( ! $this->collection->has($step)) {
168 168
             throw new InvalidIdentifierException($step, $this->default_step);
169 169
         }
170 170
         if ($this->collection->setCurrent($step)) {
Please login to merge, or discard this patch.