-
Notifications
You must be signed in to change notification settings - Fork 461
/
Mockery.php
1048 lines (909 loc) · 24.9 KB
/
Mockery.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Mockery (https://docs.mockery.io/)
*
* @copyright https://github.com/mockery/mockery/blob/HEAD/COPYRIGHT.md
* @license https://github.com/mockery/mockery/blob/HEAD/LICENSE BSD 3-Clause License
* @link https://github.com/mockery/mockery for the canonical source repository
*/
use Mockery\ClosureWrapper;
use Mockery\CompositeExpectation;
use Mockery\Configuration;
use Mockery\Container;
use Mockery\Exception as MockeryException;
use Mockery\ExpectationInterface;
use Mockery\Generator\CachingGenerator;
use Mockery\Generator\Generator;
use Mockery\Generator\MockConfigurationBuilder;
use Mockery\Generator\MockNameBuilder;
use Mockery\Generator\StringManipulationGenerator;
use Mockery\LegacyMockInterface;
use Mockery\Loader\EvalLoader;
use Mockery\Loader\Loader;
use Mockery\Matcher\AndAnyOtherArgs;
use Mockery\Matcher\Any;
use Mockery\Matcher\AnyOf;
use Mockery\Matcher\Closure as ClosureMatcher;
use Mockery\Matcher\Contains;
use Mockery\Matcher\Ducktype;
use Mockery\Matcher\HasKey;
use Mockery\Matcher\HasValue;
use Mockery\Matcher\IsEqual;
use Mockery\Matcher\IsSame;
use Mockery\Matcher\MatcherInterface;
use Mockery\Matcher\MustBe;
use Mockery\Matcher\Not;
use Mockery\Matcher\NotAnyOf;
use Mockery\Matcher\Pattern;
use Mockery\Matcher\Subset;
use Mockery\Matcher\Type;
use Mockery\MockInterface;
use Mockery\Reflector;
class Mockery
{
public const BLOCKS = 'Mockery_Forward_Blocks';
/**
* Global configuration handler containing configuration options.
*
* @var Configuration
*/
protected static $_config = null;
/**
* Global container to hold all mocks for the current unit test running.
*
* @var null|Container
*/
protected static $_container = null;
/**
* @var Generator
*/
protected static $_generator;
/**
* @var Loader
*/
protected static $_loader;
/**
* @var list<string>
*/
private static $_filesToCleanUp = [];
/**
* Return instance of AndAnyOtherArgs matcher.
*
* @return AndAnyOtherArgs
*/
public static function andAnyOtherArgs()
{
return new AndAnyOtherArgs();
}
/**
* Return instance of AndAnyOtherArgs matcher.
*
* An alternative name to `andAnyOtherArgs` so
* the API stays closer to `any` as well.
*
* @return AndAnyOtherArgs
*/
public static function andAnyOthers()
{
return new AndAnyOtherArgs();
}
/**
* Return instance of ANY matcher.
*
* @return Any
*/
public static function any()
{
return new Any();
}
/**
* Return instance of ANYOF matcher.
*
* @template TAnyOf
*
* @param TAnyOf ...$args
*
* @return AnyOf
*/
public static function anyOf(...$args)
{
return new AnyOf($args);
}
/**
* @return array
*
* @deprecated since 1.3.2 and will be removed in 2.0.
*/
public static function builtInTypes()
{
return ['array', 'bool', 'callable', 'float', 'int', 'iterable', 'object', 'self', 'string', 'void'];
}
/**
* Return instance of CLOSURE matcher.
*
* @template TReference
*
* @param TReference $reference
*
* @return ClosureMatcher
*/
public static function capture(&$reference)
{
$closure = static function ($argument) use (&$reference) {
$reference = $argument;
return true;
};
return new ClosureMatcher($closure);
}
/**
* Static shortcut to closing up and verifying all mocks in the global
* container, and resetting the container static variable to null.
*
* @return void
*/
public static function close()
{
foreach (self::$_filesToCleanUp as $fileName) {
@\unlink($fileName);
}
self::$_filesToCleanUp = [];
if (self::$_container === null) {
return;
}
$container = self::$_container;
self::$_container = null;
$container->mockery_teardown();
$container->mockery_close();
}
/**
* Return instance of CONTAINS matcher.
*
* @template TContains
*
* @param TContains $args
*
* @return Contains
*/
public static function contains(...$args)
{
return new Contains($args);
}
/**
* @param class-string $fqn
*
* @return void
*/
public static function declareClass($fqn)
{
static::declareType($fqn, 'class');
}
/**
* @param class-string $fqn
*
* @return void
*/
public static function declareInterface($fqn)
{
static::declareType($fqn, 'interface');
}
/**
* Return instance of DUCKTYPE matcher.
*
* @template TDucktype
*
* @param TDucktype ...$args
*
* @return Ducktype
*/
public static function ducktype(...$args)
{
return new Ducktype($args);
}
/**
* Static fetching of a mock associated with a name or explicit class poser.
*
* @template TMock of object
*
* @param class-string<TMock> $name
*
* @return LegacyMockInterface&MockInterface&TMock
*/
public static function fetchMock($name)
{
return self::getContainer()->fetchMock($name);
}
/**
* Utility method to format method name and arguments into a string.
*
* @param string $method
*
* @return string
*/
public static function formatArgs($method, ?array $arguments = null)
{
if ($arguments === null) {
return $method . '()';
}
$formattedArguments = [];
foreach ($arguments as $argument) {
$formattedArguments[] = self::formatArgument($argument);
}
return $method . '(' . \implode(', ', $formattedArguments) . ')';
}
/**
* Utility function to format objects to printable arrays.
*
* @return string
*/
public static function formatObjects(?array $objects = null)
{
static $formatting;
if ($formatting) {
return '[Recursion]';
}
if ($objects === null) {
return '';
}
$objects = \array_filter($objects, 'is_object');
if ($objects === []) {
return '';
}
$formatting = true;
$parts = [];
foreach ($objects as $object) {
$parts[\get_class($object)] = self::objectToArray($object);
}
$formatting = false;
return 'Objects: ( ' . \var_export($parts, true) . ')';
}
/**
* Lazy loader and Getter for the global
* configuration container.
*
* @return Configuration
*/
public static function getConfiguration()
{
if (self::$_config === null) {
self::$_config = new Configuration();
}
return self::$_config;
}
/**
* Lazy loader and getter for the container property.
*
* @return Container
*/
public static function getContainer()
{
if (self::$_container === null) {
self::$_container = new Container(self::getGenerator(), self::getLoader());
}
return self::$_container;
}
/**
* Creates and returns a default generator
* used inside this class.
*
* @return CachingGenerator
*/
public static function getDefaultGenerator()
{
return new CachingGenerator(StringManipulationGenerator::withDefaultPasses());
}
/**
* Gets an EvalLoader to be used as default.
*
* @return EvalLoader
*/
public static function getDefaultLoader()
{
return new EvalLoader();
}
/**
* Lazy loader method and getter for
* the generator property.
*
* @return Generator
*/
public static function getGenerator()
{
if (self::$_generator === null) {
self::$_generator = self::getDefaultGenerator();
}
return self::$_generator;
}
/**
* Lazy loader method and getter for
* the $_loader property.
*
* @return Loader
*/
public static function getLoader()
{
if (self::$_loader === null) {
self::$_loader = self::getDefaultLoader();
}
return self::$_loader;
}
/**
* Defines the global helper functions
*
* @return void
*/
public static function globalHelpers()
{
require_once __DIR__ . '/helpers.php';
}
/**
* Return instance of HASKEY matcher.
*
* @template THasKey
*
* @param THasKey $key
*
* @return HasKey
*/
public static function hasKey($key)
{
return new HasKey($key);
}
/**
* Return instance of HASVALUE matcher.
*
* @template THasValue
*
* @param THasValue $val
*
* @return HasValue
*/
public static function hasValue($val)
{
return new HasValue($val);
}
/**
* Static and Semantic shortcut to Container::mock().
*
* @template TInstanceMock
*
* @param array<class-string<TInstanceMock>|TInstanceMock> $args
*
* @return LegacyMockInterface&MockInterface&TInstanceMock
*/
public static function instanceMock(...$args)
{
return self::getContainer()->mock(...$args);
}
/**
* @param string $type
*
* @return bool
*
* @deprecated since 1.3.2 and will be removed in 2.0.
*/
public static function isBuiltInType($type)
{
return \in_array($type, self::builtInTypes(), true);
}
/**
* Return instance of IsEqual matcher.
*
* @template TExpected
*
* @param TExpected $expected
*/
public static function isEqual($expected): IsEqual
{
return new IsEqual($expected);
}
/**
* Return instance of IsSame matcher.
*
* @template TExpected
*
* @param TExpected $expected
*/
public static function isSame($expected): IsSame
{
return new IsSame($expected);
}
/**
* Static shortcut to Container::mock().
*
* @template TMock
*
* @param array<class-string<TMock>|TMock> $args
*
* @return LegacyMockInterface&MockInterface&TMock
*/
public static function mock(...$args)
{
return self::getContainer()->mock(...$args);
}
/**
* Return instance of MUSTBE matcher.
*
* @template TExpected
*
* @param TExpected $expected
*
* @return MustBe
*/
public static function mustBe($expected)
{
return new MustBe($expected);
}
/**
* Static shortcut to Container::mock(), first argument names the mock.
*
* @template TNamedMock
*
* @param array<class-string<TNamedMock>|TNamedMock> $args
*
* @return LegacyMockInterface&MockInterface&TNamedMock
*/
public static function namedMock(...$args)
{
$name = \array_shift($args);
$builder = new MockConfigurationBuilder();
$builder->setName($name);
\array_unshift($args, $builder);
return self::getContainer()->mock(...$args);
}
/**
* Return instance of NOT matcher.
*
* @template TNotExpected
*
* @param TNotExpected $expected
*
* @return Not
*/
public static function not($expected)
{
return new Not($expected);
}
/**
* Return instance of NOTANYOF matcher.
*
* @template TNotAnyOf
*
* @param TNotAnyOf ...$args
*
* @return NotAnyOf
*/
public static function notAnyOf(...$args)
{
return new NotAnyOf($args);
}
/**
* Return instance of CLOSURE matcher.
*
* @template TClosure of Closure
*
* @param TClosure $closure
*
* @return ClosureMatcher
*/
public static function on($closure)
{
return new ClosureMatcher($closure);
}
/**
* Utility function to parse shouldReceive() arguments and generate
* expectations from such as needed.
*
* @template TReturnArgs
*
* @param TReturnArgs ...$args
* @param Closure $add
*
* @return CompositeExpectation
*/
public static function parseShouldReturnArgs(LegacyMockInterface $mock, $args, $add)
{
$composite = new CompositeExpectation();
foreach ($args as $arg) {
if (\is_string($arg)) {
$composite->add(self::buildDemeterChain($mock, $arg, $add));
continue;
}
if (\is_array($arg)) {
foreach ($arg as $k => $v) {
$composite->add(self::buildDemeterChain($mock, $k, $add)->andReturn($v));
}
}
}
return $composite;
}
/**
* Return instance of PATTERN matcher.
*
* @template TPatter
*
* @param TPatter $expected
*
* @return Pattern
*/
public static function pattern($expected)
{
return new Pattern($expected);
}
/**
* Register a file to be deleted on tearDown.
*
* @param string $fileName
*/
public static function registerFileForCleanUp($fileName)
{
self::$_filesToCleanUp[] = $fileName;
}
/**
* Reset the container to null.
*
* @return void
*/
public static function resetContainer()
{
self::$_container = null;
}
/**
* Static shortcut to Container::self().
*
* @throws LogicException
*
* @return LegacyMockInterface|MockInterface
*/
public static function self()
{
if (self::$_container === null) {
throw new LogicException('You have not declared any mocks yet');
}
return self::$_container->self();
}
/**
* Set the container.
*
* @return Container
*/
public static function setContainer(Container $container)
{
return self::$_container = $container;
}
/**
* Setter for the $_generator static property.
*/
public static function setGenerator(Generator $generator)
{
self::$_generator = $generator;
}
/**
* Setter for the $_loader static property.
*/
public static function setLoader(Loader $loader)
{
self::$_loader = $loader;
}
/**
* Static and semantic shortcut for getting a mock from the container
* and applying the spy's expected behavior into it.
*
* @template TSpy
*
* @param array<class-string<TSpy>|TSpy> $args
*
* @return LegacyMockInterface&MockInterface&TSpy
*/
public static function spy(...$args)
{
if (\count($args) && $args[0] instanceof Closure) {
$args[0] = new ClosureWrapper($args[0]);
}
return self::getContainer()->mock(...$args)->shouldIgnoreMissing();
}
/**
* Return instance of SUBSET matcher.
*
* @param bool $strict - (Optional) True for strict comparison, false for loose
*
* @return Subset
*/
public static function subset(array $part, $strict = true)
{
return new Subset($part, $strict);
}
/**
* Return instance of TYPE matcher.
*
* @template TExpectedType
*
* @param TExpectedType $expected
*
* @return Type
*/
public static function type($expected)
{
return new Type($expected);
}
/**
* Sets up expectations on the members of the CompositeExpectation and
* builds up any demeter chain that was passed to shouldReceive.
*
* @param string $arg
* @param Closure $add
*
* @throws MockeryException
*
* @return ExpectationInterface
*/
protected static function buildDemeterChain(LegacyMockInterface $mock, $arg, $add)
{
$container = $mock->mockery_getContainer();
$methodNames = \explode('->', $arg);
\reset($methodNames);
if (
! $mock->mockery_isAnonymous()
&& ! self::getConfiguration()->mockingNonExistentMethodsAllowed()
&& ! \in_array(\current($methodNames), $mock->mockery_getMockableMethods(), true)
) {
throw new MockeryException(
"Mockery's configuration currently forbids mocking the method "
. \current($methodNames) . ' as it does not exist on the class or object '
. 'being mocked'
);
}
/** @var Closure $nextExp */
$nextExp = static function ($method) use ($add) {
return $add($method);
};
$parent = \get_class($mock);
/** @var null|ExpectationInterface $expectations */
$expectations = null;
while (true) {
$method = \array_shift($methodNames);
$expectations = $mock->mockery_getExpectationsFor($method);
if ($expectations === null || self::noMoreElementsInChain($methodNames)) {
$expectations = $nextExp($method);
if (self::noMoreElementsInChain($methodNames)) {
break;
}
$mock = self::getNewDemeterMock($container, $parent, $method, $expectations);
} else {
$demeterMockKey = $container->getKeyOfDemeterMockFor($method, $parent);
if ($demeterMockKey) {
$mock = self::getExistingDemeterMock($container, $demeterMockKey);
}
}
$parent .= '->' . $method;
$nextExp = static function ($n) use ($mock) {
return $mock->allows($n);
};
}
return $expectations;
}
/**
* Utility method for recursively generating a representation of the given array.
*
* @template TArray or array
*
* @param TArray $argument
* @param int $nesting
*
* @return TArray
*/
private static function cleanupArray($argument, $nesting = 3)
{
if ($nesting === 0) {
return '...';
}
foreach ($argument as $key => $value) {
if (\is_array($value)) {
$argument[$key] = self::cleanupArray($value, $nesting - 1);
continue;
}
if (\is_object($value)) {
$argument[$key] = self::objectToArray($value, $nesting - 1);
}
}
return $argument;
}
/**
* Utility method used for recursively generating
* an object or array representation.
*
* @template TArgument
*
* @param TArgument $argument
* @param int $nesting
*
* @return mixed
*/
private static function cleanupNesting($argument, $nesting)
{
if (\is_object($argument)) {
$object = self::objectToArray($argument, $nesting - 1);
$object['class'] = \get_class($argument);
return $object;
}
if (\is_array($argument)) {
return self::cleanupArray($argument, $nesting - 1);
}
return $argument;
}
/**
* @param string $fqn
* @param string $type
*/
private static function declareType($fqn, $type): void
{
$targetCode = '<?php ';
$shortName = $fqn;
if (\strpos($fqn, '\\')) {
$parts = \explode('\\', $fqn);
$shortName = \trim(\array_pop($parts));
$namespace = \implode('\\', $parts);
$targetCode.= "namespace {$namespace};\n";
}
$targetCode.= \sprintf('%s %s {} ', $type, $shortName);
/*
* We could eval here, but it doesn't play well with the way
* PHPUnit tries to backup global state and the require definition
* loader
*/
$fileName = \tempnam(\sys_get_temp_dir(), 'Mockery');
\file_put_contents($fileName, $targetCode);
require $fileName;
self::registerFileForCleanUp($fileName);
}
/**
* Returns all public instance properties.
*
* @param object $object
* @param int $nesting
*
* @return array<string, mixed>
*/
private static function extractInstancePublicProperties($object, $nesting)
{
$reflection = new ReflectionClass($object);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$cleanedProperties = [];
foreach ($properties as $publicProperty) {
if (! $publicProperty->isStatic()) {
$name = $publicProperty->getName();
try {
$cleanedProperties[$name] = self::cleanupNesting($object->{$name}, $nesting);
} catch (Exception $exception) {
$cleanedProperties[$name] = $exception->getMessage();
}
}
}
return $cleanedProperties;
}
/**
* Gets the string representation
* of any passed argument.
*
* @param mixed $argument
* @param int $depth
*
* @return mixed
*/
private static function formatArgument($argument, $depth = 0)
{
if ($argument instanceof MatcherInterface) {
return (string) $argument;
}
if (\is_object($argument)) {
return 'object(' . \get_class($argument) . ')';
}
if (\is_int($argument) || \is_float($argument)) {
return $argument;
}
if (\is_array($argument)) {
if ($depth === 1) {
$argument = '[...]';
} else {
$sample = [];
foreach ($argument as $key => $value) {
$key = \is_int($key) ? $key : \sprintf("'%s'", $key);
$value = self::formatArgument($value, $depth + 1);
$sample[] = \sprintf('%s => %s', $key, $value);
}
$argument = '[' . \implode(', ', $sample) . ']';
}
return (\strlen($argument) > 1000) ? \substr($argument, 0, 1000) . '...]' : $argument;
}
if (\is_bool($argument)) {
return $argument ? 'true' : 'false';
}
if (\is_resource($argument)) {
return 'resource(...)';
}
if ($argument === null) {
return 'NULL';
}
return "'" . $argument . "'";
}
/**
* Gets a specific demeter mock from the ones kept by the container.
*
* @template TMock of object
*
* @param class-string<TMock> $demeterMockKey
*
* @return LegacyMockInterface&MockInterface&TMock
*/
private static function getExistingDemeterMock(Container $container, $demeterMockKey)
{
return $container->getMocks()[$demeterMockKey] ?? null;
}
/**
* Gets a new demeter configured
* mock from the container.
*
* @param string $parent
* @param string $method
*
* @return LegacyMockInterface&MockInterface
*/
private static function getNewDemeterMock(Container $container, $parent, $method, ExpectationInterface $exp)
{
$newMockName = 'demeter_' . \md5($parent) . '_' . $method;
$parRef = null;
$parentMock = $exp->getMock();
if ($parentMock !== null) {
$parRef = new ReflectionObject($parentMock);
}
if ($parRef instanceof ReflectionObject && $parRef->hasMethod($method)) {
$parRefMethod = $parRef->getMethod($method);
$parRefMethodRetType = Reflector::getReturnType($parRefMethod, true);
if ($parRefMethodRetType !== null && $parRefMethodRetType !== 'mixed') {
$nameBuilder = new MockNameBuilder();
$nameBuilder->addPart('\\' . $newMockName);
$mock = self::namedMock($nameBuilder->build(), $parRefMethodRetType);
$exp->andReturn($mock);
return $mock;
}
}
$mock = $container->mock($newMockName);