Repository: phpspec/prophecy Branch: master Commit: 0da07c10d5fe Files: 240 Total size: 512.9 KB Directory structure: gitextract_tlvewwen/ ├── .editorconfig ├── .gitattributes ├── .github/ │ └── workflows/ │ └── build.yml ├── .gitignore ├── .php-cs-fixer.dist.php ├── CHANGES.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── fixtures/ │ ├── AbstractBaseClassWithMethodWithReturnType.php │ ├── ClassExtendAbstractWithMethodWithReturnType.php │ ├── DnfArgumentType.php │ ├── DnfReturnType.php │ ├── EmptyClass.php │ ├── EmptyInterface.php │ ├── Enum.php │ ├── FinalClass.php │ ├── IntersectionArgumentType.php │ ├── IntersectionReturnType.php │ ├── MethodWithAdditionalParam.php │ ├── MixedTypes.php │ ├── ModifierInterface.php │ ├── Named.php │ ├── NeverType.php │ ├── NullableArrayParameter.php │ ├── NullableParameterTypeFalse.php │ ├── NullableParameterTypeTrue.php │ ├── NullableReturnTypeFalse.php │ ├── NullableReturnTypeTrue.php │ ├── OptionalDepsClass.php │ ├── ReadOnlyClass.php │ ├── ReturningFinalClass.php │ ├── SelfReferencing.php │ ├── SpecialMethods.php │ ├── StandaloneParameterTypeFalse.php │ ├── StandaloneParameterTypeNull.php │ ├── StandaloneParameterTypeTrue.php │ ├── StandaloneReturnTypeFalse.php │ ├── StandaloneReturnTypeNull.php │ ├── StandaloneReturnTypeTrue.php │ ├── TentativeReturnTypeNull.php │ ├── ThrowableInterface.php │ ├── UnionArgumentTypeFalse.php │ ├── UnionArgumentTypes.php │ ├── UnionReturnTypeFalse.php │ ├── UnionReturnTypes.php │ ├── WithArguments.php │ ├── WithCallableArgument.php │ ├── WithFinalMethod.php │ ├── WithFinalVirtuallyPrivateMethod.php │ ├── WithPhpdocClass.php │ ├── WithProtectedAbstractMethod.php │ ├── WithReferences.php │ ├── WithReturnTypehints.php │ ├── WithStaticMethod.php │ ├── WithTypehintedVariadicArgument.php │ ├── WithVariadicArgument.php │ └── WithVirtuallyPrivateMethod.php ├── phpstan-baseline.neon ├── phpstan.dist.neon ├── phpunit.xml.dist ├── spec/ │ └── Prophecy/ │ ├── Argument/ │ │ ├── ArgumentsWildcardSpec.php │ │ └── Token/ │ │ ├── AnyValueTokenSpec.php │ │ ├── AnyValuesTokenSpec.php │ │ ├── ApproximateValueTokenSpec.php │ │ ├── ArrayCountTokenSpec.php │ │ ├── ArrayEntryTokenSpec.php │ │ ├── ArrayEveryEntryTokenSpec.php │ │ ├── CallbackTokenSpec.php │ │ ├── ExactValueTokenSpec.php │ │ ├── IdenticalValueTokenSpec.php │ │ ├── InArrayTokenSpec.php │ │ ├── LogicalAndTokenSpec.php │ │ ├── LogicalNotTokenSpec.php │ │ ├── NotInArrayTokenSpec.php │ │ ├── ObjectStateTokenSpec.php │ │ ├── StringContainsTokenSpec.php │ │ └── TypeTokenSpec.php │ ├── ArgumentSpec.php │ ├── Call/ │ │ ├── CallCenterSpec.php │ │ └── CallSpec.php │ ├── Comparator/ │ │ ├── ClosureComparatorSpec.php │ │ ├── FactorySpec.php │ │ └── ProphecyComparatorSpec.php │ ├── Doubler/ │ │ ├── CachedDoublerSpec.php │ │ ├── ClassPatch/ │ │ │ ├── DisableConstructorPatchSpec.php │ │ │ ├── KeywordPatchSpec.php │ │ │ ├── MagicCallPatchSpec.php │ │ │ ├── ProphecySubjectPatchSpec.php │ │ │ ├── ReflectionClassNewInstancePatchSpec.php │ │ │ ├── SplFileInfoPatchSpec.php │ │ │ ├── ThrowablePatchSpec.php │ │ │ └── TraversablePatchSpec.php │ │ ├── DoublerSpec.php │ │ ├── Generator/ │ │ │ ├── ClassCodeGeneratorSpec.php │ │ │ ├── ClassCreatorSpec.php │ │ │ └── Node/ │ │ │ ├── ArgumentNodeSpec.php │ │ │ ├── ArgumentTypeNodeSpec.php │ │ │ ├── ClassNodeSpec.php │ │ │ ├── MethodNodeSpec.php │ │ │ ├── ReturnTypeNodeSpec.php │ │ │ └── Type/ │ │ │ ├── BuiltinTypeSpec.php │ │ │ ├── IntersectionTypeSpec.php │ │ │ ├── ObjectTypeSpec.php │ │ │ └── UnionTypeSpec.php │ │ ├── LazyDoubleSpec.php │ │ └── NameGeneratorSpec.php │ ├── Exception/ │ │ ├── Call/ │ │ │ └── UnexpectedCallExceptionSpec.php │ │ ├── Doubler/ │ │ │ ├── ClassCreatorExceptionSpec.php │ │ │ ├── ClassMirrorExceptionSpec.php │ │ │ ├── ClassNotFoundExceptionSpec.php │ │ │ ├── DoubleExceptionSpec.php │ │ │ ├── InterfaceNotFoundExceptionSpec.php │ │ │ ├── MethodNotExtendableExceptionSpec.php │ │ │ └── MethodNotFoundExceptionSpec.php │ │ ├── Prediction/ │ │ │ ├── AggregateExceptionSpec.php │ │ │ ├── NoCallsExceptionSpec.php │ │ │ ├── UnexpectedCallsCountExceptionSpec.php │ │ │ └── UnexpectedCallsExceptionSpec.php │ │ └── Prophecy/ │ │ ├── MethodProphecyExceptionSpec.php │ │ └── ObjectProphecyExceptionSpec.php │ ├── Prediction/ │ │ ├── CallPredictionSpec.php │ │ ├── CallTimesPredictionSpec.php │ │ ├── CallbackPredictionSpec.php │ │ └── NoCallsPredictionSpec.php │ ├── Promise/ │ │ ├── CallbackPromiseSpec.php │ │ ├── ReturnArgumentPromiseSpec.php │ │ ├── ReturnPromiseSpec.php │ │ └── ThrowPromiseSpec.php │ ├── Prophecy/ │ │ ├── MethodProphecySpec.php │ │ ├── ObjectProphecySpec.php │ │ └── RevealerSpec.php │ ├── ProphetSpec.php │ └── Util/ │ └── StringUtilSpec.php ├── src/ │ └── Prophecy/ │ ├── Argument/ │ │ ├── ArgumentsWildcard.php │ │ └── Token/ │ │ ├── AnyValueToken.php │ │ ├── AnyValuesToken.php │ │ ├── ApproximateValueToken.php │ │ ├── ArrayCountToken.php │ │ ├── ArrayEntryToken.php │ │ ├── ArrayEveryEntryToken.php │ │ ├── CallbackToken.php │ │ ├── ExactValueToken.php │ │ ├── IdenticalValueToken.php │ │ ├── InArrayToken.php │ │ ├── LogicalAndToken.php │ │ ├── LogicalNotToken.php │ │ ├── NotInArrayToken.php │ │ ├── ObjectStateToken.php │ │ ├── StringContainsToken.php │ │ ├── TokenInterface.php │ │ └── TypeToken.php │ ├── Argument.php │ ├── Call/ │ │ ├── Call.php │ │ └── CallCenter.php │ ├── Comparator/ │ │ ├── ClosureComparator.php │ │ ├── Factory.php │ │ ├── FactoryProvider.php │ │ └── ProphecyComparator.php │ ├── Doubler/ │ │ ├── CachedDoubler.php │ │ ├── ClassPatch/ │ │ │ ├── ClassPatchInterface.php │ │ │ ├── DisableConstructorPatch.php │ │ │ ├── KeywordPatch.php │ │ │ ├── MagicCallPatch.php │ │ │ ├── ProphecySubjectPatch.php │ │ │ ├── ReflectionClassNewInstancePatch.php │ │ │ ├── SplFileInfoPatch.php │ │ │ ├── ThrowablePatch.php │ │ │ └── TraversablePatch.php │ │ ├── DoubleInterface.php │ │ ├── Doubler.php │ │ ├── Generator/ │ │ │ ├── ClassCodeGenerator.php │ │ │ ├── ClassCreator.php │ │ │ ├── ClassMirror.php │ │ │ ├── Node/ │ │ │ │ ├── ArgumentNode.php │ │ │ │ ├── ArgumentTypeNode.php │ │ │ │ ├── ClassNode.php │ │ │ │ ├── MethodNode.php │ │ │ │ ├── ReturnTypeNode.php │ │ │ │ ├── Type/ │ │ │ │ │ ├── BuiltinType.php │ │ │ │ │ ├── IntersectionType.php │ │ │ │ │ ├── ObjectType.php │ │ │ │ │ ├── SimpleType.php │ │ │ │ │ ├── TypeInterface.php │ │ │ │ │ └── UnionType.php │ │ │ │ └── TypeNodeAbstract.php │ │ │ ├── ReflectionInterface.php │ │ │ └── TypeHintReference.php │ │ ├── LazyDouble.php │ │ └── NameGenerator.php │ ├── Exception/ │ │ ├── Call/ │ │ │ └── UnexpectedCallException.php │ │ ├── Doubler/ │ │ │ ├── ClassCreatorException.php │ │ │ ├── ClassMirrorException.php │ │ │ ├── ClassNotFoundException.php │ │ │ ├── DoubleException.php │ │ │ ├── DoublerException.php │ │ │ ├── InterfaceNotFoundException.php │ │ │ ├── MethodNotExtendableException.php │ │ │ ├── MethodNotFoundException.php │ │ │ └── ReturnByReferenceException.php │ │ ├── Exception.php │ │ ├── InvalidArgumentException.php │ │ ├── Prediction/ │ │ │ ├── AggregateException.php │ │ │ ├── FailedPredictionException.php │ │ │ ├── NoCallsException.php │ │ │ ├── PredictionException.php │ │ │ ├── UnexpectedCallsCountException.php │ │ │ └── UnexpectedCallsException.php │ │ └── Prophecy/ │ │ ├── MethodProphecyException.php │ │ ├── ObjectProphecyException.php │ │ └── ProphecyException.php │ ├── PhpDocumentor/ │ │ ├── ClassAndInterfaceTagRetriever.php │ │ ├── ClassTagRetriever.php │ │ └── MethodTagRetrieverInterface.php │ ├── Prediction/ │ │ ├── CallPrediction.php │ │ ├── CallTimesPrediction.php │ │ ├── CallbackPrediction.php │ │ ├── NoCallsPrediction.php │ │ └── PredictionInterface.php │ ├── Promise/ │ │ ├── CallbackPromise.php │ │ ├── PromiseInterface.php │ │ ├── ReturnArgumentPromise.php │ │ ├── ReturnPromise.php │ │ └── ThrowPromise.php │ ├── Prophecy/ │ │ ├── MethodProphecy.php │ │ ├── ObjectProphecy.php │ │ ├── ProphecyInterface.php │ │ ├── ProphecySubjectInterface.php │ │ ├── Revealer.php │ │ └── RevealerInterface.php │ ├── Prophet.php │ └── Util/ │ ├── ExportUtil.php │ └── StringUtil.php └── tests/ ├── Argument/ │ └── Token/ │ └── ExactValueTokenTest.php ├── Comparator/ │ └── FactoryProviderTest.php ├── Doubler/ │ ├── ClassPatch/ │ │ └── MagicCallPatchTest.php │ └── Generator/ │ ├── ClassMirrorTest.php │ └── Node/ │ └── TypeNodeAbstractTest.php └── FunctionalTest.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true tab_width = 4 trim_trailing_whitespace = true [.github/workflows/*.yml] indent_size = 2 ================================================ FILE: .gitattributes ================================================ /.editorconfig export-ignore /.gitattributes export-ignore /.gitignore export-ignore /CONTRIBUTING.md export-ignore /.github/ export-ignore /fixtures/ export-ignore /phpunit.xml.dist export-ignore /phpstan*.neon export-ignore /spec/ export-ignore /tests/ export-ignore ================================================ FILE: .github/workflows/build.yml ================================================ name: Build on: push: branches: [master] pull_request: release: types: [created] jobs: tests: runs-on: ubuntu-latest name: Build and test continue-on-error: ${{ matrix.experimental || false }} strategy: fail-fast: false matrix: php: ["8.2", "8.3", "8.4"] composer-flags: [ "" ] experimental: [ false ] include: - php: 8.2 composer-flags: "--prefer-lowest" - php: "8.5" # TODO move that to a normal job once phpspec supports PHP 8.5 composer-flags: "--ignore-platform-req=php+" - php: nightly composer-flags: "--ignore-platform-req=php+" experimental: true steps: - uses: actions/checkout@v5 - name: Set up PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" coverage: none - name: Install dependencies run: COMPOSER_ROOT_VERSION=dev-master composer update ${{ matrix.composer-flags }} --no-scripts id: end-of-setup - name: Run tests (phpspec) run: ./vendor/bin/phpspec run --format=dot if: always() && steps.end-of-setup.outcome == 'success' - name: Run tests (phpunit) run: ./vendor/bin/phpunit if: always() && steps.end-of-setup.outcome == 'success' phpstan: runs-on: ubuntu-latest name: Static analysis steps: - uses: actions/checkout@v5 - name: Set up PHP uses: shivammathur/setup-php@v2 with: php-version: "8.3" coverage: none - name: Install dependencies run: COMPOSER_ROOT_VERSION=dev-master composer update --no-scripts - run: ./vendor/bin/phpstan coding-standards: runs-on: ubuntu-latest name: Coding standards steps: - uses: actions/checkout@v5 - name: Set up PHP uses: shivammathur/setup-php@v2 with: php-version: "8.3" coverage: none - name: Install dependencies run: COMPOSER_ROOT_VERSION=dev-master composer update --no-scripts - run: composer cs:check -- --ansi ================================================ FILE: .gitignore ================================================ *.tgz *.phar /.php-cs-fixer.cache /composer.lock /dev-tools/vendor/ /vendor /phpstan.neon /phpunit.xml /.phpunit.result.cache /.phpunit.cache/ ================================================ FILE: .php-cs-fixer.dist.php ================================================ setRiskyAllowed(false) ->setRules([ '@PER-CS' => true, 'array_syntax' => false, 'braces_position' => [ 'control_structures_opening_brace' => 'same_line', ], 'no_unused_imports' => true, 'concat_space' => ['spacing' => 'none'], 'method_argument_space' => ['on_multiline' => 'ignore'], // Since PHP 7.2 is supported we can't add trailing commas in arguments, parameters and match 'trailing_comma_in_multiline' => ['elements' => ['arrays']], 'modifier_keywords' => false, ]) ->setFinder( (new PhpCsFixer\Finder()) ->ignoreDotFiles(false) ->ignoreVCSIgnored(true) ->exclude(['fixtures']) ->notPath(['phpstan-baseline.php']) ->in(__DIR__) ) ; ================================================ FILE: CHANGES.md ================================================ Unreleased ========== 1.26.0 ====== **Added:** * Add support for `phpdocumentor/reflection-docblock` v6 (@mspirkov) 1.25.0 ====== **Added:** * Add support for PHPUnit 13 (@Jean85) 1.24.0 ====== **Added:** * Add support for PHP 8.5 (@andypost) 1.23.1 ====== **Changed:** * Refactor the ProphecyComparator to use composition instead of extending internal comparator classes (@stof) 1.23.0 ====== **Removed:** * Remove support for PHP lower than 8.2 (@Nek-) **Added:** * Add support for doubling classes using intersection types and DNF types (@Nek-) **Fixed:** * Fix deprecation for `SplObjectStorage` changes in PHP 8.5 (@Nek-) **Changed:** * Improve error message for unsupported default return values (@stof) 1.22.0 ====== **Removed:** * Support for PHP 7.2 and 7.3 (@jean85) 1.21.0 ====== **Added:** * Add support for PHPUnit 12 (@jean85) 1.20.0 ====== **Added:** * Add support for PHP 8.4 (@andypost) **Fixed:** * Fix support for doubling methods using an enum case as default value of a parameter (@jdreesen) * Fix deprecation when doubling a class with constructor parameters (@singinwhale, @W0rma) * Fix deprecation warning when using phpdocumentor/reflection-docblock 5.4+ (@jrfnl) 1.19.0 ====== **Added:** * Allow sebastian/comparator and sebastian/recursion-context 6 1.18.0 / 2023-12-07 =================== * [added] Add support for PHP 8.3 [@rajeshreeputra] * [changed] Improve the error when using return types that Prophecy does not support for mocking [@stof] * [changed] Add more precise type for static analysis [@stof] * [fixed] Error when comparing object arguments with integers [@lucassabreu] * [changed] Add PHP 8.2 to test matrix [@Jean85] * [Added] Allow sebastian/comparator and sebastian/recursion-context 5, and phpunit/phpunit 10 [@Jean85] * [docs] Switch travis status badge to GHA one [@michalbundyra] 1.17.0 / 2023-02-02 =================== * [added] Add generic types for ProphecyInterface and ObjectProphecy [@stof] * [added] Add the conditional return type for `ObjectProphecy::getMethodProphecies` [@stof] * [added] Add support for doctrine/instantiator 2.0 [@stof] * [added] Add the ability to customize the __toString representation of a CallbackToken [@ian-zunderdorp] * [changed] Remove support for instantiating a MethodProphecy without its arguments [@stof] * [deprecated] Deprecate `\Prophecy\Comparator\Factory` as `sebastian/comparator` v5 makes it parent class final [@stof] 1.16.0 / 2022/11/29 =================== * [added] Allow installing with PHP 8.2 [@gquemener] * [added] Use shorter object IDs for object comparison [@TysonAndre] * [added] Support standalone false,true and null types [@kschatzle] * [added] Support doubling readonly classes [@gquemener] * [fixed] Remove workarounds for unsupported HHVM [@TysonAndre] * [fixed] Clear error message when doubling DNF types [@kschatzle] 1.15.0 / 2021/12/08 =================== * [added] Support for the `static` return type [@denis-rolling-scopes] * [fixed] Add return types for Comparator implementations to avoid deprecation warnings from Symfony's DebugClassLoader [@stof] 1.14.0 / 2021/09/16 =================== * [added] Support for static closures in will and should [@ntzm] * [added] Allow install on PHP 8.1 (with test suite fixes) [@javer] * [added] Support for the 'never' return type [@ciaranmcnulty] * [fixed] Better error message when doubling intersection return types [@ciaranmcnulty] 1.13.0 / 2021/03/17 =================== * [added] willYield can now specify a return value [@camilledejoye] * [added] Prophecy exception interfaces are explicitly Throwable [@ciaranmcnulty] * [fixed] Argument::in() and notIn() now marked as static [@tyteen4a03] * [fixed] Can now double unions containing false [@ciaranmcnulty] * [fixed] Virtual magic methods with arguments are now doublable in PHP 8 [@ciaranmcnulty] 1.12.2 / 2020/12/19 =================== * [fixed] MethodNotFoundException sometimes thrown with wrong class attached [@ciaranmcnulty] 1.12.1 / 2020/10/29 =================== * [fixed] Incorrect handling of inherited 'self' return types [@ciaranmcnulty] 1.12.0 / 2020/10/28 =================== * [added] PHP 8 support [@ciaranmcnulty] * [added] Argument::in() and Argument::notIn() [@viniciusalonso] * [added] Support for union and mixed types [@ciaranmcnulty] * [fixed] Issues caused by introduction of named parameters [@ciaranmcnulty] * [fixed] Issues caused by stricter rounding [@ciaranmcnulty] 1.11.1 / 2020/07/08 =================== * [fixed] can't double objects with `self` type hints (@greg0ire) * [fixed] cloned doubes were not loosely comparable (@tkulka) 1.11.0 / 2020/07/07 =================== * [changed] dropped support for PHP versions earlier than 7.2 (@ciaranmcnulty) * [fixed] removed use of Reflection APIs deprecated in PHP 8.0 (@Ayesh) 1.10.3 / 2020/03/05 =================== * [fixed] removed fatal error when phpdocumentor/reflection-docblock 5 parses an invalid `@method` tag (@stof) 1.10.2 / 2020/01/20 =================== * [added] support for new versions of `sebastian/comparator` and `sebastian/recursion-context` (@sebastianbergmann) 1.10.1 / 2019/12/22 =================== * [fixed] identical callables no longer match as arguments (@ciaranmcnulty) 1.10.0 / 2019/12/17 =================== * [added] shouldHaveBeenCalled evaluation happens later so un-stubbed calls don't throw (@elvetemedve) * [added] methods can now be doubled case-insensitively to match PHP semantics (@michalbundyra) * [fixed] reduced memory usage by optimising CachedDoubler (@DonCallisto) * [fixed] removed fatal error nesting level when comparing large objects (@scroach) 1.9.0 / 2019/10/03 ================== * [added] Add willYield feature to Method Prophecy(@tkotosz) * [fixed] Allow `MethodProphecy::willThrow()` to accept Throwable as string (@timoschinkel ) * [fixed] Allow new version of phpdocumentor/reflection-docblock (@ricpelo) 1.8.1 / 2019/06/13 ================== * [fixed] Don't try to patch final constructors (@NiR) 1.8.0 / 2018/08/05 ================== * Support for void return types without explicit will (@crellbar) * Clearer error message for unexpected method calls (@meridius) * Clearer error message for aggregate exceptions (@meridius) * More verbose `shouldBeCalledOnce` expectation (@olvlvl) * Ability to double Throwable, or methods that extend it (@ciaranmcnulty) * [fixed] Doubling methods where class has additional arguments to interface (@webimpress) * [fixed] Doubling methods where arguments are nullable but default is not null (@webimpress) * [fixed] Doubling magic methods on parent class (@dsnopek) * [fixed] Check method predictions only once (@dontub) * [fixed] Argument::containingString throwing error when called with non-string (@dcabrejas) 1.7.6 / 2018/04/18 ================== * Allow sebastian/comparator ^3.0 (@sebastianbergmann) 1.7.5 / 2018/02/11 ================== * Support for object return type hints (thanks @greg0ire) 1.7.4 / 2018/02/11 ================== * Fix issues with PHP 7.2 (thanks @greg0ire) * Support object type hints in PHP 7.2 (thanks @@jansvoboda11) 1.7.3 / 2017/11/24 ================== * Fix SplInfo ClassPatch to work with Symfony 4 (Thanks @gnugat) 1.7.2 / 2017-10-04 ================== * Reverted "check method predictions only once" due to it breaking Spies 1.7.1 / 2017-10-03 ================== * Allow PHP5 keywords methods generation on PHP7 (thanks @bycosta) * Allow reflection-docblock v4 (thanks @GrahamCampbell) * Check method predictions only once (thanks @dontub) * Escape file path sent to \SplFileObjectConstructor when running on Windows (thanks @danmartin-epiphany) 1.7.0 / 2017-03-02 ================== * Add full PHP 7.1 Support (thanks @prolic) * Allow `sebastian/comparator ^2.0` (thanks @sebastianbergmann) * Allow `sebastian/recursion-context ^3.0` (thanks @sebastianbergmann) * Allow `\Error` instances in `ThrowPromise` (thanks @jameshalsall) * Support `phpspec/phpspect ^3.2` (thanks @Sam-Burns) * Fix failing builds (thanks @Sam-Burns) 1.6.2 / 2016-11-21 ================== * Added support for detecting @method on interfaces that the class itself implements, or when the stubbed class is an interface itself (thanks @Seldaek) * Added support for sebastian/recursion-context 2 (thanks @sebastianbergmann) * Added testing on PHP 7.1 on Travis (thanks @danizord) * Fixed the usage of the phpunit comparator (thanks @Anyqax) 1.6.1 / 2016-06-07 ================== * Ignored empty method names in invalid `@method` phpdoc * Fixed the mocking of SplFileObject * Added compatibility with phpdocumentor/reflection-docblock 3 1.6.0 / 2016-02-15 ================== * Add Variadics support (thanks @pamil) * Add ProphecyComparator for comparing objects that need revealing (thanks @jon-acker) * Add ApproximateValueToken (thanks @dantleech) * Add support for 'self' and 'parent' return type (thanks @bendavies) * Add __invoke to allowed reflectable methods list (thanks @ftrrtf) * Updated ExportUtil to reflect the latest changes by Sebastian (thanks @jakari) * Specify the required php version for composer (thanks @jakzal) * Exclude 'args' in the generated backtrace (thanks @oradwell) * Fix code generation for scalar parameters (thanks @trowski) * Fix missing sprintf in InvalidArgumentException __construct call (thanks @emmanuelballery) * Fix phpdoc for magic methods (thanks @Tobion) * Fix PhpDoc for interfaces usage (thanks @ImmRanneft) * Prevent final methods from being manually extended (thanks @kamioftea) * Enhance exception for invalid argument to ThrowPromise (thanks @Tobion) 1.5.0 / 2015-04-27 ================== * Add support for PHP7 scalar type hints (thanks @trowski) * Add support for PHP7 return types (thanks @trowski) * Update internal test suite to support PHP7 1.4.1 / 2015-04-27 ================== * Fixed bug in closure-based argument tokens (#181) 1.4.0 / 2015-03-27 ================== * Fixed errors in return type phpdocs (thanks @sobit) * Fixed stringifying of hash containing one value (thanks @avant1) * Improved clarity of method call expectation exception (thanks @dantleech) * Add ability to specify which argument is returned in willReturnArgument (thanks @coderbyheart) * Add more information to MethodNotFound exceptions (thanks @ciaranmcnulty) * Support for mocking classes with methods that return references (thanks @edsonmedina) * Improved object comparison (thanks @whatthejeff) * Adopted '^' in composer dependencies (thanks @GrahamCampbell) * Fixed non-typehinted arguments being treated as optional (thanks @whatthejeff) * Magic methods are now filtered for keywords (thanks @seagoj) * More readable errors for failure when expecting single calls (thanks @dantleech) 1.3.1 / 2014-11-17 ================== * Fix the edge case when failed predictions weren't recorded for `getCheckedPredictions()` 1.3.0 / 2014-11-14 ================== * Add a way to get checked predictions with `MethodProphecy::getCheckedPredictions()` * Fix HHVM compatibility * Remove dead code (thanks @stof) * Add support for DirectoryIterators (thanks @shanethehat) 1.2.0 / 2014-07-18 ================== * Added support for doubling magic methods documented in the class phpdoc (thanks @armetiz) * Fixed a segfault appearing in some cases (thanks @dmoreaulf) * Fixed the doubling of methods with typehints on non-existent classes (thanks @gquemener) * Added support for internal classes using keywords as method names (thanks @milan) * Added IdenticalValueToken and Argument::is (thanks @florianv) * Removed the usage of scalar typehints in HHVM as HHVM 3 does not support them anymore in PHP code (thanks @whatthejeff) 1.1.2 / 2014-01-24 ================== * Spy automatically promotes spied method call to an expected one 1.1.1 / 2014-01-15 ================== * Added support for HHVM 1.1.0 / 2014-01-01 ================== * Changed the generated class names to use a static counter instead of a random number * Added a clss patch for ReflectionClass::newInstance to make its argument optional consistently (thanks @docteurklein) * Fixed mirroring of classes with typehints on non-existent classes (thanks @docteurklein) * Fixed the support of array callables in CallbackPromise and CallbackPrediction (thanks @ciaranmcnulty) * Added support for properties in ObjectStateToken (thanks @adrienbrault) * Added support for mocking classes with a final constructor (thanks @ciaranmcnulty) * Added ArrayEveryEntryToken and Argument::withEveryEntry() (thanks @adrienbrault) * Added an exception when trying to prophesize on a final method instead of ignoring silently (thanks @docteurklein) * Added StringContainToken and Argument::containingString() (thanks @peterjmit) * Added ``shouldNotHaveBeenCalled`` on the MethodProphecy (thanks @ciaranmcnulty) * Fixed the comparison of objects in ExactValuetoken (thanks @sstok) * Deprecated ``shouldNotBeenCalled`` in favor of ``shouldNotHaveBeenCalled`` 1.0.4 / 2013-08-10 ================== * Better randomness for generated class names (thanks @sstok) * Add support for interfaces into TypeToken and Argument::type() (thanks @sstok) * Add support for old-style (method name === class name) constructors (thanks @l310 for report) 1.0.3 / 2013-07-04 ================== * Support callable typehints (thanks @stof) * Do not attempt to autoload arrays when generating code (thanks @MarcoDeBortoli) * New ArrayEntryToken (thanks @kagux) 1.0.2 / 2013-05-19 ================== * Logical `AND` token added (thanks @kagux) * Logical `NOT` token added (thanks @kagux) * Add support for setting custom constructor arguments * Properly stringify hashes * Record calls that throw exceptions * Migrate spec suite to PhpSpec 2.0 1.0.1 / 2013-04-30 ================== * Fix broken UnexpectedCallException message * Trim AggregateException message 1.0.0 / 2013-04-29 ================== * Improve exception messages 1.0.0-BETA2 / 2013-04-03 ======================== * Add more debug information to CallTimes and Call prediction exception messages * Fix MethodNotFoundException wrong namespace (thanks @gunnarlium) * Fix some typos in the exception messages (thanks @pborreli) 1.0.0-BETA1 / 2013-03-25 ======================== * Initial release ================================================ FILE: CONTRIBUTING.md ================================================ Contributing ------------ Prophecy is an open source, community-driven project. If you'd like to contribute, feel free to do this, but remember to follow these few simple rules: - Make your feature addition or bug fix, - Add either specs or examples for any changes you're making (bugfixes or additions) (please look into `spec/` folder for some examples). This is important so we don't break it in a future version unintentionally, - Commit your code, but do not mess with `CHANGES.md`, Running tests ------------- Make sure that you don't break anything with your changes by running: ```bash $> composer install --prefer-dist $> vendor/bin/phpspec run $> vendor/bin/phpunit ``` ================================================ FILE: LICENSE ================================================ Copyright (c) 2013 Konstantin Kudryashov Copyright (c) 2013 Marcello Duarte Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Prophecy [![Stable release](https://poser.pugx.org/phpspec/prophecy/version.svg)](https://packagist.org/packages/phpspec/prophecy) [![Build](https://github.com/phpspec/prophecy/actions/workflows/build.yml/badge.svg)](https://github.com/phpspec/prophecy/actions/workflows/build.yml) Prophecy is a highly opinionated yet very powerful and flexible PHP object mocking framework. Though initially it was created to fulfil phpspec2 needs, it is flexible enough to be used inside any testing framework out there with minimal effort. ## A simple example ```php prophet->prophesize('App\Security\Hasher'); $user = new App\Entity\User($hasher->reveal()); $hasher->generateHash($user, 'qwerty')->willReturn('hashed_pass'); $user->setPassword('qwerty'); $this->assertEquals('hashed_pass', $user->getPassword()); } protected function setUp() { $this->prophet = new \Prophecy\Prophet; } protected function tearDown() { $this->prophet->checkPredictions(); } } ``` ## Installation ### Prerequisites Prophecy requires PHP 7.2.0 or greater. ### Setup through composer First, add Prophecy to the list of dependencies inside your `composer.json`: ```json { "require-dev": { "phpspec/prophecy": "~1.0" } } ``` Then simply install it with composer: ```bash $> composer install --prefer-dist ``` You can read more about Composer on its [official webpage](http://getcomposer.org). ## How to use it First of all, in Prophecy every word has a logical meaning, even the name of the library itself (Prophecy). When you start feeling that, you'll become very fluid with this tool. For example, Prophecy has been named that way because it concentrates on describing the future behavior of objects with very limited knowledge about them. But as with any other prophecy, those object prophecies can't create themselves - there should be a Prophet: ```php $prophet = new Prophecy\Prophet; ``` The Prophet creates prophecies by *prophesizing* them: ```php $prophecy = $prophet->prophesize(); ``` The result of the `prophesize()` method call is a new object of class `ObjectProphecy`. Yes, that's your specific object prophecy, which describes how your object would behave in the near future. But first, you need to specify which object you're talking about, right? ```php $prophecy->willExtend('stdClass'); $prophecy->willImplement('SessionHandlerInterface'); ``` There are 2 interesting calls - `willExtend` and `willImplement`. The first one tells object prophecy that our object should extend a specific class. The second one says that it should implement some interface. Obviously, objects in PHP can implement multiple interfaces, but extend only one parent class. ### Dummies Ok, now we have our object prophecy. What can we do with it? First of all, we can get our object *dummy* by revealing its prophecy: ```php $dummy = $prophecy->reveal(); ``` The `$dummy` variable now holds a special dummy object. Dummy objects are objects that extend and/or implement preset classes/interfaces by overriding all their public methods. The key point about dummies is that they do not hold any logic - they just do nothing. Any method of the dummy will always return `null` and the dummy will never throw any exceptions. Dummy is your friend if you don't care about the actual behavior of this double and just need a token object to satisfy a method typehint. You need to understand one thing - a dummy is not a prophecy. Your object prophecy is still assigned to `$prophecy` variable and in order to manipulate with your expectations, you should work with it. `$dummy` is a dummy - a simple php object that tries to fulfil your prophecy. ### Stubs Ok, now we know how to create basic prophecies and reveal dummies from them. That's awesome if we don't care about our _doubles_ (objects that reflect originals) interactions. If we do, we need to use *stubs* or *mocks*. A stub is an object double, which doesn't have any expectations about the object behavior, but when put in specific environment, behaves in specific way. Ok, I know, it's cryptic, but bear with me for a minute. Simply put, a stub is a dummy, which depending on the called method signature does different things (has logic). To create stubs in Prophecy: ```php $prophecy->read('123')->willReturn('value'); ``` Oh wow. We've just made an arbitrary call on the object prophecy? Yes, we did. And this call returned us a new object instance of class `MethodProphecy`. Yep, that's a specific method with arguments prophecy. Method prophecies give you the ability to create method promises or predictions. We'll talk about method predictions later in the _Mocks_ section. #### Promises Promises are logical blocks, that represent your fictional methods in prophecy terms and they are handled by the `MethodProphecy::will(PromiseInterface $promise)` method. As a matter of fact, the call that we made earlier (`willReturn('value')`) is a simple shortcut to: ```php $prophecy->read('123')->will(new Prophecy\Promise\ReturnPromise(array('value'))); ``` This promise will cause any call to our double's `read()` method with exactly one argument - `'123'` to always return `'value'`. But that's only for this promise, there's plenty others you can use: - `ReturnPromise` or `->willReturn(1)` - returns a value from a method call - `ReturnArgumentPromise` or `->willReturnArgument($index)` - returns the nth method argument from call - `ThrowPromise` or `->willThrow($exception)` - causes the method to throw specific exception - `CallbackPromise` or `->will($callback)` - gives you a quick way to define your own custom logic Keep in mind, that you can always add even more promises by implementing `Prophecy\Promise\PromiseInterface`. #### Method prophecies idempotency Prophecy enforces same method prophecies and, as a consequence, same promises and predictions for the same method calls with the same arguments. This means: ```php $methodProphecy1 = $prophecy->read('123'); $methodProphecy2 = $prophecy->read('123'); $methodProphecy3 = $prophecy->read('321'); $methodProphecy1 === $methodProphecy2; $methodProphecy1 !== $methodProphecy3; ``` That's interesting, right? Now you might ask me how would you define more complex behaviors where some method call changes behavior of others. In PHPUnit or Mockery you do that by predicting how many times your method will be called. In Prophecy, you'll use promises for that: ```php $user->getName()->willReturn(null); // For PHP 5.4 $user->setName('everzet')->will(function () { $this->getName()->willReturn('everzet'); }); // For PHP 5.3 $user->setName('everzet')->will(function ($args, $user) { $user->getName()->willReturn('everzet'); }); // Or $user->setName('everzet')->will(function ($args) use ($user) { $user->getName()->willReturn('everzet'); }); ``` And now it doesn't matter how many times or in which order your methods are called. What matters is their behaviors and how well you faked it. Note: If the method is called several times, you can use the following syntax to return different values for each call: ```php $prophecy->read('123')->willReturn(1, 2, 3); ``` This feature is actually not recommended for most cases. Relying on the order of calls for the same arguments tends to make test fragile, as adding one more call can break everything. #### Arguments wildcarding The previous example is awesome (at least I hope it is for you), but that's not optimal enough. We hardcoded `'everzet'` in our expectation. Isn't there a better way? In fact there is, but it involves understanding what this `'everzet'` actually is. You see, even if method arguments used during method prophecy creation look like simple method arguments, in reality they are not. They are argument token wildcards. As a matter of fact, `->setName('everzet')` looks like a simple call just because Prophecy automatically transforms it under the hood into: ```php $user->setName(new Prophecy\Argument\Token\ExactValueToken('everzet')); ``` Those argument tokens are simple PHP classes, that implement `Prophecy\Argument\Token\TokenInterface` and tell Prophecy how to compare real arguments with your expectations. And yes, those classnames are damn big. That's why there's a shortcut class `Prophecy\Argument`, which you can use to create tokens like that: ```php use Prophecy\Argument; $user->setName(Argument::exact('everzet')); ``` `ExactValueToken` is not very useful in our case as it forced us to hardcode the username. That's why Prophecy comes bundled with a bunch of other tokens: - `IdenticalValueToken` or `Argument::is($value)` - checks that the argument is identical to a specific value - `ExactValueToken` or `Argument::exact($value)` - checks that the argument matches a specific value - `TypeToken` or `Argument::type($typeOrClass)` - checks that the argument matches a specific type or classname - `ObjectStateToken` or `Argument::which($method, $value)` - checks that the argument method returns a specific value - `CallbackToken` or `Argument::that(callback)` - checks that the argument matches a custom callback - `AnyValueToken` or `Argument::any()` - matches any argument - `AnyValuesToken` or `Argument::cetera()` - matches any arguments to the rest of the signature - `StringContainsToken` or `Argument::containingString($value)` - checks that the argument contains a specific string value - `InArrayToken` or `Argument::in($array)` - checks if value is in array - `NotInArrayToken` or `Argument::notIn($array)` - checks if value is not in array And you can add even more by implementing `TokenInterface` with your own custom classes. So, let's refactor our initial `{set,get}Name()` logic with argument tokens: ```php use Prophecy\Argument; $user->getName()->willReturn(null); // For PHP 5.4 $user->setName(Argument::type('string'))->will(function ($args) { $this->getName()->willReturn($args[0]); }); // For PHP 5.3 $user->setName(Argument::type('string'))->will(function ($args, $user) { $user->getName()->willReturn($args[0]); }); // Or $user->setName(Argument::type('string'))->will(function ($args) use ($user) { $user->getName()->willReturn($args[0]); }); ``` That's it. Now our `{set,get}Name()` prophecy will work with any string argument provided to it. We've just described how our stub object should behave, even though the original object could have no behavior whatsoever. One last bit about arguments now. You might ask, what happens in case of: ```php use Prophecy\Argument; $user->getName()->willReturn(null); // For PHP 5.4 $user->setName(Argument::type('string'))->will(function ($args) { $this->getName()->willReturn($args[0]); }); // For PHP 5.3 $user->setName(Argument::type('string'))->will(function ($args, $user) { $user->getName()->willReturn($args[0]); }); // Or $user->setName(Argument::type('string'))->will(function ($args) use ($user) { $user->getName()->willReturn($args[0]); }); $user->setName(Argument::any())->will(function () { }); ``` Nothing. Your stub will continue behaving the way it did before. That's because of how arguments wildcarding works. Every argument token type has a different score level, which wildcard then uses to calculate the final arguments match score and use the method prophecy promise that has the highest score. In this case, `Argument::type()` in case of success scores `5` and `Argument::any()` scores `3`. So the type token wins, as does the first `setName()` method prophecy and its promise. The simple rule of thumb - more precise token always wins. #### Getting stub objects Ok, now we know how to define our prophecy method promises, let's get our stub from it: ```php $stub = $prophecy->reveal(); ``` As you might see, the only difference between how we get dummies and stubs is that with stubs we describe every object conversation instead of just agreeing with `null` returns (object being *dummy*). As a matter of fact, after you define your first promise (method call), Prophecy will force you to define all the communications - it throws the `UnexpectedCallException` for any call you didn't describe with object prophecy before calling it on a stub. ### Mocks Now we know how to define doubles without behavior (dummies) and doubles with behavior, but no expectations (stubs). What's left is doubles for which we have some expectations. These are called mocks and in Prophecy they look almost exactly the same as stubs, except that they define *predictions* instead of *promises* on method prophecies: ```php $entityManager->flush()->shouldBeCalled(); ``` #### Predictions The `shouldBeCalled()` method here assigns `CallPrediction` to our method prophecy. Predictions are a delayed behavior check for your prophecies. You see, during the entire lifetime of your doubles, Prophecy records every single call you're making against it inside your code. After that, Prophecy can use this collected information to check if it matches defined predictions. You can assign predictions to method prophecies using the `MethodProphecy::should(PredictionInterface $prediction)` method. As a matter of fact, the `shouldBeCalled()` method we used earlier is just a shortcut to: ```php $entityManager->flush()->should(new Prophecy\Prediction\CallPrediction()); ``` It checks if your method of interest (that matches both the method name and the arguments wildcard) was called 1 or more times. If the prediction failed then it throws an exception. When does this check happen? Whenever you call `checkPredictions()` on the main Prophet object: ```php $prophet->checkPredictions(); ``` In PHPUnit, you would want to put this call into the `tearDown()` method. If no predictions are defined, it would do nothing. So it won't harm to call it after every test. There are plenty more predictions you can play with: - `CallPrediction` or `shouldBeCalled()` - checks that the method has been called 1 or more times - `NoCallsPrediction` or `shouldNotBeCalled()` - checks that the method has not been called - `CallTimesPrediction` or `shouldBeCalledTimes($count)` - checks that the method has been called `$count` times - `CallbackPrediction` or `should($callback)` - checks the method against your own custom callback Of course, you can always create your own custom prediction any time by implementing `PredictionInterface`. ### Spies The last bit of awesomeness in Prophecy is out-of-the-box spies support. As I said in the previous section, Prophecy records every call made during the double's entire lifetime. This means you don't need to record predictions in order to check them. You can also do it manually by using the `MethodProphecy::shouldHave(PredictionInterface $prediction)` method: ```php $em = $prophet->prophesize('Doctrine\ORM\EntityManager'); $controller->createUser($em->reveal()); $em->flush()->shouldHaveBeenCalled(); ``` Such manipulation with doubles is called spying. And with Prophecy it just works. ## FAQ ### Can I call the original methods on a prophesized class? Prophecy does not support calling the original methods on a phrophesized class. If you find yourself needing to mock some methods of a class while calling the original version of other methods, it's likely a sign that your class violates the [single-responsibility principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) and should be refactored. ================================================ FILE: composer.json ================================================ { "name": "phpspec/prophecy", "description": "Highly opinionated mocking framework for PHP 5.3+", "keywords": ["Mock", "Stub", "Dummy", "Double", "Fake", "Spy", "dev"], "homepage": "https://github.com/phpspec/prophecy", "type": "library", "license": "MIT", "authors": [ { "name": "Konstantin Kudryashov", "email": "ever.zet@gmail.com", "homepage": "http://everzet.com" }, { "name": "Marcello Duarte", "email": "marcello.duarte@gmail.com" } ], "require": { "php": "8.2.* || 8.3.* || 8.4.* || 8.5.*", "phpdocumentor/reflection-docblock": "^5.2 || ^6.0", "sebastian/comparator": "^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0", "doctrine/instantiator": "^1.2 || ^2.0", "sebastian/recursion-context": "^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0", "symfony/deprecation-contracts": "^2.5 || ^3.1" }, "require-dev": { "php-cs-fixer/shim": "^3.93.1", "phpspec/phpspec": "^6.0 || ^7.0 || ^8.0", "phpstan/phpstan": "^2.1.13, <2.1.34 || ^2.1.39", "phpunit/phpunit": "^11.0 || ^12.0 || ^13.0" }, "autoload": { "psr-4": { "Prophecy\\": "src/Prophecy" } }, "autoload-dev": { "psr-4": { "Fixtures\\Prophecy\\": "fixtures", "Tests\\Prophecy\\": "tests" } }, "scripts": { "cs:check": "@php php-cs-fixer check --verbose --diff", "cs:fix": "@php php-cs-fixer fix", "phpstan": "phpstan analyse", "phpstan:baseline": "phpstan analyse --generate-baseline" }, "scripts-descriptions": { "cs:check": "Check coding standards", "cs:fix": "Fix coding standards", "phpstan": "Run PHPStan analysis", "phpstan:baseline": "Dump PHPStan baseline file - use only for updating, do not add new errors when possible" }, "extra": { "branch-alias": { "dev-master": "1.x-dev" } } } ================================================ FILE: fixtures/AbstractBaseClassWithMethodWithReturnType.php ================================================ but returns class\-string\.$#' identifier: return.type count: 1 path: src/Prophecy/Doubler/CachedDoubler.php - message: '#^Parameter \#1 \$types of class Prophecy\\Doubler\\Generator\\Node\\Type\\UnionType constructor expects list\, array\{Prophecy\\Doubler\\Generator\\Node\\Type\\BuiltinType, Prophecy\\Doubler\\Generator\\Node\\Type\\TypeInterface\} given\.$#' identifier: argument.type count: 1 path: src/Prophecy/Doubler/ClassPatch/DisableConstructorPatch.php - message: '#^Method Prophecy\\Doubler\\Doubler\:\:createDoubleClass\(\) should return class\-string\ but returns class\-string\.$#' identifier: return.type count: 1 path: src/Prophecy/Doubler/Doubler.php - message: '#^Call to function method_exists\(\) with ''ReflectionClass'' and ''isReadOnly'' will always evaluate to true\.$#' identifier: function.alreadyNarrowedType count: 1 path: src/Prophecy/Doubler/Generator/ClassMirror.php - message: '#^Call to function method_exists\(\) with ReflectionMethod and ''hasTentativeReturnT…'' will always evaluate to true\.$#' identifier: function.alreadyNarrowedType count: 1 path: src/Prophecy/Doubler/Generator/ClassMirror.php - message: '#^PHPDoc tag @var with type static\(Prophecy\\Doubler\\LazyDouble\\) is not subtype of native type \$this\(Prophecy\\Doubler\\LazyDouble\\)\.$#' identifier: varTag.nativeType count: 1 path: src/Prophecy/Doubler/LazyDouble.php - message: '#^Property Prophecy\\Doubler\\LazyDouble\:\:\$class \(ReflectionClass\\|null\) does not accept ReflectionClass\\.$#' identifier: assign.propertyType count: 1 path: src/Prophecy/Doubler/LazyDouble.php - message: '#^Call to function method_exists\(\) with ReflectionMethod and ''hasTentativeReturnT…'' will always evaluate to true\.$#' identifier: function.alreadyNarrowedType count: 1 path: src/Prophecy/Prophecy/MethodProphecy.php - message: '#^Parameter \#1 \$callback of function array_map expects \(callable\(ReflectionIntersectionType\|ReflectionNamedType\)\: mixed\)\|null, Closure\(ReflectionNamedType\)\: string given\.$#' identifier: argument.type count: 1 path: src/Prophecy/Prophecy/MethodProphecy.php - message: '#^Possibly invalid array key type mixed\.$#' identifier: offsetAccess.invalidOffset count: 1 path: src/Prophecy/Util/ExportUtil.php - message: '#^Call to an undefined method phpDocumentor\\Reflection\\DocBlock\\Tags\\Method\:\:getArguments\(\)\.$#' identifier: method.notFound count: 1 path: src/Prophecy/Doubler/ClassPatch/MagicCallPatch.php ================================================ FILE: phpstan.dist.neon ================================================ parameters: level: 9 inferPrivatePropertyTypeFromConstructor: true treatPhpDocTypesAsCertain: false paths: - ./src/ excludePaths: - src/Prophecy/Comparator/Factory.php includes: - phpstan-baseline.neon ================================================ FILE: phpunit.xml.dist ================================================ tests ./src/ ================================================ FILE: spec/Prophecy/Argument/ArgumentsWildcardSpec.php ================================================ beConstructedWith(array(42, 'zet', $object)); $class = get_class($object->getWrappedObject()); $id = spl_object_id($object->getWrappedObject()); $objHash = "exact(42), exact(\"zet\"), exact($class#$id Object (\n 'objectProphecyClosure' => Closure#%s Object (\n 0 => Closure#%s Object\n )\n))"; $idRegexExpr = '[0-9]+'; $this->__toString()->shouldMatch(sprintf('/^%s$/', sprintf(preg_quote("$objHash"), $idRegexExpr, $idRegexExpr))); } function it_generates_string_representation_from_all_tokens_imploded( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->__toString()->willReturn('token_1'); $token2->__toString()->willReturn('token_2'); $token3->__toString()->willReturn('token_3'); $this->beConstructedWith(array($token1, $token2, $token3)); $this->__toString()->shouldReturn('token_1, token_2, token_3'); } function it_exposes_list_of_tokens(TokenInterface $token) { $this->beConstructedWith(array($token)); $this->getTokens()->shouldReturn(array($token)); } function it_returns_score_of_1_if_there_are_no_tokens_and_arguments() { $this->beConstructedWith(array()); $this->scoreArguments(array())->shouldReturn(1); } function it_should_return_match_score_based_on_all_tokens_score( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->scoreArgument('one')->willReturn(3); $token1->isLast()->willReturn(false); $token2->scoreArgument(2)->willReturn(5); $token2->isLast()->willReturn(false); $token3->scoreArgument($obj = new \stdClass())->willReturn(10); $token3->isLast()->willReturn(false); $this->beConstructedWith(array($token1, $token2, $token3)); $this->scoreArguments(array('one', 2, $obj))->shouldReturn(18); } function it_returns_false_if_there_is_less_arguments_than_tokens( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->scoreArgument('one')->willReturn(3); $token1->isLast()->willReturn(false); $token2->scoreArgument(2)->willReturn(5); $token2->isLast()->willReturn(false); $token3->scoreArgument(null)->willReturn(false); $token3->isLast()->willReturn(false); $this->beConstructedWith(array($token1, $token2, $token3)); $this->scoreArguments(array('one', 2))->shouldReturn(false); } function it_returns_false_if_there_is_less_tokens_than_arguments( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->scoreArgument('one')->willReturn(3); $token1->isLast()->willReturn(false); $token2->scoreArgument(2)->willReturn(5); $token2->isLast()->willReturn(false); $token3->scoreArgument($obj = new \stdClass())->willReturn(10); $token3->isLast()->willReturn(false); $this->beConstructedWith(array($token1, $token2, $token3)); $this->scoreArguments(array('one', 2, $obj, 4))->shouldReturn(false); } function it_should_return_false_if_one_of_the_tokens_returns_false( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->scoreArgument('one')->willReturn(3); $token1->isLast()->willReturn(false); $token2->scoreArgument(2)->willReturn(false); $token2->isLast()->willReturn(false); $token3->scoreArgument($obj = new \stdClass())->willReturn(10); $token3->isLast()->willReturn(false); $this->beConstructedWith(array($token1, $token2, $token3)); $this->scoreArguments(array('one', 2, $obj))->shouldReturn(false); } function it_should_calculate_score_until_last_token( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->scoreArgument('one')->willReturn(3); $token1->isLast()->willReturn(false); $token2->scoreArgument(2)->willReturn(7); $token2->isLast()->willReturn(true); $token3->scoreArgument($obj = new \stdClass())->willReturn(10); $token3->isLast()->willReturn(false); $this->beConstructedWith(array($token1, $token2, $token3)); $this->scoreArguments(array('one', 2, $obj))->shouldReturn(10); } } ================================================ FILE: spec/Prophecy/Argument/Token/AnyValueTokenSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function its_string_representation_is_star() { $this->__toString()->shouldReturn('*'); } function it_scores_any_argument_as_3() { $this->scoreArgument(42)->shouldReturn(3); } } ================================================ FILE: spec/Prophecy/Argument/Token/AnyValuesTokenSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_last() { $this->shouldBeLast(); } function its_string_representation_is_star_with_followup() { $this->__toString()->shouldReturn('* [, ...]'); } function it_scores_any_argument_as_2() { $this->scoreArgument(42)->shouldReturn(2); } } ================================================ FILE: spec/Prophecy/Argument/Token/ApproximateValueTokenSpec.php ================================================ beConstructedWith(10.12345678, 4); } function it_is_initializable() { $this->shouldHaveType('Prophecy\Argument\Token\ApproximateValueToken'); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_scores_10_if_rounded_argument_matches_rounded_value() { $this->scoreArgument(10.12345)->shouldReturn(10); } function it_does_not_score_if_rounded_argument_does_not_match_rounded_value() { $this->scoreArgument(10.1234)->shouldReturn(false); } function it_uses_a_default_precision_of_zero() { $this->beConstructedWith(10.7); $this->scoreArgument(11.4)->shouldReturn(10); } function it_does_not_score_if_rounded_argument_is_not_numeric() { $this->scoreArgument('hello')->shouldReturn(false); $this->scoreArgument(new \stdClass())->shouldReturn(false); $this->scoreArgument(false)->shouldReturn(false); } function it_has_simple_string_representation() { $this->__toString()->shouldBe('≅10.1235'); } } ================================================ FILE: spec/Prophecy/Argument/Token/ArrayCountTokenSpec.php ================================================ beConstructedWith(2); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_scores_6_if_argument_array_has_proper_count() { $this->scoreArgument(array(1,2))->shouldReturn(6); } function it_scores_6_if_argument_countable_object_has_proper_count(\Countable $countable) { $countable->count()->willReturn(2); $this->scoreArgument($countable)->shouldReturn(6); } function it_does_not_score_if_argument_is_neither_array_nor_countable_object() { $this->scoreArgument('string')->shouldBe(false); $this->scoreArgument(5)->shouldBe(false); $this->scoreArgument(new \stdClass())->shouldBe(false); } function it_does_not_score_if_argument_array_has_wrong_count() { $this->scoreArgument(array(1))->shouldReturn(false); } function it_does_not_score_if_argument_countable_object_has_wrong_count(\Countable $countable) { $countable->count()->willReturn(3); $this->scoreArgument($countable)->shouldReturn(false); } function it_has_simple_string_representation() { $this->__toString()->shouldBe('count(2)'); } } ================================================ FILE: spec/Prophecy/Argument/Token/ArrayEntryTokenSpec.php ================================================ beConstructedWith($key, $value); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_holds_key_and_value($key, $value) { $this->getKey()->shouldBe($key); $this->getValue()->shouldBe($value); } function its_string_representation_tells_that_its_an_array_containing_the_key_value_pair($key, $value) { $key->__toString()->willReturn('key'); $value->__toString()->willReturn('value'); $this->__toString()->shouldBe('[..., key => value, ...]'); } function it_wraps_non_token_value_into_ExactValueToken(TokenInterface $key, \stdClass $object) { $this->beConstructedWith($key, $object); $this->getValue()->shouldHaveType('\Prophecy\Argument\Token\ExactValueToken'); } function it_wraps_non_token_key_into_ExactValueToken(\stdClass $object, TokenInterface $value) { $this->beConstructedWith($object, $value); $this->getKey()->shouldHaveType('\Prophecy\Argument\Token\ExactValueToken'); } function it_scores_array_half_of_combined_scores_from_key_and_value_tokens($key, $value) { $key->scoreArgument('key')->willReturn(4); $value->scoreArgument('value')->willReturn(6); $this->scoreArgument(array('key' => 'value'))->shouldBe(5); } function it_scores_traversable_object_half_of_combined_scores_from_key_and_value_tokens( TokenInterface $key, TokenInterface $value, \Iterator $object ) { $object->current()->will(function () use ($object) { $object->valid()->willReturn(false); return 'value'; }); $object->key()->willReturn('key'); (\PHP_VERSION_ID < 80100) ? $object->rewind()->willReturn(null) : $object->rewind()->shouldBeCalled(); (\PHP_VERSION_ID < 80100) ? $object->next()->willReturn(null) : $object->next()->shouldBeCalled(); $object->valid()->willReturn(true); $key->scoreArgument('key')->willReturn(6); $value->scoreArgument('value')->willReturn(2); $this->scoreArgument($object)->shouldBe(4); } function it_throws_exception_during_scoring_of_array_accessible_object_if_key_is_not_ExactValueToken( TokenInterface $key, TokenInterface $value, \ArrayAccess $object ) { $key->__toString()->willReturn('any_token'); $this->beConstructedWith($key, $value); $errorMessage = 'You can only use exact value tokens to match key of ArrayAccess object'.PHP_EOL .'But you used `any_token`.'; $this->shouldThrow(new InvalidArgumentException($errorMessage))->duringScoreArgument($object); } function it_scores_array_accessible_object_half_of_combined_scores_from_key_and_value_tokens( ExactValueToken $key, TokenInterface $value, \ArrayAccess $object ) { $object->offsetExists('key')->willReturn(true); $object->offsetGet('key')->willReturn('value'); $key->getValue()->willReturn('key'); $key->scoreArgument('key')->willReturn(3); $value->scoreArgument('value')->willReturn(1); $this->scoreArgument($object)->shouldBe(2); } function it_accepts_any_key_token_type_to_score_object_that_is_both_traversable_and_array_accessible( TokenInterface $key, TokenInterface $value, \ArrayIterator $object ) { $this->beConstructedWith($key, $value); $object->current()->will(function () use ($object) { $object->valid()->willReturn(false); return 'value'; }); $object->key()->willReturn('key'); (\PHP_VERSION_ID < 80100) ? $object->rewind()->willReturn(null) : $object->rewind()->shouldBeCalled(); (\PHP_VERSION_ID < 80100) ? $object->next()->willReturn(null) : $object->next()->shouldBeCalled(); $object->valid()->willReturn(true); $this->shouldNotThrow(new InvalidArgumentException())->duringScoreArgument($object); } function it_does_not_score_if_argument_is_neither_array_nor_traversable_nor_array_accessible() { $this->scoreArgument('string')->shouldBe(false); $this->scoreArgument(new \stdClass())->shouldBe(false); } function it_does_not_score_empty_array() { $this->scoreArgument(array())->shouldBe(false); } function it_does_not_score_array_if_key_and_value_tokens_do_not_score_same_entry($key, $value) { $argument = array(1 => 'foo', 2 => 'bar'); $key->scoreArgument(1)->willReturn(true); $key->scoreArgument(2)->willReturn(false); $value->scoreArgument('foo')->willReturn(false); $value->scoreArgument('bar')->willReturn(true); $this->scoreArgument($argument)->shouldBe(false); } function it_does_not_score_traversable_object_without_entries(\Iterator $object) { (\PHP_VERSION_ID < 80100) ? $object->rewind()->willReturn(null) : $object->rewind()->shouldBeCalled(); (\PHP_VERSION_ID < 80100) && $object->next()->willReturn(null); $object->valid()->willReturn(false); $this->scoreArgument($object)->shouldBe(false); } function it_does_not_score_traversable_object_if_key_and_value_tokens_do_not_score_same_entry( TokenInterface $key, TokenInterface $value, \Iterator $object ) { $object->current()->willReturn('foo'); $object->current()->will(static function () use ($object) { $object->valid()->willReturn(false); return 'bar'; }); $object->key()->willReturn(1); $object->key()->willReturn(2); (\PHP_VERSION_ID < 80100) ? $object->rewind()->willReturn(null) : $object->rewind()->shouldBeCalled(); (\PHP_VERSION_ID < 80100) ? $object->next()->willReturn(null) : $object->next()->shouldBeCalled(); $object->valid()->willReturn(true); $key->scoreArgument(1)->willReturn(true); $key->scoreArgument(2)->willReturn(false); $value->scoreArgument('foo')->willReturn(false); $value->scoreArgument('bar')->willReturn(true); $this->scoreArgument($object)->shouldBe(false); } function it_does_not_score_array_accessible_object_if_it_has_no_offset_with_key_token_value( ExactValueToken $key, \ArrayAccess $object ) { $object->offsetExists('key')->willReturn(false); $key->getValue()->willReturn('key'); $this->scoreArgument($object)->shouldBe(false); } function it_does_not_score_array_accessible_object_if_key_and_value_tokens_do_not_score_same_entry( ExactValueToken $key, TokenInterface $value, \ArrayAccess $object ) { $object->offsetExists('key')->willReturn(true); $object->offsetGet('key')->willReturn('value'); $key->getValue()->willReturn('key'); $value->scoreArgument('value')->willReturn(false); $key->scoreArgument('key')->willReturn(true); $this->scoreArgument($object)->shouldBe(false); } function its_score_is_capped_at_8($key, $value) { $key->scoreArgument('key')->willReturn(10); $value->scoreArgument('value')->willReturn(10); $this->scoreArgument(array('key' => 'value'))->shouldBe(8); } } ================================================ FILE: spec/Prophecy/Argument/Token/ArrayEveryEntryTokenSpec.php ================================================ beConstructedWith($value); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_holds_value($value) { $this->getValue()->shouldBe($value); } function its_string_representation_tells_that_its_an_array_containing_only_value($value) { $value->__toString()->willReturn('value'); $this->__toString()->shouldBe('[value, ..., value]'); } function it_wraps_non_token_value_into_ExactValueToken(\stdClass $stdClass) { $this->beConstructedWith($stdClass); $this->getValue()->shouldHaveType('Prophecy\Argument\Token\ExactValueToken'); } function it_does_not_score_if_argument_is_neither_array_nor_traversable() { $this->scoreArgument('string')->shouldBe(false); $this->scoreArgument(new \stdClass())->shouldBe(false); } function it_does_not_score_empty_array() { $this->scoreArgument(array())->shouldBe(false); } function it_does_not_score_traversable_object_without_entries(\Iterator $object) { (\PHP_VERSION_ID < 80100) ? $object->rewind()->willReturn(null) : $object->rewind()->shouldBeCalled(); (\PHP_VERSION_ID < 80100) && $object->next()->willReturn(null); $object->valid()->willReturn(false); $this->scoreArgument($object)->shouldBe(false); } function it_scores_avg_of_scores_from_value_tokens($value) { $value->scoreArgument('value1')->willReturn(6); $value->scoreArgument('value2')->willReturn(3); $this->scoreArgument(array('value1', 'value2'))->shouldBe(4.5); } function it_scores_false_if_entry_scores_false($value) { $value->scoreArgument('value1')->willReturn(6); $value->scoreArgument('value2')->willReturn(false); $this->scoreArgument(array('value1', 'value2'))->shouldBe(false); } function it_does_not_score_array_keys($value) { $value->scoreArgument('value')->willReturn(6); $value->scoreArgument('key')->shouldNotBeCalled(0); $this->scoreArgument(array('key' => 'value'))->shouldBe(6); } function it_scores_traversable_object_from_value_token(TokenInterface $value, \Iterator $object) { $object->current()->will(function ($args, $object) { $object->valid()->willReturn(false); return 'value'; }); $object->key()->willReturn('key'); (\PHP_VERSION_ID < 80100) ? $object->rewind()->willReturn(null) : $object->rewind()->shouldBeCalled(); (\PHP_VERSION_ID < 80100) ? $object->next()->willReturn(null) : $object->next()->shouldBeCalled(); $object->valid()->willReturn(true); $value->scoreArgument('value')->willReturn(2); $this->scoreArgument($object)->shouldBe(2); } } ================================================ FILE: spec/Prophecy/Argument/Token/CallbackTokenSpec.php ================================================ beConstructedWith('get_class'); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_scores_7_if_argument_matches_callback() { $this->beConstructedWith(function ($argument) { return 2 === $argument; }); $this->scoreArgument(2)->shouldReturn(7); } function it_does_not_scores_if_argument_does_not_match_callback() { $this->beConstructedWith(function ($argument) { return 2 === $argument; }); $this->scoreArgument(5)->shouldReturn(false); } function its_string_representation_should_tell_that_its_callback() { $this->__toString()->shouldReturn('callback()'); } function its_string_representation_can_be_customized() { $this->beConstructedWith('get_class', 'MyCustomTestCase'); $this->__toString()->shouldReturn('MyCustomTestCase'); } } ================================================ FILE: spec/Prophecy/Argument/Token/ExactValueTokenSpec.php ================================================ beConstructedWith(42); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_holds_value() { $this->getValue()->shouldReturn(42); } function it_scores_10_if_value_is_equal_to_argument() { $this->scoreArgument(42)->shouldReturn(10); $this->scoreArgument('42')->shouldReturn(10); } function it_scores_10_if_value_is_an_object_and_equal_to_argument() { $value = new \DateTime(); $value2 = clone $value; $this->beConstructedWith($value); $this->scoreArgument($value2)->shouldReturn(10); } function it_scores_10_if_value_is_a_double_object_and_equal_to_argument(\stdClass $value) { $value2 = clone $value->getWrappedObject(); $this->beConstructedWith($value); $this->scoreArgument($value2)->shouldReturn(10); } function it_does_not_scores_if_value_is_not_equal_to_argument() { $this->scoreArgument(50)->shouldReturn(false); $this->scoreArgument(new \stdClass())->shouldReturn(false); } function it_does_not_scores_if_value_an_object_and_is_not_equal_to_argument() { $value = new ExactValueTokenFixtureB('ABC'); $value2 = new ExactValueTokenFixtureB('CBA'); $this->beConstructedWith($value); $this->scoreArgument($value2)->shouldReturn(false); } function it_does_not_scores_if_value_type_and_is_not_equal_to_argument() { $this->beConstructedWith(false); $this->scoreArgument(0)->shouldReturn(false); } function it_generates_proper_string_representation_for_integer() { $this->beConstructedWith(42); $this->__toString()->shouldReturn('exact(42)'); } function it_generates_proper_string_representation_for_string() { $this->beConstructedWith('some string'); $this->__toString()->shouldReturn('exact("some string")'); } function it_generates_single_line_representation_for_multiline_string() { $this->beConstructedWith("some\nstring"); $this->__toString()->shouldReturn('exact("some\\nstring")'); } function it_generates_proper_string_representation_for_double() { $this->beConstructedWith(42.3); $this->__toString()->shouldReturn('exact(42.3)'); } function it_generates_proper_string_representation_for_boolean_true() { $this->beConstructedWith(true); $this->__toString()->shouldReturn('exact(true)'); } function it_generates_proper_string_representation_for_boolean_false() { $this->beConstructedWith(false); $this->__toString()->shouldReturn('exact(false)'); } function it_generates_proper_string_representation_for_null() { $this->beConstructedWith(null); $this->__toString()->shouldReturn('exact(null)'); } function it_generates_proper_string_representation_for_empty_array() { $this->beConstructedWith(array()); $this->__toString()->shouldReturn('exact([])'); } function it_generates_proper_string_representation_for_array() { $this->beConstructedWith(array('zet', 42)); $this->__toString()->shouldReturn('exact(["zet", 42])'); } function it_generates_proper_string_representation_for_resource() { $resource = fopen(__FILE__, 'r'); $this->beConstructedWith($resource); $this->__toString()->shouldReturn('exact(stream:'.$resource.')'); } function it_generates_proper_string_representation_for_object(\stdClass $object) { $objHash = sprintf('exact(%s#%s', get_class($object->getWrappedObject()), spl_object_id($object->getWrappedObject()) )." Object (\n 'objectProphecyClosure' => Closure#%s Object (\n 0 => Closure#%s Object\n )\n))"; $this->beConstructedWith($object); $idRegexExpr = '[0-9]+'; $this->__toString()->shouldMatch(sprintf('/^%s$/', sprintf(preg_quote("$objHash"), $idRegexExpr, $idRegexExpr))); } function it_scores_10_if_value_an_numeric_and_equal_to_argument_as_stringable() { $value = 10; $argument = new ExactValueTokenC("10"); $this->beConstructedWith($value); $this->scoreArgument($argument)->shouldReturn(10); } function it_does_not_scores_if_value_an_numeric_and_equal_to_argument_as_stringable() { $value = 10; $argument = new ExactValueTokenC("example"); $this->beConstructedWith($value); $this->scoreArgument($argument)->shouldReturn(false); } function it_does_not_scores_if_value_an_object_and_not_equal_to_argument_object() { $value = new ExactValueTokenFixtureA(); $argument = new ExactValueTokenC("example"); $this->beConstructedWith($value); $this->scoreArgument($argument)->shouldReturn(false); } } class ExactValueTokenFixtureA { public $errors; } class ExactValueTokenFixtureB extends ExactValueTokenFixtureA { public $errors; public $value = null; public function __construct($value) { $this->value = $value; } } class ExactValueTokenC { public $value; public function __construct($value) { $this->value = $value; } public function __toString() { return $this->value; } } ================================================ FILE: spec/Prophecy/Argument/Token/IdenticalValueTokenSpec.php ================================================ beConstructedWith(42); } function it_is_initializable() { $this->shouldHaveType('Prophecy\Argument\Token\IdenticalValueToken'); } function it_scores_11_if_string_value_is_identical_to_argument() { $this->beConstructedWith('foo'); $this->scoreArgument('foo')->shouldReturn(11); } function it_scores_11_if_boolean_value_is_identical_to_argument() { $this->beConstructedWith(false); $this->scoreArgument(false)->shouldReturn(11); } function it_scores_11_if_integer_value_is_identical_to_argument() { $this->beConstructedWith(31); $this->scoreArgument(31)->shouldReturn(11); } function it_scores_11_if_float_value_is_identical_to_argument() { $this->beConstructedWith(31.12); $this->scoreArgument(31.12)->shouldReturn(11); } function it_scores_11_if_array_value_is_identical_to_argument() { $this->beConstructedWith(array('foo' => 'bar')); $this->scoreArgument(array('foo' => 'bar'))->shouldReturn(11); } function it_scores_11_if_object_value_is_identical_to_argument() { $object = new \stdClass(); $this->beConstructedWith($object); $this->scoreArgument($object)->shouldReturn(11); } function it_scores_false_if_value_is_not_identical_to_argument() { $this->beConstructedWith(new \stdClass()); $this->scoreArgument('foo')->shouldReturn(false); } function it_scores_false_if_object_value_is_not_the_same_instance_than_argument() { $this->beConstructedWith(new \stdClass()); $this->scoreArgument(new \stdClass())->shouldReturn(false); } function it_scores_false_if_integer_value_is_not_identical_to_boolean_argument() { $this->beConstructedWith(1); $this->scoreArgument(true)->shouldReturn(false); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_generates_proper_string_representation_for_integer() { $this->beConstructedWith(42); $this->__toString()->shouldReturn('identical(42)'); } function it_generates_proper_string_representation_for_string() { $this->beConstructedWith('some string'); $this->__toString()->shouldReturn('identical("some string")'); } function it_generates_single_line_representation_for_multiline_string() { $this->beConstructedWith("some\nstring"); $this->__toString()->shouldReturn('identical("some\\nstring")'); } function it_generates_proper_string_representation_for_double() { $this->beConstructedWith(42.3); $this->__toString()->shouldReturn('identical(42.3)'); } function it_generates_proper_string_representation_for_boolean_true() { $this->beConstructedWith(true); $this->__toString()->shouldReturn('identical(true)'); } function it_generates_proper_string_representation_for_boolean_false() { $this->beConstructedWith(false); $this->__toString()->shouldReturn('identical(false)'); } function it_generates_proper_string_representation_for_null() { $this->beConstructedWith(null); $this->__toString()->shouldReturn('identical(null)'); } function it_generates_proper_string_representation_for_empty_array() { $this->beConstructedWith(array()); $this->__toString()->shouldReturn('identical([])'); } function it_generates_proper_string_representation_for_array() { $this->beConstructedWith(array('zet', 42)); $this->__toString()->shouldReturn('identical(["zet", 42])'); } function it_generates_proper_string_representation_for_resource() { $resource = fopen(__FILE__, 'r'); $this->beConstructedWith($resource); $this->__toString()->shouldReturn('identical(stream:'.$resource.')'); } function it_generates_proper_string_representation_for_object($object) { $objHash = sprintf('identical(%s#%s', get_class($object->getWrappedObject()), spl_object_id($object->getWrappedObject()) )." Object (\n 'objectProphecyClosure' => Closure#%s Object (\n 0 => Closure#%s Object\n )\n))"; $this->beConstructedWith($object); $idRegexExpr = '[0-9]+'; $this->__toString()->shouldMatch(sprintf('/^%s$/', sprintf(preg_quote("$objHash"), $idRegexExpr, $idRegexExpr))); } } ================================================ FILE: spec/Prophecy/Argument/Token/InArrayTokenSpec.php ================================================ beConstructedWith(array()); $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->beConstructedWith(array()); $this->shouldNotBeLast(); } function it_scores_8_if_argument_is_in_array() { $this->beConstructedWith(array(1, 2, 3)); $this->scoreArgument(2)->shouldReturn(8); } function it_scores_false_if_argument_is_not_in_array() { $this->beConstructedWith(array(1, 2, 3)); $this->scoreArgument(5)->shouldReturn(false); } function it_generates_array_in_string_format() { $this->beConstructedWith(array(1, 2, 3)); $this->__toString()->shouldBe('[1, 2, 3]'); } function it_generates_an_empty_array_as_string_when_token_is_empty() { $this->beConstructedWith(array()); $this->__toString()->shouldBe('[]'); } } ================================================ FILE: spec/Prophecy/Argument/Token/LogicalAndTokenSpec.php ================================================ beConstructedWith(array()); $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->beConstructedWith(array()); $this->shouldNotBeLast(); } function it_generates_string_representation_from_all_tokens_imploded( TokenInterface $token1, TokenInterface $token2, TokenInterface $token3 ) { $token1->__toString()->willReturn('token_1'); $token2->__toString()->willReturn('token_2'); $token3->__toString()->willReturn('token_3'); $this->beConstructedWith(array($token1, $token2, $token3)); $this->__toString()->shouldReturn('bool(token_1 AND token_2 AND token_3)'); } function it_wraps_non_token_arguments_into_ExactValueToken() { $this->beConstructedWith(array(15, '1985')); $this->__toString()->shouldReturn("bool(exact(15) AND exact(\"1985\"))"); } function it_scores_the_maximum_score_from_all_scores_returned_by_tokens(TokenInterface $token1, TokenInterface $token2) { $token1->scoreArgument(1)->willReturn(10); $token2->scoreArgument(1)->willReturn(5); $this->beConstructedWith(array($token1, $token2)); $this->scoreArgument(1)->shouldReturn(10); } function it_does_not_score_if_there_are_no_arguments_or_tokens() { $this->beConstructedWith(array()); $this->scoreArgument('any')->shouldReturn(false); } function it_does_not_score_if_either_of_tokens_does_not_score(TokenInterface $token1, TokenInterface $token2) { $token1->scoreArgument(1)->willReturn(10); $token1->scoreArgument(2)->willReturn(false); $token2->scoreArgument(1)->willReturn(false); $token2->scoreArgument(2)->willReturn(10); $this->beConstructedWith(array($token1, $token2)); $this->scoreArgument(1)->shouldReturn(false); $this->scoreArgument(2)->shouldReturn(false); } } ================================================ FILE: spec/Prophecy/Argument/Token/LogicalNotTokenSpec.php ================================================ beConstructedWith($token); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_holds_originating_token($token) { $this->getOriginatingToken()->shouldReturn($token); } function it_has_simple_string_representation($token) { $token->__toString()->willReturn('value'); $this->__toString()->shouldBe('not(value)'); } function it_wraps_non_token_argument_into_ExactValueToken() { $this->beConstructedWith(5); $token = $this->getOriginatingToken(); $token->shouldhaveType('Prophecy\Argument\Token\ExactValueToken'); $token->getValue()->shouldBe(5); } function it_scores_4_if_preset_token_does_not_match_the_argument($token) { $token->scoreArgument('argument')->willReturn(false); $this->scoreArgument('argument')->shouldBe(4); } function it_does_not_score_if_preset_token_matches_argument($token) { $token->scoreArgument('argument')->willReturn(5); $this->scoreArgument('argument')->shouldBe(false); } function it_is_last_if_preset_token_is_last($token) { $token->isLast()->willReturn(true); $this->shouldBeLast(); } function it_is_not_last_if_preset_token_is_not_last($token) { $token->isLast()->willReturn(false); $this->shouldNotBeLast(); } } ================================================ FILE: spec/Prophecy/Argument/Token/NotInArrayTokenSpec.php ================================================ beConstructedWith(array()); $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->beConstructedWith(array()); $this->shouldNotBeLast(); } function it_scores_8_if_argument_is_not_in_array() { $this->beConstructedWith(array(1, 2, 3)); $this->scoreArgument(5)->shouldReturn(8); } function it_scores_false_if_argument_is_in_array() { $this->beConstructedWith(array(1, 2, 3)); $this->scoreArgument(2)->shouldReturn(false); } function it_generates_array_in_string_format() { $this->beConstructedWith(array(1, 2, 3)); $this->__toString()->shouldBe('[1, 2, 3]'); } function it_generates_an_empty_array_as_string_when_token_is_empty() { $this->beConstructedWith(array()); $this->__toString()->shouldBe('[]'); } } ================================================ FILE: spec/Prophecy/Argument/Token/ObjectStateTokenSpec.php ================================================ beConstructedWith('getName', 'stdClass'); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_scores_8_if_argument_object_has_specific_method_state(\ReflectionClass $reflection) { $reflection->getName()->willReturn('stdClass'); $this->scoreArgument($reflection)->shouldReturn(8); } function it_scores_8_if_argument_object_has_specific_property_state(\stdClass $class) { $class->getName = 'stdClass'; $this->scoreArgument($class)->shouldReturn(8); } function it_does_not_score_if_argument_method_state_does_not_match() { $value = new ObjectStateTokenFixtureB('ABC'); $value2 = new ObjectStateTokenFixtureB('CBA'); $this->beConstructedWith('getSelf', $value); $this->scoreArgument($value2)->shouldReturn(false); } function it_does_not_score_if_argument_property_state_does_not_match(\stdClass $class) { $class->getName = 'SplFileInfo'; $this->scoreArgument($class)->shouldReturn(false); } function it_does_not_score_if_argument_object_does_not_have_method_or_property(ObjectStateTokenFixtureA $class) { $this->scoreArgument($class)->shouldReturn(false); } function it_does_not_score_if_argument_is_not_object() { $this->scoreArgument(42)->shouldReturn(false); } function it_has_simple_string_representation() { $this->__toString()->shouldReturn('state(getName(), "stdClass")'); } } class ObjectStateTokenFixtureA { public $errors; } class ObjectStateTokenFixtureB extends ObjectStateTokenFixtureA { public $errors; public $value = null; public function __construct($value) { $this->value = $value; } public function getSelf() { return $this; } } ================================================ FILE: spec/Prophecy/Argument/Token/StringContainsTokenSpec.php ================================================ beConstructedWith('a substring'); } function it_is_initializable() { $this->shouldHaveType('Prophecy\Argument\Token\StringContainsToken'); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_holds_value() { $this->getValue()->shouldReturn('a substring'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_scores_6_if_the_argument_contains_the_value() { $this->scoreArgument('Argument containing a substring')->shouldReturn(6); } function it_does_not_score_if_the_argument_does_not_contain_the_value() { $this->scoreArgument('Argument will not match')->shouldReturn(false); } function it_does_not_score_if_the_argument_is_not_a_string() { $this->scoreArgument(array('a substring', 'other value'))->shouldReturn(false); } function its_string_representation_shows_substring() { $this->__toString()->shouldReturn('contains("a substring")'); } } ================================================ FILE: spec/Prophecy/Argument/Token/TypeTokenSpec.php ================================================ beConstructedWith('integer'); } function it_implements_TokenInterface() { $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface'); } function it_is_not_last() { $this->shouldNotBeLast(); } function it_scores_5_if_argument_matches_simple_type() { $this->beConstructedWith('integer'); $this->scoreArgument(42)->shouldReturn(5); } function it_does_not_scores_if_argument_does_not_match_simple_type() { $this->beConstructedWith('integer'); $this->scoreArgument(42.0)->shouldReturn(false); } function it_scores_5_if_argument_is_an_instance_of_specified_class(\ReflectionObject $object) { $this->beConstructedWith('ReflectionClass'); $this->scoreArgument($object)->shouldReturn(5); } function it_has_simple_string_representation() { $this->__toString()->shouldReturn('type(integer)'); } function it_scores_5_if_argument_is_an_instance_of_specified_interface(TokenInterface $interface) { $this->beConstructedWith('Prophecy\Argument\Token\TokenInterface'); $this->scoreArgument($interface)->shouldReturn(5); } } ================================================ FILE: spec/Prophecy/ArgumentSpec.php ================================================ exact(42); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ExactValueToken'); $token->getValue()->shouldReturn(42); } function it_has_a_shortcut_for_any_argument_token() { $token = $this->any(); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\AnyValueToken'); } function it_has_a_shortcut_for_multiple_arguments_token() { $token = $this->cetera(); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\AnyValuesToken'); } function it_has_a_shortcut_for_type_token() { $token = $this->type('integer'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\TypeToken'); } function it_has_a_shortcut_for_callback_token() { $token = $this->that('get_class'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\CallbackToken'); } function it_supports_customizing_tostring_representation_for_callback_token() { $token = $this->that('get_class', 'MyCustomTestCase'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\CallbackToken'); $token->__toString()->shouldReturn('MyCustomTestCase'); } function it_has_a_shortcut_for_object_state_token() { $token = $this->which('getName', 'everzet'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ObjectStateToken'); } function it_has_a_shortcut_for_logical_and_token() { $token = $this->allOf('integer', 5); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\LogicalAndToken'); } function it_has_a_shortcut_for_array_count_token() { $token = $this->size(5); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayCountToken'); } function it_has_a_shortcut_for_array_entry_token() { $token = $this->withEntry('key', 'value'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEntryToken'); } function it_has_a_shortcut_for_array_every_entry_token() { $token = $this->withEveryEntry('value'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEveryEntryToken'); } function it_has_a_shortcut_for_identical_value_token() { $token = $this->is('value'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\IdenticalValueToken'); } function it_has_a_shortcut_for_array_entry_token_matching_any_key() { $token = $this->containing('value'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEntryToken'); $token->getKey()->shouldHaveType('Prophecy\Argument\Token\AnyValueToken'); } function it_has_a_shortcut_for_array_entry_token_matching_any_value() { $token = $this->withKey('key'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ArrayEntryToken'); $token->getValue()->shouldHaveType('Prophecy\Argument\Token\AnyValueToken'); } function it_has_a_shortcut_for_logical_not_token() { $token = $this->not('kagux'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\LogicalNotToken'); } function it_has_a_shortcut_for_string_contains_token() { $token = $this->containingString('string'); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\StringContainsToken'); } function it_has_a_shortcut_for_approximate_token() { $token = $this->approximate(10); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\ApproximateValueToken'); } function it_has_a_shortcut_for_in_token() { $token = $this->in(array(1, 2, 3)); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\InArrayToken'); } function it_has_a_shortcut_for_not_in_token() { $token = $this->notIn(array(1, 2, 3)); $token->shouldBeAnInstanceOf('Prophecy\Argument\Token\NotInArrayToken'); } } ================================================ FILE: spec/Prophecy/Call/CallCenterSpec.php ================================================ scoreArguments(array(5, 2, 3))->willReturn(10); $objectProphecy->getMethodProphecies()->willReturn(array()); $this->makeCall($objectProphecy, 'setValues', array(5, 2, 3)); $calls = $this->findCalls('setValues', $wildcard); $calls->shouldHaveCount(1); $calls[0]->shouldBeAnInstanceOf('Prophecy\Call\Call'); $calls[0]->getMethodName()->shouldReturn('setValues'); $calls[0]->getArguments()->shouldReturn(array(5, 2, 3)); $calls[0]->getReturnValue()->shouldReturn(null); } function it_returns_null_for_any_call_through_makeCall_if_no_method_prophecies_added( $objectProphecy ) { $objectProphecy->getMethodProphecies()->willReturn(array()); $this->makeCall($objectProphecy, 'setValues', array(5, 2, 3))->shouldReturn(null); } function it_executes_promise_of_method_prophecy_that_matches_signature_passed_to_makeCall( $objectProphecy, MethodProphecy $method1, MethodProphecy $method2, MethodProphecy $method3, ArgumentsWildcard $arguments1, ArgumentsWildcard $arguments2, ArgumentsWildcard $arguments3, PromiseInterface $promise ) { $method1->hasReturnVoid()->willReturn(false); $method1->getMethodName()->willReturn('getName'); $method1->getArgumentsWildcard()->willReturn($arguments1); $arguments1->scoreArguments(array('world', 'everything'))->willReturn(false); $method2->hasReturnVoid()->willReturn(false); $method2->getMethodName()->willReturn('setTitle'); $method2->getArgumentsWildcard()->willReturn($arguments2); $arguments2->scoreArguments(array('world', 'everything'))->willReturn(false); $method3->hasReturnVoid()->willReturn(false); $method3->getMethodName()->willReturn('getName'); $method3->getArgumentsWildcard()->willReturn($arguments3); $method3->getPromise()->willReturn($promise); $arguments3->scoreArguments(array('world', 'everything'))->willReturn(200); $objectProphecy->getMethodProphecies()->willReturn(array( 'method1' => array($method1), 'method2' => array($method2, $method3), )); $objectProphecy->getMethodProphecies('getName')->willReturn(array($method1, $method3)); $objectProphecy->reveal()->willReturn(new \stdClass()); $promise->execute(array('world', 'everything'), $objectProphecy->getWrappedObject(), $method3)->willReturn(42); $this->makeCall($objectProphecy, 'getName', array('world', 'everything'))->shouldReturn(42); $calls = $this->findCalls('getName', $arguments3); $calls->shouldHaveCount(1); $calls[0]->getReturnValue()->shouldReturn(42); } function it_executes_promise_of_method_prophecy_that_matches_with_highest_score_to_makeCall( $objectProphecy, MethodProphecy $method1, MethodProphecy $method2, MethodProphecy $method3, ArgumentsWildcard $arguments1, ArgumentsWildcard $arguments2, ArgumentsWildcard $arguments3, PromiseInterface $promise ) { $method1->hasReturnVoid()->willReturn(false); $method1->getMethodName()->willReturn('getName'); $method1->getArgumentsWildcard()->willReturn($arguments1); $arguments1->scoreArguments(array('world', 'everything'))->willReturn(50); $method2->hasReturnVoid()->willReturn(false); $method2->getMethodName()->willReturn('getName'); $method2->getArgumentsWildcard()->willReturn($arguments2); $method2->getPromise()->willReturn($promise); $arguments2->scoreArguments(array('world', 'everything'))->willReturn(300); $method3->hasReturnVoid()->willReturn(false); $method3->getMethodName()->willReturn('getName'); $method3->getArgumentsWildcard()->willReturn($arguments3); $arguments3->scoreArguments(array('world', 'everything'))->willReturn(200); $objectProphecy->getMethodProphecies()->willReturn(array( 'method1' => array($method1), 'method2' => array($method2, $method3), )); $objectProphecy->getMethodProphecies('getName')->willReturn(array( $method1, $method2, $method3, )); $objectProphecy->reveal()->willReturn(new \stdClass()); $promise->execute(array('world', 'everything'), $objectProphecy->getWrappedObject(), $method2) ->willReturn('second'); $this->makeCall($objectProphecy, 'getName', array('world', 'everything')) ->shouldReturn('second'); } function it_returns_null_if_method_prophecy_that_matches_makeCall_arguments_has_no_promise( $objectProphecy, MethodProphecy $method, ArgumentsWildcard $arguments ) { $method->hasReturnVoid()->willReturn(false); $method->getMethodName()->willReturn('getName'); $method->getArgumentsWildcard()->willReturn($arguments); $method->getPromise()->willReturn(null); $arguments->scoreArguments(array('world', 'everything'))->willReturn(100); $objectProphecy->getMethodProphecies()->willReturn(array($method)); $objectProphecy->getMethodProphecies('getName')->willReturn(array($method)); $this->makeCall($objectProphecy, 'getName', array('world', 'everything')) ->shouldReturn(null); } function it_finds_recorded_calls_by_a_method_name_and_arguments_wildcard( $objectProphecy, ArgumentsWildcard $wildcard ) { $objectProphecy->getMethodProphecies()->willReturn(array()); $this->makeCall($objectProphecy, 'getName', array('world')); $this->makeCall($objectProphecy, 'getName', array('everything')); $this->makeCall($objectProphecy, 'setName', array(42)); $wildcard->scoreArguments(array('world'))->willReturn(false); $wildcard->scoreArguments(array('everything'))->willReturn(10); $calls = $this->findCalls('getName', $wildcard); $calls->shouldHaveCount(1); $calls[0]->getMethodName()->shouldReturn('getName'); $calls[0]->getArguments()->shouldReturn(array('everything')); } function it_records_the_error_when_stub_has_got_unexpected_method_calls( $objectProphecy, MethodProphecy $method, ArgumentsWildcard $arguments ) { $method->getMethodName()->willReturn('getName'); $method->getArgumentsWildcard()->willReturn($arguments); $arguments->getTokens()->willReturn(array()); $objectProphecy->getMethodProphecies()->willReturn(array('getName' => array($method))); $objectProphecy->getMethodProphecies('getName')->willReturn(array($method)); $objectProphecy->getMethodProphecies('method1')->willReturn(array()); $objectProphecy->reveal()->willReturn(new \stdClass()); $this->shouldNotThrow('Prophecy\Exception\Call\UnexpectedCallException') ->duringMakeCall($objectProphecy, 'method1', array()); $this->shouldThrow('Prophecy\Exception\Call\UnexpectedCallException')->duringCheckUnexpectedCalls(); } } ================================================ FILE: spec/Prophecy/Call/CallSpec.php ================================================ beConstructedWith('setValues', array(5, 2), 42, $exception, 'some_file.php', 23); } function it_exposes_method_name_through_getter() { $this->getMethodName()->shouldReturn('setValues'); } function it_exposes_arguments_through_getter() { $this->getArguments()->shouldReturn(array(5, 2)); } function it_exposes_return_value_through_getter() { $this->getReturnValue()->shouldReturn(42); } function it_exposes_exception_through_getter($exception) { $this->getException()->shouldReturn($exception); } function it_exposes_file_and_line_through_getter() { $this->getFile()->shouldReturn('some_file.php'); $this->getLine()->shouldReturn(23); } function it_returns_shortpath_to_callPlace() { $this->getCallPlace()->shouldReturn('some_file.php:23'); } function it_returns_unknown_as_callPlace_if_no_file_or_line_provided() { $this->beConstructedWith('setValues', array(), 0, null, null, null); $this->getCallPlace()->shouldReturn('unknown'); } function it_adds_wildcard_match_score(ArgumentsWildcard $wildcard) { $this->addScore($wildcard, 99)->shouldReturn($this); $this->getScore($wildcard)->shouldReturn(99); } function it_caches_and_returns_wildcard_match_score(ArgumentsWildcard $wildcard) { $wildcard->scoreArguments(array(5, 2))->willReturn(13)->shouldBeCalledTimes(1); $this->getScore($wildcard)->shouldReturn(13); $this->getScore($wildcard)->shouldReturn(13); } } ================================================ FILE: spec/Prophecy/Comparator/ClosureComparatorSpec.php ================================================ shouldHaveType('SebastianBergmann\Comparator\Comparator'); } function it_accepts_only_closures() { $this->accepts(123, 321)->shouldReturn(false); $this->accepts('string', 'string')->shouldReturn(false); $this->accepts(false, true)->shouldReturn(false); $this->accepts(true, false)->shouldReturn(false); $this->accepts((object) array(), (object) array())->shouldReturn(false); $this->accepts(function () {}, (object) array())->shouldReturn(false); $this->accepts(function () {}, (object) array())->shouldReturn(false); $this->accepts(function () {}, function () {})->shouldReturn(true); } function it_asserts_that_different_closures_are_different() { $this->shouldThrow()->duringAssertEquals(function () {}, function () {}); } function it_asserts_that_closures_are_equal_if_its_the_same_closure() { $closure = function () {}; $this->shouldNotThrow()->duringAssertEquals($closure, $closure); } } ================================================ FILE: spec/Prophecy/Comparator/FactorySpec.php ================================================ isFinal()) { throw new SkippingException(sprintf('The deprecated "%s" class cannot be used with sebastian/comparator 5+.', Factory::class)); } } function it_extends_Sebastian_Comparator_Factory() { $this->shouldHaveType('SebastianBergmann\Comparator\Factory'); } function it_should_have_ClosureComparator_registered() { $comparator = $this->getInstance()->getComparatorFor(function () {}, function () {}); $comparator->shouldHaveType('Prophecy\Comparator\ClosureComparator'); } } ================================================ FILE: spec/Prophecy/Comparator/ProphecyComparatorSpec.php ================================================ shouldHaveType(Comparator::class); } function it_accepts_only_prophecy_objects() { $this->accepts(123, 321)->shouldReturn(false); $this->accepts('string', 'string')->shouldReturn(false); $this->accepts(false, true)->shouldReturn(false); $this->accepts(true, false)->shouldReturn(false); $this->accepts((object) array(), (object) array())->shouldReturn(false); $this->accepts(function () {}, (object) array())->shouldReturn(false); $this->accepts(function () {}, function () {})->shouldReturn(false); $prophet = new Prophet(); $prophecy = $prophet->prophesize('Prophecy\Prophecy\ObjectProphecy'); $this->accepts($prophecy, $prophecy)->shouldReturn(true); } function it_asserts_that_an_object_is_equal_to_its_revealed_prophecy() { $prophet = new Prophet(); $prophecy = $prophet->prophesize('Prophecy\Prophecy\ObjectProphecy'); $prophecy->__call('reveal', array())->willReturn(new \stdClass()); $factory = new Factory(); $factory->register($this->getWrappedObject()); $this->shouldNotThrow()->duringAssertEquals($prophecy->reveal(), $prophecy); } } ================================================ FILE: spec/Prophecy/Doubler/CachedDoublerSpec.php ================================================ beConstructedWith($mirror, $creator, $namer); $this->resetCache(); } /** * @todo implement * T - T * T - F * F - T * F - F * F T F * F T T */ // T - - function it_creates_only_one_class_definition_for_the_same_class_without_interfaces_and_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, \ReflectionClass $class, ClassNode $node ) { $mirror->reflect($class, array())->willReturn($node); $namer->name($class, array())->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $creator->create('SplStack', $node)->shouldBeCalledTimes(1); $this->double($class, array()); $this->double($class, array()); } // F - - function it_creates_two_class_definitions_for_different_classes_without_interfaces_and_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, \ReflectionClass $class1, \ReflectionClass $class2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class1, array())->willReturn($node1); $mirror->reflect($class2, array())->willReturn($node2); $namer->name($class1, array())->willReturn('SplStack'); $namer->name($class2, array())->willReturn('spec\Prophecy\Doubler\aClass'); $class1->getName()->willReturn('stdClass'); $class2->getName()->willReturn('aClass'); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('spec\Prophecy\Doubler\aClass', $node2)->shouldBeCalledTimes(1); $this->double($class1, array()); $this->double($class2, array()); } // T F T function it_creates_two_different_class_definitions_for_the_same_class_with_different_interfaces_and_same_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class, array($interface1))->willReturn($node1); $mirror->reflect($class, array($interface2))->willReturn($node2); $alt1->supports($node1)->willReturn(true); $alt1->supports($node2)->willReturn(true); $alt2->supports($node1)->willReturn(false); $alt2->supports($node2)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class, array($interface1))->willReturn('SplStack'); $namer->name($class, array($interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node1)->shouldBeCalled(); $alt1->apply($node2)->shouldBeCalled(); $alt2->apply($node1)->shouldNotBeCalled(); $alt2->apply($node2)->shouldNotBeCalled(); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('SplStack', $node2)->shouldBeCalledTimes(1); $this->registerClassPatch($alt1); $this->registerClassPatch($alt2); $this->double($class, array($interface1)); $this->double($class, array($interface2)); } // F F T function it_creates_two_different_class_definitions_for_different_classes_with_different_interfaces_and_same_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class1, \ReflectionClass $class2, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class1, array($interface1))->willReturn($node1); $mirror->reflect($class2, array($interface2))->willReturn($node2); $alt1->supports($node1)->willReturn(true); $alt1->supports($node2)->willReturn(true); $alt2->supports($node1)->willReturn(false); $alt2->supports($node2)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class1, array($interface1))->willReturn('SplStack'); $namer->name($class2, array($interface2))->willReturn('spec\Prophecy\Doubler\aClass'); $class1->getName()->willReturn('stdClass'); $class2->getName()->willReturn('aClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node1)->shouldBeCalled(); $alt1->apply($node2)->shouldBeCalled(); $alt2->apply($node1)->shouldNotBeCalled(); $alt2->apply($node2)->shouldNotBeCalled(); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('spec\Prophecy\Doubler\aClass', $node2)->shouldBeCalledTimes(1); $this->registerClassPatch($alt1); $this->registerClassPatch($alt2); $this->double($class1, array($interface1)); $this->double($class2, array($interface2)); } // T T - function it_creates_only_one_class_definition_for_the_same_class_with_same_interfaces_and_without_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node ) { $mirror->reflect($class, array($interface1, $interface2))->willReturn($node); $namer->name($class, array($interface1, $interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $creator->create('SplStack', $node)->shouldBeCalledTimes(1); $this->double($class, array($interface1, $interface2)); $this->double($class, array($interface1, $interface2)); } // F T - function it_creates_only_one_class_definition_for_different_classes_with_same_interfaces_and_without_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, \ReflectionClass $class1, \ReflectionClass $class2, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class1, array($interface1, $interface2))->willReturn($node1); $mirror->reflect($class2, array($interface1, $interface2))->willReturn($node2); $namer->name($class1, array($interface1, $interface2))->willReturn('SplStack'); $namer->name($class2, array($interface1, $interface2))->willReturn('spec\Prophecy\Doubler\aClass'); $class1->getName()->willReturn('stdClass'); $class2->getName()->willReturn('aClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('spec\Prophecy\Doubler\aClass', $node2)->shouldBeCalledTimes(1); $this->double($class1, array($interface1, $interface2)); $this->double($class2, array($interface1, $interface2)); } // T F - function it_creates_two_different_class_definitions_for_the_same_class_with_different_interfaces_and_without_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class, array($interface1))->willReturn($node1); $mirror->reflect($class, array($interface2))->willReturn($node2); $namer->name($class, array($interface1))->willReturn('SplStack'); $namer->name($class, array($interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('SplStack', $node2)->shouldBeCalledTimes(1); $this->double($class, array($interface1)); $this->double($class, array($interface2)); } // F F - function it_creates_two_different_class_definitions_for_different_classes_with_different_interfaces_and_without_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, \ReflectionClass $class1, \ReflectionClass $class2, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class1, array($interface1))->willReturn($node1); $mirror->reflect($class2, array($interface2))->willReturn($node2); $namer->name($class1, array($interface1))->willReturn('SplStack'); $namer->name($class2, array($interface2))->willReturn('spec\Prophecy\Doubler\aClass'); $class1->getName()->willReturn('stdClass'); $class2->getName()->willReturn('aClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('spec\Prophecy\Doubler\aClass', $node2)->shouldBeCalledTimes(1); $this->double($class1, array($interface1)); $this->double($class2, array($interface2)); } // T T T function it_creates_only_one_class_definition_for_the_same_class_with_same_interfaces_and_same_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node ) { $mirror->reflect($class, array($interface1, $interface2))->willReturn($node); $alt1->supports($node)->willReturn(true); $alt2->supports($node)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class, array($interface1, $interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node)->shouldBeCalled(); $alt2->apply($node)->shouldNotBeCalled(); $creator->create('SplStack', $node)->shouldBeCalledTimes(1); $this->registerClassPatch($alt1); $this->registerClassPatch($alt2); $this->double($class, array($interface1, $interface2)); $this->double($class, array($interface1, $interface2)); } // F F F function it_creates_two_class_definitions_for_different_classes_with_different_interfaces_and_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class1, \ReflectionClass $class2, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class1, array($interface1))->willReturn($node1); $mirror->reflect($class2, array($interface2))->willReturn($node2); $alt1->supports($node1)->willReturn(true); $alt1->supports($node2)->willReturn(true); $alt2->supports($node2)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class1, array($interface1))->willReturn('SplStack'); $namer->name($class2, array($interface2))->willReturn('spec\Prophecy\Doubler\aClass'); $class1->getName()->willReturn('stdClass'); $class2->getName()->willReturn('aClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node1)->shouldBeCalled(); $alt1->apply($node2)->shouldBeCalled(); $alt2->apply($node2)->shouldNotBeCalled(); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('spec\Prophecy\Doubler\aClass', $node2)->shouldBeCalledTimes(1); $this->registerClassPatch($alt1); $this->double($class1, array($interface1)); $this->registerClassPatch($alt2); $this->double($class2, array($interface2)); } // T F F function it_creates_two_class_definitions_for_the_same_class_with_different_interfaces_and_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class, array($interface1))->willReturn($node1); $mirror->reflect($class, array($interface2))->willReturn($node2); $alt1->supports($node1)->willReturn(true); $alt1->supports($node2)->willReturn(true); $alt2->supports($node2)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class, array($interface1))->willReturn('SplStack'); $namer->name($class, array($interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node1)->shouldBeCalled(); $alt1->apply($node2)->shouldBeCalled(); $alt2->apply($node2)->shouldNotBeCalled(); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $creator->create('SplStack', $node2)->shouldBeCalledTimes(1); $this->registerClassPatch($alt1); $this->double($class, array($interface1)); $this->registerClassPatch($alt2); $this->double($class, array($interface2)); } // T T F function it_creates_two_different_class_definitions_for_the_same_class_with_same_interfaces_and_different_patches( ClassMirror $mirror, ClassCreator $creator, NameGenerator $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node1, ClassNode $node2 ) { $mirror->reflect($class, array($interface1, $interface2))->willReturn($node1, $node2); $alt1->supports($node1)->willReturn(true); $alt1->supports($node2)->willReturn(true); $alt2->supports($node2)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class, array($interface1, $interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node1)->shouldBeCalled(); $creator->create('SplStack', $node1)->shouldBeCalledTimes(1); $this->registerClassPatch($alt1); $this->double($class, array($interface1, $interface2)); $alt1->apply($node2)->shouldBeCalled(); $alt2->apply($node2)->shouldNotBeCalled(); $creator->create('SplStack', $node2)->shouldBeCalledTimes(1); $this->registerClassPatch($alt2); $this->double($class, array($interface1, $interface2)); } } class aClass {} ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/DisableConstructorPatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function its_priority_is_100() { $this->getPriority()->shouldReturn(100); } function it_supports_anything(ClassNode $node) { $this->supports($node)->shouldReturn(true); } function it_makes_all_constructor_arguments_optional( ClassNode $class, MethodNode $method, ArgumentNode $arg1, ArgumentNode $arg2, ArgumentNode $arg3 ) { $arg1->getTypeNode()->willReturn(new ArgumentTypeNode(new UnionType([ new BuiltinType('string'), new BuiltinType('null'), ]))); $arg2->getTypeNode()->willReturn(new ArgumentTypeNode(new BuiltinType('mixed'))); $arg3->getTypeNode()->willReturn(new ArgumentTypeNode(new BuiltinType('string'))); $class->isExtendable('__construct')->willReturn(true); $class->hasMethod('__construct')->willReturn(true); $class->getMethod('__construct')->willReturn($method); $method->getArguments()->willReturn(array($arg1, $arg2, $arg3)); $arg1->setDefault(null)->shouldBeCalled(); $arg2->setDefault(null)->shouldBeCalled(); $arg3->setDefault(null)->shouldBeCalled(); $arg3->setTypeNode(new ArgumentTypeNode(new UnionType([new BuiltinType('null'), new BuiltinType('string')])))->shouldBeCalled(); $method->setCode(Argument::type('string'))->shouldBeCalled(); $this->apply($class); } function it_creates_new_constructor_if_object_has_none(ClassNode $class) { $class->isExtendable('__construct')->willReturn(true); $class->hasMethod('__construct')->willReturn(false); $class->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode')) ->shouldBeCalled(); $this->apply($class); } function it_ignores_final_constructor(ClassNode $class) { $class->isExtendable('__construct')->willReturn(false); $this->apply($class); } } ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/KeywordPatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function its_priority_is_49() { $this->getPriority()->shouldReturn(49); } function it_will_remove_halt_compiler_method( ClassNode $node, MethodNode $method1, MethodNode $method2, MethodNode $method3 ) { $node->removeMethod('__halt_compiler')->shouldBeCalled(); $method1->getName()->willReturn('__halt_compiler'); $method2->getName()->willReturn('echo'); $method3->getName()->willReturn('notKeyword'); $node->getMethods()->willReturn(array( '__halt_compiler' => $method1, 'echo' => $method2, 'notKeyword' => $method3, )); $this->apply($node); } } ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/MagicCallPatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function it_supports_anything(ClassNode $node) { $this->supports($node)->shouldReturn(true); } function it_discovers_api_using_phpdoc(ClassNode $node) { $node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApi'); $node->getInterfaces()->willReturn(array()); $node->addMethod(new MethodNode('undefinedMethod'))->shouldBeCalled(); $this->apply($node); } function it_ignores_existing_methods(ClassNode $node) { $node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiExtended'); $node->getInterfaces()->willReturn(array()); $node->addMethod(new MethodNode('undefinedMethod'))->shouldBeCalled(); $node->addMethod(new MethodNode('definedMethod'))->shouldNotBeCalled(); $this->apply($node); } function it_ignores_empty_methods_from_phpdoc(ClassNode $node) { $node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiInvalidMethodDefinition'); $node->getInterfaces()->willReturn(array()); $node->addMethod(new MethodNode(''))->shouldNotBeCalled(); $this->apply($node); } function it_discovers_api_using_phpdoc_from_implemented_interfaces(ClassNode $node) { $node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiImplemented'); $node->getInterfaces()->willReturn(array()); $node->addMethod(new MethodNode('implementedMethod'))->shouldBeCalled(); $this->apply($node); } function it_discovers_api_using_phpdoc_from_own_interfaces(ClassNode $node) { $node->getParentClass()->willReturn('stdClass'); $node->getInterfaces()->willReturn(array('spec\Prophecy\Doubler\ClassPatch\MagicalApiImplemented')); $node->addMethod(new MethodNode('implementedMethod'))->shouldBeCalled(); $this->apply($node); } function it_discovers_api_using_phpdoc_from_extended_parent_interfaces(ClassNode $node) { $node->getParentClass()->willReturn('spec\Prophecy\Doubler\ClassPatch\MagicalApiImplementedExtended'); $node->getInterfaces()->willReturn(array()); $node->addMethod(new MethodNode('implementedMethod'))->shouldBeCalled(); $this->apply($node); } function it_has_50_priority() { $this->getPriority()->shouldReturn(50); } } /** * @method void undefinedMethod() */ class MagicalApi { /** * @return void */ public function definedMethod() {} } /** * @method */ class MagicalApiInvalidMethodDefinition {} /** * @method void definedMethod() */ class MagicalApiExtended extends MagicalApi {} /** */ class MagicalApiImplemented implements MagicalApiInterface {} /** */ class MagicalApiImplementedExtended extends MagicalApiImplemented {} /** * @method void implementedMethod() */ interface MagicalApiInterface {} ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/ProphecySubjectPatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function it_has_priority_of_0() { $this->getPriority()->shouldReturn(0); } function it_supports_any_class(ClassNode $node) { $this->supports($node)->shouldReturn(true); } function it_forces_class_to_implement_ProphecySubjectInterface(ClassNode $node) { $node->addInterface('Prophecy\Prophecy\ProphecySubjectInterface')->shouldBeCalled(); $node->addProperty('objectProphecyClosure', 'private')->willReturn(null); $node->getMethods()->willReturn(array()); $node->hasMethod(Argument::any())->willReturn(false); $node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'), true)->willReturn(null); $node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'), true)->willReturn(null); $this->apply($node); } function it_forces_all_class_methods_except_constructor_to_proxy_calls_into_prophecy_makeCall( ClassNode $node, MethodNode $constructor, MethodNode $method1, MethodNode $method2, MethodNode $method3, MethodNode $method4 ) { $node->addInterface('Prophecy\Prophecy\ProphecySubjectInterface')->willReturn(null); $node->addProperty('objectProphecyClosure', 'private')->willReturn(null); $node->hasMethod(Argument::any())->willReturn(false); $node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'), true)->willReturn(null); $node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'), true)->willReturn(null); $constructor->getName()->willReturn('__construct'); $method1->getName()->willReturn('method1'); $method2->getName()->willReturn('method2'); $method3->getName()->willReturn('method3'); $method4->getName()->willReturn('method4'); $method1->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('int'))); $method2->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('int'))); $method3->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('void'))); $method4->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('never'))); $node->getMethods()->willReturn(array( 'method1' => $method1, 'method2' => $method2, 'method3' => $method3, 'method4' => $method4, )); $constructor->setCode(Argument::any())->shouldNotBeCalled(); $method1->setCode('return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());') ->shouldBeCalled(); $method2->setCode('return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());') ->shouldBeCalled(); $method3->setCode('$this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());') ->shouldBeCalled(); $method4->setCode('$this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());') ->shouldBeCalled(); $this->apply($node); } } ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/ReflectionClassNewInstancePatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function its_priority_is_50() { $this->getPriority()->shouldReturn(50); } function it_supports_ReflectionClass_only(ClassNode $reflectionClassNode, ClassNode $anotherClassNode) { $reflectionClassNode->getParentClass()->willReturn('ReflectionClass'); $anotherClassNode->getParentClass()->willReturn('stdClass'); $this->supports($reflectionClassNode)->shouldReturn(true); $this->supports($anotherClassNode)->shouldReturn(false); } function it_makes_all_newInstance_arguments_optional( ClassNode $class, MethodNode $method, ArgumentNode $arg1 ) { $class->getMethod('newInstance')->willReturn($method); $method->getArguments()->willReturn(array($arg1)); $arg1->setDefault(null)->shouldBeCalled(); $this->apply($class); } } ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/SplFileInfoPatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function its_priority_is_50() { $this->getPriority()->shouldReturn(50); } function it_does_not_support_nodes_without_parent_class(ClassNode $node) { $node->getParentClass()->willReturn('stdClass'); $this->supports($node)->shouldReturn(false); } function it_supports_nodes_with_SplFileInfo_as_parent_class(ClassNode $node) { $node->getParentClass()->willReturn('SplFileInfo'); $this->supports($node)->shouldReturn(true); } function it_supports_nodes_with_derivative_of_SplFileInfo_as_parent_class(ClassNode $node) { $node->getParentClass()->willReturn('SplFileInfo'); $this->supports($node)->shouldReturn(true); } function it_adds_a_method_to_node_if_not_exists(ClassNode $node) { $node->hasMethod('__construct')->willReturn(false); $node->addMethod(Argument::any())->shouldBeCalled(); $node->getParentClass()->shouldBeCalled(); $this->apply($node); } function it_updates_existing_method_if_found(ClassNode $node, MethodNode $method) { $node->hasMethod('__construct')->willReturn(true); $node->getMethod('__construct')->willReturn($method); $node->getParentClass()->shouldBeCalled(); $method->useParentCode()->shouldBeCalled(); $this->apply($node); } function it_should_not_supply_a_file_for_a_directory_iterator(ClassNode $node, MethodNode $method) { $node->hasMethod('__construct')->willReturn(true); $node->getMethod('__construct')->willReturn($method); $node->getParentClass()->willReturn('DirectoryIterator'); $method->setCode(Argument::that(function ($value) { return strpos($value, '.php') === false; }))->shouldBeCalled(); $this->apply($node); } function it_should_supply_a_file_for_a_spl_file_object(ClassNode $node, MethodNode $method) { $node->hasMethod('__construct')->willReturn(true); $node->getMethod('__construct')->willReturn($method); $node->getParentClass()->willReturn('SplFileObject'); $method->setCode(Argument::that(function ($value) { return strpos($value, '.php') !== false; }))->shouldBeCalled(); $this->apply($node); } function it_should_supply_a_file_for_a_symfony_spl_file_info(ClassNode $node, MethodNode $method) { $node->hasMethod('__construct')->willReturn(true); $node->getMethod('__construct')->willReturn($method); $node->getParentClass()->willReturn('Symfony\\Component\\Finder\\SplFileInfo'); $method->setCode(Argument::that(function ($value) { return strpos($value, '.php') !== false; }))->shouldBeCalled(); $this->apply($node); } } ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/ThrowablePatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function it_does_not_support_class_that_does_not_implement_throwable(ClassNode $node) { $node->getInterfaces()->willReturn(array()); $node->getParentClass()->willReturn('stdClass'); $this->supports($node)->shouldReturn(false); } function it_supports_class_that_extends_not_throwable_class(ClassNode $node) { $node->getInterfaces()->willReturn(array('Throwable')); $node->getParentClass()->willReturn('stdClass'); $this->supports($node)->shouldReturn(true); } function it_does_not_support_class_that_already_extends_a_throwable_class(ClassNode $node) { $node->getInterfaces()->willReturn(array('Throwable')); $node->getParentClass()->willReturn('InvalidArgumentException'); $this->supports($node)->shouldReturn(false); } function it_supports_class_implementing_interface_that_extends_throwable(ClassNode $node) { $node->getInterfaces()->willReturn(array('Fixtures\Prophecy\ThrowableInterface')); $node->getParentClass()->willReturn('stdClass'); $this->supports($node)->shouldReturn(true); } function it_sets_the_parent_class_to_exception(ClassNode $node) { $node->getParentClass()->willReturn('stdClass'); $node->setParentClass('Exception')->shouldBeCalled(); $node->removeMethod('getMessage')->shouldBeCalled(); $node->removeMethod('getCode')->shouldBeCalled(); $node->removeMethod('getFile')->shouldBeCalled(); $node->removeMethod('getLine')->shouldBeCalled(); $node->removeMethod('getTrace')->shouldBeCalled(); $node->removeMethod('getPrevious')->shouldBeCalled(); $node->removeMethod('getNext')->shouldBeCalled(); $node->removeMethod('getTraceAsString')->shouldBeCalled(); $this->apply($node); } function it_throws_error_when_trying_to_double_concrete_class_and_throwable_interface(ClassNode $node) { $node->getParentClass()->willReturn('ArrayObject'); $this->shouldThrow('Prophecy\Exception\Doubler\ClassCreatorException')->duringApply($node); } } ================================================ FILE: spec/Prophecy/Doubler/ClassPatch/TraversablePatchSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Doubler\ClassPatch\ClassPatchInterface'); } function it_supports_class_that_implements_only_Traversable(ClassNode $node) { $node->getInterfaces()->willReturn(array('Traversable')); $this->supports($node)->shouldReturn(true); } function it_does_not_support_class_that_implements_Iterator(ClassNode $node) { $node->getInterfaces()->willReturn(array('Traversable', 'Iterator')); $this->supports($node)->shouldReturn(false); } function it_does_not_support_class_that_implements_IteratorAggregate(ClassNode $node) { $node->getInterfaces()->willReturn(array('Traversable', 'IteratorAggregate')); $this->supports($node)->shouldReturn(false); } function it_has_100_priority() { $this->getPriority()->shouldReturn(100); } function it_forces_node_to_implement_IteratorAggregate(ClassNode $node) { $node->addInterface('Iterator')->shouldBeCalled(); $node->addMethod(Argument::type('Prophecy\Doubler\Generator\Node\MethodNode'))->willReturn(null); $this->apply($node); } function it_adds_methods_to_implement_iterator(ClassNode $node) { $node->addInterface('Iterator')->shouldBeCalled(); $methodReturnTypes = [ 'current' => 'mixed', 'key' => 'mixed', 'next' => 'void', 'rewind' => 'void', 'valid' => 'bool', ]; foreach ($methodReturnTypes as $methodName => $returnType) { $node->addMethod(Argument::that(static function ($value) use ($methodName, $returnType) { return $value instanceof MethodNode && $value->getName() === $methodName && (\PHP_VERSION_ID < 80100 || $value->getReturnTypeNode()->getTypes() === [$returnType]); }))->shouldBeCalled(); } $this->apply($node); } } ================================================ FILE: spec/Prophecy/Doubler/DoublerSpec.php ================================================ beConstructedWith($mirror, $creator, $namer); } function it_does_not_have_patches_by_default() { $this->getClassPatches()->shouldHaveCount(0); } function its_registerClassPatch_adds_a_patch_to_the_doubler(ClassPatchInterface $patch) { $this->registerClassPatch($patch); $this->getClassPatches()->shouldReturn(array($patch)); } function its_getClassPatches_sorts_patches_by_priority( ClassPatchInterface $alt1, ClassPatchInterface $alt2, ClassPatchInterface $alt3, ClassPatchInterface $alt4 ) { $alt1->getPriority()->willReturn(2); $alt2->getPriority()->willReturn(50); $alt3->getPriority()->willReturn(10); $alt4->getPriority()->willReturn(0); $this->registerClassPatch($alt1); $this->registerClassPatch($alt2); $this->registerClassPatch($alt3); $this->registerClassPatch($alt4); $this->getClassPatches()->shouldReturn(array($alt2, $alt3, $alt1, $alt4)); } function its_double_mirrors_alterates_and_instantiates_provided_class( $mirror, $creator, $namer, ClassPatchInterface $alt1, ClassPatchInterface $alt2, \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2, ClassNode $node ) { $mirror->reflect($class, array($interface1, $interface2))->willReturn($node); $alt1->supports($node)->willReturn(true); $alt2->supports($node)->willReturn(false); $alt1->getPriority()->willReturn(1); $alt2->getPriority()->willReturn(2); $namer->name($class, array($interface1, $interface2))->willReturn('SplStack'); $class->getName()->willReturn('stdClass'); $interface1->getName()->willReturn('ArrayAccess'); $interface2->getName()->willReturn('Iterator'); $alt1->apply($node)->shouldBeCalled(); $alt2->apply($node)->shouldNotBeCalled(); $creator->create('SplStack', $node)->shouldBeCalled(); $this->registerClassPatch($alt1); $this->registerClassPatch($alt2); $this->double($class, array($interface1, $interface2)) ->shouldReturnAnInstanceOf('SplStack'); } function it_double_instantiates_a_class_with_constructor_argument( $mirror, \ReflectionClass $class, ClassNode $node, $namer ) { $class->getName()->willReturn('ReflectionClass'); $mirror->reflect($class, array())->willReturn($node); $namer->name($class, array())->willReturn('ReflectionClass'); $double = $this->double($class, array(), array('stdClass')); $double->shouldBeAnInstanceOf('ReflectionClass'); $double->getName()->shouldReturn('stdClass'); } function it_can_instantiate_class_with_final_constructor( $mirror, \ReflectionClass $class, ClassNode $node, $namer ) { $class->getName()->willReturn('spec\Prophecy\Doubler\WithFinalConstructor'); $mirror->reflect($class, array())->willReturn($node); $namer->name($class, array())->willReturn('spec\Prophecy\Doubler\WithFinalConstructor'); $double = $this->double($class, array()); $double->shouldBeAnInstanceOf('spec\Prophecy\Doubler\WithFinalConstructor'); } } class WithFinalConstructor { final public function __construct() {} } ================================================ FILE: spec/Prophecy/Doubler/Generator/ClassCodeGeneratorSpec.php ================================================ getParentClass()->willReturn('RuntimeException'); $class->getInterfaces()->willReturn(array( 'Prophecy\Doubler\Generator\MirroredInterface', 'ArrayAccess', 'ArrayIterator', )); $class->getProperties()->willReturn(array('name' => 'public', 'email' => 'private')); $class->getMethods()->willReturn(array($method1, $method2, $method3, $method4, $method5)); $class->isReadOnly()->willReturn(false); $method1->getName()->willReturn('getName'); $method1->getVisibility()->willReturn('public'); $method1->returnsReference()->willReturn(false); $method1->isStatic()->willReturn(true); $method1->getArguments()->willReturn(array($argument11, $argument12, $argument13)); $method1->getReturnTypeNode()->willReturn(new ReturnTypeNode(new UnionType([ new BuiltinType('string'), new BuiltinType('null'), ]))); $method1->getCode()->willReturn('return $this->name;'); $method2->getName()->willReturn('getEmail'); $method2->getVisibility()->willReturn('protected'); $method2->returnsReference()->willReturn(false); $method2->isStatic()->willReturn(false); $method2->getArguments()->willReturn(array($argument21)); $method2->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method2->getCode()->willReturn('return $this->email;'); $method3->getName()->willReturn('getRefValue'); $method3->getVisibility()->willReturn('public'); $method3->returnsReference()->willReturn(true); $method3->isStatic()->willReturn(false); $method3->getArguments()->willReturn(array($argument31)); $method3->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('string'))); $method3->getCode()->willReturn('return $this->refValue;'); $method4->getName()->willReturn('doSomething'); $method4->getVisibility()->willReturn('public'); $method4->returnsReference()->willReturn(false); $method4->isStatic()->willReturn(false); $method4->getArguments()->willReturn(array()); $method4->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('void'))); $method4->getCode()->willReturn('return;'); $method5->getName()->willReturn('returnObject'); $method5->getVisibility()->willReturn('public'); $method5->returnsReference()->willReturn(false); $method5->isStatic()->willReturn(false); $method5->getArguments()->willReturn(array()); $method5->getReturnTypeNode()->willReturn(new ReturnTypeNode(new BuiltinType('object'))); $method5->getCode()->willReturn('return;'); $argument11->getName()->willReturn('fullname'); $argument11->isOptional()->willReturn(false); $argument11->isPassedByReference()->willReturn(false); $argument11->isVariadic()->willReturn(false); $argument11->getTypeNode()->willReturn(new ArgumentTypeNode(new BuiltinType('array'))); $argument12->getName()->willReturn('class'); $argument12->isOptional()->willReturn(false); $argument12->isPassedByReference()->willReturn(false); $argument12->isVariadic()->willReturn(false); $argument12->getTypeNode()->willReturn(new ArgumentTypeNode(new ObjectType('ReflectionClass'))); $argument13->getName()->willReturn('instance'); $argument13->isOptional()->willReturn(false); $argument13->isPassedByReference()->willReturn(false); $argument13->isVariadic()->willReturn(false); $argument13->getTypeNode()->willReturn(new ArgumentTypeNode(new BuiltinType('object'))); $argument21->getName()->willReturn('default'); $argument21->isOptional()->willReturn(true); $argument21->getDefault()->willReturn('ever.zet@gmail.com'); $argument21->isPassedByReference()->willReturn(false); $argument21->isVariadic()->willReturn(false); $argument21->getTypeNode()->willReturn(new ArgumentTypeNode(new UnionType([ new BuiltinType('string'), new BuiltinType('null'), ]))); $argument31->getName()->willReturn('refValue'); $argument31->isOptional()->willReturn(false); $argument31->getDefault()->willReturn(); $argument31->isPassedByReference()->willReturn(false); $argument31->isVariadic()->willReturn(false); $argument31->getTypeNode()->willReturn(new ArgumentTypeNode()); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \RuntimeException implements \Prophecy\Doubler\Generator\MirroredInterface, \ArrayAccess, \ArrayIterator { public $name; private $email; public static function getName(array $fullname, \ReflectionClass $class, object $instance): string|null { return $this->name; } protected function getEmail(string|null $default = 'ever.zet@gmail.com') { return $this->email; } public function &getRefValue( $refValue): string { return $this->refValue; } public function doSomething(): void { return; } public function returnObject(): object { return; } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_proper_php_code_for_variadics( ClassNode $class, MethodNode $method1, MethodNode $method2, MethodNode $method3, MethodNode $method4, ArgumentNode $argument1, ArgumentNode $argument2, ArgumentNode $argument3, ArgumentNode $argument4 ) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface')); $class->getProperties()->willReturn(array()); $class->getMethods()->willReturn(array( $method1, $method2, $method3, $method4, )); $class->isReadOnly()->willReturn(false); $method1->getName()->willReturn('variadic'); $method1->getVisibility()->willReturn('public'); $method1->returnsReference()->willReturn(false); $method1->isStatic()->willReturn(false); $method1->getArguments()->willReturn(array($argument1)); $method1->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method1->getCode()->willReturn(''); $method2->getName()->willReturn('variadicByRef'); $method2->getVisibility()->willReturn('public'); $method2->returnsReference()->willReturn(false); $method2->isStatic()->willReturn(false); $method2->getArguments()->willReturn(array($argument2)); $method2->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method2->getCode()->willReturn(''); $method3->getName()->willReturn('variadicWithType'); $method3->getVisibility()->willReturn('public'); $method3->returnsReference()->willReturn(false); $method3->isStatic()->willReturn(false); $method3->getArguments()->willReturn(array($argument3)); $method3->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method3->getCode()->willReturn(''); $method4->getName()->willReturn('variadicWithTypeByRef'); $method4->getVisibility()->willReturn('public'); $method4->returnsReference()->willReturn(false); $method4->isStatic()->willReturn(false); $method4->getArguments()->willReturn(array($argument4)); $method4->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method4->getCode()->willReturn(''); $argument1->getName()->willReturn('args'); $argument1->isOptional()->willReturn(false); $argument1->isPassedByReference()->willReturn(false); $argument1->isVariadic()->willReturn(true); $argument1->getTypeNode()->willReturn(new ArgumentTypeNode()); $argument2->getName()->willReturn('args'); $argument2->isOptional()->willReturn(false); $argument2->isPassedByReference()->willReturn(true); $argument2->isVariadic()->willReturn(true); $argument2->getTypeNode()->willReturn(new ArgumentTypeNode()); $argument3->getName()->willReturn('args'); $argument3->isOptional()->willReturn(false); $argument3->isPassedByReference()->willReturn(false); $argument3->isVariadic()->willReturn(true); $argument3->getTypeNode()->willReturn(new ArgumentTypeNode(new ObjectType('ReflectionClass'))); $argument4->getName()->willReturn('args'); $argument4->isOptional()->willReturn(false); $argument4->isPassedByReference()->willReturn(true); $argument4->isVariadic()->willReturn(true); $argument4->getTypeNode()->willReturn(new ArgumentTypeNode(new ObjectType('ReflectionClass'))); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \stdClass implements \Prophecy\Doubler\Generator\MirroredInterface { public function variadic( ...$args) { } public function variadicByRef( &...$args) { } public function variadicWithType(\ReflectionClass ...$args) { } public function variadicWithTypeByRef(\ReflectionClass &...$args) { } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_overrides_properly_methods_with_args_passed_by_reference( ClassNode $class, MethodNode $method, ArgumentNode $argument ) { $class->getParentClass()->willReturn('RuntimeException'); $class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface')); $class->getProperties()->willReturn(array()); $class->getMethods()->willReturn(array($method)); $class->isReadOnly()->willReturn(false); $method->getName()->willReturn('getName'); $method->getVisibility()->willReturn('public'); $method->isStatic()->willReturn(false); $method->getArguments()->willReturn(array($argument)); $method->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method->returnsReference()->willReturn(false); $method->getCode()->willReturn('return $this->name;'); $argument->getName()->willReturn('fullname'); $argument->isOptional()->willReturn(true); $argument->getDefault()->willReturn(null); $argument->isPassedByReference()->willReturn(true); $argument->isVariadic()->willReturn(false); $argument->getTypeNode()->willReturn(new ArgumentTypeNode(new UnionType([ new BuiltinType('array'), new BuiltinType('null'), ]))); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \RuntimeException implements \Prophecy\Doubler\Generator\MirroredInterface { public function getName(array|null &$fullname = NULL) { return $this->name; } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_proper_code_for_union_return_types( ClassNode $class, MethodNode $method ) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn([]); $class->getProperties()->willReturn([]); $class->getMethods()->willReturn(array($method)); $class->isReadOnly()->willReturn(false); $method->getName()->willReturn('foo'); $method->getVisibility()->willReturn('public'); $method->isStatic()->willReturn(false); $method->getArguments()->willReturn([]); $method->getReturnTypeNode()->willReturn(new ReturnTypeNode(new UnionType([ new BuiltinType('int'), new BuiltinType('string'), new BuiltinType('null'), ]))); $method->returnsReference()->willReturn(false); $method->getCode()->willReturn(''); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \stdClass implements { public function foo(): int|string|null { } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_proper_code_for_dnf_types( ClassNode $class, MethodNode $method ) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn([]); $class->getProperties()->willReturn([]); $class->getMethods()->willReturn(array($method)); $class->isReadOnly()->willReturn(false); $method->getName()->willReturn('foo'); $method->getVisibility()->willReturn('public'); $method->isStatic()->willReturn(false); $method->getArguments()->willReturn([]); $method->getReturnTypeNode()->willReturn(new ReturnTypeNode( new UnionType([ new IntersectionType([new ObjectType('Foo'), new ObjectType('Bar')]), new BuiltinType('string'), ]) )); $method->returnsReference()->willReturn(false); $method->getCode()->willReturn(''); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \stdClass implements { public function foo(): (\Foo&\Bar)|string { } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_proper_code_for_intersection_return_types( ClassNode $class, MethodNode $method ) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn([]); $class->getProperties()->willReturn([]); $class->getMethods()->willReturn(array($method)); $class->isReadOnly()->willReturn(false); $method->getName()->willReturn('foo'); $method->getVisibility()->willReturn('public'); $method->isStatic()->willReturn(false); $method->getArguments()->willReturn([]); $method->getReturnTypeNode()->willReturn(new ReturnTypeNode( new IntersectionType([new ObjectType('Foo'), new ObjectType('Bar')]) )); $method->returnsReference()->willReturn(false); $method->getCode()->willReturn(''); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \stdClass implements { public function foo(): \Foo&\Bar { } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_proper_code_for_union_argument_types( ClassNode $class, MethodNode $method, ArgumentNode $argument ) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn([]); $class->getProperties()->willReturn([]); $class->getMethods()->willReturn(array($method)); $class->isReadOnly()->willReturn(false); $method->getName()->willReturn('foo'); $method->getVisibility()->willReturn('public'); $method->isStatic()->willReturn(false); $method->getArguments()->willReturn([$argument]); $method->getReturnTypeNode()->willReturn(new ReturnTypeNode()); $method->returnsReference()->willReturn(false); $method->getCode()->willReturn(''); $argument->getTypeNode()->willReturn(new ArgumentTypeNode(new UnionType([ new BuiltinType('int'), new BuiltinType('string'), new BuiltinType('null'), ]))); $argument->getName()->willReturn('arg'); $argument->isPassedByReference()->willReturn(false); $argument->isVariadic()->willReturn(false); $argument->isOptional()->willReturn(false); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \stdClass implements { public function foo(int|string|null $arg) { } } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_empty_class_for_empty_ClassNode(ClassNode $class) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface')); $class->getProperties()->willReturn(array()); $class->getMethods()->willReturn(array()); $class->isReadOnly()->willReturn(false); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { class CustomClass extends \stdClass implements \Prophecy\Doubler\Generator\MirroredInterface { } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_wraps_class_in_namespace_if_it_is_namespaced(ClassNode $class) { $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface')); $class->getProperties()->willReturn(array()); $class->getMethods()->willReturn(array()); $class->isReadOnly()->willReturn(false); $code = $this->generate('My\Awesome\CustomClass', $class); $expected = <<<'PHP' namespace My\Awesome { class CustomClass extends \stdClass implements \Prophecy\Doubler\Generator\MirroredInterface { } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } function it_generates_read_only_class_if_parent_class_is_read_only(ClassNode $class) { $class->getParentClass()->willReturn('ReadOnlyClass'); $class->getInterfaces()->willReturn(array('Prophecy\Doubler\Generator\MirroredInterface')); $class->getProperties()->willReturn(array()); $class->getMethods()->willReturn(array()); $class->isReadOnly()->willReturn(true); $code = $this->generate('CustomClass', $class); $expected = <<<'PHP' namespace { readonly class CustomClass extends \ReadOnlyClass implements \Prophecy\Doubler\Generator\MirroredInterface { } } PHP; $expected = strtr($expected, array("\r\n" => "\n", "\r" => "\n")); $code->shouldBe($expected); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/ClassCreatorSpec.php ================================================ beConstructedWith($generator); } function it_evaluates_code_generated_by_ClassCodeGenerator($generator, ClassNode $class) { $generator->generate('stdClass', $class)->shouldBeCalled()->willReturn( 'return 42;' ); $this->create('stdClass', $class)->shouldReturn(42); } function it_throws_an_exception_if_class_does_not_exist_after_evaluation($generator, ClassNode $class) { $generator->generate('CustomClass', $class)->shouldBeCalled()->willReturn( 'return 42;' ); $class->getParentClass()->willReturn('stdClass'); $class->getInterfaces()->willReturn(array('Interface1', 'Interface2')); $this->shouldThrow('Prophecy\Exception\Doubler\ClassCreatorException') ->duringCreate('CustomClass', $class); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/ArgumentNodeSpec.php ================================================ beConstructedWith('name'); } function it_is_not_be_passed_by_reference_by_default() { $this->shouldNotBePassedByReference(); } function it_is_passed_by_reference_if_marked() { $this->setAsPassedByReference(); $this->shouldBePassedByReference(); } function it_is_not_variadic_by_default() { $this->shouldNotBeVariadic(); } function it_is_variadic_if_marked() { $this->setAsVariadic(); $this->shouldBeVariadic(); } function it_does_not_have_default_by_default() { $this->shouldNotHaveDefault(); } function it_does_not_have_default_if_variadic() { $this->setDefault(null); $this->setAsVariadic(); $this->shouldNotHaveDefault(); } function it_does_have_default_if_not_variadic() { $this->setDefault(null); $this->setAsVariadic(false); $this->hasDefault()->shouldReturn(true); } function it_has_name_with_which_it_was_been_constructed() { $this->getName()->shouldReturn('name'); } function it_has_no_typehint_by_default() { $this->getTypeHint()->shouldReturn(null); } function its_typeHint_is_mutable_with_deprecated_accessors() { $this->setTypeHint('array'); $this->getTypeHint()->shouldReturn('array'); } function it_can_set_nullable_type_using_deprecated_method() { $this->setTypeHint('int'); $this->setAsNullable(); $this->shouldBeNullable(); } function it_can_unset_nullable_type_using_deprecated_method() { $this->setTypeHint('int'); $this->setAsNullable(false); $this->shouldNotBeNullable(); } function it_has_an_empty_type_by_default() { $this->getTypeNode()->shouldBeLike(new ArgumentTypeNode()); } function it_has_a_mutable_type() { $this->setTypeNode(new ArgumentTypeNode(new BuiltinType('int'))); $this->getTypeNode()->shouldBeLike(new ArgumentTypeNode(new BuiltinType('int'))); } function it_does_not_have_default_value_by_default() { $this->getDefault()->shouldReturn(null); } function it_is_not_optional_by_default() { $this->isOptional()->shouldReturn(false); } function its_default_is_mutable() { $this->setDefault(array()); $this->getDefault()->shouldReturn(array()); } function it_is_marked_as_optional_when_default_is_set() { $this->setDefault(null); $this->isOptional()->shouldReturn(true); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/ArgumentTypeNodeSpec.php ================================================ getTypes()->shouldReturn([]); } function it_can_have_a_simple_type() { $this->beConstructedWith('int'); $this->getTypes()->shouldReturn(['int']); } function it_can_have_multiple_types() { $this->beConstructedWith('int', 'string'); $this->getTypes()->shouldReturn(['int', 'string']); } function it_will_prefix_fcqns() { $this->beConstructedWith('Foo'); $this->getTypes()->shouldReturn(['\\Foo']); } function it_will_not_prefix_fcqns_that_already_have_prefix() { $this->beConstructedWith('\\Foo'); $this->getTypes()->shouldReturn(['\\Foo']); } function it_can_use_shorthand_null_syntax_if_it_has_single_type_plus_null() { $this->beConstructedWith('int', 'null'); $this->canUseNullShorthand()->shouldReturn(true); } function it_can_not_use_shorthand_null_syntax_if_it_does_not_allow_null() { $this->beConstructedWith('int'); $this->canUseNullShorthand()->shouldReturn(false); } function it_can_not_use_shorthand_null_syntax_if_it_has_more_than_one_non_null_type() { $this->beConstructedWith('int', 'string', 'null'); $this->canUseNullShorthand()->shouldReturn(false); } function it_can_return_non_null_types() { $this->beConstructedWith('int', 'null'); $this->getNonNullTypes()->shouldReturn(['int']); } function it_does_not_allow_union_mixed() { $this->beConstructedWith('mixed', 'int'); if (PHP_VERSION_ID >= 80000) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } } function it_does_not_prefix_false() { $this->beConstructedWith('false', 'array'); $this->getTypes()->shouldReturn(['false', 'array']); } function it_allows_standalone_false() { $this->beConstructedWith('false'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['false']); } } function it_allows_standalone_null() { $this->beConstructedWith('null'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['null']); } } function it_allows_standalone_true() { $this->beConstructedWith('true'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['true']); } } function it_allows_nullable_false() { $this->beConstructedWith('null', 'false'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['null', 'false']); } } function it_allows_nullable_true() { $this->beConstructedWith('null', 'true'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['null', 'true']); } } function it_allows_union_with_false() { $this->beConstructedWith('false', 'Foo'); if (PHP_VERSION_ID >= 80000) { $this->getTypes()->shouldReturn(['false', '\\Foo']); } } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/ClassNodeSpec.php ================================================ getParentClass()->shouldReturn('stdClass'); } function its_parentClass_is_mutable() { $this->setParentClass('Exception'); $this->getParentClass()->shouldReturn('Exception'); } function its_parentClass_is_set_to_stdClass_if_user_set_null() { $this->setParentClass(null); $this->getParentClass()->shouldReturn('stdClass'); } function it_does_not_implement_any_interface_by_default() { $this->getInterfaces()->shouldHaveCount(0); } function its_addInterface_adds_item_to_the_list_of_implemented_interfaces() { $this->addInterface('MyInterface'); $this->getInterfaces()->shouldHaveCount(1); } function its_hasInterface_returns_true_if_class_implements_interface() { $this->addInterface('MyInterface'); $this->hasInterface('MyInterface')->shouldReturn(true); } function its_hasInterface_returns_false_if_class_does_not_implements_interface() { $this->hasInterface('MyInterface')->shouldReturn(false); } function it_supports_implementation_of_multiple_interfaces() { $this->addInterface('MyInterface'); $this->addInterface('MySecondInterface'); $this->getInterfaces()->shouldHaveCount(2); } function it_ignores_same_interfaces_added_twice() { $this->addInterface('MyInterface'); $this->addInterface('MyInterface'); $this->getInterfaces()->shouldHaveCount(1); $this->getInterfaces()->shouldReturn(array('MyInterface')); } function it_does_not_have_methods_by_default() { $this->getMethods()->shouldHaveCount(0); } function it_can_has_methods(MethodNode $method1, MethodNode $method2) { $method1->getName()->willReturn('__construct'); $method2->getName()->willReturn('getName'); $this->addMethod($method1); $this->addMethod($method2); $this->getMethods()->shouldReturn([ '__construct' => $method1, 'getName' => $method2, ]); } function its_hasMethod_returns_true_if_method_exists(MethodNode $method) { $method->getName()->willReturn('getName'); $this->addMethod($method); $this->hasMethod('getName')->shouldReturn(true); } function its_getMethod_returns_method_by_name(MethodNode $method) { $method->getName()->willReturn('getName'); $this->addMethod($method); $this->getMethod('getName')->shouldReturn($method); } function its_hasMethod_returns_false_if_method_does_not_exists() { $this->hasMethod('getName')->shouldReturn(false); } function its_hasMethod_returns_false_if_method_has_been_removed(MethodNode $method) { $method->getName()->willReturn('getName'); $this->addMethod($method); $this->removeMethod('getName'); $this->hasMethod('getName')->shouldReturn(false); } function it_does_not_have_properties_by_default() { $this->getProperties()->shouldHaveCount(0); } function it_is_able_to_have_properties() { $this->addProperty('title'); $this->addProperty('text', 'private'); $this->getProperties()->shouldReturn(array( 'title' => 'public', 'text' => 'private', )); } function its_addProperty_does_not_accept_unsupported_visibility() { $this->shouldThrow('InvalidArgumentException')->duringAddProperty('title', 'town'); } function its_addProperty_lowercases_visibility_before_setting() { $this->addProperty('text', 'PRIVATE'); $this->getProperties()->shouldReturn(array('text' => 'private')); } function its_has_no_unextendable_methods_by_default() { $this->getUnextendableMethods()->shouldHaveCount(0); } function its_addUnextendableMethods_adds_an_unextendable_method() { $this->addUnextendableMethod('testMethod'); $this->getUnextendableMethods()->shouldHaveCount(1); } function its_methods_are_extendable_by_default() { $this->isExtendable('testMethod')->shouldReturn(true); } function its_unextendable_methods_are_not_extendable() { $this->addUnextendableMethod('testMethod'); $this->isExtendable('testMethod')->shouldReturn(false); } function its_addUnextendableMethods_doesnt_create_duplicates() { $this->addUnextendableMethod('testMethod'); $this->addUnextendableMethod('testMethod'); $this->getUnextendableMethods()->shouldHaveCount(1); } function it_throws_an_exception_when_adding_a_method_that_isnt_extendable(MethodNode $method) { $this->addUnextendableMethod('testMethod'); $method->getName()->willReturn('testMethod'); $expectedException = new MethodNotExtendableException( "Method `testMethod` is not extendable, so can not be added.", "stdClass", "testMethod" ); $this->shouldThrow($expectedException)->duringAddMethod($method); } function it_is_non_read_only_by_default() { $this->isReadOnly()->shouldReturn(false); } function its_read_only_is_mutable() { $this->setReadOnly(true); $this->isReadOnly()->shouldReturn(true); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/MethodNodeSpec.php ================================================ beConstructedWith('getTitle'); } function it_has_a_name() { $this->getName()->shouldReturn('getTitle'); } function it_has_public_visibility_by_default() { $this->getVisibility()->shouldReturn('public'); } function its_visibility_is_mutable() { $this->setVisibility('private'); $this->getVisibility()->shouldReturn('private'); } function it_is_not_static_by_default() { $this->shouldNotBeStatic(); } function it_does_not_return_a_reference_by_default() { $this->returnsReference()->shouldReturn(false); } function it_should_be_settable_as_returning_a_reference_through_setter() { $this->setReturnsReference(); $this->returnsReference()->shouldReturn(true); } function it_should_be_settable_as_static_through_setter() { $this->setStatic(); $this->shouldBeStatic(); } function it_accepts_only_supported_visibilities() { $this->shouldThrow('InvalidArgumentException')->duringSetVisibility('stealth'); } function it_lowercases_visibility_before_setting_it() { $this->setVisibility('Public'); $this->getVisibility()->shouldReturn('public'); } function its_useParentCode_causes_method_to_call_parent(ArgumentNode $argument1, ArgumentNode $argument2) { $argument1->getName()->willReturn('objectName'); $argument2->getName()->willReturn('default'); $argument1->isVariadic()->willReturn(false); $argument2->isVariadic()->willReturn(true); $this->addArgument($argument1); $this->addArgument($argument2); $this->useParentCode(); $this->getCode()->shouldReturn( 'return parent::getTitle($objectName, ...$default);' ); } function its_code_is_mutable() { $this->setCode('echo "code";'); $this->getCode()->shouldReturn('echo "code";'); } function its_reference_returning_methods_will_generate_exceptions() { $this->setCode('echo "code";'); $this->setReturnsReference(); $this->getCode()->shouldReturn("throw new \Prophecy\Exception\Doubler\ReturnByReferenceException('Returning by reference not supported', get_class(\$this), 'getTitle');"); } function its_setCode_provided_with_null_cleans_method_body() { $this->setCode(null); $this->getCode()->shouldReturn(''); } function it_is_constructable_with_code() { $this->beConstructedWith('getTitle', 'die();'); $this->getCode()->shouldReturn('die();'); } function it_does_not_have_arguments_by_default() { $this->getArguments()->shouldHaveCount(0); } function it_supports_adding_arguments(ArgumentNode $argument1, ArgumentNode $argument2) { $this->addArgument($argument1); $this->addArgument($argument2); $this->getArguments()->shouldReturn(array($argument1, $argument2)); } function it_has_an_empty_return_type_by_default() { $this->getReturnTypeNode()->shouldBeLike(new ReturnTypeNode()); } function it_can_modify_return_type() { $this->setReturnTypeNode(new ReturnTypeNode(new BuiltinType('array'))); $this->getReturnTypeNode()->shouldBeLike(new ReturnTypeNode(new BuiltinType('array'))); } function it_can_modify_return_type_as_strings_using_deprecated_methods() { $this->setReturnType('array'); $this->hasReturnType()->shouldReturn(true); $this->getReturnType()->shouldReturn('array'); } function it_can_set_nullable_type_using_deprecated_method() { $this->setReturnType('int'); $this->setNullableReturnType(); $this->shouldHaveNullableReturnType(); } function it_can_unset_nullable_type_using_deprecated_method() { $this->setReturnType('int'); $this->setNullableReturnType(false); $this->shouldNotHaveNullableReturnType(); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/ReturnTypeNodeSpec.php ================================================ getTypes()->shouldReturn([]); } function it_can_have_a_simple_type() { $this->beConstructedWith('int'); $this->getTypes()->shouldReturn(['int']); } function it_can_have_multiple_types() { $this->beConstructedWith('int', 'string'); $this->getTypes()->shouldReturn(['int', 'string']); } function it_can_have_void_type() { $this->beConstructedWith('void'); $this->getTypes()->shouldReturn(['void']); } function it_will_normalise_type_aliases_types() { $this->beConstructedWith('double', 'real', 'boolean', 'integer'); $this->getTypes()->shouldReturn(['float', 'bool', 'int']); } function it_will_prefix_fcqns() { $this->beConstructedWith('Foo'); $this->getTypes()->shouldReturn(['\\Foo']); } function it_will_not_prefix_fcqns_that_already_have_prefix() { $this->beConstructedWith('\\Foo'); $this->getTypes()->shouldReturn(['\\Foo']); } function it_can_use_shorthand_null_syntax_if_it_has_single_type_plus_null() { $this->beConstructedWith('int', 'null'); $this->canUseNullShorthand()->shouldReturn(true); } function it_can_not_use_shorthand_null_syntax_if_it_does_not_allow_null() { $this->beConstructedWith('int'); $this->canUseNullShorthand()->shouldReturn(false); } function it_can_not_use_shorthand_null_syntax_if_it_has_more_than_one_non_null_type() { $this->beConstructedWith('int', 'string', 'null'); $this->canUseNullShorthand()->shouldReturn(false); } function it_can_return_non_null_types() { $this->beConstructedWith('int', 'null'); $this->getNonNullTypes()->shouldReturn(['int']); } function it_does_not_allow_union_void() { $this->beConstructedWith('void', 'int'); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_does_not_allow_union_mixed() { $this->beConstructedWith('mixed', 'int'); if (PHP_VERSION_ID >= 80000) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } } function it_does_not_prefix_false() { $this->beConstructedWith('false', 'array'); $this->getTypes()->shouldReturn(['false', 'array']); } function it_allows_standalone_false() { $this->beConstructedWith('false'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['false']); } } function it_allows_standalone_null() { $this->beConstructedWith('null'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['null']); } } function it_allows_standalone_true() { $this->beConstructedWith('true'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['true']); } } function it_allows_nullable_false() { $this->beConstructedWith('null', 'false'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['null', 'false']); } } function it_allows_nullable_true() { $this->beConstructedWith('null', 'true'); if (PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200) { $this->shouldThrow(DoubleException::class)->duringInstantiation(); } if (PHP_VERSION_ID >= 80200) { $this->getTypes()->shouldReturn(['null', 'true']); } } function it_allows_union_with_false() { $this->beConstructedWith('false', 'Foo'); if (PHP_VERSION_ID >= 80000) { $this->getTypes()->shouldReturn(['false', '\\Foo']); } } function it_does_not_prefix_never() { $this->beConstructedWith('never'); $this->getTypes()->shouldReturn(['never']); } function it_does_not_allow_union_never() { $this->beConstructedWith('never', 'int'); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_has_a_return_statement_if_it_is_a_simple_type() { $this->beConstructedWith('int'); $this->shouldHaveReturnStatement(); } function it_does_not_have_return_statement_if_it_returns_void() { $this->beConstructedWith('void'); $this->shouldNotHaveReturnStatement(); } function it_does_not_have_return_statement_if_it_returns_never() { $this->beConstructedWith('never'); $this->shouldNotHaveReturnStatement(); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/Type/BuiltinTypeSpec.php ================================================ beConstructedWith('string'); } function it_implements_type_interface(): void { $this->shouldImplement(TypeInterface::class); } function it_is_stringable(): void { $this->beConstructedWith('int'); $this->getType()->shouldReturn('int'); $this->__toString()->shouldReturn('int'); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/Type/IntersectionTypeSpec.php ================================================ beConstructedWith([ new ObjectType('Foo'), new ObjectType('Bar'), ]); } function it_should_implement_type_union(): void { $this->shouldImplement(TypeInterface::class); } function it_should_throw_double_exception_for_builtin_types() { $this->beConstructedWith([ new BuiltinType('string'), new ObjectType('Foo'), ]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_should_throw_double_exception_if_less_than_2_types_provided() { $this->beConstructedWith([ new ObjectType('Bar'), ]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_should_throw_double_exception_if_union_type_given(): void { $this->beConstructedWith([ new ObjectType('Bar'), new UnionType([new ObjectType('Foo'), new ObjectType('Baz')]), ]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_is_stringable(): void { $bar = new ObjectType('Bar'); $foo = new ObjectType('Foo'); $this->beConstructedWith([ $bar, $foo, ]); $this->__toString()->shouldReturn('\\Bar&\\Foo'); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/Type/ObjectTypeSpec.php ================================================ beConstructedWith(stdClass::class); } function it_implements_type_interface(): void { $this->shouldImplement(TypeInterface::class); } function it_is_stringable(): void { $this->beConstructedWith('stdClass'); $this->getType()->shouldReturn('stdClass'); $this->__toString()->shouldReturn('\stdClass'); } } ================================================ FILE: spec/Prophecy/Doubler/Generator/Node/Type/UnionTypeSpec.php ================================================ beConstructedWith([ new BuiltinType('int'), new BuiltinType('string'), ]); } function it_implements_type_interface(): void { $this->shouldImplement(TypeInterface::class); } function it_throws_double_exception_when_union_type_given(): void { $this->beConstructedWith([ new UnionType([new BuiltinType('int'), new BuiltinType('string')]), new BuiltinType('bool'), ]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_throws_double_exception_when_types_duplicated(): void { $this->beConstructedWith([new BuiltinType('string'), new BuiltinType('string')]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_throws_double_exception_when_union_with_void(): void { $this->beConstructedWith([new BuiltinType('void'), new BuiltinType('string')]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_throws_double_exception_when_union_with_never(): void { $this->beConstructedWith([new BuiltinType('never'), new BuiltinType('string')]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_throws_double_exception_when_union_with_mixed(): void { $this->beConstructedWith([new BuiltinType('mixed'), new BuiltinType('string')]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_throws_double_exception_when_union_with_only_one_type(): void { $this->beConstructedWith([new BuiltinType('string')]); $this->shouldThrow(DoubleException::class)->duringInstantiation(); } function it_return_array_of_its_types(): void { $this->getTypes()->shouldBeLike([ new BuiltinType('int'), new BuiltinType('string'), ]); } function it_should_accept_simple_type_and_intersection() { $type1 = new BuiltinType('string'); $type2 = new IntersectionType([new ObjectType('A'), new ObjectType('B')]); $this->beConstructedWith([$type1, $type2]); $this->has($type1)->shouldBe(true); $this->has($type2)->shouldBe(true); } function it_is_stringable(): void { $bar = new ObjectType('Bar'); $foo = new ObjectType('Foo'); $baz = new ObjectType('Baz'); $intersection = new IntersectionType([$foo, $baz]); $this->beConstructedWith([$bar, $intersection]); $this->__toString()->shouldBe('\\Bar|(\\Foo&\\Baz)'); } } ================================================ FILE: spec/Prophecy/Doubler/LazyDoubleSpec.php ================================================ beConstructedWith($doubler); } function it_returns_anonymous_double_instance_by_default($doubler, ProphecySubjectInterface $double) { $doubler->double(null, array())->willReturn($double); $this->getInstance()->shouldReturn($double); } function it_returns_class_double_instance_if_set($doubler, ProphecySubjectInterface $double, \ReflectionClass $class) { $doubler->double($class, array())->willReturn($double); $this->setParentClass($class); $this->getInstance()->shouldReturn($double); } function it_returns_same_double_instance_if_called_2_times( $doubler, ProphecySubjectInterface $double1, ProphecySubjectInterface $double2 ) { $doubler->double(null, array())->willReturn($double1); $doubler->double(null, array())->willReturn($double2); $this->getInstance()->shouldReturn($double2); $this->getInstance()->shouldReturn($double2); } function its_setParentClass_throws_ClassNotFoundException_if_class_not_found() { $this->shouldThrow('Prophecy\Exception\Doubler\ClassNotFoundException') ->duringSetParentClass('SomeUnexistingClass'); } function its_setParentClass_throws_exception_if_prophecy_is_already_created( $doubler, ProphecySubjectInterface $double ) { $doubler->double(null, array())->willReturn($double); $this->getInstance(); $this->shouldThrow('Prophecy\Exception\Doubler\DoubleException') ->duringSetParentClass('stdClass'); } function its_addInterface_throws_InterfaceNotFoundException_if_no_interface_found() { $this->shouldThrow('Prophecy\Exception\Doubler\InterfaceNotFoundException') ->duringAddInterface('SomeUnexistingInterface'); } function its_addInterface_throws_exception_if_prophecy_is_already_created( $doubler, ProphecySubjectInterface $double ) { $doubler->double(null, array())->willReturn($double); $this->getInstance(); $this->shouldThrow('Prophecy\Exception\Doubler\DoubleException') ->duringAddInterface('ArrayAccess'); } } ================================================ FILE: spec/Prophecy/Doubler/NameGeneratorSpec.php ================================================ getName()->willReturn('stdClass'); $this->name($class, array())->shouldStartWith('Double\stdClass\\'); } function its_name_generates_name_based_on_namespaced_class_reflection(\ReflectionClass $class) { $class->getName()->willReturn('Some\Custom\Class'); $this->name($class, array())->shouldStartWith('Double\Some\Custom\Class\P'); } function its_name_generates_name_based_on_interface_shortnames( \ReflectionClass $interface1, \ReflectionClass $interface2 ) { $interface1->getShortName()->willReturn('HandlerInterface'); $interface2->getShortName()->willReturn('LoaderInterface'); $this->name(null, array($interface1, $interface2))->shouldStartWith( 'Double\HandlerInterface\LoaderInterface\P' ); } function it_generates_proper_name_for_no_class_and_interfaces_list() { $this->name(null, array())->shouldStartWith('Double\stdClass\P'); } function its_name_generates_name_based_only_on_class_if_its_available( \ReflectionClass $class, \ReflectionClass $interface1, \ReflectionClass $interface2 ) { $class->getName()->willReturn('Some\Custom\Class'); $interface1->getShortName()->willReturn('HandlerInterface'); $interface2->getShortName()->willReturn('LoaderInterface'); $this->name($class, array($interface1, $interface2))->shouldStartWith( 'Double\Some\Custom\Class\P' ); } public function getMatchers(): array { return array( 'startWith' => function ($subject, $string) { return 0 === strpos($subject, $string); }, ); } } ================================================ FILE: spec/Prophecy/Exception/Call/UnexpectedCallExceptionSpec.php ================================================ beConstructedWith('msg', $objectProphecy, 'getName', array('arg1', 'arg2')); } function it_is_prophecy_exception() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ObjectProphecyException'); } function it_exposes_method_name_through_getter() { $this->getMethodName()->shouldReturn('getName'); } function it_exposes_arguments_through_getter() { $this->getArguments()->shouldReturn(array('arg1', 'arg2')); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/ClassCreatorExceptionSpec.php ================================================ beConstructedWith('', $node); } function it_is_a_prophecy_exception() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Exception'); $this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoublerException'); } function it_contains_a_reflected_node($node) { $this->getClassNode()->shouldReturn($node); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/ClassMirrorExceptionSpec.php ================================================ beConstructedWith('', $class); } function it_is_a_prophecy_exception() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Exception'); $this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoublerException'); } function it_contains_a_reflected_class_link($class) { $this->getReflectedClass()->shouldReturn($class); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/ClassNotFoundExceptionSpec.php ================================================ beConstructedWith('msg', 'CustomClass'); } function it_is_a_prophecy_exception() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Exception'); $this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoubleException'); } function its_getClassname_returns_classname() { $this->getClassname()->shouldReturn('CustomClass'); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/DoubleExceptionSpec.php ================================================ shouldBeAnInstanceOf('RuntimeException'); $this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\DoublerException'); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/InterfaceNotFoundExceptionSpec.php ================================================ beConstructedWith('msg', 'CustomInterface'); } function it_extends_ClassNotFoundException() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Doubler\ClassNotFoundException'); } function its_getClassname_returns_classname() { $this->getClassname()->shouldReturn('CustomInterface'); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/MethodNotExtendableExceptionSpec.php ================================================ beConstructedWith('', 'User', 'getName'); } function it_is_DoubleException() { $this->shouldHaveType('Prophecy\Exception\Doubler\DoubleException'); } function it_has_MethodName() { $this->getMethodName()->shouldReturn('getName'); } function it_has_classname() { $this->getClassName()->shouldReturn('User'); } } ================================================ FILE: spec/Prophecy/Exception/Doubler/MethodNotFoundExceptionSpec.php ================================================ beConstructedWith('', 'User', 'getName', array(1, 2, 3)); } function it_is_DoubleException() { $this->shouldHaveType('Prophecy\Exception\Doubler\DoubleException'); } function it_has_MethodName() { $this->getMethodName()->shouldReturn('getName'); } function it_has_classnamej() { $this->getClassname()->shouldReturn('User'); } function it_has_an_arguments_list() { $this->getArguments()->shouldReturn(array(1, 2, 3)); } function it_has_a_default_null_argument_list() { $this->beConstructedWith('', 'User', 'getName'); $this->getArguments()->shouldReturn(null); } } ================================================ FILE: spec/Prophecy/Exception/Prediction/AggregateExceptionSpec.php ================================================ beConstructedWith(''); } function it_is_prediction_exception() { $this->shouldBeAnInstanceOf('RuntimeException'); $this->shouldBeAnInstanceOf('Prophecy\Exception\Prediction\PredictionException'); } function it_can_store_objectProphecy_link(ObjectProphecy $object) { $this->setObjectProphecy($object); $this->getObjectProphecy()->shouldReturn($object); } function it_should_not_have_exceptions_at_the_beginning() { $this->getExceptions()->shouldHaveCount(0); } function it_should_append_exception_through_append_method() { $exception = new FailedPredictionException(); $this->append($exception); $this->getExceptions()->shouldReturn(array($exception)); } function it_should_update_message_during_append() { $exception = new FailedPredictionException('Exception #1'); $this->append($exception); $this->getMessage()->shouldReturn('Exception #1'); } function it_should_update_message_during_append_more_exceptions( PredictionException $exception1, PredictionException $exception2 ) { $exception1 = new FailedPredictionException('Exception #1'); $exception2 = new FailedPredictionException('Exception #2'); $this->append($exception1); $this->append($exception2); $this->getMessage()->shouldReturn("Exception #1\nException #2"); } } ================================================ FILE: spec/Prophecy/Exception/Prediction/NoCallsExceptionSpec.php ================================================ getObjectProphecy()->willReturn($objectProphecy); $this->beConstructedWith('message', $methodProphecy); } function it_is_PredictionException() { $this->shouldHaveType('Prophecy\Exception\Prediction\PredictionException'); } function it_extends_MethodProphecyException() { $this->shouldHaveType('Prophecy\Exception\Prophecy\MethodProphecyException'); } } ================================================ FILE: spec/Prophecy/Exception/Prediction/UnexpectedCallsCountExceptionSpec.php ================================================ getObjectProphecy()->willReturn($objectProphecy); $this->beConstructedWith('message', $methodProphecy, 5, array($call1, $call2)); } function it_extends_UnexpectedCallsException() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Prediction\UnexpectedCallsException'); } function it_should_expose_expectedCount_through_getter() { $this->getExpectedCount()->shouldReturn(5); } } ================================================ FILE: spec/Prophecy/Exception/Prediction/UnexpectedCallsExceptionSpec.php ================================================ getObjectProphecy()->willReturn($objectProphecy); $this->beConstructedWith('message', $methodProphecy, array($call1, $call2)); } function it_is_PredictionException() { $this->shouldHaveType('Prophecy\Exception\Prediction\PredictionException'); } function it_extends_MethodProphecyException() { $this->shouldHaveType('Prophecy\Exception\Prophecy\MethodProphecyException'); } function it_should_expose_calls_list_through_getter($call1, $call2) { $this->getCalls()->shouldReturn(array($call1, $call2)); } } ================================================ FILE: spec/Prophecy/Exception/Prophecy/MethodProphecyExceptionSpec.php ================================================ getObjectProphecy()->willReturn($objectProphecy); $this->beConstructedWith('message', $methodProphecy); } function it_extends_DoubleException() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ObjectProphecyException'); } function it_holds_a_stub_reference($methodProphecy) { $this->getMethodProphecy()->shouldReturn($methodProphecy); } } ================================================ FILE: spec/Prophecy/Exception/Prophecy/ObjectProphecyExceptionSpec.php ================================================ beConstructedWith('message', $objectProphecy); } function it_should_be_a_prophecy_exception() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ProphecyException'); } function it_holds_double_reference($objectProphecy) { $this->getObjectProphecy()->shouldReturn($objectProphecy); } } ================================================ FILE: spec/Prophecy/Prediction/CallPredictionSpec.php ================================================ shouldHaveType('Prophecy\Prediction\PredictionInterface'); } function it_does_nothing_if_there_is_more_than_one_call_been_made( ObjectProphecy $object, MethodProphecy $method, Call $call ) { $this->check(array($call), $object, $method)->shouldReturn(null); } function it_throws_NoCallsException_if_no_calls_found( ObjectProphecy $object, MethodProphecy $method, ArgumentsWildcard $arguments ) { $method->getObjectProphecy()->willReturn($object); $method->getMethodName()->willReturn('getName'); $method->getArgumentsWildcard()->willReturn($arguments); $arguments->__toString()->willReturn('123'); $object->reveal()->willReturn(new \stdClass()); $object->findProphecyMethodCalls('getName', Argument::any())->willReturn(array()); $this->shouldThrow('Prophecy\Exception\Prediction\NoCallsException') ->duringCheck(array(), $object, $method); } } ================================================ FILE: spec/Prophecy/Prediction/CallTimesPredictionSpec.php ================================================ beConstructedWith(2); } function it_is_prediction() { $this->shouldHaveType('Prophecy\Prediction\PredictionInterface'); } function it_does_nothing_if_there_were_exact_amount_of_calls_being_made( ObjectProphecy $object, MethodProphecy $method, Call $call1, Call $call2 ) { $this->check(array($call1, $call2), $object, $method)->shouldReturn(null); } function it_throws_UnexpectedCallsCountException_if_calls_found( ObjectProphecy $object, MethodProphecy $method, Call $call, ArgumentsWildcard $arguments ) { $object->reveal()->willReturn(new \stdClass()); $object->findProphecyMethodCalls('getName', Argument::any())->willReturn(array()); $method->getObjectProphecy()->willReturn($object); $method->getMethodName()->willReturn('getName'); $method->getArgumentsWildcard()->willReturn($arguments); $arguments->__toString()->willReturn('123'); $call->getMethodName()->willReturn('getName'); $call->getArguments()->willReturn(array(5, 4, 'three')); $call->getCallPlace()->willReturn('unknown'); $this->shouldThrow('Prophecy\Exception\Prediction\UnexpectedCallsCountException') ->duringCheck(array($call), $object, $method); } } ================================================ FILE: spec/Prophecy/Prediction/CallbackPredictionSpec.php ================================================ beConstructedWith('get_class'); } function it_is_prediction() { $this->shouldHaveType('Prophecy\Prediction\PredictionInterface'); } function it_proxies_call_to_callback(ObjectProphecy $object, MethodProphecy $method, Call $call) { $returnFirstCallCallback = function ($calls, $object, $method) { throw new RuntimeException(); }; $this->beConstructedWith($returnFirstCallCallback); $this->shouldThrow('RuntimeException')->duringCheck(array($call), $object, $method); } } ================================================ FILE: spec/Prophecy/Prediction/NoCallsPredictionSpec.php ================================================ shouldHaveType('Prophecy\Prediction\PredictionInterface'); } function it_does_nothing_if_there_is_no_calls_made(ObjectProphecy $object, MethodProphecy $method) { $this->check(array(), $object, $method)->shouldReturn(null); } function it_throws_UnexpectedCallsException_if_calls_found( ObjectProphecy $object, MethodProphecy $method, Call $call, ArgumentsWildcard $arguments ) { $object->reveal()->willReturn(new \stdClass()); $method->getObjectProphecy()->willReturn($object); $method->getMethodName()->willReturn('getName'); $method->getArgumentsWildcard()->willReturn($arguments); $arguments->__toString()->willReturn('123'); $call->getMethodName()->willReturn('getName'); $call->getArguments()->willReturn(array(5, 4, 'three')); $call->getCallPlace()->willReturn('unknown'); $this->shouldThrow('Prophecy\Exception\Prediction\UnexpectedCallsException') ->duringCheck(array($call), $object, $method); } } ================================================ FILE: spec/Prophecy/Promise/CallbackPromiseSpec.php ================================================ beConstructedWith('get_class'); } function it_is_promise() { $this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface'); } function it_should_execute_closure_callback(ObjectProphecy $object, MethodProphecy $method) { $firstArgumentCallback = function ($args) { return $args[0]; }; $this->beConstructedWith($firstArgumentCallback); $this->execute(array('one', 'two'), $object, $method)->shouldReturn('one'); } function it_should_execute_static_array_callback(ObjectProphecy $object, MethodProphecy $method) { $firstArgumentCallback = array('spec\Prophecy\Promise\ClassCallback', 'staticCallbackMethod'); $this->beConstructedWith($firstArgumentCallback); $this->execute(array('one', 'two'), $object, $method)->shouldReturn('one'); } function it_should_execute_instance_array_callback(ObjectProphecy $object, MethodProphecy $method) { $class = new ClassCallback(); $firstArgumentCallback = array($class, 'callbackMethod'); $this->beConstructedWith($firstArgumentCallback); $this->execute(array('one', 'two'), $object, $method)->shouldReturn('one'); } function it_should_execute_string_function_callback(ObjectProphecy $object, MethodProphecy $method) { $firstArgumentCallback = 'spec\Prophecy\Promise\functionCallbackFirstArgument'; $this->beConstructedWith($firstArgumentCallback); $this->execute(array('one', 'two'), $object, $method)->shouldReturn('one'); } } /** * Class used to test callbackpromise * * @param array * @return string */ class ClassCallback { /** * @param array $args */ function callbackMethod($args) { return $args[0]; } /** * @param array $args */ static function staticCallbackMethod($args) { return $args[0]; } } /** * Callback function used to test callbackpromise * * @param array * @return string */ function functionCallbackFirstArgument($args) { return $args[0]; } ================================================ FILE: spec/Prophecy/Promise/ReturnArgumentPromiseSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface'); } function it_should_return_first_argument_if_provided(ObjectProphecy $object, MethodProphecy $method) { $this->execute(array('one', 'two'), $object, $method)->shouldReturn('one'); } function it_should_return_null_if_no_arguments_provided(ObjectProphecy $object, MethodProphecy $method) { $this->execute(array(), $object, $method)->shouldReturn(null); } function it_should_return_nth_argument_if_provided(ObjectProphecy $object, MethodProphecy $method) { $this->beConstructedWith(1); $this->execute(array('one', 'two'), $object, $method)->shouldReturn('two'); } } ================================================ FILE: spec/Prophecy/Promise/ReturnPromiseSpec.php ================================================ beConstructedWith(array(42)); } function it_is_promise() { $this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface'); } function it_returns_value_it_was_constructed_with(ObjectProphecy $object, MethodProphecy $method) { $this->execute(array(), $object, $method)->shouldReturn(42); } function it_always_returns_last_value_left_in_the_return_values(ObjectProphecy $object, MethodProphecy $method) { $this->execute(array(), $object, $method)->shouldReturn(42); $this->execute(array(), $object, $method)->shouldReturn(42); } function it_consequently_returns_multiple_values_it_was_constructed_with( ObjectProphecy $object, MethodProphecy $method ) { $this->beConstructedWith(array(42, 24, 12)); $this->execute(array(), $object, $method)->shouldReturn(42); $this->execute(array(), $object, $method)->shouldReturn(24); $this->execute(array(), $object, $method)->shouldReturn(12); } function it_returns_null_if_constructed_with_empty_array(ObjectProphecy $object, MethodProphecy $method) { $this->beConstructedWith(array()); $this->execute(array(), $object, $method)->shouldReturn(null); } } ================================================ FILE: spec/Prophecy/Promise/ThrowPromiseSpec.php ================================================ beConstructedWith('RuntimeException'); } function it_is_promise() { $this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface'); } function it_instantiates_and_throws_exception_from_provided_classname(ObjectProphecy $object, MethodProphecy $method) { $this->beConstructedWith('InvalidArgumentException'); $this->shouldThrow('InvalidArgumentException') ->duringExecute(array(), $object, $method); } function it_instantiates_exceptions_with_required_arguments(ObjectProphecy $object, MethodProphecy $method) { $this->beConstructedWith('spec\Prophecy\Promise\RequiredArgumentException'); $this->shouldThrow('spec\Prophecy\Promise\RequiredArgumentException') ->duringExecute(array(), $object, $method); } function it_throws_provided_exception(ObjectProphecy $object, MethodProphecy $method) { $this->beConstructedWith($exc = new \RuntimeException('Some exception')); $this->shouldThrow($exc)->duringExecute(array(), $object, $method); } function it_throws_error_instances(ObjectProphecy $object, MethodProphecy $method) { if (!class_exists('\Error')) { throw new SkippingException('The class Error, introduced in PHP 7, does not exist'); } $this->beConstructedWith($exc = new \Error('Error exception')); $this->shouldThrow($exc)->duringExecute(array(), $object, $method); } function it_throws_errors_by_class_name() { if (!class_exists('\Error')) { throw new SkippingException('The class Error, introduced in PHP 7, does not exist'); } $this->beConstructedWith('\Error'); $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } function it_does_not_throw_something_that_is_not_throwable_by_class_name() { $this->beConstructedWith('\stdClass'); $this->shouldThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } function it_does_not_throw_something_that_is_not_throwable_by_instance() { $this->beConstructedWith(new \stdClass()); $this->shouldThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } function it_throws_an_exception_by_class_name() { $this->beConstructedWith('\Exception'); $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } function it_throws_an_extension_of_throwable_by_class_name() { if (!interface_exists('\Throwable')) { throw new SkippingException('The interface Throwable, introduced in PHP 7, does not exist'); } $this->beConstructedWith('\Fixtures\Prophecy\ThrowableInterface'); $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } function it_throws_a_throwable_by_class_name() { if (!interface_exists('\Throwable')) { throw new SkippingException('The interface Throwable, introduced in PHP 7, does not exist'); } $this->beConstructedWith('\Throwable'); $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } } class RequiredArgumentException extends \Exception { final public function __construct($message, $code) {} } ================================================ FILE: spec/Prophecy/Prophecy/MethodProphecySpec.php ================================================ reveal()->willReturn($reflection); if (\PHP_VERSION_ID >= 80100) { $objectProphecy->addMethodProphecy(Argument::any())->willReturn(); } $this->beConstructedWith($objectProphecy, 'getName', $argumentsWildcard); } function it_is_initializable() { $this->shouldHaveType('Prophecy\Prophecy\MethodProphecy'); } function its_constructor_throws_MethodNotFoundException_for_unexisting_method( ObjectProphecy $objectProphecy, ObjectProphecy $objectProphecyInner, ReflectionClass $reflection, ArgumentsWildcard $argumentsWildcard ) { $objectProphecy->reveal()->willReturn($objectProphecyInner); $objectProphecyInner->reveal()->willReturn($reflection); $this->beConstructedWith($objectProphecy, 'getUnexisting', $argumentsWildcard); $this->shouldThrow('Prophecy\Exception\Doubler\MethodNotFoundException')->duringInstantiation(); } function its_constructor_throws_MethodProphecyException_for_final_methods( ObjectProphecy $objectProphecy, ObjectProphecy $objectProphecyInner, ClassWithFinalMethod $subject ) { $objectProphecy->reveal()->willReturn($objectProphecyInner); $objectProphecyInner->reveal()->willReturn($subject); $this->shouldThrow('Prophecy\Exception\Prophecy\MethodProphecyException')->during( '__construct', array($objectProphecy, 'finalMethod', null) ); } function its_constructor_transforms_array_passed_as_3rd_argument_to_ArgumentsWildcard( ObjectProphecy $objectProphecy ) { $this->beConstructedWith($objectProphecy, 'getName', array(42, 33)); $wildcard = $this->getArgumentsWildcard(); $wildcard->__toString()->shouldReturn('exact(42), exact(33)'); } function its_constructor_records_default_callback_promise_for_return_type_hinted_methods( ObjectProphecy $objectProphecy, $subject, ArgumentsWildcard $argumentsWildcard ) { $subject->beADoubleOf('spec\Prophecy\Prophecy\ClassWithVoidTypeHintedMethods'); $objectProphecy->addMethodProphecy(Argument::cetera())->willReturn(null); $objectProphecy->reveal()->willReturn($subject); $this->beConstructedWith($objectProphecy, 'getVoid', $argumentsWildcard); $this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\CallbackPromise'); } function its_constructor_records_promise_that_returns_null_for_void_type_hinted_methods( ObjectProphecy $objectProphecy, $subject, ArgumentsWildcard $argumentsWildcard ) { $subject->beADoubleOf('spec\Prophecy\Prophecy\ClassWithVoidTypeHintedMethods'); $objectProphecy->addMethodProphecy(Argument::cetera())->willReturn(null); $objectProphecy->reveal()->willReturn($subject); $this->beConstructedWith($objectProphecy, 'getVoid', $argumentsWildcard); $this->getPromise()->execute(array(), $objectProphecy, $this)->shouldBeNull(); } function its_constructor_adds_itself_to_ObjectProphecy_for_return_type_hinted_methods( ObjectProphecy $objectProphecy, $subject, ArgumentsWildcard $argumentsWildcard ) { $subject->beADoubleOf('spec\Prophecy\Prophecy\ClassWithVoidTypeHintedMethods'); $objectProphecy->addMethodProphecy(Argument::cetera())->willReturn(null); $objectProphecy->reveal()->willReturn($subject); $this->beConstructedWith($objectProphecy, 'getVoid', $argumentsWildcard); $objectProphecy->addMethodProphecy($this)->shouldHaveBeenCalled(); } function it_records_promise_through_will_method(PromiseInterface $promise, ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->will($promise); $this->getPromise()->shouldReturn($promise); } function it_adds_itself_to_ObjectProphecy_during_call_to_will( ObjectProphecy $objectProphecy, PromiseInterface $promise ) { $objectProphecy->addMethodProphecy($this)->shouldBeCalled(); $this->will($promise); } function it_adds_ReturnPromise_during_willReturn_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willReturn(42); $this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\ReturnPromise'); } function it_adds_CallbackPromise_during_willYield_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willYield(array('foo', 'bar')); $this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\CallbackPromise'); } function it_yields_elements_configured_in_willYield(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willYield(array('foo', 'bar')); $this->getPromise()->execute(array(), $objectProphecy, $this)->shouldYield(array('foo', 'bar')); } function it_yields_key_value_pairs_configured_in_willYield(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willYield(array(10 => 'foo', 11 => 'bar')); $this->getPromise()->execute(array(), $objectProphecy, $this)->shouldYield(array(10 => 'foo', 11 => 'bar')); } function it_yields_and_return_elements_configured_in_willYield(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willYield(array('foo', 'bar'), true); $generator = $this->getPromise()->execute(array(), $objectProphecy, $this); $generator->shouldYield(array('foo', 'bar')); $generator->callOnWrappedObject('getReturn')->shouldReturn(true); } function it_adds_ThrowPromise_during_willThrow_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willThrow('RuntimeException'); $this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\ThrowPromise'); } function it_adds_ReturnArgumentPromise_during_willReturnArgument_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willReturnArgument(); $this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\ReturnArgumentPromise'); } function it_adds_ReturnArgumentPromise_during_willReturnArgument_call_with_index_argument( ObjectProphecy $objectProphecy ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->willReturnArgument(1); $promise = $this->getPromise(); $promise->shouldBeAnInstanceOf('Prophecy\Promise\ReturnArgumentPromise'); $promise->execute(array('one', 'two'), $objectProphecy, $this)->shouldReturn('two'); } function it_adds_CallbackPromise_during_will_call_with_callback_argument(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $callback = function () {}; $this->will($callback); $this->getPromise()->shouldBeAnInstanceOf('Prophecy\Promise\CallbackPromise'); } function it_records_prediction_through_should_method( PredictionInterface $prediction, ObjectProphecy $objectProphecy ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->callOnWrappedObject('should', array($prediction)); $this->getPrediction()->shouldReturn($prediction); } function it_adds_CallbackPrediction_during_should_call_with_callback_argument(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $callback = function () {}; $this->callOnWrappedObject('should', array($callback)); $this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallbackPrediction'); } function it_adds_itself_to_ObjectProphecy_during_call_to_should( ObjectProphecy $objectProphecy, PredictionInterface $prediction ) { $objectProphecy->addMethodProphecy($this)->shouldBeCalled(); $this->callOnWrappedObject('should', array($prediction)); } function it_adds_CallPrediction_during_shouldBeCalled_call($objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->callOnWrappedObject('shouldBeCalled', array()); $this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallPrediction'); } function it_adds_NoCallsPrediction_during_shouldNotBeCalled_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->callOnWrappedObject('shouldNotBeCalled', array()); $this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\NoCallsPrediction'); } function it_adds_CallTimesPrediction_during_shouldBeCalledTimes_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->callOnWrappedObject('shouldBeCalledTimes', array(5)); $this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallTimesPrediction'); } function it_adds_CallTimesPrediction_during_shouldBeCalledOnce_call(ObjectProphecy $objectProphecy) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->callOnWrappedObject('shouldBeCalledOnce'); $this->getPrediction()->shouldBeAnInstanceOf('Prophecy\Prediction\CallTimesPrediction'); } function it_checks_prediction_via_shouldHave_method_call( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, PredictionInterface $prediction, Call $call1, Call $call2 ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled(); $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $this->withArguments($arguments); $this->callOnWrappedObject('shouldHave', array($prediction)); } function it_sets_return_promise_during_shouldHave_call_if_none_was_set_before( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, PredictionInterface $prediction, Call $call1, Call $call2 ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled(); $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $this->withArguments($arguments); $this->callOnWrappedObject('shouldHave', array($prediction)); $this->getPromise()->shouldReturnAnInstanceOf( \PHP_VERSION_ID < 80100 ? 'Prophecy\Promise\ReturnPromise' : 'Prophecy\Promise\CallbackPromise' ); } function it_does_not_set_return_promise_during_shouldHave_call_if_it_was_set_before( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, PredictionInterface $prediction, Call $call1, Call $call2, PromiseInterface $promise ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled(); $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $this->will($promise); $this->withArguments($arguments); $this->callOnWrappedObject('shouldHave', array($prediction)); $this->getPromise()->shouldReturn($promise); } function it_records_checked_predictions( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, PredictionInterface $prediction1, PredictionInterface $prediction2, Call $call1, Call $call2, PromiseInterface $promise ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $prediction1->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->willReturn(); $prediction2->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->willReturn(); $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $this->will($promise); $this->withArguments($arguments); $this->callOnWrappedObject('shouldHave', array($prediction1)); $this->callOnWrappedObject('shouldHave', array($prediction2)); $this->getCheckedPredictions()->shouldReturn(array($prediction1, $prediction2)); } function it_records_even_failed_checked_predictions( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, PredictionInterface $prediction, Call $call1, Call $call2, PromiseInterface $promise ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->willThrow(new RuntimeException()); $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $this->will($promise); $this->withArguments($arguments); try { $this->callOnWrappedObject('shouldHave', array($prediction)); } catch (\Exception $e) { } $this->getCheckedPredictions()->shouldReturn(array($prediction)); } function it_checks_prediction_via_shouldHave_method_call_with_callback( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, Call $call1, Call $call2 ) { $objectProphecy->addMethodProphecy($this)->willReturn(null); $callback = function ($calls, $object, $method) { throw new RuntimeException(); }; $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $this->withArguments($arguments); $this->shouldThrow('RuntimeException')->duringShouldHave($callback); } function it_does_nothing_during_checkPrediction_if_no_prediction_set() { $this->checkPrediction()->shouldReturn(null); } function it_checks_set_prediction_during_checkPrediction( ObjectProphecy $objectProphecy, ArgumentsWildcard $arguments, PredictionInterface $prediction, Call $call1, Call $call2 ) { $prediction->check(array($call1, $call2), $objectProphecy->getWrappedObject(), $this)->shouldBeCalled(); $objectProphecy->findProphecyMethodCalls('getName', $arguments)->willReturn(array($call1, $call2)); $objectProphecy->addMethodProphecy($this)->willReturn(null); $this->withArguments($arguments); $this->callOnWrappedObject('should', array($prediction)); $this->checkPrediction(); } function it_links_back_to_ObjectProphecy_through_getter(ObjectProphecy $objectProphecy) { $this->getObjectProphecy()->shouldReturn($objectProphecy); } function it_has_MethodName() { $this->getMethodName()->shouldReturn('getName'); } function it_contains_ArgumentsWildcard_it_was_constructed_with( ObjectProphecy $objectProphecy, ArgumentsWildcard $wildcard ) { $this->beConstructedWith($objectProphecy, 'getName', $wildcard); $this->getArgumentsWildcard()->shouldReturn($wildcard); } function its_ArgumentWildcard_is_mutable_through_setter(ArgumentsWildcard $wildcard) { $this->withArguments($wildcard); $this->getArgumentsWildcard()->shouldReturn($wildcard); } function its_withArguments_transforms_passed_array_into_ArgumentsWildcard() { $this->withArguments(array(42, 33)); $wildcard = $this->getArgumentsWildcard(); $wildcard->shouldNotBe(null); $wildcard->__toString()->shouldReturn('exact(42), exact(33)'); } function its_withArguments_throws_exception_if_wrong_arguments_provided() { $this->shouldThrow('Prophecy\Exception\InvalidArgumentException')->duringWithArguments(42); } function it_returns_null_for_void_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'void'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBeNull(); } function it_returns_empty_string_for_string_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'string'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe(''); } function it_returns_zero_for_float_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'float'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe(0.00); } function it_returns_false_for_bool_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'bool'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe(false); } function it_returns_empty_for_array_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'array'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe([]); } function it_returns_empty_closure_for_callable_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'callable'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBeAnInstanceOf(\Closure::class); } function it_returns_empty_closure_for_closure_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'Closure'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBeAnInstanceOf(\Closure::class); } function it_returns_null_generator_for_traversable_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'Traversable'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldYieldLike([null]); } function it_returns_null_generator_for_generator_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'Generator'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldYieldLike([null]); } function it_returns_an_object_prophecy_for_other_object_return_types(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'ArrayObject'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $return = $this->getPromise()->execute([], $objectProphecy, $this); $return->shouldBeAnInstanceOf(\ArrayObject::class); $return->shouldImplement(ProphecySubjectInterface::class); } function it_returns_object_prophecy_for_nullable_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', '?ArrayObject'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $return = $this->getPromise()->execute([], $objectProphecy, $this); $return->shouldBeAnInstanceOf(\ArrayObject::class); $return->shouldImplement(ProphecySubjectInterface::class); } function it_returns_scalar_prophecy_for_scalar_and_null_union(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { if (\PHP_VERSION_ID < 80000) { return; } $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'string|null|int'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldNotBeNull(); } function it_returns_object_prophecy_for_object_scalar_union(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { if (\PHP_VERSION_ID < 80000) { return; } $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'string|ArrayObject|int'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $return = $this->getPromise()->execute([], $objectProphecy, $this); $return->shouldBeAnInstanceOf(\ArrayObject::class); $return->shouldImplement(ProphecySubjectInterface::class); } function it_returns_object_prophecy_for_object_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'object'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $return = $this->getPromise()->execute([], $objectProphecy, $this); $return->shouldImplement(ProphecySubjectInterface::class); } function it_throws_for_non_existent_class_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'NonExistentClass'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $return = $this->getPromise()->shouldThrow(MethodProphecyException::class)->during('execute', [[], $objectProphecy, $this]); } function it_returns_true_prophecy_for_true_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { if (\PHP_VERSION_ID < 80200) { return; } $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'true'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe(true); } function it_returns_false_prophecy_for_false_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { if (\PHP_VERSION_ID < 80200) { return; } $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'false'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe(false); } function it_returns_null_prophecy_for_null_return_type(ObjectProphecy $objectProphecy, ArgumentsWildcard $argumentsWildcard) { if (\PHP_VERSION_ID < 80200) { return; } $this->generateMethodProphecyWithReturnValue($objectProphecy, 'foo', 'null'); $this->beConstructedWith($objectProphecy, 'foo', $argumentsWildcard); $this->getPromise()->execute([], $objectProphecy, $this)->shouldBe(null); } private function generateMethodProphecyWithReturnValue($objectProphecy, string $methodName, string $returnType): void { $objectProphecy->reveal()->willReturn( eval( <<addMethodProphecy(Argument::any())->willReturn(); } } class ClassWithFinalMethod { final public function finalMethod() {} } class ClassWithVoidTypeHintedMethods { public function getVoid(): void {} } ================================================ FILE: spec/Prophecy/Prophecy/ObjectProphecySpec.php ================================================ beConstructedWith($lazyDouble); $lazyDouble->getInstance()->willReturn($double); } function it_implements_ProphecyInterface() { $this->shouldBeAnInstanceOf('Prophecy\Prophecy\ProphecyInterface'); } function it_sets_parentClass_during_willExtend_call($lazyDouble) { $lazyDouble->setParentClass('123')->shouldBeCalled(); $this->willExtend('123'); } function it_adds_interface_during_willImplement_call($lazyDouble) { $lazyDouble->addInterface('222')->shouldBeCalled(); $this->willImplement('222'); } function it_sets_constructor_arguments_during_willBeConstructedWith_call($lazyDouble) { $lazyDouble->setArguments(array(1, 2, 5))->shouldBeCalled(); $this->willBeConstructedWith(array(1, 2, 5)); } function it_does_not_have_method_prophecies_by_default() { $this->getMethodProphecies()->shouldHaveCount(0); } function it_should_get_method_prophecies_by_method_name( MethodProphecy $method1, MethodProphecy $method2, ArgumentsWildcard $arguments ) { $method1->getMethodName()->willReturn('getName'); $method1->getArgumentsWildcard()->willReturn($arguments); $method2->getMethodName()->willReturn('setName'); $method2->getArgumentsWildcard()->willReturn($arguments); $this->addMethodProphecy($method1); $this->addMethodProphecy($method2); $methods = $this->getMethodProphecies('setName'); $methods->shouldHaveCount(1); $methods[0]->getMethodName()->shouldReturn('setName'); } function it_should_return_empty_array_if_no_method_prophecies_found() { $methods = $this->getMethodProphecies('setName'); $methods->shouldHaveCount(0); } function it_should_proxy_makeProphecyMethodCall_to_CallCenter($lazyDouble, CallCenter $callCenter) { $this->beConstructedWith($lazyDouble, $callCenter); $callCenter->makeCall($this->getWrappedObject(), 'setName', array('everzet'))->willReturn(42); $this->makeProphecyMethodCall('setName', array('everzet'))->shouldReturn(42); } function it_should_reveal_arguments_and_return_values_from_callCenter( $lazyDouble, CallCenter $callCenter, RevealerInterface $revealer ) { $this->beConstructedWith($lazyDouble, $callCenter, $revealer); $revealer->reveal(array('question'))->willReturn(array('life')); $revealer->reveal('answer')->willReturn(42); $callCenter->makeCall($this->getWrappedObject(), 'setName', array('life'))->willReturn('answer'); $this->makeProphecyMethodCall('setName', array('question'))->shouldReturn(42); } function it_should_proxy_getProphecyMethodCalls_to_CallCenter( $lazyDouble, CallCenter $callCenter, ArgumentsWildcard $wildcard, Call $call ) { $this->beConstructedWith($lazyDouble, $callCenter); $callCenter->findCalls('setName', $wildcard)->willReturn(array($call)); $this->findProphecyMethodCalls('setName', $wildcard)->shouldReturn(array($call)); } function its_addMethodProphecy_adds_method_prophecy( MethodProphecy $methodProphecy, ArgumentsWildcard $argumentsWildcard ) { $methodProphecy->getArgumentsWildcard()->willReturn($argumentsWildcard); $methodProphecy->getMethodName()->willReturn('getUsername'); $this->addMethodProphecy($methodProphecy); $this->getMethodProphecies()->shouldReturn(array( 'getusername' => array($methodProphecy), )); } function its_addMethodProphecy_handles_prophecies_with_different_arguments( MethodProphecy $methodProphecy1, MethodProphecy $methodProphecy2, ArgumentsWildcard $argumentsWildcard1, ArgumentsWildcard $argumentsWildcard2 ) { $methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1); $methodProphecy1->getMethodName()->willReturn('getUsername'); $methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2); $methodProphecy2->getMethodName()->willReturn('getUsername'); $this->addMethodProphecy($methodProphecy1); $this->addMethodProphecy($methodProphecy2); $this->getMethodProphecies()->shouldReturn(array( 'getusername' => array( $methodProphecy1, $methodProphecy2, ), )); } function its_addMethodProphecy_handles_prophecies_for_caseinsensitive_method_names( MethodProphecy $methodProphecy1, MethodProphecy $methodProphecy2, ArgumentsWildcard $argumentsWildcard1, ArgumentsWildcard $argumentsWildcard2 ) { $methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1); $methodProphecy1->getMethodName()->willReturn('getUsername'); $methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2); $methodProphecy2->getMethodName()->willReturn('getUserName'); $this->addMethodProphecy($methodProphecy1); $this->addMethodProphecy($methodProphecy2); $this->getMethodProphecies()->shouldReturn(array( 'getusername' => array( $methodProphecy1, $methodProphecy2, ), )); } function its_addMethodProphecy_handles_prophecies_for_different_methods( MethodProphecy $methodProphecy1, MethodProphecy $methodProphecy2, ArgumentsWildcard $argumentsWildcard1, ArgumentsWildcard $argumentsWildcard2 ) { $methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1); $methodProphecy1->getMethodName()->willReturn('getUsername'); $methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2); $methodProphecy2->getMethodName()->willReturn('isUsername'); $this->addMethodProphecy($methodProphecy1); $this->addMethodProphecy($methodProphecy2); $this->getMethodProphecies()->shouldReturn(array( 'getusername' => array( $methodProphecy1, ), 'isusername' => array( $methodProphecy2, ), )); } function it_returns_null_after_checkPredictions_call_if_there_is_no_method_prophecies() { $this->checkProphecyMethodsPredictions()->shouldReturn(null); } function it_throws_AggregateException_during_checkPredictions_if_predictions_fail( MethodProphecy $methodProphecy1, MethodProphecy $methodProphecy2, ArgumentsWildcard $argumentsWildcard1, ArgumentsWildcard $argumentsWildcard2 ) { $methodProphecy1->getMethodName()->willReturn('getName'); $methodProphecy1->getArgumentsWildcard()->willReturn($argumentsWildcard1); $methodProphecy1->checkPrediction() ->willThrow('Prophecy\Exception\Prediction\AggregateException'); $methodProphecy2->getMethodName()->willReturn('setName'); $methodProphecy2->getArgumentsWildcard()->willReturn($argumentsWildcard2); $methodProphecy2->checkPrediction() ->willThrow('Prophecy\Exception\Prediction\AggregateException'); $this->addMethodProphecy($methodProphecy1); $this->addMethodProphecy($methodProphecy2); $this->shouldThrow('Prophecy\Exception\Prediction\AggregateException') ->duringCheckProphecyMethodsPredictions(); } function it_returns_new_MethodProphecy_instance_for_arbitrary_call( Doubler $doubler, ProphecySubjectInterface $reflection ) { $doubler->double(Argument::any())->willReturn($reflection); $return = $this->getProphecy(); $return->shouldBeAnInstanceOf('Prophecy\Prophecy\MethodProphecy'); $return->getMethodName()->shouldReturn('getProphecy'); } function it_returns_same_MethodProphecy_for_same_registered_signature( Doubler $doubler, ProphecySubjectInterface $reflection ) { $doubler->double(Argument::any())->willReturn($reflection); $this->addMethodProphecy($methodProphecy1 = $this->getProphecy(1, 2, 3)); $methodProphecy2 = $this->getProphecy(1, 2, 3); $methodProphecy2->shouldBe($methodProphecy1); } function it_returns_new_MethodProphecy_for_different_signatures( Doubler $doubler, ProphecySubjectInterface $reflection ) { $doubler->double(Argument::any())->willReturn($reflection); $value = new ObjectProphecySpecFixtureB('ABC'); $value2 = new ObjectProphecySpecFixtureB('CBA'); $this->addMethodProphecy($methodProphecy1 = $this->getProphecy(1, 2, 3, $value)); $methodProphecy2 = $this->getProphecy(1, 2, 3, $value2); $methodProphecy2->shouldNotBe($methodProphecy1); } function it_returns_new_MethodProphecy_for_all_callback_signatures( Doubler $doubler, ProphecySubjectInterface $reflection ) { $doubler->double(Argument::any())->willReturn($reflection); $this->addMethodProphecy($methodProphecy1 = $this->getProphecy(function () {})); $methodProphecy2 = $this->getProphecy(function () {}); $methodProphecy2->shouldNotBe($methodProphecy1); } function it_throws_UnexpectedCallException_during_checkPredictions_if_unexpected_method_was_called( $lazyDouble, CallCenter $callCenter ) { $this->beConstructedWith($lazyDouble, $callCenter); $callCenter->checkUnexpectedCalls()->willThrow('Prophecy\Exception\Call\UnexpectedCallException'); $this->shouldThrow('Prophecy\Exception\Call\UnexpectedCallException') ->duringCheckProphecyMethodsPredictions(); } } class ObjectProphecySpecFixtureA { public $errors; } class ObjectProphecySpecFixtureB extends ObjectProphecySpecFixtureA { public $errors; public $value = null; public function __construct($value) { $this->value = $value; } } ================================================ FILE: spec/Prophecy/Prophecy/RevealerSpec.php ================================================ shouldBeAnInstanceOf('Prophecy\Prophecy\RevealerInterface'); } function it_reveals_single_instance_of_ProphecyInterface(ProphecyInterface $prophecy, \stdClass $object) { $prophecy->reveal()->willReturn($object); $this->reveal($prophecy)->shouldReturn($object); } function it_reveals_instances_of_ProphecyInterface_inside_array( ProphecyInterface $prophecy1, ProphecyInterface $prophecy2, \stdClass $object1, \stdClass $object2 ) { $prophecy1->reveal()->willReturn($object1); $prophecy2->reveal()->willReturn($object2); $this->reveal(array( array('item' => $prophecy2), $prophecy1, ))->shouldReturn(array( array('item' => $object2), $object1, )); } function it_does_not_touch_non_prophecy_interface() { $this->reveal(42)->shouldReturn(42); } } ================================================ FILE: spec/Prophecy/ProphetSpec.php ================================================ double(null, array())->willReturn($double); $this->beConstructedWith($doubler); } function it_constructs_new_prophecy_on_prophesize_call() { $prophecy = $this->prophesize(); $prophecy->shouldBeAnInstanceOf('Prophecy\Prophecy\ObjectProphecy'); } function it_constructs_new_prophecy_with_parent_class_if_specified($doubler, ProphecySubjectInterface $newDouble) { $doubler->double(Argument::any(), array())->willReturn($newDouble); $this->prophesize('Prophecy\Prophet')->reveal()->shouldReturn($newDouble); } function it_constructs_new_prophecy_with_interface_if_specified($doubler, ProphecySubjectInterface $newDouble) { $doubler->double(null, Argument::any())->willReturn($newDouble); $this->prophesize('ArrayAccess')->reveal()->shouldReturn($newDouble); } function it_exposes_all_created_prophecies_through_getter() { $prophecy1 = $this->prophesize(); $prophecy2 = $this->prophesize(); $this->getProphecies()->shouldReturn(array($prophecy1, $prophecy2)); } function it_does_nothing_during_checkPredictions_call_if_no_predictions_defined() { $this->checkPredictions()->shouldReturn(null); } function it_throws_AggregateException_if_defined_predictions_fail( MethodProphecy $method1, MethodProphecy $method2, ArgumentsWildcard $arguments1, ArgumentsWildcard $arguments2 ) { $method1->getMethodName()->willReturn('getName'); $method1->getArgumentsWildcard()->willReturn($arguments1); $method1->checkPrediction()->willReturn(null); $method2->getMethodName()->willReturn('isSet'); $method2->getArgumentsWildcard()->willReturn($arguments2); $method2->checkPrediction()->willThrow( 'Prophecy\Exception\Prediction\AggregateException' ); $this->prophesize()->addMethodProphecy($method1); $this->prophesize()->addMethodProphecy($method2); $this->shouldThrow('Prophecy\Exception\Prediction\AggregateException') ->duringCheckPredictions(); } function it_exposes_doubler_through_getter($doubler) { $this->getDoubler()->shouldReturn($doubler); } function it_throws_ClassNotFound_if_class_to_prophesize_does_not_exist() { $this->shouldThrow('Prophecy\Exception\Doubler\ClassNotFoundException') ->duringProphesize('This\ClassOrInterface\Does\Not\Exist'); } function it_does_not_throw_when_creating_void_mock() { $this->shouldNotThrow() ->duringProphesize(); } } ================================================ FILE: spec/Prophecy/Util/StringUtilSpec.php ================================================ stringify(42)->shouldReturn('42'); } function it_generates_proper_string_representation_for_string() { $this->stringify('some string')->shouldReturn('"some string"'); } function it_generates_single_line_representation_for_multiline_string() { $this->stringify("some\nstring")->shouldReturn('"some\\nstring"'); } function it_generates_proper_string_representation_for_double() { $this->stringify(42.3)->shouldReturn('42.3'); } function it_generates_proper_string_representation_for_boolean_true() { $this->stringify(true)->shouldReturn('true'); } function it_generates_proper_string_representation_for_boolean_false() { $this->stringify(false)->shouldReturn('false'); } function it_generates_proper_string_representation_for_null() { $this->stringify(null)->shouldReturn('null'); } function it_generates_proper_string_representation_for_empty_array() { $this->stringify(array())->shouldReturn('[]'); } function it_generates_proper_string_representation_for_array() { $this->stringify(array('zet', 42))->shouldReturn('["zet", 42]'); } function it_generates_proper_string_representation_for_hash_containing_one_value() { $this->stringify(array('ever' => 'zet'))->shouldReturn('["ever" => "zet"]'); } function it_generates_proper_string_representation_for_hash() { $this->stringify(array('ever' => 'zet', 52 => 'hey', 'num' => 42))->shouldReturn( '["ever" => "zet", 52 => "hey", "num" => 42]' ); } function it_generates_proper_string_representation_for_resource() { $resource = fopen(__FILE__, 'r'); $this->stringify($resource)->shouldReturn('stream:'.$resource); } function it_generates_proper_string_representation_for_object(\stdClass $object) { $objHash = sprintf('%s#%s', get_class($object->getWrappedObject()), spl_object_id($object->getWrappedObject()) )." Object (\n 'objectProphecyClosure' => Closure#%s Object (\n 0 => Closure#%s Object\n )\n)"; $idRegexExpr = '[0-9]+'; $this->stringify($object)->shouldMatch(sprintf('/^%s$/', sprintf(preg_quote("$objHash"), $idRegexExpr, $idRegexExpr))); } function it_generates_proper_string_representation_for_object_without_exporting(\stdClass $object) { $objHash = sprintf('%s#%s', get_class($object->getWrappedObject()), spl_object_id($object->getWrappedObject()) ); $this->stringify($object, false)->shouldReturn("$objHash"); } } ================================================ FILE: src/Prophecy/Argument/ArgumentsWildcard.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument; /** * Arguments wildcarding. * * @author Konstantin Kudryashov */ class ArgumentsWildcard { /** * @var list */ private $tokens = array(); /** * @var string|null */ private $string; /** * Initializes wildcard. * * @param array $arguments Array of argument tokens or values */ public function __construct(array $arguments) { foreach ($arguments as $argument) { if (!$argument instanceof Token\TokenInterface) { $argument = new Token\ExactValueToken($argument); } $this->tokens[] = $argument; } } /** * Calculates wildcard match score for provided arguments. * * @param array $arguments * * @return false|int False OR integer score (higher - better) */ public function scoreArguments(array $arguments) { if (0 == count($arguments) && 0 == count($this->tokens)) { return 1; } $arguments = array_values($arguments); $totalScore = 0; foreach ($this->tokens as $i => $token) { $argument = isset($arguments[$i]) ? $arguments[$i] : null; if (1 >= $score = $token->scoreArgument($argument)) { return false; } $totalScore += $score; if (true === $token->isLast()) { return $totalScore; } } if (count($arguments) > count($this->tokens)) { return false; } return $totalScore; } /** * Returns string representation for wildcard. * * @return string */ public function __toString() { if (null === $this->string) { $this->string = implode(', ', array_map(function ($token) { return (string) $token; }, $this->tokens)); } return $this->string; } /** * @return list */ public function getTokens() { return $this->tokens; } } ================================================ FILE: src/Prophecy/Argument/Token/AnyValueToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Any single value token. * * @author Konstantin Kudryashov */ class AnyValueToken implements TokenInterface { /** * Always scores 3 for any argument. * * @param mixed $argument * * @return int */ public function scoreArgument($argument) { return 3; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return '*'; } } ================================================ FILE: src/Prophecy/Argument/Token/AnyValuesToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Any values token. * * @author Konstantin Kudryashov */ class AnyValuesToken implements TokenInterface { /** * Always scores 2 for any argument. * * @param $argument * * @return int */ public function scoreArgument($argument) { return 2; } /** * Returns true to stop wildcard from processing other tokens. * * @return bool */ public function isLast() { return true; } /** * Returns string representation for token. * * @return string */ public function __toString() { return '* [, ...]'; } } ================================================ FILE: src/Prophecy/Argument/Token/ApproximateValueToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Approximate value token * * @author Daniel Leech */ class ApproximateValueToken implements TokenInterface { private $value; private $precision; /** * @param float $value * @param int $precision */ public function __construct($value, $precision = 0) { $this->value = $value; $this->precision = $precision; } /** * {@inheritdoc} */ public function scoreArgument($argument) { if (!\is_float($argument) && !\is_int($argument) && !\is_numeric($argument)) { return false; } return round((float) $argument, $this->precision) === round($this->value, $this->precision) ? 10 : false; } /** * {@inheritdoc} */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('≅%s', round($this->value, $this->precision)); } } ================================================ FILE: src/Prophecy/Argument/Token/ArrayCountToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Array elements count token. * * @author Boris Mikhaylov */ class ArrayCountToken implements TokenInterface { private $count; /** * @param integer $value */ public function __construct($value) { $this->count = $value; } /** * Scores 6 when argument has preset number of elements. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument) { return $this->isCountable($argument) && $this->hasProperCount($argument) ? 6 : false; } /** * Returns false. * * @return boolean */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('count(%s)', $this->count); } /** * Returns true if object is either array or instance of \Countable * * @param mixed $argument * @return bool * * @phpstan-assert-if-true array|\Countable $argument */ private function isCountable($argument) { return (is_array($argument) || $argument instanceof \Countable); } /** * Returns true if $argument has expected number of elements * * @param array|\Countable $argument * * @return bool */ private function hasProperCount($argument) { return $this->count === count($argument); } } ================================================ FILE: src/Prophecy/Argument/Token/ArrayEntryToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; use Prophecy\Exception\InvalidArgumentException; /** * Array entry token. * * @author Boris Mikhaylov */ class ArrayEntryToken implements TokenInterface { /** @var TokenInterface */ private $key; /** @var TokenInterface */ private $value; /** * @param mixed $key exact value or token * @param mixed $value exact value or token */ public function __construct($key, $value) { $this->key = $this->wrapIntoExactValueToken($key); $this->value = $this->wrapIntoExactValueToken($value); } /** * Scores half of combined scores from key and value tokens for same entry. Capped at 8. * If argument implements \ArrayAccess without \Traversable, then key token is restricted to ExactValueToken. * * @param mixed $argument * * @throws InvalidArgumentException * @return false|int */ public function scoreArgument($argument) { if ($argument instanceof \Traversable) { $argument = iterator_to_array($argument); } if ($argument instanceof \ArrayAccess) { $argument = $this->convertArrayAccessToEntry($argument); } if (!is_array($argument) || empty($argument)) { return false; } $keyScores = array_map(array($this->key,'scoreArgument'), array_keys($argument)); $valueScores = array_map(array($this->value,'scoreArgument'), $argument); $scoreEntry = static function ($value, $key) { return $value && $key ? (int) min(8, ($key + $value) / 2) : false; }; return max(array_map($scoreEntry, $valueScores, $keyScores)); } /** * Returns false. * * @return boolean */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('[..., %s => %s, ...]', $this->key, $this->value); } /** * Returns key * * @return TokenInterface */ public function getKey() { return $this->key; } /** * Returns value * * @return TokenInterface */ public function getValue() { return $this->value; } /** * Wraps non token $value into ExactValueToken * * @param mixed $value * @return TokenInterface */ private function wrapIntoExactValueToken($value) { return $value instanceof TokenInterface ? $value : new ExactValueToken($value); } /** * Converts instance of \ArrayAccess to key => value array entry * * @param \ArrayAccess $object * * @return array * @throws InvalidArgumentException */ private function convertArrayAccessToEntry(\ArrayAccess $object) { if (!$this->key instanceof ExactValueToken) { throw new InvalidArgumentException(sprintf( 'You can only use exact value tokens to match key of ArrayAccess object'.PHP_EOL .'But you used `%s`.', $this->key )); } $key = $this->key->getValue(); if (!\is_int($key) && !\is_string($key)) { throw new InvalidArgumentException(sprintf( 'You can only use integer or string keys to match key of ArrayAccess object'.PHP_EOL .'But you used `%s`.', $this->key )); } return $object->offsetExists($key) ? array($key => $object[$key]) : array(); } } ================================================ FILE: src/Prophecy/Argument/Token/ArrayEveryEntryToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Array every entry token. * * @author Adrien Brault */ class ArrayEveryEntryToken implements TokenInterface { /** * @var TokenInterface */ private $value; /** * @param mixed $value exact value or token */ public function __construct($value) { if (!$value instanceof TokenInterface) { $value = new ExactValueToken($value); } $this->value = $value; } /** * {@inheritdoc} */ public function scoreArgument($argument) { if (!$argument instanceof \Traversable && !is_array($argument)) { return false; } $scores = array(); foreach ($argument as $key => $argumentEntry) { $scores[] = $this->value->scoreArgument($argumentEntry); } if (empty($scores) || in_array(false, $scores, true)) { return false; } return array_sum($scores) / count($scores); } /** * {@inheritdoc} */ public function isLast() { return false; } /** * {@inheritdoc} */ public function __toString() { return sprintf('[%s, ..., %s]', $this->value, $this->value); } /** * @return TokenInterface */ public function getValue() { return $this->value; } } ================================================ FILE: src/Prophecy/Argument/Token/CallbackToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; use Prophecy\Exception\InvalidArgumentException; /** * Callback-verified token. * * @author Konstantin Kudryashov */ class CallbackToken implements TokenInterface { private $callback; /** * @var string|null */ private $customStringRepresentation; /** * Initializes token. * * @param callable $callback * @param string|null $customStringRepresentation Customize the __toString() representation of this token * * @throws \Prophecy\Exception\InvalidArgumentException */ public function __construct($callback, ?string $customStringRepresentation = null) { if (!is_callable($callback)) { throw new InvalidArgumentException(sprintf( 'Callable expected as an argument to CallbackToken, but got %s.', gettype($callback) )); } $this->callback = $callback; $this->customStringRepresentation = $customStringRepresentation; } /** * Scores 7 if callback returns true, false otherwise. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument) { return call_user_func($this->callback, $argument) ? 7 : false; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { if ($this->customStringRepresentation !== null) { return $this->customStringRepresentation; } return 'callback()'; } } ================================================ FILE: src/Prophecy/Argument/Token/ExactValueToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; use Prophecy\Comparator\FactoryProvider; use SebastianBergmann\Comparator\ComparisonFailure; use SebastianBergmann\Comparator\Factory as ComparatorFactory; use Prophecy\Util\StringUtil; /** * Exact value token. * * @author Konstantin Kudryashov */ class ExactValueToken implements TokenInterface { private $value; /** * @var string|null */ private $string; private $util; private $comparatorFactory; /** * Initializes token. * * @param mixed $value */ public function __construct($value, ?StringUtil $util = null, ?ComparatorFactory $comparatorFactory = null) { $this->value = $value; $this->util = $util ?: new StringUtil(); $this->comparatorFactory = $comparatorFactory ?: FactoryProvider::getInstance(); } /** * Scores 10 if argument matches preset value. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument) { if (is_object($argument) && is_object($this->value)) { $comparator = $this->comparatorFactory->getComparatorFor( $argument, $this->value ); try { $comparator->assertEquals($argument, $this->value); return 10; } catch (ComparisonFailure $failure) { return false; } } // If either one is an object it should be castable to a string if (is_object($argument) xor is_object($this->value)) { if (is_object($argument) && !method_exists($argument, '__toString')) { return false; } if (is_object($this->value) && !method_exists($this->value, '__toString')) { return false; } if (is_numeric($argument) xor is_numeric($this->value)) { return strval($argument) == strval($this->value) ? 10 : false; } } elseif (is_numeric($argument) && is_numeric($this->value)) { // noop } elseif (gettype($argument) !== gettype($this->value)) { return false; } return $argument == $this->value ? 10 : false; } /** * Returns preset value against which token checks arguments. * * @return mixed */ public function getValue() { return $this->value; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { if (null === $this->string) { $this->string = sprintf('exact(%s)', $this->util->stringify($this->value)); } return $this->string; } } ================================================ FILE: src/Prophecy/Argument/Token/IdenticalValueToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; use Prophecy\Util\StringUtil; /** * Identical value token. * * @author Florian Voutzinos */ class IdenticalValueToken implements TokenInterface { private $value; /** * @var string|null */ private $string; private $util; /** * Initializes token. * * @param mixed $value */ public function __construct($value, ?StringUtil $util = null) { $this->value = $value; $this->util = $util ?: new StringUtil(); } /** * Scores 11 if argument matches preset value. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument) { return $argument === $this->value ? 11 : false; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { if (null === $this->string) { $this->string = sprintf('identical(%s)', $this->util->stringify($this->value)); } return $this->string; } } ================================================ FILE: src/Prophecy/Argument/Token/InArrayToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Check if values is in array * * @author Vinícius Alonso */ class InArrayToken implements TokenInterface { private $token = array(); private $strict; /** * @param array $arguments tokens * @param bool $strict */ public function __construct(array $arguments, $strict = true) { $this->token = $arguments; $this->strict = $strict; } /** * Return scores 8 score if argument is in array. * * @param $argument * * @return bool|int */ public function scoreArgument($argument) { if (count($this->token) === 0) { return false; } if (\in_array($argument, $this->token, $this->strict)) { return 8; } return false; } /** * Returns false. * * @return boolean */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { $arrayAsString = implode(', ', $this->token); return "[{$arrayAsString}]"; } } ================================================ FILE: src/Prophecy/Argument/Token/LogicalAndToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Logical AND token. * * @author Boris Mikhaylov */ class LogicalAndToken implements TokenInterface { /** * @var list */ private $tokens = array(); /** * @param array $arguments exact values or tokens */ public function __construct(array $arguments) { foreach ($arguments as $argument) { if (!$argument instanceof TokenInterface) { $argument = new ExactValueToken($argument); } $this->tokens[] = $argument; } } /** * Scores maximum score from scores returned by tokens for this argument if all of them score. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument) { if (0 === count($this->tokens)) { return false; } $maxScore = 0; foreach ($this->tokens as $token) { $score = $token->scoreArgument($argument); if (false === $score) { return false; } $maxScore = max($score, $maxScore); } return $maxScore; } /** * Returns false. * * @return boolean */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('bool(%s)', implode(' AND ', $this->tokens)); } } ================================================ FILE: src/Prophecy/Argument/Token/LogicalNotToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Logical NOT token. * * @author Boris Mikhaylov */ class LogicalNotToken implements TokenInterface { /** @var TokenInterface */ private $token; /** * @param mixed $value exact value or token */ public function __construct($value) { $this->token = $value instanceof TokenInterface ? $value : new ExactValueToken($value); } /** * Scores 4 when preset token does not match the argument. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument) { return false === $this->token->scoreArgument($argument) ? 4 : false; } /** * Returns true if preset token is last. * * @return bool */ public function isLast() { return $this->token->isLast(); } /** * Returns originating token. * * @return TokenInterface */ public function getOriginatingToken() { return $this->token; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('not(%s)', $this->token); } } ================================================ FILE: src/Prophecy/Argument/Token/NotInArrayToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Check if values is not in array * * @author Vinícius Alonso */ class NotInArrayToken implements TokenInterface { private $token = array(); private $strict; /** * @param array $arguments tokens * @param bool $strict */ public function __construct(array $arguments, $strict = true) { $this->token = $arguments; $this->strict = $strict; } /** * Return scores 8 score if argument is in array. * * @param $argument * * @return bool|int */ public function scoreArgument($argument) { if (count($this->token) === 0) { return false; } if (!\in_array($argument, $this->token, $this->strict)) { return 8; } return false; } /** * Returns false. * * @return boolean */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { $arrayAsString = implode(', ', $this->token); return "[{$arrayAsString}]"; } } ================================================ FILE: src/Prophecy/Argument/Token/ObjectStateToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; use Prophecy\Comparator\FactoryProvider; use SebastianBergmann\Comparator\ComparisonFailure; use SebastianBergmann\Comparator\Factory as ComparatorFactory; use Prophecy\Util\StringUtil; /** * Object state-checker token. * * @author Konstantin Kudryashov */ class ObjectStateToken implements TokenInterface { private $name; private $value; private $util; private $comparatorFactory; /** * Initializes token. * * @param string $methodName * @param mixed $value Expected return value */ public function __construct( $methodName, $value, ?StringUtil $util = null, ?ComparatorFactory $comparatorFactory = null ) { $this->name = $methodName; $this->value = $value; $this->util = $util ?: new StringUtil(); $this->comparatorFactory = $comparatorFactory ?: FactoryProvider::getInstance(); } /** * Scores 8 if argument is an object, which method returns expected value. * * @param mixed $argument * * @return bool|int */ public function scoreArgument($argument) { $methodCallable = array($argument, $this->name); if (is_object($argument) && method_exists($argument, $this->name) && is_callable($methodCallable)) { $actual = call_user_func($methodCallable); $comparator = $this->comparatorFactory->getComparatorFor( $this->value, $actual ); try { $comparator->assertEquals($this->value, $actual); return 8; } catch (ComparisonFailure $failure) { return false; } } if (is_object($argument) && property_exists($argument, $this->name)) { return $argument->{$this->name} === $this->value ? 8 : false; } return false; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('state(%s(), %s)', $this->name, $this->util->stringify($this->value) ); } } ================================================ FILE: src/Prophecy/Argument/Token/StringContainsToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * String contains token. * * @author Peter Mitchell */ class StringContainsToken implements TokenInterface { private $value; /** * Initializes token. * * @param string $value */ public function __construct($value) { $this->value = $value; } public function scoreArgument($argument) { return is_string($argument) && strpos($argument, $this->value) !== false ? 6 : false; } /** * Returns preset value against which token checks arguments. * * @return mixed */ public function getValue() { return $this->value; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('contains("%s")', $this->value); } } ================================================ FILE: src/Prophecy/Argument/Token/TokenInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; /** * Argument token interface. * * @author Konstantin Kudryashov */ interface TokenInterface { /** * Calculates token match score for provided argument. * * @param mixed $argument * * @return false|int */ public function scoreArgument($argument); /** * Returns true if this token prevents check of other tokens (is last one). * * @return bool */ public function isLast(); /** * Returns string representation for token. * * @return string */ public function __toString(); } ================================================ FILE: src/Prophecy/Argument/Token/TypeToken.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Argument\Token; use Prophecy\Exception\InvalidArgumentException; /** * Value type token. * * @author Konstantin Kudryashov */ class TypeToken implements TokenInterface { private $type; /** * @param string $type */ public function __construct($type) { $checker = "is_{$type}"; if (!function_exists($checker) && !interface_exists($type) && !class_exists($type)) { throw new InvalidArgumentException(sprintf( 'Type or class name expected as an argument to TypeToken, but got %s.', $type )); } $this->type = $type; } /** * Scores 5 if argument has the same type this token was constructed with. * * @param $argument * * @return bool|int */ public function scoreArgument($argument) { $checker = "is_{$this->type}"; if (function_exists($checker)) { return call_user_func($checker, $argument) ? 5 : false; } return $argument instanceof $this->type ? 5 : false; } /** * Returns false. * * @return bool */ public function isLast() { return false; } /** * Returns string representation for token. * * @return string */ public function __toString() { return sprintf('type(%s)', $this->type); } } ================================================ FILE: src/Prophecy/Argument.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy; use Prophecy\Argument\Token; /** * Argument tokens shortcuts. * * @author Konstantin Kudryashov */ class Argument { /** * Checks that argument is exact value or object. * * @param mixed $value * * @return Token\ExactValueToken */ public static function exact($value) { return new Token\ExactValueToken($value); } /** * Checks that argument is of specific type or instance of specific class. * * @param string $type Type name (`integer`, `string`) or full class name * * @return Token\TypeToken */ public static function type($type) { return new Token\TypeToken($type); } /** * Checks that argument object has specific state. * * @param string $methodName * @param mixed $value * * @return Token\ObjectStateToken */ public static function which($methodName, $value) { return new Token\ObjectStateToken($methodName, $value); } /** * Checks that argument matches provided callback. * * @param callable $callback * @param string|null $customStringRepresentation Customize the __toString() representation of this token * * @return Token\CallbackToken */ public static function that($callback, ?string $customStringRepresentation = null) { return new Token\CallbackToken($callback, $customStringRepresentation); } /** * Matches any single value. * * @return Token\AnyValueToken */ public static function any() { return new Token\AnyValueToken(); } /** * Matches all values to the rest of the signature. * * @return Token\AnyValuesToken */ public static function cetera() { return new Token\AnyValuesToken(); } /** * Checks that argument matches all tokens * * @param mixed ...$tokens a list of tokens * * @return Token\LogicalAndToken */ public static function allOf(...$tokens) { return new Token\LogicalAndToken($tokens); } /** * Checks that argument array or countable object has exact number of elements. * * @param integer $value array elements count * * @return Token\ArrayCountToken */ public static function size($value) { return new Token\ArrayCountToken($value); } /** * Checks that argument array contains (key, value) pair * * @param mixed $key exact value or token * @param mixed $value exact value or token * * @return Token\ArrayEntryToken */ public static function withEntry($key, $value) { return new Token\ArrayEntryToken($key, $value); } /** * Checks that arguments array entries all match value * * @param mixed $value * * @return Token\ArrayEveryEntryToken */ public static function withEveryEntry($value) { return new Token\ArrayEveryEntryToken($value); } /** * Checks that argument array contains value * * @param mixed $value * * @return Token\ArrayEntryToken */ public static function containing($value) { return new Token\ArrayEntryToken(self::any(), $value); } /** * Checks that argument array has key * * @param mixed $key exact value or token * * @return Token\ArrayEntryToken */ public static function withKey($key) { return new Token\ArrayEntryToken($key, self::any()); } /** * Checks that argument does not match the value|token. * * @param mixed $value either exact value or argument token * * @return Token\LogicalNotToken */ public static function not($value) { return new Token\LogicalNotToken($value); } /** * @param string $value * * @return Token\StringContainsToken */ public static function containingString($value) { return new Token\StringContainsToken($value); } /** * Checks that argument is identical value. * * @param mixed $value * * @return Token\IdenticalValueToken */ public static function is($value) { return new Token\IdenticalValueToken($value); } /** * Check that argument is same value when rounding to the * given precision. * * @param float $value * @param int $precision * * @return Token\ApproximateValueToken */ public static function approximate($value, $precision = 0) { return new Token\ApproximateValueToken($value, $precision); } /** * Checks that argument is in array. * * @param array $value * * @return Token\InArrayToken */ public static function in($value) { return new Token\InArrayToken($value); } /** * Checks that argument is not in array. * * @param array $value * * @return Token\NotInArrayToken */ public static function notIn($value) { return new Token\NotInArrayToken($value); } } ================================================ FILE: src/Prophecy/Call/Call.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Call; use Exception; use Prophecy\Argument\ArgumentsWildcard; /** * Call object. * * @author Konstantin Kudryashov */ class Call { private $methodName; private $arguments; private $returnValue; private $exception; /** * @var string|null */ private $file; /** * @var int|null */ private $line; /** * @var \SplObjectStorage */ private $scores; /** * Initializes call. * * @param string $methodName * @param array $arguments * @param mixed $returnValue * @param Exception|null $exception * @param null|string $file * @param null|int $line */ public function __construct($methodName, array $arguments, $returnValue, ?Exception $exception, $file, $line) { $this->methodName = $methodName; $this->arguments = $arguments; $this->returnValue = $returnValue; $this->exception = $exception; $this->scores = new \SplObjectStorage(); if ($file) { $this->file = $file; $this->line = intval($line); } } /** * Returns called method name. * * @return string */ public function getMethodName() { return $this->methodName; } /** * Returns called method arguments. * * @return array */ public function getArguments() { return $this->arguments; } /** * Returns called method return value. * * @return null|mixed */ public function getReturnValue() { return $this->returnValue; } /** * Returns exception that call thrown. * * @return null|Exception */ public function getException() { return $this->exception; } /** * Returns callee filename. * * @return string|null */ public function getFile() { return $this->file; } /** * Returns callee line number. * * @return int|null */ public function getLine() { return $this->line; } /** * Returns short notation for callee place. * * @return string */ public function getCallPlace() { if (null === $this->file) { return 'unknown'; } return sprintf('%s:%d', $this->file, $this->line); } /** * Adds the wildcard match score for the provided wildcard. * * @param ArgumentsWildcard $wildcard * @param false|int $score * * @return $this */ public function addScore(ArgumentsWildcard $wildcard, $score) { $this->scores[$wildcard] = $score; return $this; } /** * Returns wildcard match score for the provided wildcard. The score is * calculated if not already done. * * @param ArgumentsWildcard $wildcard * * @return false|int False OR integer score (higher - better) */ public function getScore(ArgumentsWildcard $wildcard) { if (isset($this->scores[$wildcard])) { return $this->scores[$wildcard]; } return $this->scores[$wildcard] = $wildcard->scoreArguments($this->getArguments()); } } ================================================ FILE: src/Prophecy/Call/CallCenter.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Call; use Prophecy\Exception\Prophecy\MethodProphecyException; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Argument\ArgumentsWildcard; use Prophecy\Util\StringUtil; use Prophecy\Exception\Call\UnexpectedCallException; use SplObjectStorage; /** * Calls receiver & manager. * * @author Konstantin Kudryashov */ class CallCenter { private $util; /** * @var Call[] */ private $recordedCalls = array(); /** * @var SplObjectStorage> */ private $unexpectedCalls; /** * Initializes call center. * * @param StringUtil $util */ public function __construct(?StringUtil $util = null) { $this->util = $util ?: new StringUtil(); $this->unexpectedCalls = new SplObjectStorage(); } /** * Makes and records specific method call for object prophecy. * * @param ObjectProphecy $prophecy * @param string $methodName * @param array $arguments * * @return mixed Returns null if no promise for prophecy found or promise return value. * * @throws \Prophecy\Exception\Call\UnexpectedCallException If no appropriate method prophecy found */ public function makeCall(ObjectProphecy $prophecy, $methodName, array $arguments) { // For efficiency exclude 'args' from the generated backtrace // Limit backtrace to last 3 calls as we don't use the rest $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); $file = $line = null; if (isset($backtrace[2]) && isset($backtrace[2]['file']) && isset($backtrace[2]['line'])) { $file = $backtrace[2]['file']; $line = $backtrace[2]['line']; } // If no method prophecies defined, then it's a dummy, so we'll just return null if ('__destruct' === strtolower($methodName) || 0 == count($prophecy->getMethodProphecies())) { $this->recordedCalls[] = new Call($methodName, $arguments, null, null, $file, $line); return null; } // There are method prophecies, so it's a fake/stub. Searching prophecy for this call $matches = $this->findMethodProphecies($prophecy, $methodName, $arguments); // If fake/stub doesn't have method prophecy for this call - throw exception if (!count($matches)) { $this->unexpectedCalls->offsetSet(new Call($methodName, $arguments, null, null, $file, $line), $prophecy); $this->recordedCalls[] = new Call($methodName, $arguments, null, null, $file, $line); return null; } // Sort matches by their score value @usort($matches, function ($match1, $match2) { return $match2[0] - $match1[0]; }); $score = $matches[0][0]; // If Highest rated method prophecy has a promise - execute it or return null instead $methodProphecy = $matches[0][1]; $returnValue = null; $exception = null; if ($promise = $methodProphecy->getPromise()) { try { $returnValue = $promise->execute($arguments, $prophecy, $methodProphecy); } catch (\Exception $e) { $exception = $e; } } if ($methodProphecy->hasReturnVoid() && $returnValue !== null) { throw new MethodProphecyException( "The method \"$methodName\" has a void return type, but the promise returned a value", $methodProphecy ); } $this->recordedCalls[] = $call = new Call( $methodName, $arguments, $returnValue, $exception, $file, $line ); $call->addScore($methodProphecy->getArgumentsWildcard(), $score); if (null !== $exception) { throw $exception; } return $returnValue; } /** * Searches for calls by method name & arguments wildcard. * * @param string $methodName * @param ArgumentsWildcard $wildcard * * @return list */ public function findCalls($methodName, ArgumentsWildcard $wildcard) { $methodName = strtolower($methodName); return array_values( array_filter($this->recordedCalls, function (Call $call) use ($methodName, $wildcard) { return $methodName === strtolower($call->getMethodName()) && 0 < $call->getScore($wildcard) ; }) ); } /** * @return void * @throws UnexpectedCallException */ public function checkUnexpectedCalls() { foreach ($this->unexpectedCalls as $call) { $prophecy = $this->unexpectedCalls[$call]; // If fake/stub doesn't have method prophecy for this call - throw exception if (!count($this->findMethodProphecies($prophecy, $call->getMethodName(), $call->getArguments()))) { throw $this->createUnexpectedCallException($prophecy, $call->getMethodName(), $call->getArguments()); } } } /** * @param ObjectProphecy $prophecy * @param string $methodName * @param array $arguments * * @return UnexpectedCallException */ private function createUnexpectedCallException(ObjectProphecy $prophecy, $methodName, array $arguments) { $classname = get_class($prophecy->reveal()); $indentationLength = 8; // looks good $argstring = implode( ",\n", $this->indentArguments( array_map(array($this->util, 'stringify'), $arguments), $indentationLength ) ); $expected = array(); foreach (array_merge(...array_values($prophecy->getMethodProphecies())) as $methodProphecy) { $expected[] = sprintf( " - %s(\n" ."%s\n" ." )", $methodProphecy->getMethodName(), implode( ",\n", $this->indentArguments( array_map('strval', $methodProphecy->getArgumentsWildcard()->getTokens()), $indentationLength ) ) ); } return new UnexpectedCallException( sprintf( "Unexpected method call on %s:\n" ." - %s(\n" ."%s\n" ." )\n" ."expected calls were:\n" ."%s", $classname, $methodName, $argstring, implode("\n", $expected) ), $prophecy, $methodName, $arguments ); } /** * @param string[] $arguments * @param int $indentationLength * * @return string[] */ private function indentArguments(array $arguments, $indentationLength) { return preg_replace_callback( '/^/m', function () use ($indentationLength) { return str_repeat(' ', $indentationLength); }, $arguments ); } /** * @param ObjectProphecy $prophecy * @param string $methodName * @param array $arguments * * @return array * * @phpstan-return list */ private function findMethodProphecies(ObjectProphecy $prophecy, $methodName, array $arguments) { $matches = array(); foreach ($prophecy->getMethodProphecies($methodName) as $methodProphecy) { if (0 < $score = $methodProphecy->getArgumentsWildcard()->scoreArguments($arguments)) { $matches[] = array($score, $methodProphecy); } } return $matches; } } ================================================ FILE: src/Prophecy/Comparator/ClosureComparator.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Comparator; use SebastianBergmann\Comparator\Comparator; use SebastianBergmann\Comparator\ComparisonFailure; /** * Closure comparator. * * @author Konstantin Kudryashov */ final class ClosureComparator extends Comparator { /** * @param mixed $expected * @param mixed $actual */ public function accepts($expected, $actual): bool { return is_object($expected) && $expected instanceof \Closure && is_object($actual) && $actual instanceof \Closure; } /** * @param mixed $expected * @param mixed $actual * @param float $delta * @param bool $canonicalize * @param bool $ignoreCase */ public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false): void { if ($expected !== $actual) { // Support for sebastian/comparator < 5 if ((new \ReflectionMethod(ComparisonFailure::class, '__construct'))->getNumberOfParameters() >= 6) { // @phpstan-ignore-next-line throw new ComparisonFailure($expected, $actual, '', '', false, 'all closures are different if not identical'); } throw new ComparisonFailure( $expected, $actual, // we don't need a diff '', '', 'all closures are different if not identical' ); } } } ================================================ FILE: src/Prophecy/Comparator/Factory.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Comparator; use SebastianBergmann\Comparator\Factory as BaseFactory; /** * Prophecy comparator factory. * * @author Konstantin Kudryashov * * @deprecated Use "Prophecy\Comparator\FactoryProvider" instead to get a "SebastianBergmann\Comparator\Factory" instance. */ final class Factory extends BaseFactory { /** * @var Factory */ private static $instance; public function __construct() { parent::__construct(); $this->register(new ClosureComparator()); $this->register(new ProphecyComparator()); } /** * @return Factory */ public static function getInstance() { if (self::$instance === null) { self::$instance = new Factory(); } return self::$instance; } } ================================================ FILE: src/Prophecy/Comparator/FactoryProvider.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Comparator; use SebastianBergmann\Comparator\Factory; /** * Prophecy comparator factory. * * @author Konstantin Kudryashov */ final class FactoryProvider { /** * @var Factory|null */ private static $instance; private function __construct() {} public static function getInstance(): Factory { if (self::$instance === null) { self::$instance = new Factory(); self::$instance->register(new ClosureComparator()); self::$instance->register(new ProphecyComparator()); } return self::$instance; } } ================================================ FILE: src/Prophecy/Comparator/ProphecyComparator.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Comparator; use Prophecy\Prophecy\ProphecyInterface; use SebastianBergmann\Comparator\Comparator; use SebastianBergmann\Comparator\Factory; /** * @final */ class ProphecyComparator extends Comparator { /** * @param mixed $expected * @param mixed $actual */ public function accepts($expected, $actual): bool { return \is_object($expected) && $actual instanceof ProphecyInterface; } /** * @param mixed $expected * @param mixed $actual * @param float $delta * @param bool $canonicalize * @param bool $ignoreCase */ public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false): void { \assert($actual instanceof ProphecyInterface); $this->getComparatorFactory()->getComparatorFor($expected, $actual->reveal())->assertEquals($expected, $actual->reveal(), $delta, $canonicalize, $ignoreCase); } private function getComparatorFactory(): Factory { // sebastianbergmann/comparator 5+ // @phpstan-ignore function.alreadyNarrowedType if (\method_exists($this, 'factory')) { return $this->factory(); } // sebastianbergmann/comparator <5 // @phpstan-ignore property.private return $this->factory; } } ================================================ FILE: src/Prophecy/Doubler/CachedDoubler.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler; use ReflectionClass; /** * Cached class doubler. * Prevents mirroring/creation of the same structure twice. * * @author Konstantin Kudryashov */ class CachedDoubler extends Doubler { /** * @var array */ private static $classes = array(); protected function createDoubleClass(?ReflectionClass $class, array $interfaces) { $classId = $this->generateClassId($class, $interfaces); if (isset(self::$classes[$classId])) { return self::$classes[$classId]; } return self::$classes[$classId] = parent::createDoubleClass($class, $interfaces); } /** * @param ReflectionClass|null $class * @param ReflectionClass[] $interfaces * * @return string */ private function generateClassId(?ReflectionClass $class, array $interfaces) { $parts = array(); if (null !== $class) { $parts[] = $class->getName(); } foreach ($interfaces as $interface) { $parts[] = $interface->getName(); } foreach ($this->getClassPatches() as $patch) { $parts[] = get_class($patch); } sort($parts); return md5(implode('', $parts)); } /** * @return void */ public function resetCache() { self::$classes = array(); } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/ClassPatchInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ClassNode; /** * Class patch interface. * Class patches extend doubles functionality or help * Prophecy to avoid some internal PHP bugs. * * @author Konstantin Kudryashov */ interface ClassPatchInterface { /** * Checks if patch supports specific class node. * * @param ClassNode $node * * @return bool */ public function supports(ClassNode $node); /** * Applies patch to the specific class node. * * @param ClassNode $node * @return void */ public function apply(ClassNode $node); /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher - earlier) */ public function getPriority(); } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/DisableConstructorPatch.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ArgumentTypeNode; use Prophecy\Doubler\Generator\Node\ClassNode; use Prophecy\Doubler\Generator\Node\MethodNode; use Prophecy\Doubler\Generator\Node\Type\BuiltinType; use Prophecy\Doubler\Generator\Node\Type\UnionType; /** * Disable constructor. * Makes all constructor arguments optional. * * @author Konstantin Kudryashov */ class DisableConstructorPatch implements ClassPatchInterface { /** * Checks if class has `__construct` method. * * @param ClassNode $node * * @return bool */ public function supports(ClassNode $node) { return true; } /** * Makes all class constructor arguments optional. * * @param ClassNode $node */ public function apply(ClassNode $node) { if (!$node->isExtendable('__construct')) { return; } if (!$node->hasMethod('__construct')) { $node->addMethod(new MethodNode('__construct', '')); return; } $constructor = $node->getMethod('__construct'); \assert($constructor !== null); foreach ($constructor->getArguments() as $argument) { $argument->setDefault(null); $type = $argument->getTypeNode()->getType(); if ( $type instanceof BuiltinType && ($type->getType() === 'null' || $type->getType() === 'mixed') ) { continue; } if ($type instanceof UnionType && $type->has(new BuiltinType('null'))) { continue; } if (null === $type) { continue; } if ($type instanceof UnionType) { $argument->setTypeNode(new ArgumentTypeNode(new UnionType( [new BuiltinType('null'), ...$type->getTypes()] ))); continue; } $argument->setTypeNode(new ArgumentTypeNode(new UnionType( [new BuiltinType('null'), $type] ))); } $constructor->setCode(<< * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ClassNode; /** * Remove method functionality from the double which will clash with php keywords. * * @author Milan Magudia */ class KeywordPatch implements ClassPatchInterface { /** * Support any class * * @param ClassNode $node * * @return boolean */ public function supports(ClassNode $node) { return true; } /** * Remove methods that clash with php keywords * * @param ClassNode $node */ public function apply(ClassNode $node) { $methodNames = array_keys($node->getMethods()); $methodsToRemove = array_intersect($methodNames, $this->getKeywords()); foreach ($methodsToRemove as $methodName) { $node->removeMethod($methodName); } } /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher - earlier) */ public function getPriority() { return 49; } /** * Returns array of php keywords. * * @return list */ private function getKeywords() { return ['__halt_compiler']; } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/MagicCallPatch.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ArgumentNode; use Prophecy\Doubler\Generator\Node\ClassNode; use Prophecy\Doubler\Generator\Node\MethodNode; use Prophecy\PhpDocumentor\ClassAndInterfaceTagRetriever; use Prophecy\PhpDocumentor\MethodTagRetrieverInterface; /** * Discover Magical API using "@method" PHPDoc format. * * @author Thomas Tourlourat * @author Kévin Dunglas * @author Théo FIDRY */ class MagicCallPatch implements ClassPatchInterface { const MAGIC_METHODS_WITH_ARGUMENTS = ['__call', '__callStatic', '__get', '__isset', '__set', '__set_state', '__unserialize', '__unset']; private $tagRetriever; public function __construct(?MethodTagRetrieverInterface $tagRetriever = null) { $this->tagRetriever = null === $tagRetriever ? new ClassAndInterfaceTagRetriever() : $tagRetriever; } /** * Support any class * * @param ClassNode $node * * @return boolean */ public function supports(ClassNode $node) { return true; } /** * Discover Magical API * * @param ClassNode $node */ public function apply(ClassNode $node) { $types = array_filter($node->getInterfaces(), function ($interface) { return 0 !== strpos($interface, 'Prophecy\\'); }); $types[] = $node->getParentClass(); foreach ($types as $type) { $reflectionClass = new \ReflectionClass($type); while ($reflectionClass) { $tagList = $this->tagRetriever->getTagList($reflectionClass); foreach ($tagList as $tag) { $methodName = $tag->getMethodName(); if (empty($methodName)) { continue; } if (!$reflectionClass->hasMethod($methodName)) { $methodNode = new MethodNode($methodName); // only magic methods can have a contract that needs to be enforced if (in_array($methodName, self::MAGIC_METHODS_WITH_ARGUMENTS)) { if (method_exists($tag, 'getParameters')) { // Reflection Docblock 5.4.0+. foreach ($tag->getParameters() as $argument) { $argumentNode = new ArgumentNode($argument->getName()); $methodNode->addArgument($argumentNode); } } else { // Reflection Docblock < 5.4.0. foreach ($tag->getArguments() as $argument) { $argumentNode = new ArgumentNode($argument['name']); $methodNode->addArgument($argumentNode); } } } $methodNode->setStatic($tag->isStatic()); $node->addMethod($methodNode); } } $reflectionClass = $reflectionClass->getParentClass(); } } } /** * Returns patch priority, which determines when patch will be applied. * * @return integer Priority number (higher - earlier) */ public function getPriority() { return 50; } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/ProphecySubjectPatch.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ArgumentTypeNode; use Prophecy\Doubler\Generator\Node\ClassNode; use Prophecy\Doubler\Generator\Node\MethodNode; use Prophecy\Doubler\Generator\Node\ArgumentNode; use Prophecy\Doubler\Generator\Node\Type\ObjectType; /** * Add Prophecy functionality to the double. * This is a core class patch for Prophecy. * * @author Konstantin Kudryashov */ class ProphecySubjectPatch implements ClassPatchInterface { /** * Always returns true. * * @param ClassNode $node * * @return bool */ public function supports(ClassNode $node) { return true; } /** * Apply Prophecy functionality to class node. * * @param ClassNode $node */ public function apply(ClassNode $node) { $node->addInterface('Prophecy\Prophecy\ProphecySubjectInterface'); $node->addProperty('objectProphecyClosure', 'private'); foreach ($node->getMethods() as $name => $method) { if ('__construct' === strtolower($name)) { continue; } if (!$method->getReturnTypeNode()->hasReturnStatement()) { $method->setCode( '$this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());' ); } else { $method->setCode( 'return $this->getProphecy()->makeProphecyMethodCall(__FUNCTION__, func_get_args());' ); } } $prophecySetter = new MethodNode('setProphecy'); $prophecyArgument = new ArgumentNode('prophecy'); $prophecyArgument->setTypeNode(new ArgumentTypeNode(new ObjectType('Prophecy\Prophecy\ProphecyInterface'))); $prophecySetter->addArgument($prophecyArgument); $prophecySetter->setCode(<<objectProphecyClosure) { \$this->objectProphecyClosure = static function () use (\$prophecy) { return \$prophecy; }; } PHP ); $prophecyGetter = new MethodNode('getProphecy'); $prophecyGetter->setCode('return \call_user_func($this->objectProphecyClosure);'); if ($node->hasMethod('__call')) { $__call = $node->getMethod('__call'); \assert($__call !== null); } else { $__call = new MethodNode('__call'); $__call->addArgument(new ArgumentNode('name')); $__call->addArgument(new ArgumentNode('arguments')); $node->addMethod($__call, true); } $__call->setCode(<<addMethod($prophecySetter, true); $node->addMethod($prophecyGetter, true); } /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher - earlier) */ public function getPriority() { return 0; } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/ReflectionClassNewInstancePatch.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ClassNode; /** * ReflectionClass::newInstance patch. * Makes first argument of newInstance optional, since it works but signature is misleading * * @author Florian Klein */ class ReflectionClassNewInstancePatch implements ClassPatchInterface { /** * Supports ReflectionClass * * @param ClassNode $node * * @return bool */ public function supports(ClassNode $node) { return 'ReflectionClass' === $node->getParentClass(); } /** * Updates newInstance's first argument to make it optional * * @param ClassNode $node */ public function apply(ClassNode $node) { $method = $node->getMethod('newInstance'); \assert($method !== null); foreach ($method->getArguments() as $argument) { $argument->setDefault(null); } } /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher = earlier) */ public function getPriority() { return 50; } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/SplFileInfoPatch.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ClassNode; use Prophecy\Doubler\Generator\Node\MethodNode; /** * SplFileInfo patch. * Makes SplFileInfo and derivative classes usable with Prophecy. * * @author Konstantin Kudryashov */ class SplFileInfoPatch implements ClassPatchInterface { /** * Supports everything that extends SplFileInfo. * * @param ClassNode $node * * @return bool */ public function supports(ClassNode $node) { return 'SplFileInfo' === $node->getParentClass() || is_subclass_of($node->getParentClass(), 'SplFileInfo') ; } /** * Updated constructor code to call parent one with dummy file argument. * * @param ClassNode $node */ public function apply(ClassNode $node) { if ($node->hasMethod('__construct')) { $constructor = $node->getMethod('__construct'); \assert($constructor !== null); } else { $constructor = new MethodNode('__construct'); $node->addMethod($constructor); } if ($this->nodeIsDirectoryIterator($node)) { $constructor->setCode('return parent::__construct("'.__DIR__.'");'); return; } if ($this->nodeIsSplFileObject($node)) { $filePath = str_replace('\\', '\\\\', __FILE__); $constructor->setCode('return parent::__construct("'.$filePath.'");'); return; } if ($this->nodeIsSymfonySplFileInfo($node)) { $filePath = str_replace('\\', '\\\\', __FILE__); $constructor->setCode('return parent::__construct("'.$filePath.'", "", "");'); return; } $constructor->useParentCode(); } /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher - earlier) */ public function getPriority() { return 50; } /** * @param ClassNode $node * @return boolean */ private function nodeIsDirectoryIterator(ClassNode $node) { $parent = $node->getParentClass(); return 'DirectoryIterator' === $parent || is_subclass_of($parent, 'DirectoryIterator'); } /** * @param ClassNode $node * @return boolean */ private function nodeIsSplFileObject(ClassNode $node) { $parent = $node->getParentClass(); return 'SplFileObject' === $parent || is_subclass_of($parent, 'SplFileObject'); } /** * @param ClassNode $node * @return boolean */ private function nodeIsSymfonySplFileInfo(ClassNode $node) { $parent = $node->getParentClass(); return 'Symfony\\Component\\Finder\\SplFileInfo' === $parent; } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/ThrowablePatch.php ================================================ implementsAThrowableInterface($node) && $this->doesNotExtendAThrowableClass($node); } /** * @param ClassNode $node * @return bool */ private function implementsAThrowableInterface(ClassNode $node) { foreach ($node->getInterfaces() as $type) { if (is_a($type, 'Throwable', true)) { return true; } } return false; } /** * @param ClassNode $node * @return bool */ private function doesNotExtendAThrowableClass(ClassNode $node) { return !is_a($node->getParentClass(), 'Throwable', true); } /** * Applies patch to the specific class node. * * @param ClassNode $node * * @return void */ public function apply(ClassNode $node) { $this->checkItCanBeDoubled($node); $this->setParentClassToException($node); } private function checkItCanBeDoubled(ClassNode $node): void { $className = $node->getParentClass(); if ($className !== 'stdClass') { throw new ClassCreatorException( sprintf( 'Cannot double concrete class %s as well as implement Traversable', $className ), $node ); } } private function setParentClassToException(ClassNode $node): void { $node->setParentClass('Exception'); $node->removeMethod('getMessage'); $node->removeMethod('getCode'); $node->removeMethod('getFile'); $node->removeMethod('getLine'); $node->removeMethod('getTrace'); $node->removeMethod('getPrevious'); $node->removeMethod('getNext'); $node->removeMethod('getTraceAsString'); } /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher - earlier) */ public function getPriority() { return 100; } } ================================================ FILE: src/Prophecy/Doubler/ClassPatch/TraversablePatch.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\ClassPatch; use Prophecy\Doubler\Generator\Node\ClassNode; use Prophecy\Doubler\Generator\Node\MethodNode; use Prophecy\Doubler\Generator\Node\ReturnTypeNode; use Prophecy\Doubler\Generator\Node\Type\BuiltinType; /** * Traversable interface patch. * Forces classes that implement interfaces, that extend Traversable to also implement Iterator. * * @author Konstantin Kudryashov */ class TraversablePatch implements ClassPatchInterface { /** * Supports nodetree, that implement Traversable, but not Iterator or IteratorAggregate. * * @param ClassNode $node * * @return bool */ public function supports(ClassNode $node) { if (in_array('Iterator', $node->getInterfaces())) { return false; } if (in_array('IteratorAggregate', $node->getInterfaces())) { return false; } foreach ($node->getInterfaces() as $interface) { if ('Traversable' !== $interface && !is_subclass_of($interface, 'Traversable')) { continue; } if ('Iterator' === $interface || is_subclass_of($interface, 'Iterator')) { continue; } if ('IteratorAggregate' === $interface || is_subclass_of($interface, 'IteratorAggregate')) { continue; } return true; } return false; } /** * Forces class to implement Iterator interface. * * @param ClassNode $node */ public function apply(ClassNode $node) { $node->addInterface('Iterator'); $currentMethod = new MethodNode('current'); $currentMethod->setReturnTypeNode(new ReturnTypeNode(new BuiltinType('mixed'))); $node->addMethod($currentMethod); $keyMethod = new MethodNode('key'); $keyMethod->setReturnTypeNode(new ReturnTypeNode(new BuiltinType('mixed'))); $node->addMethod($keyMethod); $nextMethod = new MethodNode('next'); $nextMethod->setReturnTypeNode(new ReturnTypeNode(new BuiltinType('void'))); $node->addMethod($nextMethod); $rewindMethod = new MethodNode('rewind'); $rewindMethod->setReturnTypeNode(new ReturnTypeNode(new BuiltinType('void'))); $node->addMethod($rewindMethod); $validMethod = new MethodNode('valid'); $validMethod->setReturnTypeNode(new ReturnTypeNode(new BuiltinType('bool'))); $node->addMethod($validMethod); } /** * Returns patch priority, which determines when patch will be applied. * * @return int Priority number (higher - earlier) */ public function getPriority() { return 100; } } ================================================ FILE: src/Prophecy/Doubler/DoubleInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler; /** * Core double interface. * All doubled classes will implement this one. * * @author Konstantin Kudryashov */ interface DoubleInterface {} ================================================ FILE: src/Prophecy/Doubler/Doubler.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler; use Doctrine\Instantiator\Instantiator; use Prophecy\Doubler\ClassPatch\ClassPatchInterface; use Prophecy\Doubler\Generator\ClassMirror; use Prophecy\Doubler\Generator\ClassCreator; use Prophecy\Exception\InvalidArgumentException; use ReflectionClass; /** * Cached class doubler. * Prevents mirroring/creation of the same structure twice. * * @author Konstantin Kudryashov */ class Doubler { private $mirror; private $creator; private $namer; /** * @var list */ private $patches = array(); /** * @var Instantiator|null */ private $instantiator; public function __construct(?ClassMirror $mirror = null, ?ClassCreator $creator = null, ?NameGenerator $namer = null) { $this->mirror = $mirror ?: new ClassMirror(); $this->creator = $creator ?: new ClassCreator(); $this->namer = $namer ?: new NameGenerator(); } /** * Returns list of registered class patches. * * @return list */ public function getClassPatches() { return $this->patches; } /** * Registers new class patch. * * @param ClassPatchInterface $patch * * @return void */ public function registerClassPatch(ClassPatchInterface $patch) { $this->patches[] = $patch; @usort($this->patches, function (ClassPatchInterface $patch1, ClassPatchInterface $patch2) { return $patch2->getPriority() - $patch1->getPriority(); }); } /** * Creates double from specific class or/and list of interfaces. * * @template T of object * * @param ReflectionClass|null $class * @param ReflectionClass[] $interfaces Array of ReflectionClass instances * @param array|null $args Constructor arguments * * @return T&DoubleInterface * * @throws \Prophecy\Exception\InvalidArgumentException */ public function double(?ReflectionClass $class, array $interfaces, ?array $args = null) { foreach ($interfaces as $interface) { if (!$interface instanceof ReflectionClass) { throw new InvalidArgumentException(sprintf( "[ReflectionClass \$interface1 [, ReflectionClass \$interface2]] array expected as\n" ."a second argument to `Doubler::double(...)`, but got %s.", is_object($interface) ? get_class($interface).' class' : gettype($interface) )); } } $classname = $this->createDoubleClass($class, $interfaces); $reflection = new ReflectionClass($classname); if (null !== $args) { return $reflection->newInstanceArgs($args); } if ((null === $constructor = $reflection->getConstructor()) || ($constructor->isPublic() && !$constructor->isFinal())) { return $reflection->newInstance(); } if (!$this->instantiator) { $this->instantiator = new Instantiator(); } return $this->instantiator->instantiate($classname); } /** * Creates double class and returns its FQN. * * @template T of object * * @param ReflectionClass|null $class * @param ReflectionClass[] $interfaces * * @return class-string */ protected function createDoubleClass(?ReflectionClass $class, array $interfaces) { $name = $this->namer->name($class, $interfaces); $node = $this->mirror->reflect($class, $interfaces); foreach ($this->patches as $patch) { if ($patch->supports($node)) { $patch->apply($node); } } $node->addInterface(DoubleInterface::class); $this->creator->create($name, $node); \assert(class_exists($name, false)); return $name; } } ================================================ FILE: src/Prophecy/Doubler/Generator/ClassCodeGenerator.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator; use Prophecy\Doubler\Generator\Node\TypeNodeAbstract; /** * Class code creator. * Generates PHP code for specific class node tree. * * @author Konstantin Kudryashov */ class ClassCodeGenerator { // Used to accept an optional first argument with the deprecated Prophecy\Doubler\Generator\TypeHintReference so careful when adding a new argument in a minor version. public function __construct() {} /** * Generates PHP code for class node. * * @param string $classname * @param Node\ClassNode $class * * @return string */ public function generate($classname, Node\ClassNode $class) { $parts = explode('\\', $classname); $classname = array_pop($parts); $namespace = implode('\\', $parts); $code = sprintf("%sclass %s extends \%s implements %s {\n", $class->isReadOnly() ? 'readonly ' : '', $classname, $class->getParentClass(), implode(', ', array_map(function ($interface) {return '\\'.$interface;}, $class->getInterfaces()) ) ); foreach ($class->getProperties() as $name => $visibility) { $code .= sprintf("%s \$%s;\n", $visibility, $name); } $code .= "\n"; foreach ($class->getMethods() as $method) { $code .= $this->generateMethod($method)."\n"; } $code .= "\n}"; return sprintf("namespace %s {\n%s\n}", $namespace, $code); } private function generateMethod(Node\MethodNode $method): string { $php = sprintf("%s %s function %s%s(%s)%s {\n", $method->getVisibility(), $method->isStatic() ? 'static' : '', $method->returnsReference() ? '&' : '', $method->getName(), implode(', ', $this->generateArguments($method->getArguments())), ($ret = $this->generateTypes($method->getReturnTypeNode())) ? ': '.$ret : '' ); $php .= $method->getCode()."\n"; return $php.'}'; } private function generateTypes(TypeNodeAbstract $typeNode): string { if ($typeNode->getType() === null) { return ''; } return (string) $typeNode->getType(); } /** * @param list $arguments * * @return list */ private function generateArguments(array $arguments): array { return array_map(function (Node\ArgumentNode $argument) { $php = $this->generateTypes($argument->getTypeNode()); $php .= ' '.($argument->isPassedByReference() ? '&' : ''); $php .= $argument->isVariadic() ? '...' : ''; $php .= '$'.$argument->getName(); if ($argument->isOptional() && !$argument->isVariadic()) { $default = var_export($argument->getDefault(), true); // This is necessary for PHP 8.1, as enum cases are exported without a leading slash in this version if ($argument->getDefault() instanceof \UnitEnum && 0 !== strpos($default, '\\')) { $default = '\\'.$default; } $php .= ' = '.$default; } return $php; }, $arguments); } } ================================================ FILE: src/Prophecy/Doubler/Generator/ClassCreator.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator; use Prophecy\Exception\Doubler\ClassCreatorException; /** * Class creator. * Creates specific class in current environment. * * @author Konstantin Kudryashov */ class ClassCreator { private $generator; public function __construct(?ClassCodeGenerator $generator = null) { $this->generator = $generator ?: new ClassCodeGenerator(); } /** * Creates class. * * @param string $classname * @param Node\ClassNode $class * * @return mixed * * @throws \Prophecy\Exception\Doubler\ClassCreatorException */ public function create($classname, Node\ClassNode $class) { $code = $this->generator->generate($classname, $class); $return = eval($code); if (!class_exists($classname, false)) { if (count($class->getInterfaces())) { throw new ClassCreatorException(sprintf( 'Could not double `%s` and implement interfaces: [%s].', $class->getParentClass(), implode(', ', $class->getInterfaces()) ), $class); } throw new ClassCreatorException( sprintf('Could not double `%s`.', $class->getParentClass()), $class ); } return $return; } } ================================================ FILE: src/Prophecy/Doubler/Generator/ClassMirror.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator; use Prophecy\Doubler\Generator\Node\ArgumentTypeNode; use Prophecy\Doubler\Generator\Node\ReturnTypeNode; use Prophecy\Doubler\Generator\Node\Type\BuiltinType; use Prophecy\Doubler\Generator\Node\Type\IntersectionType; use Prophecy\Doubler\Generator\Node\Type\ObjectType; use Prophecy\Doubler\Generator\Node\Type\TypeInterface; use Prophecy\Doubler\Generator\Node\Type\SimpleType; use Prophecy\Doubler\Generator\Node\Type\UnionType; use Prophecy\Exception\InvalidArgumentException; use Prophecy\Exception\Doubler\ClassMirrorException; use ReflectionClass; use ReflectionIntersectionType; use ReflectionMethod; use ReflectionNamedType; use ReflectionParameter; use ReflectionType; use ReflectionUnionType; /** * Class mirror. * Core doubler class. Mirrors specific class and/or interfaces into class node tree. * * @author Konstantin Kudryashov */ class ClassMirror { private const REFLECTABLE_METHODS = array( '__construct', '__destruct', '__sleep', '__wakeup', '__toString', '__call', '__invoke', ); /** * Reflects provided arguments into class node. * * @param ReflectionClass|null $class * @param ReflectionClass[] $interfaces * * @return Node\ClassNode * */ public function reflect(?ReflectionClass $class, array $interfaces) { $node = new Node\ClassNode(); if (null !== $class) { if (true === $class->isInterface()) { throw new InvalidArgumentException(sprintf( "Could not reflect %s as a class, because it\n" ."is interface - use the second argument instead.", $class->getName() )); } $this->reflectClassToNode($class, $node); } foreach ($interfaces as $interface) { if (!$interface instanceof ReflectionClass) { throw new InvalidArgumentException(sprintf( "[ReflectionClass \$interface1 [, ReflectionClass \$interface2]] array expected as\n" ."a second argument to `ClassMirror::reflect(...)`, but got %s.", is_object($interface) ? get_class($interface).' class' : gettype($interface) )); } if (false === $interface->isInterface()) { throw new InvalidArgumentException(sprintf( "Could not reflect %s as an interface, because it\n" ."is class - use the first argument instead.", $interface->getName() )); } $this->reflectInterfaceToNode($interface, $node); } $node->addInterface('Prophecy\Doubler\Generator\ReflectionInterface'); return $node; } /** * @param ReflectionClass $class */ private function reflectClassToNode(ReflectionClass $class, Node\ClassNode $node): void { if (true === $class->isFinal()) { throw new ClassMirrorException(sprintf( 'Could not reflect class %s as it is marked final.', $class->getName() ), $class); } if (method_exists(ReflectionClass::class, 'isReadOnly')) { $node->setReadOnly($class->isReadOnly()); } $node->setParentClass($class->getName()); foreach ($class->getMethods(ReflectionMethod::IS_ABSTRACT) as $method) { if (false === $method->isProtected()) { continue; } $this->reflectMethodToNode($method, $node); } foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { if (0 === strpos($method->getName(), '_') && !in_array($method->getName(), self::REFLECTABLE_METHODS)) { continue; } if (true === $method->isFinal()) { $node->addUnextendableMethod($method->getName()); continue; } $this->reflectMethodToNode($method, $node); } } /** * @param ReflectionClass $interface */ private function reflectInterfaceToNode(ReflectionClass $interface, Node\ClassNode $node): void { $node->addInterface($interface->getName()); foreach ($interface->getMethods() as $method) { $this->reflectMethodToNode($method, $node); } } private function reflectMethodToNode(ReflectionMethod $method, Node\ClassNode $classNode): void { $node = new Node\MethodNode($method->getName()); if (true === $method->isProtected()) { $node->setVisibility('protected'); } if (true === $method->isStatic()) { $node->setStatic(); } if (true === $method->returnsReference()) { $node->setReturnsReference(); } $returnReflectionType = null; if ($method->hasReturnType()) { $returnReflectionType = $method->getReturnType(); } elseif (method_exists($method, 'hasTentativeReturnType') && $method->hasTentativeReturnType()) { // Tentative return types also need reflection $returnReflectionType = $method->getTentativeReturnType(); } if (null !== $returnReflectionType) { $returnType = $this->createTypeFromReflection( $returnReflectionType, $method->getDeclaringClass() ); $node->setReturnTypeNode(new ReturnTypeNode($returnType)); } if (is_array($params = $method->getParameters()) && count($params)) { foreach ($params as $param) { $this->reflectArgumentToNode($param, $method->getDeclaringClass(), $node); } } $classNode->addMethod($node); } /** * @param ReflectionClass $declaringClass * * @return void */ private function reflectArgumentToNode(ReflectionParameter $parameter, ReflectionClass $declaringClass, Node\MethodNode $methodNode): void { $name = $parameter->getName() == '...' ? '__dot_dot_dot__' : $parameter->getName(); $node = new Node\ArgumentNode($name); $refType = $parameter->getType(); if (null !== $refType) { $typeHint = $this->createTypeFromReflection($refType, $declaringClass); $node->setTypeNode(new ArgumentTypeNode($typeHint)); } if ($parameter->isVariadic()) { $node->setAsVariadic(); } if ($this->hasDefaultValue($parameter)) { $node->setDefault($this->getDefaultValue($parameter)); } if ($parameter->isPassedByReference()) { $node->setAsPassedByReference(); } $methodNode->addArgument($node); } private function hasDefaultValue(ReflectionParameter $parameter): bool { if ($parameter->isVariadic()) { return false; } if ($parameter->isDefaultValueAvailable()) { return true; } return $parameter->isOptional(); } /** * @return mixed */ private function getDefaultValue(ReflectionParameter $parameter) { if (!$parameter->isDefaultValueAvailable()) { return null; } return $parameter->getDefaultValue(); } /** * @param ReflectionClass $declaringClass Context reflection class */ private function createTypeFromReflection(ReflectionType $type, ReflectionClass $declaringClass): TypeInterface { if ($type instanceof ReflectionIntersectionType) { $innerTypes = []; /** @var ReflectionNamedType $innerReflectionType */ foreach ($type->getTypes() as $innerReflectionType) { // Intersections cannot be composed of builtin types /** @var class-string $objectType */ $objectType = $innerReflectionType->getName(); $innerTypes[] = new ObjectType($objectType); } return new IntersectionType($innerTypes); } if ($type instanceof ReflectionUnionType) { $innerTypes = []; /** @var ReflectionIntersectionType|ReflectionNamedType $innerReflectionType */ foreach ($type->getTypes() as $innerReflectionType) { if ($innerReflectionType instanceof ReflectionIntersectionType) { /** @var IntersectionType $intersection */ $intersection = $this->createTypeFromReflection($innerReflectionType, $declaringClass); $innerTypes[] = $intersection; continue; } $name = $this->resolveTypeName($innerReflectionType->getName(), $declaringClass); if ($innerReflectionType->isBuiltin() || $name === 'static') { $innerTypes[] = new BuiltinType($name); } elseif ($name === 'self') { $innerTypes[] = new ObjectType($declaringClass->getName()); } else { /** @var class-string $name */ $innerTypes[] = new ObjectType($name); } } // Nullability is handled by 'null' being one of the types in the union return new UnionType($innerTypes); } // Handle Named Types (single types like int, string, MyClass, ?MyClass) if ($type instanceof ReflectionNamedType) { $name = $this->resolveTypeName($type->getName(), $declaringClass); if ($type->isBuiltin() || $name === 'static') { $simpleType = new BuiltinType($name); // SimpleType constructor normalizes } else { /** @var class-string $name */ $simpleType = new ObjectType($name); } // Handle nullability for named types explicitly by wrapping in a UnionType if needed if ($type->allowsNull() && $name !== 'mixed' && $name !== 'null') { return new UnionType([new BuiltinType('null'), $simpleType]); } return $simpleType; } // Unknown ReflectionType implementation throw new ClassMirrorException('Unknown reflection type: '.get_class($type), $declaringClass); } /** * @param ReflectionClass $contextClass */ private function resolveTypeName(string $name, \ReflectionClass $contextClass): string { if ($name === 'self') { return $contextClass->getName(); } if ($name === 'parent') { $parent = $contextClass->getParentClass(); if (false === $parent) { throw new ClassMirrorException(sprintf('Cannot use "parent" type hint in class "%s" as it does not have a parent.', $contextClass->getName()), $contextClass); } return $parent->getName(); } return $name; } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/ArgumentNode.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator\Node; /** * Argument node. * * @author Konstantin Kudryashov */ class ArgumentNode { private $name; /** * @var mixed */ private $default; /** * @var bool */ private $optional = false; /** * @var bool */ private $byReference = false; /** * @var bool */ private $isVariadic = false; /** @var ArgumentTypeNode */ private $typeNode; /** * @param string $name */ public function __construct($name) { $this->name = $name; $this->typeNode = new ArgumentTypeNode(); } /** * @return string */ public function getName() { return $this->name; } /** * @return void */ public function setTypeNode(ArgumentTypeNode $typeNode) { $this->typeNode = $typeNode; } public function getTypeNode(): ArgumentTypeNode { return $this->typeNode; } /** * @return bool */ public function hasDefault() { return $this->isOptional() && !$this->isVariadic(); } /** * @return mixed */ public function getDefault() { return $this->default; } /** * @param mixed $default * * @return void */ public function setDefault($default = null) { $this->optional = true; $this->default = $default; } /** * @return bool */ public function isOptional() { return $this->optional; } /** * @param bool $byReference * * @return void */ public function setAsPassedByReference($byReference = true) { $this->byReference = $byReference; } /** * @return bool */ public function isPassedByReference() { return $this->byReference; } /** * @param bool $isVariadic * * @return void */ public function setAsVariadic($isVariadic = true) { $this->isVariadic = $isVariadic; } /** * @return bool */ public function isVariadic() { return $this->isVariadic; } /** * @deprecated use getArgumentTypeNode instead * @return string|null */ public function getTypeHint() { $type = $this->typeNode->getNonNullTypes() ? $this->typeNode->getNonNullTypes()[0] : null; return $type ? ltrim($type, '\\') : null; } /** * @deprecated use setArgumentTypeNode instead * @param string|null $typeHint * * @return void */ public function setTypeHint($typeHint = null) { $this->typeNode = ($typeHint === null) ? new ArgumentTypeNode() : new ArgumentTypeNode($typeHint); } /** * @deprecated use getArgumentTypeNode instead * @return bool */ public function isNullable() { return $this->typeNode->canUseNullShorthand(); } /** * @deprecated use getArgumentTypeNode instead * @param bool $isNullable * * @return void */ public function setAsNullable($isNullable = true) { $nonNullTypes = $this->typeNode->getNonNullTypes(); $this->typeNode = $isNullable ? new ArgumentTypeNode('null', ...$nonNullTypes) : new ArgumentTypeNode(...$nonNullTypes); } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/ArgumentTypeNode.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator\Node; use Prophecy\Exception\Doubler\MethodNotExtendableException; use Prophecy\Exception\InvalidArgumentException; /** * Class node. * * @author Konstantin Kudryashov */ class ClassNode { /** * @var class-string */ private $parentClass = 'stdClass'; /** * @var list */ private $interfaces = array(); /** * @var array * * @phpstan-var array */ private $properties = array(); /** * @var list */ private $unextendableMethods = array(); /** * @var bool */ private $readOnly = false; /** * @var array */ private $methods = array(); /** * @return class-string */ public function getParentClass() { return $this->parentClass; } /** * @param class-string|null $class * * @return void */ public function setParentClass($class) { $this->parentClass = $class ?: 'stdClass'; } /** * @return list */ public function getInterfaces() { return $this->interfaces; } /** * @param class-string $interface * * @return void */ public function addInterface($interface) { if ($this->hasInterface($interface)) { return; } array_unshift($this->interfaces, $interface); } /** * @param class-string $interface * * @return bool */ public function hasInterface($interface) { return in_array($interface, $this->interfaces); } /** * @return array * * @phpstan-return array */ public function getProperties() { return $this->properties; } /** * @param string $name * @param string $visibility * * @return void * * @phpstan-param 'public'|'private'|'protected' $visibility */ public function addProperty($name, $visibility = 'public') { $visibility = strtolower($visibility); if (!\in_array($visibility, array('public', 'private', 'protected'), true)) { throw new InvalidArgumentException(sprintf( '`%s` property visibility is not supported.', $visibility )); } $this->properties[$name] = $visibility; } /** * @return array */ public function getMethods() { return $this->methods; } /** * @param MethodNode $method * @param bool $force * * @return void */ public function addMethod(MethodNode $method, $force = false) { if (!$this->isExtendable($method->getName())) { $message = sprintf( 'Method `%s` is not extendable, so can not be added.', $method->getName() ); throw new MethodNotExtendableException($message, $this->getParentClass(), $method->getName()); } if ($force || !isset($this->methods[$method->getName()])) { $this->methods[$method->getName()] = $method; } } /** * @param string $name * * @return void */ public function removeMethod($name) { unset($this->methods[$name]); } /** * @param string $name * * @return MethodNode|null */ public function getMethod($name) { return $this->hasMethod($name) ? $this->methods[$name] : null; } /** * @param string $name * * @return bool */ public function hasMethod($name) { return isset($this->methods[$name]); } /** * @return list */ public function getUnextendableMethods() { return $this->unextendableMethods; } /** * @param string $unextendableMethod * * @return void */ public function addUnextendableMethod($unextendableMethod) { if (!$this->isExtendable($unextendableMethod)) { return; } $this->unextendableMethods[] = $unextendableMethod; } /** * @param string $method * * @return bool */ public function isExtendable($method) { return !in_array($method, $this->unextendableMethods); } /** * @return bool */ public function isReadOnly() { return $this->readOnly; } /** * @param bool $readOnly * * @return void */ public function setReadOnly($readOnly) { $this->readOnly = $readOnly; } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/MethodNode.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator\Node; use Prophecy\Exception\InvalidArgumentException; /** * Method node. * * @author Konstantin Kudryashov */ class MethodNode { private $name; private $code; /** * @var string * * @phpstan-var 'public'|'private'|'protected' */ private $visibility = 'public'; /** * @var bool */ private $static = false; /** * @var bool */ private $returnsReference = false; /** @var ReturnTypeNode */ private $returnTypeNode; /** * @var list */ private $arguments = array(); // Used to accept an optional third argument with the deprecated Prophecy\Doubler\Generator\TypeHintReference so careful when adding a new argument in a minor version. /** * @param string $name * @param string|null $code */ public function __construct($name, $code = null) { $this->name = $name; $this->code = $code; $this->returnTypeNode = new ReturnTypeNode(); } /** * @return string * * @phpstan-return 'public'|'private'|'protected' */ public function getVisibility() { return $this->visibility; } /** * @param string $visibility * * @return void */ public function setVisibility($visibility) { $visibility = strtolower($visibility); if (!\in_array($visibility, array('public', 'private', 'protected'), true)) { throw new InvalidArgumentException(sprintf( '`%s` method visibility is not supported.', $visibility )); } $this->visibility = $visibility; } /** * @return bool */ public function isStatic() { return $this->static; } /** * @param bool $static * * @return void */ public function setStatic($static = true) { $this->static = (bool) $static; } /** * @return bool */ public function returnsReference() { return $this->returnsReference; } /** * @return void */ public function setReturnsReference() { $this->returnsReference = true; } /** * @return string */ public function getName() { return $this->name; } /** * @return void */ public function addArgument(ArgumentNode $argument) { $this->arguments[] = $argument; } /** * @return list */ public function getArguments() { return $this->arguments; } /** * @deprecated use getReturnTypeNode instead * @return bool */ public function hasReturnType() { return (bool) $this->returnTypeNode->getNonNullTypes(); } public function setReturnTypeNode(ReturnTypeNode $returnTypeNode): void { $this->returnTypeNode = $returnTypeNode; } /** * @deprecated use setReturnTypeNode instead * @param string $type * * @return void */ public function setReturnType($type = null) { $this->returnTypeNode = ($type === '' || $type === null) ? new ReturnTypeNode() : new ReturnTypeNode($type); } /** * @deprecated use setReturnTypeNode instead * @param bool $bool * * @return void */ public function setNullableReturnType($bool = true) { if ($bool) { $this->returnTypeNode = new ReturnTypeNode('null', ...$this->returnTypeNode->getTypes()); } else { $this->returnTypeNode = new ReturnTypeNode(...$this->returnTypeNode->getNonNullTypes()); } } /** * @deprecated use getReturnTypeNode instead * @return string|null */ public function getReturnType() { if ($types = $this->returnTypeNode->getNonNullTypes()) { return $types[0]; } return null; } public function getReturnTypeNode(): ReturnTypeNode { return $this->returnTypeNode; } /** * @deprecated use getReturnTypeNode instead * @return bool */ public function hasNullableReturnType() { return $this->returnTypeNode->isNullable(); } /** * @param string $code * * @return void */ public function setCode($code) { $this->code = $code; } /** * @return string */ public function getCode() { if ($this->returnsReference) { return "throw new \Prophecy\Exception\Doubler\ReturnByReferenceException('Returning by reference not supported', get_class(\$this), '{$this->name}');"; } return (string) $this->code; } /** * @return void */ public function useParentCode() { $this->code = sprintf( 'return parent::%s(%s);', $this->getName(), implode(', ', array_map(array($this, 'generateArgument'), $this->arguments) ) ); } /** * @return string */ private function generateArgument(ArgumentNode $arg) { $argument = '$'.$arg->getName(); if ($arg->isVariadic()) { $argument = '...'.$argument; } return $argument; } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/ReturnTypeNode.php ================================================ getType() === null) { return true; } return $this->getType()->equals(new BuiltinType('void')); } public function hasReturnStatement(): bool { if ($this->getType() === null) { return true; } return !$this->getType()->equals(new BuiltinType('void')) && !$this->getType()->equals(new BuiltinType('never')); } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/Type/BuiltinType.php ================================================ getType(); } public function getType(): string { return $this->type; } public function equals(TypeInterface $givenType): bool { if (!$givenType instanceof BuiltinType) { return false; } return $this->getType() === $givenType->getType(); } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/Type/IntersectionType.php ================================================ $types */ public function __construct(private array $types) { $this->guard(); } /** * @return list */ public function getTypes(): array { return $this->types; } /** * @param SimpleType $givenType */ private function has(SimpleType $givenType): bool { foreach ($this->types as $type) { if ($type->equals($givenType)) { return true; } } return false; } public function equals(TypeInterface $givenType): bool { if (!$givenType instanceof IntersectionType) { return false; } if (count($this->types) !== count($givenType->getTypes())) { return false; } foreach ($this->types as $type) { if (!$givenType->has($type)) { return false; } } return true; } private function guard(): void { // Cannot contain void, never, null, scalar types, mixed, union types etc. foreach ($this->types as $type) { if (!$type instanceof ObjectType) { throw new DoubleException('Intersection types can only contain class/interface names.'); } } if (count($this->types) < 2) { throw new DoubleException('Intersection types must contain at least two types.'); } } public function __toString(): string { $result = ''; foreach ($this->types as $type) { if ($result !== '') { $result .= '&'; } $result .= (string) $type; } return $result; } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/Type/ObjectType.php ================================================ type; } /** * @return class-string */ public function getType(): string { return $this->type; } public function equals(TypeInterface $givenType): bool { if (!$givenType instanceof ObjectType) { return false; } return $this->getType() === $givenType->getType(); } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/Type/SimpleType.php ================================================ $types */ public function __construct(private array $types) { $this->guard(); } /** * @return list */ public function getTypes(): array { return $this->types; } private function guard(): void { $typeCount = count($this->types); if ($typeCount < 2) { // Throwing LogicException as this indicates misuse of the UnionType class itself. throw new DoubleException(sprintf( 'UnionType must be constructed with at least two types. Got %d.', $typeCount )); } // To detect duplicates $typeStrings = []; foreach ($this->types as $type) { if ($type instanceof UnionType) { throw new DoubleException('Union types cannot contain other unions.'); } if ($type instanceof IntersectionType) { $typeStrings[] = implode('&', array_map(fn(SimpleType $type) => (string) $type, $type->getTypes())); continue; // Valid type, nothing to be checked } if (!$type instanceof SimpleType) { throw new DoubleException(sprintf('Unexpected type "%s". Only IntersectionType and SimpleType are supported in UnionType.', get_class($type))); } $typeName = $type->getType(); $typeStrings[] = $typeName; if (in_array($typeName, ['void', 'never', 'mixed'], true)) { throw new DoubleException(sprintf('Type "%s" cannot be part of a union type.', $typeName)); } } // Rule: Union types cannot contain duplicate types (e.g., int|string|int is invalid). // Reflection usually resolves this, but it's good practice to ensure consistency. if (count(array_unique($typeStrings)) !== $typeCount) { throw new DoubleException(sprintf( 'Union types cannot contain duplicate types. Found duplicates in: %s', implode('|', $typeStrings) )); } } public function has(SimpleType|IntersectionType $givenType): bool { foreach ($this->types as $type) { if ($type->equals($givenType)) { return true; } } return false; } public function equals(TypeInterface $givenType): bool { if (!$givenType instanceof UnionType) { return false; } if (count($this->types) !== count($givenType->getTypes())) { return false; } foreach ($this->types as $type) { if (!$givenType->has($type)) { return false; } } return true; } public function __toString(): string { $result = ''; foreach ($this->types as $type) { if ($result !== '') { $result .= '|'; } if ($type instanceof IntersectionType && count($this->types) > 1) { $result .= '('.((string) $type).')'; continue; } $result .= (string) $type; } return $result; } } ================================================ FILE: src/Prophecy/Doubler/Generator/Node/TypeNodeAbstract.php ================================================ $union */ $union = []; foreach ($types as $type) { if (!is_string($type)) { throw new DoubleException('Building a TypeNode with string is deprecated. Mixing strings and type object is not allowed.'); } if ($this->isBuiltIn($type)) { $type = new BuiltinType($this->normalizeBuiltinType($type)); } else { /** @var class-string $typeName */ $typeName = $this->removePrefixNsSeparator($type); $type = new ObjectType($typeName); } if (!in_array($type->getType(), $typesNormalized, true)) { $union[] = $type; $typesNormalized[] = $type->getType(); } } if (count($union) > 1) { $this->type = new UnionType($union); } else { $this->type = $union[0]; } } else { /** @var TypeInterface|null $type */ $this->type = $type; } } /** * @deprecated use isNullable() instead */ public function canUseNullShorthand(): bool { trigger_deprecation( 'phpspec/prophecy', '1.23', 'This method is deprecated in favor of nullable()' ); if ($this->type instanceof UnionType) { return $this->type->has(new BuiltinType('null')) && count($this->type->getTypes()) === 2; } return false; } public function isNullable(): bool { if ($this->type instanceof UnionType) { return $this->type->has(new BuiltinType('null')); } if ($this->type instanceof SimpleType && $this->type->getType() === 'null') { return true; } return false; } /** * @return list * @deprecated use getType() instead */ public function getTypes(): array { trigger_deprecation( 'phpspec/prophecy', '1.23', 'This method is deprecated in favor of getType()', ); if ($this->type instanceof SimpleType) { return [(string) $this->type]; } $types = []; if ($this->type instanceof UnionType) { foreach ($this->type->getTypes() as $type) { if ($type instanceof IntersectionType) { throw new DoubleException('getType() method is deprecated and do not support IntersectionType by design. Use getType() instead.'); } $types[$type->getType()] = (string) $type; } } $types = array_values($types); $types = array_map([$this, 'normalizeBuiltinType'], $types); return array_values(array_unique($types)); } public function getType(): ?TypeInterface { return $this->type; } /** * @deprecated use getType() instead * @return list */ public function getNonNullTypes(): array { trigger_deprecation( 'phpspec/prophecy', '1.23', 'This method is deprecated in favor of getType() and the usage of the new type API.', ); if ($this->type === null) { return []; } if ($this->type instanceof UnionType) { $types = []; foreach ($this->type->getTypes() as $type) { if ($type instanceof IntersectionType) { throw new DoubleException('You are using the old (and deprecated) API which is not compatible with intersections'); } if (!$type instanceof BuiltinType || $type->getType() !== 'null') { $types[] = $type->getType(); } } return $types; } if ($this->type instanceof SimpleType) { if ($this->type->getType() === 'null') { return []; } return [$this->type->getType()]; } throw new DoubleException('getNonNullTypes() method is deprecated and do not support IntersectionType by design. Use getType() instead.'); } private function normalizeBuiltinType(string $type): string { switch ($type) { // normalize alias types case 'double': case 'real': return 'float'; case 'integer': return 'int'; case 'boolean': return 'bool'; default: return $type; } } protected function isBuiltIn(string $type): bool { switch ($type) { // type aliases case 'double': case 'real': case 'boolean': case 'integer': // built in types case 'self': case 'static': case 'array': case 'callable': case 'bool': case 'false': case 'true': case 'float': case 'int': case 'string': case 'iterable': case 'object': case 'null': case 'mixed': case 'void': case 'never': return true; default: // Class / Interface type return false; } } protected function removePrefixNsSeparator(string $type): string { return ltrim($type, '\\'); } } ================================================ FILE: src/Prophecy/Doubler/Generator/ReflectionInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler\Generator; /** * Reflection interface. * All reflected classes implement this interface. * * @author Konstantin Kudryashov */ interface ReflectionInterface {} ================================================ FILE: src/Prophecy/Doubler/Generator/TypeHintReference.php ================================================ isBuiltInParamTypeHint($type); } } ================================================ FILE: src/Prophecy/Doubler/LazyDouble.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler; use Prophecy\Exception\Doubler\DoubleException; use Prophecy\Exception\Doubler\ClassNotFoundException; use Prophecy\Exception\Doubler\InterfaceNotFoundException; use ReflectionClass; /** * Lazy double. * Gives simple interface to describe double before creating it. * * @template T of object * * @author Konstantin Kudryashov */ class LazyDouble { private $doubler; /** * @var ReflectionClass|null */ private $class; /** * @var list> */ private $interfaces = array(); /** * @var array|null */ private $arguments = null; /** * @var (T&DoubleInterface)|null */ private $double; public function __construct(Doubler $doubler) { $this->doubler = $doubler; } /** * Tells doubler to use specific class as parent one for double. * * @param class-string|ReflectionClass $class * * @return void * * @template U of object * @phpstan-param class-string|ReflectionClass $class * @phpstan-this-out static * * @throws ClassNotFoundException * @throws DoubleException */ public function setParentClass($class) { if (null !== $this->double) { throw new DoubleException('Can not extend class with already instantiated double.'); } if (!$class instanceof ReflectionClass) { if (!class_exists($class)) { throw new ClassNotFoundException(sprintf('Class %s not found.', $class), $class); } $class = new ReflectionClass($class); } /** @var static $this */ $this->class = $class; } /** * Tells doubler to implement specific interface with double. * * @param class-string|ReflectionClass $interface * * @return void * * @template U of object * @phpstan-param class-string|ReflectionClass $interface * @phpstan-this-out static * * @throws InterfaceNotFoundException * @throws DoubleException */ public function addInterface($interface) { if (null !== $this->double) { throw new DoubleException( 'Can not implement interface with already instantiated double.' ); } if (!$interface instanceof ReflectionClass) { if (!interface_exists($interface)) { throw new InterfaceNotFoundException( sprintf('Interface %s not found.', $interface), $interface ); } $interface = new ReflectionClass($interface); } $this->interfaces[] = $interface; } /** * Sets constructor arguments. * * @param array|null $arguments * * @return void */ public function setArguments(?array $arguments = null) { $this->arguments = $arguments; } /** * Creates double instance or returns already created one. * * @return T&DoubleInterface */ public function getInstance() { if (null === $this->double) { if (null !== $this->arguments) { return $this->double = $this->doubler->double( $this->class, $this->interfaces, $this->arguments ); } $this->double = $this->doubler->double($this->class, $this->interfaces); } return $this->double; } } ================================================ FILE: src/Prophecy/Doubler/NameGenerator.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Doubler; use ReflectionClass; /** * Name generator. * Generates classname for double. * * @author Konstantin Kudryashov */ class NameGenerator { /** * @var int */ private static $counter = 1; /** * Generates name. * * @param ReflectionClass|null $class * @param ReflectionClass[] $interfaces * * @return string */ public function name(?ReflectionClass $class, array $interfaces) { $parts = array(); if (null !== $class) { $parts[] = $class->getName(); } else { foreach ($interfaces as $interface) { $parts[] = $interface->getShortName(); } } if (!count($parts)) { $parts[] = 'stdClass'; } return sprintf('Double\%s\P%d', implode('\\', $parts), self::$counter++); } } ================================================ FILE: src/Prophecy/Exception/Call/UnexpectedCallException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Call; use Prophecy\Exception\Prophecy\ObjectProphecyException; use Prophecy\Prophecy\ObjectProphecy; class UnexpectedCallException extends ObjectProphecyException { private $methodName; private $arguments; /** * @param string $message * @param ObjectProphecy $objectProphecy * @param string $methodName * @param array $arguments */ public function __construct($message, ObjectProphecy $objectProphecy, $methodName, array $arguments) { parent::__construct($message, $objectProphecy); $this->methodName = $methodName; $this->arguments = $arguments; } /** * @return string */ public function getMethodName() { return $this->methodName; } /** * @return array */ public function getArguments() { return $this->arguments; } } ================================================ FILE: src/Prophecy/Exception/Doubler/ClassCreatorException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; use Prophecy\Doubler\Generator\Node\ClassNode; class ClassCreatorException extends \RuntimeException implements DoublerException { private $node; /** * @param string $message * @param ClassNode $node */ public function __construct($message, ClassNode $node) { parent::__construct($message); $this->node = $node; } /** * @return ClassNode */ public function getClassNode() { return $this->node; } } ================================================ FILE: src/Prophecy/Exception/Doubler/ClassMirrorException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; use ReflectionClass; class ClassMirrorException extends \RuntimeException implements DoublerException { private $class; /** * @param string $message * @param ReflectionClass $class */ public function __construct($message, ReflectionClass $class) { parent::__construct($message); $this->class = $class; } /** * @return ReflectionClass */ public function getReflectedClass() { return $this->class; } } ================================================ FILE: src/Prophecy/Exception/Doubler/ClassNotFoundException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; class ClassNotFoundException extends DoubleException { private $classname; /** * @param string $message * @param string $classname */ public function __construct($message, $classname) { parent::__construct($message); $this->classname = $classname; } /** * @return string */ public function getClassname() { return $this->classname; } } ================================================ FILE: src/Prophecy/Exception/Doubler/DoubleException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; use RuntimeException; class DoubleException extends RuntimeException implements DoublerException {} ================================================ FILE: src/Prophecy/Exception/Doubler/DoublerException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; use Prophecy\Exception\Exception; interface DoublerException extends Exception {} ================================================ FILE: src/Prophecy/Exception/Doubler/InterfaceNotFoundException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; class InterfaceNotFoundException extends ClassNotFoundException { /** * @return string */ public function getInterfaceName() { return $this->getClassname(); } } ================================================ FILE: src/Prophecy/Exception/Doubler/MethodNotExtendableException.php ================================================ methodName = $methodName; $this->className = $className; } /** * @return string */ public function getMethodName() { return $this->methodName; } /** * @return string */ public function getClassName() { return $this->className; } } ================================================ FILE: src/Prophecy/Exception/Doubler/MethodNotFoundException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; use Prophecy\Argument\ArgumentsWildcard; class MethodNotFoundException extends DoubleException { /** * @var string|object */ private $classname; /** * @var string */ private $methodName; /** * @var null|ArgumentsWildcard|array */ private $arguments; /** * @param string $message * @param string|object $classname * @param string $methodName * @param null|ArgumentsWildcard|array $arguments */ public function __construct($message, $classname, $methodName, $arguments = null) { parent::__construct($message); $this->classname = $classname; $this->methodName = $methodName; $this->arguments = $arguments; } /** * @return object|string */ public function getClassname() { return $this->classname; } /** * @return string */ public function getMethodName() { return $this->methodName; } /** * @return null|ArgumentsWildcard|array */ public function getArguments() { return $this->arguments; } } ================================================ FILE: src/Prophecy/Exception/Doubler/ReturnByReferenceException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Doubler; class ReturnByReferenceException extends DoubleException { private $classname; private $methodName; /** * @param string $message * @param string $classname * @param string $methodName */ public function __construct($message, $classname, $methodName) { parent::__construct($message); $this->classname = $classname; $this->methodName = $methodName; } /** * @return string */ public function getClassname() { return $this->classname; } /** * @return string */ public function getMethodName() { return $this->methodName; } } ================================================ FILE: src/Prophecy/Exception/Exception.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception; /** * Core Prophecy exception interface. * All Prophecy exceptions implement it. * * @author Konstantin Kudryashov */ interface Exception extends \Throwable {} ================================================ FILE: src/Prophecy/Exception/InvalidArgumentException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception; class InvalidArgumentException extends \InvalidArgumentException implements Exception {} ================================================ FILE: src/Prophecy/Exception/Prediction/AggregateException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prediction; use Prophecy\Prophecy\ObjectProphecy; class AggregateException extends \RuntimeException implements PredictionException { /** * @var list */ private $exceptions = array(); /** * @var ObjectProphecy|null */ private $objectProphecy; /** * @return void */ public function append(PredictionException $exception) { $message = $exception->getMessage(); $message = strtr($message, array("\n" => "\n "))."\n"; $message = empty($this->exceptions) ? $message : "\n".$message; $this->message = rtrim($this->message.$message); $this->exceptions[] = $exception; } /** * @return list */ public function getExceptions() { return $this->exceptions; } /** * @param ObjectProphecy $objectProphecy * * @return void */ public function setObjectProphecy(ObjectProphecy $objectProphecy) { $this->objectProphecy = $objectProphecy; } /** * @return ObjectProphecy|null */ public function getObjectProphecy() { return $this->objectProphecy; } } ================================================ FILE: src/Prophecy/Exception/Prediction/FailedPredictionException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prediction; use RuntimeException; /** * Basic failed prediction exception. * Use it for custom prediction failures. * * @author Konstantin Kudryashov */ class FailedPredictionException extends RuntimeException implements PredictionException {} ================================================ FILE: src/Prophecy/Exception/Prediction/NoCallsException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prediction; use Prophecy\Exception\Prophecy\MethodProphecyException; class NoCallsException extends MethodProphecyException implements PredictionException {} ================================================ FILE: src/Prophecy/Exception/Prediction/PredictionException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prediction; use Prophecy\Exception\Exception; interface PredictionException extends Exception {} ================================================ FILE: src/Prophecy/Exception/Prediction/UnexpectedCallsCountException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prediction; use Prophecy\Call\Call; use Prophecy\Prophecy\MethodProphecy; class UnexpectedCallsCountException extends UnexpectedCallsException { private $expectedCount; /** * @param string $message * @param MethodProphecy $methodProphecy * @param int $count * @param array $calls */ public function __construct($message, MethodProphecy $methodProphecy, $count, array $calls) { parent::__construct($message, $methodProphecy, $calls); $this->expectedCount = intval($count); } /** * @return int */ public function getExpectedCount() { return $this->expectedCount; } } ================================================ FILE: src/Prophecy/Exception/Prediction/UnexpectedCallsException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prediction; use Prophecy\Call\Call; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Exception\Prophecy\MethodProphecyException; class UnexpectedCallsException extends MethodProphecyException implements PredictionException { /** @var list */ private $calls; /** * @param string $message * @param MethodProphecy $methodProphecy * @param array $calls */ public function __construct($message, MethodProphecy $methodProphecy, array $calls) { parent::__construct($message, $methodProphecy); $this->calls = array_values($calls); } /** * @return list */ public function getCalls() { return $this->calls; } } ================================================ FILE: src/Prophecy/Exception/Prophecy/MethodProphecyException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prophecy; use Prophecy\Prophecy\MethodProphecy; class MethodProphecyException extends ObjectProphecyException { private $methodProphecy; /** * @param string $message */ public function __construct($message, MethodProphecy $methodProphecy, ?\Throwable $previous = null) { parent::__construct($message, $methodProphecy->getObjectProphecy(), $previous); $this->methodProphecy = $methodProphecy; } /** * @return MethodProphecy */ public function getMethodProphecy() { return $this->methodProphecy; } } ================================================ FILE: src/Prophecy/Exception/Prophecy/ObjectProphecyException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prophecy; use Prophecy\Prophecy\ObjectProphecy; class ObjectProphecyException extends \RuntimeException implements ProphecyException { private $objectProphecy; /** * @param string $message * @param ObjectProphecy $objectProphecy */ public function __construct($message, ObjectProphecy $objectProphecy, ?\Throwable $previous = null) { parent::__construct($message, 0, $previous); $this->objectProphecy = $objectProphecy; } /** * @return ObjectProphecy */ public function getObjectProphecy() { return $this->objectProphecy; } } ================================================ FILE: src/Prophecy/Exception/Prophecy/ProphecyException.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Exception\Prophecy; use Prophecy\Exception\Exception; interface ProphecyException extends Exception {} ================================================ FILE: src/Prophecy/PhpDocumentor/ClassAndInterfaceTagRetriever.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\PhpDocumentor; use phpDocumentor\Reflection\DocBlock\Tags\Method; /** * @author Théo FIDRY * * @internal */ final class ClassAndInterfaceTagRetriever implements MethodTagRetrieverInterface { /** * @var MethodTagRetrieverInterface */ private $classRetriever; public function __construct(?MethodTagRetrieverInterface $classRetriever = null) { if (null !== $classRetriever) { $this->classRetriever = $classRetriever; return; } $this->classRetriever = new ClassTagRetriever(); } public function getTagList(\ReflectionClass $reflectionClass) { return array_merge( $this->classRetriever->getTagList($reflectionClass), $this->getInterfacesTagList($reflectionClass) ); } /** * @param \ReflectionClass $reflectionClass * * @return list */ private function getInterfacesTagList(\ReflectionClass $reflectionClass) { $interfaces = $reflectionClass->getInterfaces(); $tagList = array(); foreach ($interfaces as $interface) { $tagList = array_merge($tagList, $this->classRetriever->getTagList($interface)); } return $tagList; } } ================================================ FILE: src/Prophecy/PhpDocumentor/ClassTagRetriever.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\PhpDocumentor; use phpDocumentor\Reflection\DocBlock\Tags\Method; use phpDocumentor\Reflection\DocBlockFactory; use phpDocumentor\Reflection\Types\ContextFactory; /** * @author Théo FIDRY * * @internal */ final class ClassTagRetriever implements MethodTagRetrieverInterface { private $docBlockFactory; private $contextFactory; public function __construct() { $this->docBlockFactory = DocBlockFactory::createInstance(); $this->contextFactory = new ContextFactory(); } public function getTagList(\ReflectionClass $reflectionClass) { try { $phpdoc = $this->docBlockFactory->create( $reflectionClass, $this->contextFactory->createFromReflector($reflectionClass) ); $methods = array(); foreach ($phpdoc->getTagsByName('method') as $tag) { if ($tag instanceof Method) { $methods[] = $tag; } } return $methods; } catch (\InvalidArgumentException $e) { return array(); } } } ================================================ FILE: src/Prophecy/PhpDocumentor/MethodTagRetrieverInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\PhpDocumentor; use phpDocumentor\Reflection\DocBlock\Tags\Method; /** * @author Théo FIDRY * * @internal */ interface MethodTagRetrieverInterface { /** * @param \ReflectionClass $reflectionClass * * @return list */ public function getTagList(\ReflectionClass $reflectionClass); } ================================================ FILE: src/Prophecy/Prediction/CallPrediction.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prediction; use Prophecy\Call\Call; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Argument\ArgumentsWildcard; use Prophecy\Argument\Token\AnyValuesToken; use Prophecy\Util\StringUtil; use Prophecy\Exception\Prediction\NoCallsException; /** * Tests that there was at least one call. * * @author Konstantin Kudryashov */ class CallPrediction implements PredictionInterface { private $util; public function __construct(?StringUtil $util = null) { $this->util = $util ?: new StringUtil(); } public function check(array $calls, ObjectProphecy $object, MethodProphecy $method) { if (count($calls)) { return; } $methodCalls = $object->findProphecyMethodCalls( $method->getMethodName(), new ArgumentsWildcard(array(new AnyValuesToken())) ); if (count($methodCalls)) { throw new NoCallsException(sprintf( "No calls have been made that match:\n" ." %s->%s(%s)\n" ."but expected at least one.\n" ."Recorded `%s(...)` calls:\n%s", get_class($object->reveal()), $method->getMethodName(), $method->getArgumentsWildcard(), $method->getMethodName(), $this->util->stringifyCalls($methodCalls) ), $method); } throw new NoCallsException(sprintf( "No calls have been made that match:\n" ." %s->%s(%s)\n" ."but expected at least one.", get_class($object->reveal()), $method->getMethodName(), $method->getArgumentsWildcard() ), $method); } } ================================================ FILE: src/Prophecy/Prediction/CallTimesPrediction.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prediction; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Argument\ArgumentsWildcard; use Prophecy\Argument\Token\AnyValuesToken; use Prophecy\Util\StringUtil; use Prophecy\Exception\Prediction\UnexpectedCallsCountException; /** * Tests that there was exact amount of calls made. * * @author Konstantin Kudryashov */ class CallTimesPrediction implements PredictionInterface { private $times; private $util; /** * @param int $times */ public function __construct($times, ?StringUtil $util = null) { $this->times = intval($times); $this->util = $util ?: new StringUtil(); } public function check(array $calls, ObjectProphecy $object, MethodProphecy $method) { if ($this->times == count($calls)) { return; } $methodCalls = $object->findProphecyMethodCalls( $method->getMethodName(), new ArgumentsWildcard(array(new AnyValuesToken())) ); if (count($calls)) { $message = sprintf( "Expected exactly %d calls that match:\n" ." %s->%s(%s)\n" ."but %d were made:\n%s", $this->times, get_class($object->reveal()), $method->getMethodName(), $method->getArgumentsWildcard(), count($calls), $this->util->stringifyCalls($calls) ); } elseif (count($methodCalls)) { $message = sprintf( "Expected exactly %d calls that match:\n" ." %s->%s(%s)\n" ."but none were made.\n" ."Recorded `%s(...)` calls:\n%s", $this->times, get_class($object->reveal()), $method->getMethodName(), $method->getArgumentsWildcard(), $method->getMethodName(), $this->util->stringifyCalls($methodCalls) ); } else { $message = sprintf( "Expected exactly %d calls that match:\n" ." %s->%s(%s)\n" ."but none were made.", $this->times, get_class($object->reveal()), $method->getMethodName(), $method->getArgumentsWildcard() ); } throw new UnexpectedCallsCountException($message, $method, $this->times, $calls); } } ================================================ FILE: src/Prophecy/Prediction/CallbackPrediction.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prediction; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Exception\InvalidArgumentException; use Closure; use ReflectionFunction; /** * Executes preset callback. * * @author Konstantin Kudryashov */ class CallbackPrediction implements PredictionInterface { private $callback; /** * @param callable $callback Custom callback * * @throws \Prophecy\Exception\InvalidArgumentException */ public function __construct($callback) { if (!is_callable($callback)) { throw new InvalidArgumentException(sprintf( 'Callable expected as an argument to CallbackPrediction, but got %s.', gettype($callback) )); } $this->callback = $callback; } public function check(array $calls, ObjectProphecy $object, MethodProphecy $method) { $callback = $this->callback; if ($callback instanceof Closure && (new ReflectionFunction($callback))->getClosureThis() !== null) { $callback = Closure::bind($callback, $object) ?? $this->callback; } call_user_func($callback, $calls, $object, $method); } } ================================================ FILE: src/Prophecy/Prediction/NoCallsPrediction.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prediction; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Util\StringUtil; use Prophecy\Exception\Prediction\UnexpectedCallsException; /** * Tests that there were no calls made. * * @author Konstantin Kudryashov */ class NoCallsPrediction implements PredictionInterface { private $util; public function __construct(?StringUtil $util = null) { $this->util = $util ?: new StringUtil(); } public function check(array $calls, ObjectProphecy $object, MethodProphecy $method) { if (!count($calls)) { return; } $verb = count($calls) === 1 ? 'was' : 'were'; throw new UnexpectedCallsException(sprintf( "No calls expected that match:\n" ." %s->%s(%s)\n" ."but %d %s made:\n%s", get_class($object->reveal()), $method->getMethodName(), $method->getArgumentsWildcard(), count($calls), $verb, $this->util->stringifyCalls($calls) ), $method, $calls); } } ================================================ FILE: src/Prophecy/Prediction/PredictionInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prediction; use Prophecy\Call\Call; use Prophecy\Exception\Prediction\PredictionException; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; /** * Prediction interface. * Predictions are logical test blocks, tied to `should...` keyword. * * @author Konstantin Kudryashov */ interface PredictionInterface { /** * Tests that double fulfilled prediction. * * @param Call[] $calls * @param ObjectProphecy $object * @param MethodProphecy $method * * @throws PredictionException * @return void */ public function check(array $calls, ObjectProphecy $object, MethodProphecy $method); } ================================================ FILE: src/Prophecy/Promise/CallbackPromise.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Promise; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Exception\InvalidArgumentException; use Closure; use ReflectionFunction; /** * Evaluates promise callback. * * @author Konstantin Kudryashov */ class CallbackPromise implements PromiseInterface { private $callback; /** * Initializes callback promise. * * @param callable $callback Custom callback * * @throws \Prophecy\Exception\InvalidArgumentException */ public function __construct($callback) { if (!is_callable($callback)) { throw new InvalidArgumentException(sprintf( 'Callable expected as an argument to CallbackPromise, but got %s.', gettype($callback) )); } $this->callback = $callback; } public function execute(array $args, ObjectProphecy $object, MethodProphecy $method) { $callback = $this->callback; if ($callback instanceof Closure && (new ReflectionFunction($callback))->getClosureThis() !== null) { $callback = Closure::bind($callback, $object) ?? $this->callback; } return call_user_func($callback, $args, $object, $method); } } ================================================ FILE: src/Prophecy/Promise/PromiseInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Promise; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; /** * Promise interface. * Promises are logical blocks, tied to `will...` keyword. * * @author Konstantin Kudryashov */ interface PromiseInterface { /** * Evaluates promise. * * @param array $args * @param ObjectProphecy $object * @param MethodProphecy $method * * @return mixed */ public function execute(array $args, ObjectProphecy $object, MethodProphecy $method); } ================================================ FILE: src/Prophecy/Promise/ReturnArgumentPromise.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Promise; use Prophecy\Exception\InvalidArgumentException; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; /** * Returns nth argument if has one, null otherwise. * * @author Konstantin Kudryashov */ class ReturnArgumentPromise implements PromiseInterface { /** * @var int */ private $index; /** * Initializes callback promise. * * @param int $index The zero-indexed number of the argument to return * * @throws \Prophecy\Exception\InvalidArgumentException */ public function __construct($index = 0) { if (!is_int($index) || $index < 0) { throw new InvalidArgumentException(sprintf( 'Zero-based index expected as argument to ReturnArgumentPromise, but got %s.', $index )); } $this->index = $index; } public function execute(array $args, ObjectProphecy $object, MethodProphecy $method) { return count($args) > $this->index ? $args[$this->index] : null; } } ================================================ FILE: src/Prophecy/Promise/ReturnPromise.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Promise; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; /** * Returns saved values one by one until last one, then continuously returns last value. * * @author Konstantin Kudryashov */ class ReturnPromise implements PromiseInterface { private $returnValues = array(); /** * Initializes promise. * * @param array $returnValues Array of values */ public function __construct(array $returnValues) { $this->returnValues = $returnValues; } public function execute(array $args, ObjectProphecy $object, MethodProphecy $method) { $value = array_shift($this->returnValues); if (!count($this->returnValues)) { $this->returnValues[] = $value; } return $value; } } ================================================ FILE: src/Prophecy/Promise/ThrowPromise.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Promise; use Doctrine\Instantiator\Instantiator; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\MethodProphecy; use Prophecy\Exception\InvalidArgumentException; use ReflectionClass; /** * Throws predefined exception. * * @author Konstantin Kudryashov */ class ThrowPromise implements PromiseInterface { private $exception; /** * @var Instantiator|null */ private $instantiator; /** * Initializes promise. * * @param string|\Throwable $exception Exception class name or instance * * @throws \Prophecy\Exception\InvalidArgumentException * * @phpstan-param class-string<\Throwable>|\Throwable $exception */ public function __construct($exception) { if (is_string($exception)) { if ((!class_exists($exception) && !interface_exists($exception)) || !$this->isAValidThrowable($exception)) { throw new InvalidArgumentException(sprintf( 'Exception / Throwable class or instance expected as argument to ThrowPromise, but got %s.', $exception )); } } elseif (!$exception instanceof \Exception && !$exception instanceof \Throwable) { throw new InvalidArgumentException(sprintf( 'Exception / Throwable class or instance expected as argument to ThrowPromise, but got %s.', is_object($exception) ? get_class($exception) : gettype($exception) )); } $this->exception = $exception; } public function execute(array $args, ObjectProphecy $object, MethodProphecy $method) { if (is_string($this->exception)) { $classname = $this->exception; $reflection = new ReflectionClass($classname); $constructor = $reflection->getConstructor(); if ($constructor === null || $constructor->isPublic() && 0 == $constructor->getNumberOfRequiredParameters()) { throw $reflection->newInstance(); } if (!$this->instantiator) { $this->instantiator = new Instantiator(); } throw $this->instantiator->instantiate($classname); } throw $this->exception; } /** * @param string $exception * * @return bool */ private function isAValidThrowable($exception) { return is_a($exception, 'Exception', true) || is_a($exception, 'Throwable', true); } } ================================================ FILE: src/Prophecy/Prophecy/MethodProphecy.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prophecy; use Prophecy\Argument; use Prophecy\Exception\Doubler\ClassMirrorException; use Prophecy\Exception\Prediction\PredictionException; use Prophecy\Prophet; use Prophecy\Promise; use Prophecy\Prediction; use Prophecy\Exception\Doubler\MethodNotFoundException; use Prophecy\Exception\InvalidArgumentException; use Prophecy\Exception\Prophecy\MethodProphecyException; use ReflectionNamedType; use ReflectionUnionType; /** * Method prophecy. * * @author Konstantin Kudryashov */ class MethodProphecy { private $objectProphecy; private $methodName; /** * @var Argument\ArgumentsWildcard */ private $argumentsWildcard; /** * @var Promise\PromiseInterface|null */ private $promise; /** * @var Prediction\PredictionInterface|null */ private $prediction; /** * @var list */ private $checkedPredictions = array(); /** * @var bool */ private $bound = false; /** * @var bool */ private $voidReturnType = false; /** * @param ObjectProphecy $objectProphecy * @param string $methodName * @param Argument\ArgumentsWildcard|array $arguments * * @throws \Prophecy\Exception\Doubler\MethodNotFoundException If method not found * * @internal */ public function __construct(ObjectProphecy $objectProphecy, $methodName, $arguments) { $double = $objectProphecy->reveal(); if (!method_exists($double, $methodName)) { throw new MethodNotFoundException(sprintf( 'Method `%s::%s()` is not defined.', get_class($double), $methodName ), get_class($double), $methodName, $arguments); } $this->objectProphecy = $objectProphecy; $this->methodName = $methodName; $reflectedMethod = new \ReflectionMethod($double, $methodName); if ($reflectedMethod->isFinal()) { throw new MethodProphecyException(sprintf( "Can not add prophecy for a method `%s::%s()`\n" ."as it is a final method.", get_class($double), $methodName ), $this); } $this->withArguments($arguments); $hasTentativeReturnType = method_exists($reflectedMethod, 'hasTentativeReturnType') && $reflectedMethod->hasTentativeReturnType(); if (true === $reflectedMethod->hasReturnType() || $hasTentativeReturnType) { if ($hasTentativeReturnType) { $reflectionType = $reflectedMethod->getTentativeReturnType(); } else { $reflectionType = $reflectedMethod->getReturnType(); } if ($reflectionType instanceof ReflectionNamedType) { $types = [$reflectionType]; } elseif ($reflectionType instanceof ReflectionUnionType) { $types = $reflectionType->getTypes(); } else { throw new MethodProphecyException(sprintf( "Can not add prophecy for a method `%s::%s()`\nas its return type is not supported by Prophecy yet.", get_class($double), $methodName ), $this); } $types = array_map( function (ReflectionNamedType $type) { return $type->getName(); }, $types ); usort( $types, static function (string $type1, string $type2) { // null is lowest priority if ($type2 == 'null') { return -1; } elseif ($type1 == 'null') { return 1; } // objects are higher priority than scalars $isObject = static function ($type) { return class_exists($type) || interface_exists($type); }; if ($isObject($type1) && !$isObject($type2)) { return -1; } elseif (!$isObject($type1) && $isObject($type2)) { return 1; } // don't sort both-scalars or both-objects return 0; } ); $defaultType = $types[0]; if ('void' === $defaultType) { $this->voidReturnType = true; } $this->will(function ($args, ObjectProphecy $object, MethodProphecy $method) use ($defaultType) { switch ($defaultType) { case 'void': return; case 'string': return ''; case 'float': return 0.0; case 'int': return 0; case 'bool': return false; case 'array': return array(); case 'true': return true; case 'false': return false; case 'null': return null; case 'callable': case 'Closure': return function () {}; case 'Traversable': case 'Generator': return (function () { yield; })(); case 'object': $prophet = new Prophet(); return $prophet->prophesize()->reveal(); default: if (!class_exists($defaultType) && !interface_exists($defaultType)) { throw new MethodProphecyException(sprintf('Cannot create a return value for the method as the type "%s" is not supported. Configure an explicit return value instead.', $defaultType), $method); } $prophet = new Prophet(); try { return $prophet->prophesize($defaultType)->reveal(); } catch (ClassMirrorException $e) { throw new MethodProphecyException(\sprintf('Cannot create a return value for the method. Configure an explicit return value instead.'), $method, $e); } } }); } } /** * Sets argument wildcard. * * @param array|Argument\ArgumentsWildcard $arguments * * @return $this * * @throws \Prophecy\Exception\InvalidArgumentException */ public function withArguments($arguments) { if (is_array($arguments)) { $arguments = new Argument\ArgumentsWildcard($arguments); } if (!$arguments instanceof Argument\ArgumentsWildcard) { throw new InvalidArgumentException(sprintf( "Either an array or an instance of ArgumentsWildcard expected as\n" .'a `MethodProphecy::withArguments()` argument, but got %s.', gettype($arguments) )); } $this->argumentsWildcard = $arguments; return $this; } /** * Sets custom promise to the prophecy. * * @param callable|Promise\PromiseInterface $promise * * @return $this * * @throws \Prophecy\Exception\InvalidArgumentException */ public function will($promise) { if (is_callable($promise)) { $promise = new Promise\CallbackPromise($promise); } if (!$promise instanceof Promise\PromiseInterface) { throw new InvalidArgumentException(sprintf( 'Expected callable or instance of PromiseInterface, but got %s.', gettype($promise) )); } $this->bindToObjectProphecy(); $this->promise = $promise; return $this; } /** * Sets return promise to the prophecy. * * @see \Prophecy\Promise\ReturnPromise * * @param mixed ...$return a list of return values * * @return $this */ public function willReturn(...$return) { if ($this->voidReturnType) { throw new MethodProphecyException( "The method \"$this->methodName\" has a void return type, and so cannot return anything", $this ); } return $this->will(new Promise\ReturnPromise($return)); } /** * @param array $items * @param mixed $return * * @return $this * * @throws \Prophecy\Exception\InvalidArgumentException */ public function willYield($items, $return = null) { if ($this->voidReturnType) { throw new MethodProphecyException( "The method \"$this->methodName\" has a void return type, and so cannot yield anything", $this ); } if (!is_array($items)) { throw new InvalidArgumentException(sprintf( 'Expected array, but got %s.', gettype($items) )); } $generator = function () use ($items, $return) { yield from $items; return $return; }; return $this->will($generator); } /** * Sets return argument promise to the prophecy. * * @param int $index The zero-indexed number of the argument to return * * @see \Prophecy\Promise\ReturnArgumentPromise * * @return $this */ public function willReturnArgument($index = 0) { if ($this->voidReturnType) { throw new MethodProphecyException("The method \"$this->methodName\" has a void return type", $this); } return $this->will(new Promise\ReturnArgumentPromise($index)); } /** * Sets throw promise to the prophecy. * * @see \Prophecy\Promise\ThrowPromise * * @param string|\Throwable $exception Exception class or instance * * @return $this * * @phpstan-param class-string<\Throwable>|\Throwable $exception */ public function willThrow($exception) { return $this->will(new Promise\ThrowPromise($exception)); } /** * Sets custom prediction to the prophecy. * * @param callable|Prediction\PredictionInterface $prediction * * @return $this * * @throws \Prophecy\Exception\InvalidArgumentException */ public function should($prediction) { if (is_callable($prediction)) { $prediction = new Prediction\CallbackPrediction($prediction); } if (!$prediction instanceof Prediction\PredictionInterface) { throw new InvalidArgumentException(sprintf( 'Expected callable or instance of PredictionInterface, but got %s.', gettype($prediction) )); } $this->bindToObjectProphecy(); $this->prediction = $prediction; return $this; } /** * Sets call prediction to the prophecy. * * @see \Prophecy\Prediction\CallPrediction * * @return $this */ public function shouldBeCalled() { return $this->should(new Prediction\CallPrediction()); } /** * Sets no calls prediction to the prophecy. * * @see \Prophecy\Prediction\NoCallsPrediction * * @return $this */ public function shouldNotBeCalled() { return $this->should(new Prediction\NoCallsPrediction()); } /** * Sets call times prediction to the prophecy. * * @see \Prophecy\Prediction\CallTimesPrediction * * @param int $count * * @return $this */ public function shouldBeCalledTimes($count) { return $this->should(new Prediction\CallTimesPrediction($count)); } /** * Sets call times prediction to the prophecy. * * @see \Prophecy\Prediction\CallTimesPrediction * * @return $this */ public function shouldBeCalledOnce() { return $this->shouldBeCalledTimes(1); } /** * Checks provided prediction immediately. * * @param callable|Prediction\PredictionInterface $prediction * * @return $this * * @throws \Prophecy\Exception\InvalidArgumentException * @throws PredictionException */ public function shouldHave($prediction) { if (is_callable($prediction)) { $prediction = new Prediction\CallbackPrediction($prediction); } if (!$prediction instanceof Prediction\PredictionInterface) { throw new InvalidArgumentException(sprintf( 'Expected callable or instance of PredictionInterface, but got %s.', gettype($prediction) )); } if (null === $this->promise && !$this->voidReturnType) { $this->willReturn(); } $calls = $this->getObjectProphecy()->findProphecyMethodCalls( $this->getMethodName(), $this->getArgumentsWildcard() ); try { $prediction->check($calls, $this->getObjectProphecy(), $this); $this->checkedPredictions[] = $prediction; } catch (\Exception $e) { $this->checkedPredictions[] = $prediction; throw $e; } return $this; } /** * Checks call prediction. * * @see \Prophecy\Prediction\CallPrediction * * @return $this * * @throws PredictionException */ public function shouldHaveBeenCalled() { return $this->shouldHave(new Prediction\CallPrediction()); } /** * Checks no calls prediction. * * @see \Prophecy\Prediction\NoCallsPrediction * * @return $this * * @throws PredictionException */ public function shouldNotHaveBeenCalled() { return $this->shouldHave(new Prediction\NoCallsPrediction()); } /** * Checks no calls prediction. * * @see \Prophecy\Prediction\NoCallsPrediction * @deprecated * * @return $this */ public function shouldNotBeenCalled() { return $this->shouldNotHaveBeenCalled(); } /** * Checks call times prediction. * * @see \Prophecy\Prediction\CallTimesPrediction * * @param int $count * * @return $this */ public function shouldHaveBeenCalledTimes($count) { return $this->shouldHave(new Prediction\CallTimesPrediction($count)); } /** * Checks call times prediction. * * @see \Prophecy\Prediction\CallTimesPrediction * * @return $this */ public function shouldHaveBeenCalledOnce() { return $this->shouldHaveBeenCalledTimes(1); } /** * Checks currently registered [with should(...)] prediction. * * @return void * * @throws PredictionException */ public function checkPrediction() { if (null === $this->prediction) { return; } $this->shouldHave($this->prediction); } /** * Returns currently registered promise. * * @return null|Promise\PromiseInterface */ public function getPromise() { return $this->promise; } /** * Returns currently registered prediction. * * @return null|Prediction\PredictionInterface */ public function getPrediction() { return $this->prediction; } /** * Returns predictions that were checked on this object. * * @return list */ public function getCheckedPredictions() { return $this->checkedPredictions; } /** * Returns object prophecy this method prophecy is tied to. * * @return ObjectProphecy */ public function getObjectProphecy() { return $this->objectProphecy; } /** * Returns method name. * * @return string */ public function getMethodName() { return $this->methodName; } /** * Returns arguments wildcard. * * @return Argument\ArgumentsWildcard */ public function getArgumentsWildcard() { return $this->argumentsWildcard; } /** * @return bool */ public function hasReturnVoid() { return $this->voidReturnType; } /** * @return void */ private function bindToObjectProphecy() { if ($this->bound) { return; } $this->getObjectProphecy()->addMethodProphecy($this); $this->bound = true; } } ================================================ FILE: src/Prophecy/Prophecy/ObjectProphecy.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prophecy; use Prophecy\Comparator\FactoryProvider; use SebastianBergmann\Comparator\ComparisonFailure; use SebastianBergmann\Comparator\Factory as ComparatorFactory; use Prophecy\Call\Call; use Prophecy\Doubler\LazyDouble; use Prophecy\Argument\ArgumentsWildcard; use Prophecy\Call\CallCenter; use Prophecy\Exception\Prophecy\ObjectProphecyException; use Prophecy\Exception\Prediction\AggregateException; use Prophecy\Exception\Prediction\PredictionException; /** * @author Konstantin Kudryashov * * @template-covariant T of object * @template-implements ProphecyInterface */ class ObjectProphecy implements ProphecyInterface { /** * @var LazyDouble */ private $lazyDouble; private $callCenter; private $revealer; private $comparatorFactory; /** * @var array> */ private $methodProphecies = array(); /** * @param LazyDouble $lazyDouble */ public function __construct( LazyDouble $lazyDouble, ?CallCenter $callCenter = null, ?RevealerInterface $revealer = null, ?ComparatorFactory $comparatorFactory = null ) { $this->lazyDouble = $lazyDouble; $this->callCenter = $callCenter ?: new CallCenter(); $this->revealer = $revealer ?: new Revealer(); $this->comparatorFactory = $comparatorFactory ?: FactoryProvider::getInstance(); } /** * Forces double to extend specific class. * * @param string $class * * @return $this * * @template U of object * @phpstan-param class-string $class * @phpstan-this-out static */ public function willExtend($class) { $this->lazyDouble->setParentClass($class); return $this; } /** * Forces double to implement specific interface. * * @param string $interface * * @return $this * * @template U of object * @phpstan-param class-string $interface * @phpstan-this-out static */ public function willImplement($interface) { $this->lazyDouble->addInterface($interface); return $this; } /** * Sets constructor arguments. * * @param array $arguments * * @return $this */ public function willBeConstructedWith(?array $arguments = null) { $this->lazyDouble->setArguments($arguments); return $this; } /** * Reveals double. * * @return object * * @throws \Prophecy\Exception\Prophecy\ObjectProphecyException If double doesn't implement needed interface * * @phpstan-return T */ public function reveal() { $double = $this->lazyDouble->getInstance(); if (!$double instanceof ProphecySubjectInterface) { throw new ObjectProphecyException( "Generated double must implement ProphecySubjectInterface, but it does not.\n" .'It seems you have wrongly configured doubler without required ClassPatch.', $this ); } $double->setProphecy($this); return $double; } /** * Adds method prophecy to object prophecy. * * @param MethodProphecy $methodProphecy * * @return void */ public function addMethodProphecy(MethodProphecy $methodProphecy) { $methodName = strtolower($methodProphecy->getMethodName()); if (!isset($this->methodProphecies[$methodName])) { $this->methodProphecies[$methodName] = []; } $this->methodProphecies[$methodName][] = $methodProphecy; } /** * Returns either all or related to single method prophecies. * * @param null|string $methodName * * @return MethodProphecy[]|array * * @phpstan-return ($methodName is string ? list : array>) */ public function getMethodProphecies($methodName = null) { if (null === $methodName) { return $this->methodProphecies; } $methodName = strtolower($methodName); if (!isset($this->methodProphecies[$methodName])) { return []; } return $this->methodProphecies[$methodName]; } /** * Makes specific method call. * * @param string $methodName * @param array $arguments * * @return mixed */ public function makeProphecyMethodCall($methodName, array $arguments) { $arguments = $this->revealer->reveal($arguments); \assert(\is_array($arguments)); $return = $this->callCenter->makeCall($this, $methodName, $arguments); return $this->revealer->reveal($return); } /** * Finds calls by method name & arguments wildcard. * * @param string $methodName * @param ArgumentsWildcard $wildcard * * @return list */ public function findProphecyMethodCalls($methodName, ArgumentsWildcard $wildcard) { return $this->callCenter->findCalls($methodName, $wildcard); } /** * Checks that registered method predictions do not fail. * * @return void * * @throws \Prophecy\Exception\Prediction\AggregateException If any of registered predictions fail * @throws \Prophecy\Exception\Call\UnexpectedCallException */ public function checkProphecyMethodsPredictions() { $exception = new AggregateException(sprintf("%s:\n", get_class($this->reveal()))); $exception->setObjectProphecy($this); $this->callCenter->checkUnexpectedCalls(); foreach ($this->methodProphecies as $prophecies) { foreach ($prophecies as $prophecy) { try { $prophecy->checkPrediction(); } catch (PredictionException $e) { $exception->append($e); } } } if (count($exception->getExceptions())) { throw $exception; } } /** * Creates new method prophecy using specified method name and arguments. * * @param string $methodName * @param array $arguments * * @return MethodProphecy */ public function __call($methodName, array $arguments) { $arguments = $this->revealer->reveal($arguments); \assert(\is_array($arguments)); $arguments = new ArgumentsWildcard($arguments); foreach ($this->getMethodProphecies($methodName) as $prophecy) { $argumentsWildcard = $prophecy->getArgumentsWildcard(); $comparator = $this->comparatorFactory->getComparatorFor( $argumentsWildcard, $arguments ); try { $comparator->assertEquals($argumentsWildcard, $arguments); return $prophecy; } catch (ComparisonFailure $failure) { } } return new MethodProphecy($this, $methodName, $arguments); } /** * Tries to get property value from double. * * @param string $name * * @return mixed */ public function __get($name) { return $this->reveal()->$name; } /** * Tries to set property value to double. * * @param string $name * @param mixed $value * * @return void */ public function __set($name, $value) { $this->reveal()->$name = $this->revealer->reveal($value); } } ================================================ FILE: src/Prophecy/Prophecy/ProphecyInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prophecy; /** * Core Prophecy interface. * * @author Konstantin Kudryashov * * @template-covariant T of object */ interface ProphecyInterface { /** * Reveals prophecy object (double) . * * @return object * * @phpstan-return T */ public function reveal(); } ================================================ FILE: src/Prophecy/Prophecy/ProphecySubjectInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prophecy; /** * Controllable doubles interface. * * @author Konstantin Kudryashov */ interface ProphecySubjectInterface { /** * Sets subject prophecy. * * @param ProphecyInterface $prophecy * * @return void */ public function setProphecy(ProphecyInterface $prophecy); /** * Returns subject prophecy. * * @return ProphecyInterface */ public function getProphecy(); } ================================================ FILE: src/Prophecy/Prophecy/Revealer.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prophecy; /** * Basic prophecies revealer. * * @author Konstantin Kudryashov */ class Revealer implements RevealerInterface { /** * Unwraps value(s). * * @param mixed $value * * @return mixed */ public function reveal($value) { if (is_array($value)) { return array_map(array($this, __FUNCTION__), $value); } if (!is_object($value)) { return $value; } if ($value instanceof ProphecyInterface) { $value = $value->reveal(); } return $value; } } ================================================ FILE: src/Prophecy/Prophecy/RevealerInterface.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Prophecy; /** * Prophecies revealer interface. * * @author Konstantin Kudryashov */ interface RevealerInterface { /** * Unwraps value(s). * * @param mixed $value * * @return mixed */ public function reveal($value); } ================================================ FILE: src/Prophecy/Prophet.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy; use Prophecy\Doubler\CachedDoubler; use Prophecy\Doubler\Doubler; use Prophecy\Doubler\LazyDouble; use Prophecy\Doubler\ClassPatch; use Prophecy\Exception\Doubler\ClassNotFoundException; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophecy\RevealerInterface; use Prophecy\Prophecy\Revealer; use Prophecy\Call\CallCenter; use Prophecy\Util\StringUtil; use Prophecy\Exception\Prediction\PredictionException; use Prophecy\Exception\Prediction\AggregateException; /** * Prophet creates prophecies. * * @author Konstantin Kudryashov */ class Prophet { /** * @var Doubler */ private $doubler; private $revealer; private $util; /** * @var list> */ private $prophecies = array(); public function __construct( ?Doubler $doubler = null, ?RevealerInterface $revealer = null, ?StringUtil $util = null ) { if (null === $doubler) { $doubler = new CachedDoubler(); $doubler->registerClassPatch(new ClassPatch\SplFileInfoPatch()); $doubler->registerClassPatch(new ClassPatch\TraversablePatch()); $doubler->registerClassPatch(new ClassPatch\ThrowablePatch()); $doubler->registerClassPatch(new ClassPatch\DisableConstructorPatch()); $doubler->registerClassPatch(new ClassPatch\ProphecySubjectPatch()); $doubler->registerClassPatch(new ClassPatch\ReflectionClassNewInstancePatch()); $doubler->registerClassPatch(new ClassPatch\MagicCallPatch()); $doubler->registerClassPatch(new ClassPatch\KeywordPatch()); } $this->doubler = $doubler; $this->revealer = $revealer ?: new Revealer(); $this->util = $util ?: new StringUtil(); } /** * Creates new object prophecy. * * @param null|string $classOrInterface Class or interface name * * @return ObjectProphecy * * @template T of object * @phpstan-param class-string|null $classOrInterface * @phpstan-return ($classOrInterface is null ? ObjectProphecy : ObjectProphecy) */ public function prophesize($classOrInterface = null) { $this->prophecies[] = $prophecy = new ObjectProphecy( new LazyDouble($this->doubler), new CallCenter($this->util), $this->revealer ); if ($classOrInterface) { if (class_exists($classOrInterface)) { return $prophecy->willExtend($classOrInterface); } if (interface_exists($classOrInterface)) { return $prophecy->willImplement($classOrInterface); } throw new ClassNotFoundException(sprintf( 'Cannot prophesize class %s, because it cannot be found.', $classOrInterface ), $classOrInterface); } return $prophecy; } /** * Returns all created object prophecies. * * @return list> */ public function getProphecies() { return $this->prophecies; } /** * Returns Doubler instance assigned to this Prophet. * * @return Doubler */ public function getDoubler() { return $this->doubler; } /** * Checks all predictions defined by prophecies of this Prophet. * * @return void * * @throws Exception\Prediction\AggregateException If any prediction fails */ public function checkPredictions() { $exception = new AggregateException("Some predictions failed:\n"); foreach ($this->prophecies as $prophecy) { try { $prophecy->checkProphecyMethodsPredictions(); } catch (PredictionException $e) { $exception->append($e); } } if (count($exception->getExceptions())) { throw $exception; } } } ================================================ FILE: src/Prophecy/Util/ExportUtil.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * This class is a modification from sebastianbergmann/exporter * @see https://github.com/sebastianbergmann/exporter */ class ExportUtil { /** * Exports a value as a string * * The output of this method is similar to the output of print_r(), but * improved in various aspects: * * - NULL is rendered as "null" (instead of "") * - TRUE is rendered as "true" (instead of "1") * - FALSE is rendered as "false" (instead of "") * - Strings are always quoted with single quotes * - Carriage returns and newlines are normalized to \n * - Recursion and repeated rendering is treated properly * * @param mixed $value * @param int $indentation The indentation level of the 2nd+ line * @return string */ public static function export($value, $indentation = 0) { return self::recursiveExport($value, $indentation); } /** * Converts an object to an array containing all of its private, protected * and public properties. * * @param mixed $value * @return array */ public static function toArray($value) { if (!is_object($value)) { return (array) $value; } $array = array(); foreach ((array) $value as $key => $val) { // properties are transformed to keys in the following way: // private $property => "\0Classname\0property" // protected $property => "\0*\0property" // public $property => "property" if (preg_match('/^\0.+\0(.+)$/', $key, $matches)) { $key = $matches[1]; } // See https://github.com/php/php-src/commit/5721132 if ($key === "\0gcdata") { continue; } $array[$key] = $val; } // Some internal classes like SplObjectStorage don't work with the // above (fast) mechanism nor with reflection in Zend. // Format the output similarly to print_r() in this case if ($value instanceof \SplObjectStorage) { foreach ($value as $key => $val) { // Use the same identifier that would be printed alongside the object's representation elsewhere. $array[spl_object_id($val)] = array( 'obj' => $val, 'inf' => $value->getInfo(), ); } } return $array; } /** * Recursive implementation of export * * @param mixed $value The value to export * @param int $indentation The indentation level of the 2nd+ line * @param \SebastianBergmann\RecursionContext\Context $processed Previously processed objects * @return string * @see SebastianBergmann\Exporter\Exporter::export */ protected static function recursiveExport(&$value, $indentation, $processed = null) { if ($value === null) { return 'null'; } if ($value === true) { return 'true'; } if ($value === false) { return 'false'; } if (is_float($value) && floatval(intval($value)) === $value) { return "$value.0"; } if (is_resource($value)) { return sprintf( 'resource(%d) of type (%s)', (int) $value, get_resource_type($value) ); } if (is_string($value)) { // Match for most non printable chars somewhat taking multibyte chars into account if (preg_match('/[^\x09-\x0d\x20-\xff]/', $value)) { return 'Binary String: 0x'.bin2hex($value); } return "'" .str_replace(array("\r\n", "\n\r", "\r"), array("\n", "\n", "\n"), $value) ."'"; } $whitespace = str_repeat(' ', 4 * $indentation); if (!$processed) { $processed = new Context(); } if (is_array($value)) { if (($key = $processed->contains($value)) !== false) { return 'Array &'.$key; } $array = $value; $key = $processed->add($value); $values = ''; if (count($array) > 0) { foreach ($array as $k => $v) { $values .= sprintf( '%s %s => %s'."\n", $whitespace, self::recursiveExport($k, $indentation), self::recursiveExport($value[$k], $indentation + 1, $processed) ); } $values = "\n".$values.$whitespace; } return sprintf('Array &%s (%s)', $key, $values); } if (is_object($value)) { $class = get_class($value); if ($processed->contains($value)) { return sprintf('%s#%d Object', $class, spl_object_id($value)); } $processed->add($value); $values = ''; $array = self::toArray($value); if (count($array) > 0) { foreach ($array as $k => $v) { $values .= sprintf( '%s %s => %s'."\n", $whitespace, self::recursiveExport($k, $indentation), self::recursiveExport($v, $indentation + 1, $processed) ); } $values = "\n".$values.$whitespace; } return sprintf('%s#%d Object (%s)', $class, spl_object_id($value), $values); } return var_export($value, true); } } ================================================ FILE: src/Prophecy/Util/StringUtil.php ================================================ * Marcello Duarte * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Util; use Prophecy\Call\Call; /** * String utility. * * @author Konstantin Kudryashov */ class StringUtil { private $verbose; /** * @param bool $verbose */ public function __construct($verbose = true) { $this->verbose = $verbose; } /** * Stringifies any provided value. * * @param mixed $value * @param boolean $exportObject * * @return string */ public function stringify($value, $exportObject = true) { if (\is_array($value)) { if (range(0, count($value) - 1) === array_keys($value)) { return '['.implode(', ', array_map(array($this, __FUNCTION__), $value)).']'; } $stringify = array($this, __FUNCTION__); return '['.implode(', ', array_map(function ($item, $key) use ($stringify) { return (is_integer($key) ? $key : '"'.$key.'"') .' => '.call_user_func($stringify, $item); }, $value, array_keys($value))).']'; } if (\is_resource($value)) { return get_resource_type($value).':'.$value; } if (\is_object($value)) { return $exportObject ? ExportUtil::export($value) : sprintf('%s#%s', get_class($value), spl_object_id($value)); } if (\is_bool($value)) { return $value ? 'true' : 'false'; } if (\is_string($value)) { $str = sprintf('"%s"', str_replace("\n", '\\n', $value)); if (!$this->verbose && 50 <= strlen($str)) { return substr($str, 0, 50).'"...'; } return $str; } if (null === $value) { return 'null'; } \assert(\is_int($value) || \is_float($value)); return (string) $value; } /** * Stringifies provided array of calls. * * @param Call[] $calls Array of Call instances * * @return string */ public function stringifyCalls(array $calls) { $self = $this; return implode(PHP_EOL, array_map(function (Call $call) use ($self) { return sprintf(' - %s(%s) @ %s', $call->getMethodName(), implode(', ', array_map(array($self, 'stringify'), $call->getArguments())), str_replace(GETCWD().DIRECTORY_SEPARATOR, '', $call->getCallPlace()) ); }, $calls)); } } ================================================ FILE: tests/Argument/Token/ExactValueTokenTest.php ================================================ scoreArgument($child2)); } #[Test] public function scores_10_for_objects_with_same_fields(): void { $child1 = new ChildClass('A', new ParentClass()); $child2 = new ChildClass('A', new ParentClass()); $exactValueToken = new ExactValueToken($child1); self::assertEquals(10, $exactValueToken->scoreArgument($child2)); } #[Test] public function scores_10_for_matching_callables(): void { $callable = function () {}; $exactValueToken = new ExactValueToken($callable); self::assertEquals(10, $exactValueToken->scoreArgument($callable)); } #[Test] public function scores_false_for_object_and_string(): void { $child1 = new ChildClass('A', new ParentClass()); $exactValueToken = new ExactValueToken($child1); self::assertEquals(false, $exactValueToken->scoreArgument("A")); } #[Test] public function scores_false_for_object_and_int(): void { $child1 = new ChildClass('A', new ParentClass()); $exactValueToken = new ExactValueToken($child1); self::assertEquals(false, $exactValueToken->scoreArgument(100)); } #[Test] public function scores_false_for_object_and_stdclass(): void { $child1 = new ChildClass('A', new ParentClass()); $exactValueToken = new ExactValueToken($child1); self::assertEquals(false, $exactValueToken->scoreArgument(new \stdClass())); } #[Test] public function scores_false_for_object_and_null(): void { $child1 = new ChildClass('A', new ParentClass()); $exactValueToken = new ExactValueToken($child1); self::assertEquals(false, $exactValueToken->scoreArgument(null)); } } class ParentClass { public $children = array(); public function addChild($child) { $this->children[] = $child; } } class ChildClass { public $parent = null; public $name = null; public function __construct($name, $parent) { $this->name = $name; $this->parent = $parent; $this->parent->addChild($this); } } ================================================ FILE: tests/Comparator/FactoryProviderTest.php ================================================ getComparatorFor(function () {}, function () {}); $this->assertInstanceOf(ClosureComparator::class, $comparator); } } ================================================ FILE: tests/Doubler/ClassPatch/MagicCallPatchTest.php ================================================ applyPatchTo($class); // Newer phpDocumentor versions allow reading valid method tags, even when some other tags are invalid // Some older versions might also have this method due to not considering the method tag invalid as rule evolved, but we don't track that. if (class_exists('phpDocumentor\Reflection\DocBlock\Tags\InvalidTag')) { $this->assertTrue($classNode->hasMethod('name')); } // We expect no error when processing the class patch. But we still need to increment the assertion count. $this->assertTrue(true); } #[Test] public function it_supports_arguments_for_magic_methods(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithPhpdocClass'); $classNode = $this->applyPatchTo($class); $method = $classNode->getMethod('__unserialize'); if (method_exists($method, 'getParameters')) { // Reflection Docblock 5.4.0+. $args = $method->getParameters(); } else { // Reflection Docblock < 5.4.0. $args = $method->getArguments(); } $this->assertEquals([new ArgumentNode('data')], $args); } private function applyPatchTo(\ReflectionClass $class): ClassNode { $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $patch = new MagicCallPatch(); $patch->apply($classNode); return $classNode; } } ================================================ FILE: tests/Doubler/Generator/ClassMirrorTest.php ================================================ reflect($class, array()); $this->assertCount(7, $node->getMethods()); } #[Test] public function it_reflects_protected_abstract_methods(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithProtectedAbstractMethod'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertEquals('Fixtures\Prophecy\WithProtectedAbstractMethod', $classNode->getParentClass()); $methodNodes = $classNode->getMethods(); $this->assertCount(1, $methodNodes); $this->assertEquals('protected', $methodNodes['innerDetail']->getVisibility()); } #[Test] public function it_reflects_public_static_methods(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithStaticMethod'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertEquals('Fixtures\Prophecy\WithStaticMethod', $classNode->getParentClass()); $methodNodes = $classNode->getMethods(); $this->assertCount(1, $methodNodes); $this->assertTrue($methodNodes['innerDetail']->isStatic()); } #[Test] public function it_marks_required_args_without_types_as_not_optional(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithArguments'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $methodNode = $classNode->getMethod('methodWithoutTypeHints'); $argNodes = $methodNode->getArguments(); $this->assertCount(1, $argNodes); $this->assertEquals('arg', $argNodes[0]->getName()); $this->assertEquals(new ArgumentTypeNode(), $argNodes[0]->getTypeNode()); $this->assertFalse($argNodes[0]->isOptional()); $this->assertNull($argNodes[0]->getDefault()); $this->assertFalse($argNodes[0]->isPassedByReference()); $this->assertFalse($argNodes[0]->isVariadic()); } #[Test] public function it_properly_reads_methods_arguments_with_types(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithArguments'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $methodNode = $classNode->getMethod('methodWithArgs'); $argNodes = $methodNode->getArguments(); $this->assertCount(3, $argNodes); $this->assertEquals('arg_1', $argNodes[0]->getName()); $this->assertEquals(new ArgumentTypeNode(new ObjectType('ArrayAccess')), $argNodes[0]->getTypeNode()); $this->assertFalse($argNodes[0]->isOptional()); $this->assertEquals('arg_2', $argNodes[1]->getName()); $this->assertEquals(new ArgumentTypeNode(new BuiltinType('array')), $argNodes[1]->getTypeNode()); $this->assertTrue($argNodes[1]->isOptional()); $this->assertEquals(array(), $argNodes[1]->getDefault()); $this->assertFalse($argNodes[1]->isPassedByReference()); $this->assertFalse($argNodes[1]->isVariadic()); $this->assertEquals('arg_3', $argNodes[2]->getName()); $this->assertEquals(new ArgumentTypeNode(new UnionType([ new BuiltinType('null'), new ObjectType('ArrayAccess'), ])), $argNodes[2]->getTypeNode()); $this->assertTrue($argNodes[2]->isOptional()); $this->assertNull($argNodes[2]->getDefault()); $this->assertFalse($argNodes[2]->isPassedByReference()); $this->assertFalse($argNodes[2]->isVariadic()); } #[Test] public function it_properly_reads_methods_arguments_with_callable_types(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithCallableArgument'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $methodNode = $classNode->getMethod('methodWithArgs'); $argNodes = $methodNode->getArguments(); $this->assertCount(2, $argNodes); $this->assertEquals('arg_1', $argNodes[0]->getName()); $this->assertEquals(new ArgumentTypeNode(new BuiltinType('callable')), $argNodes[0]->getTypeNode()); $this->assertFalse($argNodes[0]->isOptional()); $this->assertFalse($argNodes[0]->isPassedByReference()); $this->assertFalse($argNodes[0]->isVariadic()); $this->assertEquals('arg_2', $argNodes[1]->getName()); $this->assertEquals(new ArgumentTypeNode(new UnionType([ new BuiltinType('null'), new BuiltinType('callable'), ])), $argNodes[1]->getTypeNode()); $this->assertTrue($argNodes[1]->isOptional()); $this->assertNull($argNodes[1]->getDefault()); $this->assertFalse($argNodes[1]->isPassedByReference()); $this->assertFalse($argNodes[1]->isVariadic()); } #[Test] public function it_properly_reads_methods_variadic_arguments(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithVariadicArgument'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $methodNode = $classNode->getMethod('methodWithArgs'); $argNodes = $methodNode->getArguments(); $this->assertCount(1, $argNodes); $this->assertEquals('args', $argNodes[0]->getName()); $this->assertEquals(new ArgumentTypeNode(), $argNodes[0]->getTypeNode()); $this->assertFalse($argNodes[0]->isOptional()); $this->assertFalse($argNodes[0]->isPassedByReference()); $this->assertTrue($argNodes[0]->isVariadic()); } #[Test] public function it_properly_reads_methods_typehinted_variadic_arguments(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithTypehintedVariadicArgument'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $methodNode = $classNode->getMethod('methodWithTypeHintedArgs'); $argNodes = $methodNode->getArguments(); $this->assertCount(1, $argNodes); $this->assertEquals('args', $argNodes[0]->getName()); $this->assertEquals(new ArgumentTypeNode(new BuiltinType('array')), $argNodes[0]->getTypeNode()); $this->assertFalse($argNodes[0]->isOptional()); $this->assertFalse($argNodes[0]->isPassedByReference()); $this->assertTrue($argNodes[0]->isVariadic()); } #[Test] public function it_marks_passed_by_reference_args_as_passed_by_reference(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithReferences'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertTrue($classNode->hasMethod('methodWithReferenceArgument')); $argNodes = $classNode->getMethod('methodWithReferenceArgument')->getArguments(); $this->assertCount(2, $argNodes); $this->assertTrue($argNodes[0]->isPassedByReference()); $this->assertTrue($argNodes[1]->isPassedByReference()); } #[Test] public function it_throws_an_exception_if_class_is_final(): void { $class = new \ReflectionClass('Fixtures\Prophecy\FinalClass'); $mirror = new ClassMirror(); $this->expectException(ClassMirrorException::class); $mirror->reflect($class, array()); } #[Test] public function it_ignores_final_methods(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithFinalMethod'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertCount(0, $classNode->getMethods()); } #[Test] public function it_marks_final_methods_as_unextendable(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithFinalMethod'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertCount(1, $classNode->getUnextendableMethods()); $this->assertFalse($classNode->isExtendable('finalImplementation')); } #[Test] public function it_throws_an_exception_if_interface_provided_instead_of_class(): void { $class = new \ReflectionClass('Fixtures\Prophecy\EmptyInterface'); $mirror = new ClassMirror(); $this->expectException(InvalidArgumentException::class); $mirror->reflect($class, array()); } #[Test] public function it_reflects_all_interfaces_methods(): void { $mirror = new ClassMirror(); $classNode = $mirror->reflect(null, array( new \ReflectionClass('Fixtures\Prophecy\Named'), new \ReflectionClass('Fixtures\Prophecy\ModifierInterface'), )); $this->assertEquals('stdClass', $classNode->getParentClass()); $this->assertEquals(array( 'Prophecy\Doubler\Generator\ReflectionInterface', 'Fixtures\Prophecy\ModifierInterface', 'Fixtures\Prophecy\Named', ), $classNode->getInterfaces()); $this->assertCount(3, $classNode->getMethods()); $this->assertTrue($classNode->hasMethod('getName')); $this->assertTrue($classNode->hasMethod('isAbstract')); $this->assertTrue($classNode->hasMethod('getVisibility')); } #[Test] public function it_ignores_virtually_private_methods(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithVirtuallyPrivateMethod'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertCount(2, $classNode->getMethods()); $this->assertTrue($classNode->hasMethod('isAbstract')); $this->assertTrue($classNode->hasMethod('__toString')); $this->assertFalse($classNode->hasMethod('_getName')); } #[Test] public function it_does_not_throw_exception_for_virtually_private_finals(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithFinalVirtuallyPrivateMethod'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertCount(0, $classNode->getMethods()); } #[Test] public function it_reflects_return_typehints(): void { $class = new \ReflectionClass('Fixtures\Prophecy\WithReturnTypehints'); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class, array()); $this->assertCount(3, $classNode->getMethods()); $this->assertTrue($classNode->hasMethod('getName')); $this->assertTrue($classNode->hasMethod('getSelf')); $this->assertTrue($classNode->hasMethod('getParent')); $this->assertEquals(new ReturnTypeNode(new BuiltinType('string')), $classNode->getMethod('getName')->getReturnTypeNode()); $this->assertEquals(new ReturnTypeNode(new ObjectType('Fixtures\Prophecy\WithReturnTypehints')), $classNode->getMethod('getSelf')->getReturnTypeNode()); $this->assertEquals(new ReturnTypeNode(new ObjectType('Fixtures\Prophecy\EmptyClass')), $classNode->getMethod('getParent')->getReturnTypeNode()); } #[Test] public function it_throws_an_exception_if_class_provided_in_interfaces_list(): void { $class = new \ReflectionClass('Fixtures\Prophecy\EmptyClass'); $mirror = new ClassMirror(); $this->expectException(\InvalidArgumentException::class); $mirror->reflect(null, array($class)); } #[Test] public function it_throws_an_exception_if_not_reflection_provided_as_interface(): void { $mirror = new ClassMirror(); $this->expectException(\InvalidArgumentException::class); $mirror->reflect(null, array(null)); } #[Test] public function it_doesnt_fail_to_typehint_nonexistent_FQCN(): void { $mirror = new ClassMirror(); $classNode = $mirror->reflect(new \ReflectionClass('Fixtures\Prophecy\OptionalDepsClass'), array()); $method = $classNode->getMethod('iHaveAStrangeTypeHintedArg'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode('I\Simply\Am\Nonexistent'), $arguments[0]->getTypeNode()); } #[Test] public function it_doesnt_fail_on_array_nullable_parameter_with_not_null_default_value(): void { $mirror = new ClassMirror(); $classNode = $mirror->reflect(new \ReflectionClass('Fixtures\Prophecy\NullableArrayParameter'), array()); $method = $classNode->getMethod('iHaveNullableArrayParameterWithNotNullDefaultValue'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode(new UnionType([ new BuiltinType('null'), new BuiltinType('array'), ])), $arguments[0]->getTypeNode()); } #[Test] public function it_doesnt_fail_to_typehint_nonexistent_RQCN(): void { $mirror = new ClassMirror(); $classNode = $mirror->reflect(new \ReflectionClass('Fixtures\Prophecy\OptionalDepsClass'), array()); $method = $classNode->getMethod('iHaveAnEvenStrangerTypeHintedArg'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode('I\Simply\Am\Not'), $arguments[0]->getTypeNode()); } #[Test] function it_doesnt_fail_when_method_is_extended_with_more_params(): void { $mirror = new ClassMirror(); $classNode = $mirror->reflect( new \ReflectionClass('Fixtures\Prophecy\MethodWithAdditionalParam'), array(new \ReflectionClass('Fixtures\Prophecy\Named')) ); $method = $classNode->getMethod('getName'); $this->assertCount(1, $method->getArguments()); $method = $classNode->getMethod('methodWithoutTypeHints'); $this->assertCount(2, $method->getArguments()); } #[Test] function it_doesnt_fail_to_mock_self_referencing_interface(): void { $mirror = new ClassMirror(); $classNode = $mirror->reflect(null, array(new \ReflectionClass(SelfReferencing::class))); $method = $classNode->getMethod('__invoke'); $this->assertCount(1, $method->getArguments()); $this->assertEquals(new ArgumentTypeNode(SelfReferencing::class), $method->getArguments()[0]->getTypeNode()); $this->assertEquals(new ReturnTypeNode(SelfReferencing::class), $method->getReturnTypeNode()); } #[Test] function it_changes_argument_names_if_they_are_varying(): void { // Use test doubles in this test, as arguments named ... in the Reflection API can only happen for internal classes $prophet = new Prophet(); $class = $prophet->prophesize('ReflectionClass'); $method = $prophet->prophesize('ReflectionMethod'); $parameter = $prophet->prophesize('ReflectionParameter'); if (PHP_VERSION_ID >= 80200) { $class->isReadOnly()->willReturn(false); } $class->getName()->willReturn('Custom\ClassName'); $class->isInterface()->willReturn(false); $class->isFinal()->willReturn(false); $class->getMethods(\ReflectionMethod::IS_PUBLIC)->willReturn(array($method)); $class->getMethods(\ReflectionMethod::IS_ABSTRACT)->willReturn(array()); $method->getParameters()->willReturn(array($parameter)); $method->getName()->willReturn('methodName'); $method->isFinal()->willReturn(false); $method->isProtected()->willReturn(false); $method->isStatic()->willReturn(false); $method->returnsReference()->willReturn(false); $method->hasReturnType()->willReturn(false); $method->getDeclaringClass()->willReturn($class); if (\PHP_VERSION_ID >= 80100) { $method->hasTentativeReturnType()->willReturn(false); } $parameter->getName()->willReturn('...'); $parameter->isDefaultValueAvailable()->willReturn(true); $parameter->getDefaultValue()->willReturn(null); $parameter->isPassedByReference()->willReturn(false); $parameter->allowsNull()->willReturn(true); $parameter->getClass()->willReturn($class); $parameter->getType()->willReturn(null); $parameter->hasType()->willReturn(false); $parameter->isVariadic()->willReturn(false); $mirror = new ClassMirror(); $classNode = $mirror->reflect($class->reveal(), array()); $methodNodes = $classNode->getMethods(); $argumentNodes = $methodNodes['methodName']->getArguments(); $argumentNode = $argumentNodes[0]; $this->assertEquals('__dot_dot_dot__', $argumentNode->getName()); } #[Test] public function it_can_double_a_class_with_union_return_types(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Union types are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\UnionReturnTypes'), []); $methodNode = $classNode->getMethods()['doSomething']; $this->assertEquals(new UnionType([ new ObjectType('stdClass'), new BuiltinType('bool'), ]), $methodNode->getReturnTypeNode()->getType()); } #[Test] public function it_can_double_a_class_with_union_return_type_with_false(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Union types with false are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\UnionReturnTypeFalse'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new UnionType([ new ObjectType('stdClass'), new BuiltinType('false'), ]), $methodNode->getReturnTypeNode()->getType()); } #[Test] public function it_can_double_a_class_with_union_argument_types(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Union types are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\UnionArgumentTypes'), []); $methodNode = $classNode->getMethods()['doSomething']; $this->assertEquals(new ArgumentTypeNode(\stdClass::class, 'bool'), $methodNode->getArguments()[0]->getTypeNode()); } #[Test] public function it_can_double_a_class_with_union_argument_type_with_false(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Union types with false are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\UnionArgumentTypeFalse'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new ArgumentTypeNode(\stdClass::class, 'false'), $methodNode->getArguments()[0]->getTypeNode()); } #[Test] public function it_can_double_a_class_with_mixed_types(): void { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Mixed type is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\MixedTypes'), []); $methodNode = $classNode->getMethods()['doSomething']; $this->assertEquals(new ArgumentTypeNode('mixed'), $methodNode->getArguments()[0]->getTypeNode()); $this->assertEquals(new ReturnTypeNode('mixed'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_double_inherited_self_return_type(): void { $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\ClassExtendAbstractWithMethodWithReturnType'), []); $methodNode = $classNode->getMethods()['returnSelf']; $this->assertEquals(new ReturnTypeNode('Fixtures\Prophecy\AbstractBaseClassWithMethodWithReturnType'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_double_never_return_type(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Never type is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\NeverType'), []); $methodNode = $classNode->getMethods()['doSomething']; $this->assertEquals(new ReturnTypeNode('never'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_not_double_an_enum(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Enums are not supported in this PHP version'); } $this->expectException(ClassMirrorException::class); $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\Enum'), []); } #[Test] public function it_can_double_intersection_return_types(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Intersection types are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\IntersectionReturnType'), []); $method = $classNode->getMethod('doSomething'); $returnType = $method->getReturnTypeNode(); $this->assertEquals( new IntersectionType([ new ObjectType('Fixtures\Prophecy\Bar'), new ObjectType('Fixtures\Prophecy\Baz'), ]), $returnType->getType() ); } #[Test] public function it_can_double_intersection_argument_types(): void { if (PHP_VERSION_ID < 80100) { $this->markTestSkipped('Intersection types are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\IntersectionArgumentType'), []); $method = $classNode->getMethod('doSomething'); $argType = $method->getArguments()[0]->getTypeNode(); $this->assertEquals( new IntersectionType([ new ObjectType('Fixtures\Prophecy\Bar'), new ObjectType('Fixtures\Prophecy\Baz'), ]), $argType->getType() ); } #[Test] public function it_can_double_a_standalone_return_type_of_false(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Standalone return type of false is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\StandaloneReturnTypeFalse'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new ReturnTypeNode('false'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_double_a_standalone_parameter_type_of_false(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Standalone parameter type of false is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\StandaloneParameterTypeFalse'), []); $method = $classNode->getMethod('method'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode('false'), $arguments[0]->getTypeNode()); } #[Test] public function it_can_double_a_nullable_return_type_of_false(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Nullable return type of false is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\NullableReturnTypeFalse'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new ReturnTypeNode('null', 'false'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_double_a_nullable_parameter_type_of_false(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Nullable parameter type of false is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\NullableParameterTypeFalse'), []); $method = $classNode->getMethod('method'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode(new UnionType([ new BuiltinType('null'), new BuiltinType('false'), ])), $arguments[0]->getTypeNode()); } #[Test] public function it_can_not_double_dnf_intersection_argument_types(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('DNF intersection types are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\DnfArgumentType'), []); $method = $classNode->getMethod('doSomething'); $argType = $method->getArguments()[0]->getTypeNode(); $this->assertEquals( new UnionType([ new IntersectionType([ new ObjectType('Fixtures\Prophecy\A'), new ObjectType('Fixtures\Prophecy\B'), ]), new ObjectType('Fixtures\Prophecy\C'), ]), $argType->getType() ); } #[Test] public function it_can_double_dnf_intersection_return_types(): void { $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\DnfReturnType'), []); $method = $classNode->getMethod('doSomething'); $returnType = $method->getReturnTypeNode(); $this->assertEquals( new UnionType([ new IntersectionType([ new ObjectType('Fixtures\Prophecy\A'), new ObjectType('Fixtures\Prophecy\B'), ]), new ObjectType('Fixtures\Prophecy\C'), ]), $returnType->getType() ); } #[Test] public function it_can_double_a_standalone_return_type_of_true(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Standalone return type of true is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\StandaloneReturnTypeTrue'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new ReturnTypeNode('true'), $methodNode->getReturnTypeNode()); } #[Test] public function it_reflects_non_read_only_class(): void { $classNode = (new ClassMirror())->reflect( new \ReflectionClass('Fixtures\Prophecy\EmptyClass'), [] ); $this->assertFalse($classNode->isReadOnly()); } #[Test] public function it_can_double_a_standalone_parameter_type_of_true(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Standalone parameter type of true is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\StandaloneParameterTypeTrue'), []); $method = $classNode->getMethod('method'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode('true'), $arguments[0]->getTypeNode()); } #[Test] public function it_can_double_a_nullable_return_type_of_true(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Nullable return type of true is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\NullableReturnTypeTrue'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new ReturnTypeNode('null', 'true'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_double_a_nullable_parameter_type_of_true(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Nullable parameter type of true is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\NullableParameterTypeTrue'), []); $method = $classNode->getMethod('method'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode(new UnionType([ new BuiltinType('null'), new BuiltinType('true'), ])), $arguments[0]->getTypeNode()); } #[Test] public function it_can_double_a_standalone_return_type_of_null(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Standalone return type of null is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\StandaloneReturnTypeNull'), []); $methodNode = $classNode->getMethods()['method']; $this->assertEquals(new ReturnTypeNode('null'), $methodNode->getReturnTypeNode()); } #[Test] public function it_can_double_a_standalone_parameter_type_of_null(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Standalone parameter type of null is not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect(new \ReflectionClass('Fixtures\Prophecy\StandaloneParameterTypeNull'), []); $method = $classNode->getMethod('method'); $arguments = $method->getArguments(); $this->assertEquals(new ArgumentTypeNode('null'), $arguments[0]->getTypeNode()); } #[Test] public function it_reflects_read_only_class(): void { if (PHP_VERSION_ID < 80200) { $this->markTestSkipped('Read only classes are not supported in this PHP version'); } $classNode = (new ClassMirror())->reflect( new \ReflectionClass('Fixtures\Prophecy\ReadOnlyClass'), [] ); $this->assertTrue($classNode->isReadOnly()); } } ================================================ FILE: tests/Doubler/Generator/Node/TypeNodeAbstractTest.php ================================================ */ public static function childClassDataProvider(): \Generator { $typesCombination = [ ['bool', 'null'], ['int', 'bool', 'null'], ]; if (PHP_VERSION_ID >= 80200) { $typesCombination[] = ['null']; } foreach ($typesCombination as $types) { $count = count($types); $expected = $count === 2; yield $count.' return types' => [new ReturnTypeNode(...$types), $expected]; yield $count.' argument types' => [new ArgumentTypeNode(...$types), $expected]; } } #[DataProvider('childClassDataProvider')] #[Test] public function it_can_use_null_shorthand_only_with_two_types(TypeNodeAbstract $node, bool $expected): void { $this->assertSame($expected, $node->canUseNullShorthand()); } } ================================================ FILE: tests/FunctionalTest.php ================================================ prophesize('ArrayObject'); $prophecy->offsetGet(1)->willReturn(1)->shouldBeCalledTimes(1); $prophecy->offsetget(2)->willReturn(2)->shouldBeCalledTimes(1); $prophecy->OffsetGet(3)->willReturn(3)->shouldBeCalledTimes(1); $arrayObject = $prophecy->reveal(); self::assertSame(1, $arrayObject->offsetGet(1)); self::assertSame(2, $arrayObject->offsetGet(2)); self::assertSame(3, $arrayObject->offsetGet(3)); } #[Test] public function it_implements_the_double_interface(): void { $prophet = new Prophet(); $object = $prophet->prophesize('stdClass')->reveal(); $this->assertInstanceOf(DoubleInterface::class, $object); } #[Test] public function it_implements_the_prophecy_subject_interface(): void { $prophet = new Prophet(); $object = $prophet->prophesize('stdClass')->reveal(); $this->assertInstanceOf(ProphecySubjectInterface::class, $object); } public function testUnconfiguredFinalReturnType(): void { $prophet = new Prophet(); $object = $prophet->prophesize(ReturningFinalClass::class); $object->doSomething()->shouldBeCalled(); $double = $object->reveal(); $this->expectException(MethodProphecyException::class); $this->expectExceptionMessage('Cannot create a return value for the method. Configure an explicit return value instead.'); $double->doSomething(); } }