Completed
Pull Request — master (#566)
by
unknown
03:50
created

Expectation::globally()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Mockery
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to the new BSD license that is bundled
8
 * with this package in the file LICENSE.txt.
9
 * It is also available through the world-wide-web at this URL:
10
 * http://github.com/padraic/mockery/blob/master/LICENSE
11
 * If you did not receive a copy of the license and are unable to
12
 * obtain it through the world-wide-web, please send an email
13
 * to [email protected] so we can send you a copy immediately.
14
 *
15
 * @category   Mockery
16
 * @package    Mockery
17
 * @copyright  Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
18
 * @license    http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
19
 */
20
21
namespace Mockery;
22
23
use Closure;
24
use Mockery\Matcher\MultiArgumentClosure;
25
26
class Expectation implements ExpectationInterface
27
{
28
    /**
29
     * Mock object to which this expectation belongs
30
     *
31
     * @var object
32
     */
33
    protected $_mock = null;
34
35
    /**
36
     * Method name
37
     *
38
     * @var string
39
     */
40
    protected $_name = null;
41
42
    /**
43
     * Arguments expected by this expectation
44
     *
45
     * @var array
46
     */
47
    protected $_expectedArgs = array();
48
49
    /**
50
     * Count validator store
51
     *
52
     * @var \Mockery\CountValidator\CountValidatorAbstract[]
53
     */
54
    protected $_countValidators = array();
55
56
    /**
57
     * The count validator class to use
58
     *
59
     * @var string
60
     */
61
    protected $_countValidatorClass = 'Mockery\CountValidator\Exact';
62
63
    /**
64
     * Actual count of calls to this expectation
65
     *
66
     * @var int
67
     */
68
    protected $_actualCount = 0;
69
70
    /**
71
     * Value to return from this expectation
72
     *
73
     * @var mixed
74
     */
75
    protected $_returnValue = null;
76
77
    /**
78
     * Array of return values as a queue for multiple return sequence
79
     *
80
     * @var array
81
     */
82
    protected $_returnQueue = array();
83
84
    /**
85
     * Array of closures executed with given arguments to generate a result
86
     * to be returned
87
     *
88
     * @var array
89
     */
90
    protected $_closureQueue = array();
91
92
    /**
93
     * Array of values to be set when this expectation matches
94
     *
95
     * @var array
96
     */
97
    protected $_setQueue = array();
98
99
    /**
100
     * Integer representing the call order of this expectation
101
     *
102
     * @var int
103
     */
104
    protected $_orderNumber = null;
105
106
    /**
107
     * Integer representing the call order of this expectation on a global basis
108
     *
109
     * @var int
110
     */
111
    protected $_globalOrderNumber = null;
112
113
    /**
114
     * Flag indicating that an exception is expected to be throw (not returned)
115
     *
116
     * @var bool
117
     */
118
    protected $_throw = false;
119
120
    /**
121
     * Flag indicating whether the order of calling is determined locally or
122
     * globally
123
     *
124
     * @var bool
125
     */
126
    protected $_globally = false;
127
128
    /**
129
     * Flag indicating we expect no arguments
130
     *
131
     * @var bool
132
     */
133
    protected $_noArgsExpectation = false;
134
135
    /**
136
     * Flag indicating if the return value should be obtained from the original
137
     * class method instead of returning predefined values from the return queue
138
     *
139
     * @var bool
140
     */
141
    protected $_passthru = false;
142
143
    /**
144
     * Constructor
145
     *
146
     * @param \Mockery\MockInterface $mock
147
     * @param string $name
148
     */
149 311
    public function __construct(\Mockery\MockInterface $mock, $name)
150
    {
151 311
        $this->_mock = $mock;
152 311
        $this->_name = $name;
153 311
    }
154
155
    /**
156
     * Return a string with the method name and arguments formatted
157
     *
158
     * @param string $name Name of the expected method
159
     * @param array $args List of arguments to the method
160
     * @return string
161
     */
162 45
    public function __toString()
163
    {
164 45
        return \Mockery::formatArgs($this->_name, $this->_expectedArgs);
165
    }
166
167
    /**
168
     * Verify the current call, i.e. that the given arguments match those
169
     * of this expectation
170
     *
171
     * @param array $args
172
     * @return mixed
173
     */
174 239
    public function verifyCall(array $args)
175
    {
176 239
        $this->validateOrder();
177 239
        $this->_actualCount++;
178 239
        if (true === $this->_passthru) {
179 3
            return $this->_mock->mockery_callSubjectMethod($this->_name, $args);
180
        }
181 237
        $return = $this->_getReturnValue($args);
182 237
        if ($return instanceof \Exception && $this->_throw === true) {
183 7
            throw $return;
184
        }
185 231
        $this->_setValues();
186 231
        return $return;
187
    }
188
189
    /**
190
     * Sets public properties with queued values to the mock object
191
     *
192
     * @param array $args
0 ignored issues
show
Bug introduced by
There is no parameter named $args. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
193
     * @return mixed
194
     */
195 231
    protected function _setValues()
196
    {
197 231
        foreach ($this->_setQueue as $name => &$values) {
198 8
            if (count($values) > 0) {
199 8
                $value = array_shift($values);
200 8
                $this->_mock->{$name} = $value;
201 8
            }
202 231
        }
203 231
    }
204
205
    /**
206
     * Fetch the return value for the matching args
207
     *
208
     * @param array $args
209
     * @return mixed
210
     */
211 237
    protected function _getReturnValue(array $args)
212
    {
213 237
        if (count($this->_closureQueue) > 1) {
214
            return call_user_func_array(array_shift($this->_closureQueue), $args);
215 237
        } elseif (count($this->_closureQueue) > 0) {
216 1
            return call_user_func_array(current($this->_closureQueue), $args);
217 236
        } elseif (count($this->_returnQueue) > 1) {
218 5
            return array_shift($this->_returnQueue);
219 235
        } elseif (count($this->_returnQueue) > 0) {
220 98
            return current($this->_returnQueue);
221
        }
222
223 138
        return $this->_mock->mockery_returnValueForMethod($this->_name);
224
    }
225
226
    /**
227
     * Checks if this expectation is eligible for additional calls
228
     *
229
     * @return bool
230
     */
231 279
    public function isEligible()
232
    {
233 279
        foreach ($this->_countValidators as $validator) {
234 142
            if (!$validator->isEligible($this->_actualCount)) {
235 16
                return false;
236
            }
237 276
        }
238 276
        return true;
239
    }
240
241 246
    public function isExpected()
242
    {
243 246
        foreach ($this->_countValidators as $validator) {
244 136
            if ($validator->isEligible($this->_actualCount)) {
245 133
                return true;
246
            }
247 162
        }
248 162
        return false;
249
    }
250
251
    /**
252
     * Check if there is a constraint on call count
253
     *
254
     * @return bool
255
     */
256
    public function isCallCountConstrained()
257
    {
258
        return (count($this->_countValidators) > 0);
259
    }
260
261
    /**
262
     * Verify call order
263
     *
264
     * @return void
265
     */
266 239
    public function validateOrder()
267
    {
268 239
        if ($this->_orderNumber) {
269 17
            $this->_mock->mockery_validateOrder((string) $this, $this->_orderNumber, $this->_mock);
270 17
        }
271 239
        if ($this->_globalOrderNumber) {
272 1
            $this->_mock->mockery_getContainer()
273 1
                ->mockery_validateOrder((string) $this, $this->_globalOrderNumber, $this->_mock);
274 1
        }
275 239
    }
276
277
    /**
278
     * Verify this expectation
279
     *
280
     * @return bool
281
     */
282 149
    public function verify()
283
    {
284 149
        foreach ($this->_countValidators as $validator) {
285 120
            $validator->validate($this->_actualCount);
286 133
        }
287 131
    }
288
289
    /**
290
     * Check if the registered expectation is a MultiArgumentClosureExpectation.
291
     * @return bool
292
     */
293 125
    private function isMultiArgumentClosureExpectation()
294
    {
295 125
        return (count($this->_expectedArgs) === 1 && ($this->_expectedArgs[0] instanceof \Mockery\Matcher\MultiArgumentClosure));
296
    }
297
298
    /**
299
     * Check if passed arguments match an argument expectation
300
     *
301
     * @param array $args
302
     * @return bool
303
     */
304 285
    public function matchArgs(array $args)
305
    {
306 285
        if (empty($this->_expectedArgs) && !$this->_noArgsExpectation) {
307 165
            return true;
308
        }
309 125
        if ($this->isMultiArgumentClosureExpectation()) {
310 6
            return $this->_matchArg($this->_expectedArgs[0], $args);
311
        }
312 119
        $argCount = count($args);
313 119
        if ($argCount !== count($this->_expectedArgs)) {
314 8
            return false;
315
        }
316 113
        for ($i=0; $i<$argCount; $i++) {
317 110
            $param =& $args[$i];
318 110
            if (!$this->_matchArg($this->_expectedArgs[$i], $param)) {
319 47
                return false;
320
            }
321 72
        }
322
323 75
        return true;
324
    }
325
326
    /**
327
     * Check if passed argument matches an argument expectation
328
     *
329
     * @param mixed $expected
330
     * @param mixed &$actual
331
     * @return bool
332
     */
333 116
    protected function _matchArg($expected, &$actual)
334
    {
335 116
        if ($expected === $actual) {
336 33
            return true;
337
        }
338 95
        if (!is_object($expected) && !is_object($actual) && $expected == $actual) {
339 1
            return true;
340
        }
341 94
        if (is_string($expected) && !is_array($actual) && !is_object($actual)) {
342
            # push/pop an error handler here to to make sure no error/exception thrown if $expected is not a regex
343 6
            set_error_handler(function () {
344 6
            });
345 6
            $result = preg_match($expected, (string) $actual);
346 6
            restore_error_handler();
347
348 6
            if ($result) {
349 3
                return true;
350
            }
351 3
        }
352 93
        if (is_string($expected) && is_object($actual)) {
353 1
            $result = $actual instanceof $expected;
354 1
            if ($result) {
355 1
                return true;
356
            }
357
        }
358 92
        if ($expected instanceof \Mockery\Matcher\MatcherAbstract) {
359 70
            return $expected->match($actual);
360
        }
361 22
        if ($expected instanceof \Hamcrest\Matcher || $expected instanceof \Hamcrest_Matcher) {
0 ignored issues
show
Bug introduced by
The class Hamcrest_Matcher does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
362 3
            return $expected->matches($actual);
363
        }
364 19
        return false;
365
    }
366
367
    /**
368
     * Expected argument setter for the expectation
369
     *
370
     * @param mixed ...
371
     * @return Expectation
372
     */
373 141
    public function with()
374
    {
375 141
        return $this->withArgs(func_get_args());
376
    }
377
378
    /**
379
     * Expected arguments for the expectation passed as an array
380
     *
381
     * @param array $arguments
382
     * @return Expectation
383
     */
384 146
    private function withArgsInArray(array $arguments)
385
    {
386 146
        if (empty($arguments)) {
387 6
            return $this->withNoArgs();
388
        }
389 143
        $this->_expectedArgs = $arguments;
390 143
        $this->_noArgsExpectation = false;
391 143
        return $this;
392
    }
393
394
    /**
395
     * Expected arguments have to be matched by the given closure.
396
     *
397
     * @param Closure $closure
398
     * @return Expectation
399
     */
400 6
    private function withArgsMatchedByClosure(Closure $closure)
401
    {
402 6
        $this->_expectedArgs = [new MultiArgumentClosure($closure)];
403 6
        $this->_noArgsExpectation = false;
404 6
        return $this;
405
    }
406
407
    /**
408
     * Expected arguments for the expectation passed as an array or a closure that matches each passed argument on
409
     * each function call.
410
     *
411
     * @param array|Closure $argsOrClosure
412
     * @return Expectation
413
     */
414 153
    public function withArgs($argsOrClosure)
415
    {
416 153
        if (is_array($argsOrClosure)) {
417 146
            $this->withArgsInArray($argsOrClosure);
418 153
        } elseif ($argsOrClosure instanceof Closure) {
419 6
            $this->withArgsMatchedByClosure($argsOrClosure);
420 6
        } else {
421 1
            throw new \InvalidArgumentException(sprintf('Call to %s with an invalid argument (%s), only array and '.
422 1
                'closure are allowed', __METHOD__, $argsOrClosure));
423
        }
424 152
        return $this;
425
    }
426
427
    /**
428
     * Set with() as no arguments expected
429
     *
430
     * @return Expectation
431
     */
432 10
    public function withNoArgs()
433
    {
434 10
        $this->_noArgsExpectation = true;
435 10
        $this->_expectedArgs = [];
436 10
        return $this;
437
    }
438
439
    /**
440
     * Set expectation that any arguments are acceptable
441
     *
442
     * @return Expectation
443
     */
444 2
    public function withAnyArgs()
445
    {
446 2
        $this->_expectedArgs = array();
447 2
        return $this;
448
    }
449
450
    /**
451
     * Set a return value, or sequential queue of return values
452
     *
453
     * @param mixed ...
454
     * @return Expectation
455
     */
456 113
    public function andReturn()
457
    {
458 113
        $this->_returnQueue = func_get_args();
459 113
        return $this;
460
    }
461
462
    /**
463
     * Return this mock, like a fluent interface
464
     *
465
     * @return Expectation
466
     */
467 1
    public function andReturnSelf()
468
    {
469 1
        return $this->andReturn($this->_mock);
470
    }
471
472
    /**
473
     * Set a sequential queue of return values with an array
474
     *
475
     * @param array $values
476
     * @return Expectation
477
     */
478 2
    public function andReturnValues(array $values)
479
    {
480 2
        call_user_func_array(array($this, 'andReturn'), $values);
481 2
        return $this;
482
    }
483
484
    /**
485
     * Set a closure or sequence of closures with which to generate return
486
     * values. The arguments passed to the expected method are passed to the
487
     * closures as parameters.
488
     *
489
     * @param callable ...
490
     * @return Expectation
491
     */
492 1
    public function andReturnUsing()
493
    {
494 1
        $this->_closureQueue = func_get_args();
495 1
        return $this;
496
    }
497
498
    /**
499
     * Return a self-returning black hole object.
500
     *
501
     * @return Expectation
502
     */
503 1
    public function andReturnUndefined()
504
    {
505 1
        $this->andReturn(new \Mockery\Undefined);
506 1
        return $this;
507
    }
508
509
    /**
510
     * Return null. This is merely a language construct for Mock describing.
511
     *
512
     * @return Expectation
513
     */
514 1
    public function andReturnNull()
515
    {
516 1
        return $this;
517
    }
518
519 1
    public function andReturnFalse()
520
    {
521 1
        return $this->andReturn(false);
522
    }
523
524 1
    public function andReturnTrue()
525
    {
526 1
        return $this->andReturn(true);
527
    }
528
529
    /**
530
     * Set Exception class and arguments to that class to be thrown
531
     *
532
     * @param string|\Exception $exception
533
     * @param string $message
534
     * @param int $code
535
     * @param \Exception $previous
536
     * @return Expectation
537
     */
538 6
    public function andThrow($exception, $message = '', $code = 0, \Exception $previous = null)
539
    {
540 6
        $this->_throw = true;
541 6
        if (is_object($exception)) {
542 2
            $this->andReturn($exception);
543 2
        } else {
544 4
            $this->andReturn(new $exception($message, $code, $previous));
545
        }
546 6
        return $this;
547
    }
548
549
    /**
550
     * Set Exception classes to be thrown
551
     *
552
     * @param array $exceptions
553
     * @return Expectation
554
     */
555 2
    public function andThrowExceptions(array $exceptions)
556
    {
557 2
        $this->_throw = true;
558 2
        foreach ($exceptions as $exception) {
559 2
            if (!is_object($exception)) {
560 1
                throw new Exception('You must pass an array of exception objects to andThrowExceptions');
561
            }
562 1
        }
563 1
        return $this->andReturnValues($exceptions);
564
    }
565
566
    /**
567
     * Register values to be set to a public property each time this expectation occurs
568
     *
569
     * @param string $name
570
     * @param mixed $value
571
     * @return Expectation
572
     */
573 8
    public function andSet($name, $value)
574
    {
575 8
        $values = func_get_args();
576 8
        array_shift($values);
577 8
        $this->_setQueue[$name] = $values;
578 8
        return $this;
579
    }
580
581
    /**
582
     * Alias to andSet(). Allows the natural English construct
583
     * - set('foo', 'bar')->andReturn('bar')
584
     *
585
     * @param string $name
586
     * @param mixed $value
587
     * @return Expectation
588
     */
589 3
    public function set($name, $value)
590
    {
591 3
        return call_user_func_array(array($this, 'andSet'), func_get_args());
592
    }
593
594
    /**
595
     * Indicates this expectation should occur zero or more times
596
     *
597
     * @return Expectation
598
     */
599 2
    public function zeroOrMoreTimes()
600
    {
601 2
        $this->atLeast()->never();
602 2
    }
603
604
    /**
605
     * Indicates the number of times this expectation should occur
606
     *
607
     * @param int $limit
608
     * @throws InvalidArgumentException
609
     * @return Expectation
610
     */
611 160
    public function times($limit = null)
612
    {
613 160
        if (is_null($limit)) {
614
            return $this;
615
        }
616 160
        if (!is_int($limit)) {
617 1
            throw new \InvalidArgumentException('The passed Times limit should be an integer value');
618
        }
619 159
        $this->_countValidators[] = new $this->_countValidatorClass($this, $limit);
620 159
        $this->_countValidatorClass = 'Mockery\CountValidator\Exact';
621 159
        return $this;
622
    }
623
624
    /**
625
     * Indicates that this expectation is never expected to be called
626
     *
627
     * @return Expectation
628
     */
629 38
    public function never()
630
    {
631 38
        return $this->times(0);
632
    }
633
634
    /**
635
     * Indicates that this expectation is expected exactly once
636
     *
637
     * @return Expectation
638
     */
639 110
    public function once()
640
    {
641 110
        return $this->times(1);
642
    }
643
644
    /**
645
     * Indicates that this expectation is expected exactly twice
646
     *
647
     * @return Expectation
648
     */
649 18
    public function twice()
650
    {
651 18
        return $this->times(2);
652
    }
653
654
    /**
655
     * Sets next count validator to the AtLeast instance
656
     *
657
     * @return Expectation
658
     */
659 14
    public function atLeast()
660
    {
661 14
        $this->_countValidatorClass = 'Mockery\CountValidator\AtLeast';
662 14
        return $this;
663
    }
664
665
    /**
666
     * Sets next count validator to the AtMost instance
667
     *
668
     * @return Expectation
669
     */
670 7
    public function atMost()
671
    {
672 7
        $this->_countValidatorClass = 'Mockery\CountValidator\AtMost';
673 7
        return $this;
674
    }
675
676
    /**
677
     * Shorthand for setting minimum and maximum constraints on call counts
678
     *
679
     * @param int $minimum
680
     * @param int $maximum
681
     */
682
    public function between($minimum, $maximum)
683
    {
684
        return $this->atLeast()->times($minimum)->atMost()->times($maximum);
685
    }
686
687
    /**
688
     * Indicates that this expectation must be called in a specific given order
689
     *
690
     * @param string $group Name of the ordered group
691
     * @return Expectation
692
     */
693 20
    public function ordered($group = null)
694
    {
695 20
        if ($this->_globally) {
696 1
            $this->_globalOrderNumber = $this->_defineOrdered($group, $this->_mock->mockery_getContainer());
697 1
        } else {
698 19
            $this->_orderNumber = $this->_defineOrdered($group, $this->_mock);
699
        }
700 20
        $this->_globally = false;
701 20
        return $this;
702
    }
703
704
    /**
705
     * Indicates call order should apply globally
706
     *
707
     * @return Expectation
708
     */
709 1
    public function globally()
710
    {
711 1
        $this->_globally = true;
712 1
        return $this;
713
    }
714
715
    /**
716
     * Setup the ordering tracking on the mock or mock container
717
     *
718
     * @param string $group
719
     * @param object $ordering
720
     * @return int
721
     */
722 20
    protected function _defineOrdered($group, $ordering)
723
    {
724 20
        $groups = $ordering->mockery_getGroups();
725 20
        if (is_null($group)) {
726 19
            $result = $ordering->mockery_allocateOrder();
727 20
        } elseif (isset($groups[$group])) {
728 2
            $result = $groups[$group];
729 2
        } else {
730 4
            $result = $ordering->mockery_allocateOrder();
731 4
            $ordering->mockery_setGroup($group, $result);
732
        }
733 20
        return $result;
734
    }
735
736
    /**
737
     * Return order number
738
     *
739
     * @return int
740
     */
741 263
    public function getOrderNumber()
742
    {
743 263
        return $this->_orderNumber;
744
    }
745
746
    /**
747
     * Mark this expectation as being a default
748
     *
749
     * @return Expectation
750
     */
751 25
    public function byDefault()
752
    {
753 25
        $director = $this->_mock->mockery_getExpectationsFor($this->_name);
754 25
        if (!empty($director)) {
755 25
            $director->makeExpectationDefault($this);
756 24
        }
757 24
        return $this;
758
    }
759
760
    /**
761
     * Return the parent mock of the expectation
762
     *
763
     * @return \Mockery\MockInterface
764
     */
765 28
    public function getMock()
766
    {
767 28
        return $this->_mock;
768
    }
769
770
    /**
771
     * Flag this expectation as calling the original class method with the
772
     * any provided arguments instead of using a return value queue.
773
     *
774
     * @return Expectation
775
     */
776 3
    public function passthru()
777
    {
778 3
        if ($this->_mock instanceof Mock) {
779
            throw new Exception(
780
                'Mock Objects not created from a loaded/existing class are '
781
                . 'incapable of passing method calls through to a parent class'
782
            );
783
        }
784 3
        $this->_passthru = true;
785 3
        return $this;
786
    }
787
788
    /**
789
     * Cloning logic
790
     *
791
     */
792 9
    public function __clone()
793
    {
794 9
        $newValidators = array();
795 9
        $countValidators = $this->_countValidators;
796 9
        foreach ($countValidators as $validator) {
797 6
            $newValidators[] = clone $validator;
798 9
        }
799 9
        $this->_countValidators = $newValidators;
800 9
    }
801
802 6
    public function getName()
803
    {
804 6
        return $this->_name;
805
    }
806
}
807