PHPackages                             badoo/soft-mocks - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. badoo/soft-mocks

ActiveLibrary[Testing &amp; Quality](/categories/testing)

badoo/soft-mocks
================

The idea behind "Soft Mocks" - as opposed to "hardcore" mocks that work on the level of the PHP interpreter (runkit and uopz) - is to rewrite class code on the spot so that it can be inserted in any place. It works by rewriting code on the fly during file inclusion instead of using extensions like runkit or uopz.

4.0.2(1y ago)30935.1k↓50%38[2 issues](https://github.com/badoo/soft-mocks/issues)[2 PRs](https://github.com/badoo/soft-mocks/pulls)3MITPHPPHP &gt;=7.4CI failing

Since Apr 4Pushed 7mo ago28 watchersCompare

[ Source](https://github.com/badoo/soft-mocks)[ Packagist](https://packagist.org/packages/badoo/soft-mocks)[ RSS](/packages/badoo-soft-mocks/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (51)Used By (3)

SoftMocks
=========

[](#softmocks)

The idea behind "Soft Mocks" - as opposed to "hardcore" mocks that work on the level of the PHP interpreter (runkit and uopz) - is to rewrite class code on the spot so that it can be inserted in any place. It works by rewriting code on the fly during file inclusion instead of using extensions like runkit or uopz.

[![Build Status](https://camo.githubusercontent.com/288d23d10c51d720f7459760405fda1dc4dab7b781a0162a0b414e4578d8c1f9/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f6261646f6f2f736f66742d6d6f636b732e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/badoo/soft-mocks)[![GitHub release](https://camo.githubusercontent.com/ccec17e4e8906a2360f9a06d4f36388f597bed11f2ce42749fdac16254b6bd5e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6261646f6f2f736f66742d6d6f636b732e737667)](https://github.com/badoo/soft-mocks/releases/latest)[![Total Downloads](https://camo.githubusercontent.com/063fa4ed1c1ff5ab4d5035f5fe9915c7a507f4a0f9f5f00688058a81f55c39f5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6261646f6f2f736f66742d6d6f636b732e737667)](https://packagist.org/packages/badoo/soft-mocks)[![Daily Downloads](https://camo.githubusercontent.com/48afa8f047ea002643fdd00a920456963ac644da6fea90a905edc741b4c701c8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64642f6261646f6f2f736f66742d6d6f636b732e737667)](https://packagist.org/packages/badoo/soft-mocks)[![Minimum PHP Version](https://camo.githubusercontent.com/92fabb75236db7d7453db0680cfab230e4ba78cc321ad3864794f78327f3f3b0/687474703a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230372e342d3838393242462e737667)](https://php.net/)[![License](https://camo.githubusercontent.com/40e125ad16f25a79fc41f601fcef22259323d4b37e596e329c980f2d1a78830f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6261646f6f2f736f66742d6d6f636b732e737667)](https://packagist.org/packages/badoo/soft-mocks)

Installation
------------

[](#installation)

You can install SoftMocks via [Composer](https://getcomposer.org/):

```
composer require --dev badoo/soft-mocks
```

Usage
-----

[](#usage)

The thing that sets SoftMocks apart (and also limits their usage) is that they need to be initiated at the earliest phase of the app launch. It's necessary to do it this way because you can't redefine the classes and functions that are already loaded into the memory in PHP. For an example bootstrap presets, see *[src/bootstrap.php](src/bootstrap.php)*. For PHPUnit you should use patches form *[composer.json](composer.json)*, because you should require composer autoload through SoftMocks.

SoftMocks don't rewrite the following system parts:

- it's own code;
- PHPUnit code (see `\Badoo\SoftMocks::addIgnorePath()` for details);
- PHP-Parser code (see `\Badoo\SoftMocks::addIgnorePath()` for details);
- already rewritten code;
- code which was loaded before SoftMocks initialization.

In order to add external dependencies (for example, vendor/autoload.php) in file, which which was loaded before SoftMocks initialization, you need to use a wrapper:

```
require_once (\Badoo\SoftMocks::rewrite('vendor/autoload.php'));
require_once (\Badoo\SoftMocks::rewrite('path/to/external/lib.php'));

```

After you've added the file via `SoftMocks::rewrite()`, all nested include calls will already be "wrapped" by the system itself.

You can see a more detailed example by executing the following command:

```
$ php example/run_me.php
Result before applying SoftMocks = array (
  'TEST_CONSTANT_WITH_VALUE_42' => 42,
  'someFunc(2)' => 84,
  'Example::doSmthStatic()' => 42,
  'Example->doSmthDynamic()' => 84,
  'Example::STATIC_DO_SMTH_RESULT' => 42,
)
Result after applying SoftMocks = array (
  'TEST_CONSTANT_WITH_VALUE_42' => 43,
  'someFunc(2)' => 57,
  'Example::doSmthStatic()' => 'Example::doSmthStatic() redefined',
  'Example->doSmthDynamic()' => 'Example->doSmthDynamic() redefined',
  'Example::STATIC_DO_SMTH_RESULT' => 'Example::STATIC_DO_SMTH_RESULT value changed',
)
Result after reverting SoftMocks = array (
  'TEST_CONSTANT_WITH_VALUE_42' => 42,
  'someFunc(2)' => 84,
  'Example::doSmthStatic()' => 42,
  'Example->doSmthDynamic()' => 84,
  'Example::STATIC_DO_SMTH_RESULT' => 42,
)

```

API (short description)
-----------------------

[](#api-short-description)

Initialize SoftMocks (set phpunit injections, define internal mocks, get list of internal functions, etc):

```
\Badoo\SoftMocks::init();

```

Cache files are created in /tmp/mocks by default. If you want to choose a different path, you can redefine it as follows:

```
\Badoo\SoftMocks::setMocksCachePath($cache_path);

```

This method should be called before rewrite first file. Also you can redefine cache path using environment variable `SOFT_MOCKS_CACHE_PATH`.

### Redefine constant

[](#redefine-constant)

You can assign a new value to $constantName or create one if it wasn't already declared. Since it isn't created using the define() call, the operation can be canceled.

Both "regular constants" and class constants like "className::CONST\_NAME" are supported.

```
\Badoo\SoftMocks::redefineConstant($constantName, $value)

```

There can be next cases with class constants redefining:

- You can redefine base class constant: ```
    class A {const NAME = 'A';}
    class B {}
    echo A::NAME . "\n"; // A
    echo B::NAME . "\n"; // A
    \Badoo\SoftMocks::redefineConstant(A::class . '::NAME', 'B');
    echo A::NAME . "\n"; // B
    echo B::NAME . "\n"; // B
    ```
- You can add middle class constant: ```
    class A {const NAME = 'A';}
    class B {}
    class C {}
    echo A::NAME . "\n"; // A
    echo B::NAME . "\n"; // A
    echo C::NAME . "\n"; // A
    \Badoo\SoftMocks::redefineConstant(B::class . '::NAME', 'B');
    echo A::NAME . "\n"; // A
    echo B::NAME . "\n"; // B
    echo C::NAME . "\n"; // B
    ```
- You can add constant to base class: ```
    class A {const NAME = 'A';}
    class B {}
    echo A::NAME . "\n"; // Undefined class constant 'NAME'
    echo B::NAME . "\n"; // Undefined class constant 'NAME'
    \Badoo\SoftMocks::redefineConstant(A::class . '::NAME', 'A');
    echo A::NAME . "\n"; // A
    echo B::NAME . "\n"; // A
    ```
- You can remove middle class constant: ```
    class A {const NAME = 'A';}
    class B {const NAME = 'B';}
    class C {}
    echo A::NAME . "\n"; // A
    echo B::NAME . "\n"; // B
    echo C::NAME . "\n"; // B
    \Badoo\SoftMocks::removeConstant(B::class . '::NAME');
    echo A::NAME . "\n"; // A
    echo B::NAME . "\n"; // A
    echo C::NAME . "\n"; // A
    ```
- Other more simple cases (just add or redefine constant and etc.).

### Redefine functions

[](#redefine-functions)

SoftMocks let you redefine both user-defined and built-in functions except for those that depend on the current context (see \\Badoo\\SoftMocksTraverser::$ignore\_functions property if you want to see the full list), or for those that have built-in mocks (debug\_backtrace, call\_user\_func\* and a few others, but built-in mocks you can enable redefine by call `\Badoo\SoftMocks::setRewriteInternal(true)`).

Definition:

```
\Badoo\SoftMocks::redefineFunction($func, $functionArgs, $fakeCode)

```

Usage example (redefine strlen function and call original for the trimmed string):

```
\Badoo\SoftMocks::redefineFunction(
    'strlen',
    '$a',
    'return \\Badoo\\SoftMocks::callOriginal("strlen", [trim($a)]));'
);

var_dump(strlen("  a  ")); // int(1)

```

### Redefine methods

[](#redefine-methods)

At the moment, only user-defined method redefinition is supported. This functionality is not supported for built-in classes.

Definition:

```
\Badoo\SoftMocks::redefineMethod($class, $method, $functionArgs, $fakeCode)

```

Arguments are the same as for redefineFunction, but argument $class is introduced.

As an argument $class accepts a class name or a trait name.

### Redefining functions that are generators

[](#redefining-functions-that-are-generators)

This method that lets you replace a generator function call with another \\Generator. Generators differ from regular functions in that you can't return a value using "return"; you have to use "yield".

```
\Badoo\SoftMocks::redefineGenerator($class, $method, \Generator $replacement)

```

### Restore values

[](#restore-values)

The following functions undo mocks that were made using one of the redefine methods described above.

```
\Badoo\SoftMocks::restoreAll()

// You can also undo only chosen mocks:
\Badoo\SoftMocks::restoreConstant($constantName)
\Badoo\SoftMocks::restoreAllConstants()
\Badoo\SoftMocks::restoreFunction($func)
\Badoo\SoftMocks::restoreMethod($class, $method)
\Badoo\SoftMocks::restoreGenerator($class, $method)
\Badoo\SoftMocks::restoreNew()
\Badoo\SoftMocks::restoreAllNew()
\Badoo\SoftMocks::restoreExit()

```

Using with PHPUnit
------------------

[](#using-with-phpunit)

### Maximum supported version

[](#maximum-supported-version)

Currently, the maximum supported version is **PHPUnit 8.5.38**

### Installation

[](#installation-1)

If you want to use SoftMocks with PHPUnit 8.x then there are next particularities:

- If phpunit is installed by composer then you should apply patch to `phpunit` *[patches/phpunit7.x/phpunit\_phpunit.patch](patches/phpunit7.x/phpunit_phpunit.patch)*,so that classes loaded by composer would be rewritten by SoftMocks;
- if phpunit is installed manually then you should require *[src/bootstrap.php](src/bootstrap.php)*, so that classes loaded by composer would be rewritten by SoftMocks;
- so that trace would be readable you should apply patch for `phpunit` *[patches/phpunit8.x/phpunit\_add\_ability\_to\_set\_custom\_filename\_rewrite\_callbacks.patch](patches/phpunit8.x/phpunit_add_ability_to_set_custom_filename_rewrite_callbacks.patch)*;
- so that coverage would be right the you should apply patch to `php-code-coverage` *[patches/phpunit8.x/php-code-coverage\_add\_ability\_to\_set\_custom\_filename\_rewrite\_callbacks.patch](patches/phpunit8.x/php-code-coverage_add_ability_to_set_custom_filename_rewrite_callbacks.patch)*.

Use `phpunit7.x` directory instead of `phpunit8.x` for `phpunit7.x`. Use `phpunit6.x` directory instead of `phpunit8.x` for `phpunit6.x`. Use `phpunit5.x` directory instead of `phpunit8.x` for `phpunit5.x`. Use `phpunit4.x` directory instead of `phpunit8.x` for `phpunit4.x`.

If you want that patches are applied automatically, you should write next in в composer.json:

```
{
  "require-dev": {
    "vaimo/composer-patches": "3.23.1",
    "phpunit/phpunit": "^8.4.3" // or "^7.5.17" or "^6.5.5" or "^5.7.20" or "^4.8.35"
  }
}
```

To force reapply patches use next command:

```
composer patch --redo
```

For more information about patching see [vaimo/composer-patches documentation](https://github.com/vaimo/composer-patches/blob/3.22.4/README.md).

Using with xdebug
-----------------

[](#using-with-xdebug)

There is two possibilities to use soft-mocks with xdebug - debug rewritten files and debug original file using xdebug-proxy.

### Debug rewritten files

[](#debug-rewritten-files)

If you use soft-mocks locally then you can just debug it by calling to `xdebug_break()`. Also you can add break point to the rewritten file, but you should know rewritten file path. For getting the rewritten file path you can call `\Badoo\SoftMocks::rewrite($file)`, but be attentive - if you change the file then new one will be created and it'll have different path.

If you use soft-mocks on the server, then you can mount /tmp/mocks using sshfs or something like this.

### Debug original files using xdebug-proxy

[](#debug-original-files-using-xdebug-proxy)

As you see debug rewritten files is uncomfortable. You can also debug original files using [xdebug-proxy](https://github.com/mougrim/php-xdebug-proxy).

```
composer.phar require mougrim/php-xdebug-proxy --dev
cp -r vendor/mougrim/php-xdebug-proxy/config xdebug-proxy-config
```

After that change `xdebug-proxy-config/factory.php` to the following:

```
