This commit is contained in:
aschwarz
2023-05-12 12:27:19 +02:00
parent 757c2388de
commit e2f1846f03
1974 changed files with 255998 additions and 0 deletions

View File

@ -0,0 +1,212 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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
*
* @return Token\CallbackToken
*/
public static function that($callback)
{
return new Token\CallbackToken($callback);
}
/**
* 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 ... a list of tokens
*
* @return Token\LogicalAndToken
*/
public static function allOf()
{
return new Token\LogicalAndToken(func_get_args());
}
/**
* 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 float $precision
*
* @return Token\ApproximateValueToken
*/
public static function approximate($value, $precision = 0)
{
return new Token\ApproximateValueToken($value, $precision);
}
}

View File

@ -0,0 +1,101 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class ArgumentsWildcard
{
/**
* @var Token\TokenInterface[]
*/
private $tokens = array();
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 array
*/
public function getTokens()
{
return $this->tokens;
}
}

View File

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class AnyValueToken implements TokenInterface
{
/**
* Always scores 3 for any argument.
*
* @param $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 '*';
}
}

View File

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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 '* [, ...]';
}
}

View File

@ -0,0 +1,55 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <daniel@dantleech.com>
*/
class ApproximateValueToken implements TokenInterface
{
private $value;
private $precision;
public function __construct($value, $precision = 0)
{
$this->value = $value;
$this->precision = $precision;
}
/**
* {@inheritdoc}
*/
public function scoreArgument($argument)
{
return round($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));
}
}

View File

@ -0,0 +1,86 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <kaguxmail@gmail.com>
*/
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 $argument
*
* @return bool|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 $argument
* @return bool
*/
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);
}
}

View File

@ -0,0 +1,143 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <kaguxmail@gmail.com>
*/
class ArrayEntryToken implements TokenInterface
{
/** @var \Prophecy\Argument\Token\TokenInterface */
private $key;
/** @var \Prophecy\Argument\Token\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 array|\ArrayAccess|\Traversable $argument
*
* @throws \Prophecy\Exception\InvalidArgumentException
* @return bool|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 = function ($value, $key) {
return $value && $key ? 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 $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|null
* @throws \Prophecy\Exception\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();
return $object->offsetExists($key) ? array($key => $object[$key]) : array();
}
}

View File

@ -0,0 +1,82 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <adrien.brault@gmail.com>
*/
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;
}
}

View File

@ -0,0 +1,75 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class CallbackToken implements TokenInterface
{
private $callback;
/**
* Initializes token.
*
* @param callable $callback
*
* @throws \Prophecy\Exception\InvalidArgumentException
*/
public function __construct($callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'Callable expected as an argument to CallbackToken, but got %s.',
gettype($callback)
));
}
$this->callback = $callback;
}
/**
* Scores 7 if callback returns true, false otherwise.
*
* @param $argument
*
* @return bool|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()
{
return 'callback()';
}
}

View File

@ -0,0 +1,118 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Argument\Token;
use SebastianBergmann\Comparator\ComparisonFailure;
use Prophecy\Comparator\Factory as ComparatorFactory;
use Prophecy\Util\StringUtil;
/**
* Exact value token.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ExactValueToken implements TokenInterface
{
private $value;
private $string;
private $util;
private $comparatorFactory;
/**
* Initializes token.
*
* @param mixed $value
* @param StringUtil $util
* @param ComparatorFactory $comparatorFactory
*/
public function __construct($value, StringUtil $util = null, ComparatorFactory $comparatorFactory = null)
{
$this->value = $value;
$this->util = $util ?: new StringUtil();
$this->comparatorFactory = $comparatorFactory ?: ComparatorFactory::getInstance();
}
/**
* Scores 10 if argument matches preset value.
*
* @param $argument
*
* @return bool|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;
}
} 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;
}
}

View File

@ -0,0 +1,74 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <florian@voutzinos.com>
*/
class IdenticalValueToken implements TokenInterface
{
private $value;
private $string;
private $util;
/**
* Initializes token.
*
* @param mixed $value
* @param StringUtil $util
*/
public function __construct($value, StringUtil $util = null)
{
$this->value = $value;
$this->util = $util ?: new StringUtil();
}
/**
* Scores 11 if argument matches preset value.
*
* @param $argument
*
* @return bool|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;
}
}

View File

@ -0,0 +1,80 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <kaguxmail@gmail.com>
*/
class LogicalAndToken implements TokenInterface
{
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 $argument
*
* @return bool|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));
}
}

View File

@ -0,0 +1,73 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <kaguxmail@gmail.com>
*/
class LogicalNotToken implements TokenInterface
{
/** @var \Prophecy\Argument\Token\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 $argument
*
* @return bool|int
*/
public function scoreArgument($argument)
{
return false === $this->token->scoreArgument($argument) ? 4 : false;
}
/**
* Returns true if preset token is last.
*
* @return bool|int
*/
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);
}
}

View File

@ -0,0 +1,104 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Argument\Token;
use SebastianBergmann\Comparator\ComparisonFailure;
use Prophecy\Comparator\Factory as ComparatorFactory;
use Prophecy\Util\StringUtil;
/**
* Object state-checker token.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ObjectStateToken implements TokenInterface
{
private $name;
private $value;
private $util;
private $comparatorFactory;
/**
* Initializes token.
*
* @param string $methodName
* @param mixed $value Expected return value
* @param null|StringUtil $util
* @param ComparatorFactory $comparatorFactory
*/
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 ?: ComparatorFactory::getInstance();
}
/**
* Scores 8 if argument is an object, which method returns expected value.
*
* @param mixed $argument
*
* @return bool|int
*/
public function scoreArgument($argument)
{
if (is_object($argument) && method_exists($argument, $this->name)) {
$actual = call_user_func(array($argument, $this->name));
$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)
);
}
}

View File

@ -0,0 +1,67 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <pete@peterjmit.com>
*/
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);
}
}

View File

@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface TokenInterface
{
/**
* Calculates token match score for provided argument.
*
* @param $argument
*
* @return bool|int
*/
public function scoreArgument($argument);
/**
* Returns true if this token prevents check of other tokens (is last one).
*
* @return bool|int
*/
public function isLast();
/**
* Returns string representation for token.
*
* @return string
*/
public function __toString();
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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);
}
}

View File

@ -0,0 +1,162 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class Call
{
private $methodName;
private $arguments;
private $returnValue;
private $exception;
private $file;
private $line;
private $scores;
/**
* Initializes call.
*
* @param string $methodName
* @param array $arguments
* @param mixed $returnValue
* @param Exception $exception
* @param null|string $file
* @param null|int $line
*/
public function __construct($methodName, array $arguments, $returnValue,
Exception $exception = null, $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
*/
public function getFile()
{
return $this->file;
}
/**
* Returns callee line number.
*
* @return int
*/
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());
}
}

View File

@ -0,0 +1,248 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\ObjectProphecy;
use Prophecy\Argument\ArgumentsWildcard;
use Prophecy\Util\StringUtil;
use Prophecy\Exception\Call\UnexpectedCallException;
use SplObjectStorage;
/**
* Calls receiver & manager.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
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
if (PHP_VERSION_ID >= 50400) {
// Limit backtrace to last 3 calls as we don't use the rest
// Limit argument was introduced in PHP 5.4.0
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
} elseif (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) {
// DEBUG_BACKTRACE_IGNORE_ARGS was introduced in PHP 5.3.6
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
} else {
$backtrace = debug_backtrace();
}
$file = $line = null;
if (isset($backtrace[2]) && isset($backtrace[2]['file'])) {
$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->attach(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 Call[]
*/
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)
;
})
);
}
/**
* @throws UnexpectedCallException
*/
public function checkUnexpectedCalls()
{
/** @var Call $call */
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());
}
}
}
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 (call_user_func_array('array_merge', $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
);
}
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
*/
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;
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
final class ClosureComparator extends Comparator
{
public function accepts($expected, $actual)
{
return is_object($expected) && $expected instanceof \Closure
&& is_object($actual) && $actual instanceof \Closure;
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
{
if ($expected !== $actual) {
throw new ComparisonFailure(
$expected,
$actual,
// we don't need a diff
'',
'',
false,
'all closures are different if not identical'
);
}
}
}

View File

@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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;
}
}

View File

@ -0,0 +1,28 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\ObjectComparator;
class ProphecyComparator extends ObjectComparator
{
public function accepts($expected, $actual)
{
return is_object($expected) && is_object($actual) && $actual instanceof ProphecyInterface;
}
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
{
parent::assertEquals($expected, $actual->reveal(), $delta, $canonicalize, $ignoreCase, $processed);
}
}

View File

@ -0,0 +1,66 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class CachedDoubler extends Doubler
{
private static $classes = array();
/**
* {@inheritdoc}
*/
protected function createDoubleClass(ReflectionClass $class = null, 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 $class
* @param ReflectionClass[] $interfaces
*
* @return string
*/
private function generateClassId(ReflectionClass $class = null, 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));
}
public function resetCache()
{
self::$classes = array();
}
}

View File

@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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();
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Disable constructor.
* Makes all constructor arguments optional.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
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');
foreach ($constructor->getArguments() as $argument) {
$argument->setDefault(null);
}
$constructor->setCode(<<<PHP
if (0 < func_num_args()) {
call_user_func_array(array('parent', '__construct'), func_get_args());
}
PHP
);
}
/**
* Returns patch priority, which determines when patch will be applied.
*
* @return int Priority number (higher - earlier)
*/
public function getPriority()
{
return 100;
}
}

View File

@ -0,0 +1,63 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Exception patch for HHVM to remove the stubs from special methods
*
* @author Christophe Coevoet <stof@notk.org>
*/
class HhvmExceptionPatch implements ClassPatchInterface
{
/**
* Supports exceptions on HHVM.
*
* @param ClassNode $node
*
* @return bool
*/
public function supports(ClassNode $node)
{
if (!defined('HHVM_VERSION')) {
return false;
}
return 'Exception' === $node->getParentClass() || is_subclass_of($node->getParentClass(), 'Exception');
}
/**
* Removes special exception static methods from the doubled methods.
*
* @param ClassNode $node
*
* @return void
*/
public function apply(ClassNode $node)
{
if ($node->hasMethod('setTraceOptions')) {
$node->getMethod('setTraceOptions')->useParentCode();
}
if ($node->hasMethod('getTraceOptions')) {
$node->getMethod('getTraceOptions')->useParentCode();
}
}
/**
* {@inheritdoc}
*/
public function getPriority()
{
return -50;
}
}

View File

@ -0,0 +1,140 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <milan@magudia.com>
*/
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 array
*/
private function getKeywords()
{
if (\PHP_VERSION_ID >= 70000) {
return array('__halt_compiler');
}
return array(
'__halt_compiler',
'abstract',
'and',
'array',
'as',
'break',
'callable',
'case',
'catch',
'class',
'clone',
'const',
'continue',
'declare',
'default',
'die',
'do',
'echo',
'else',
'elseif',
'empty',
'enddeclare',
'endfor',
'endforeach',
'endif',
'endswitch',
'endwhile',
'eval',
'exit',
'extends',
'final',
'finally',
'for',
'foreach',
'function',
'global',
'goto',
'if',
'implements',
'include',
'include_once',
'instanceof',
'insteadof',
'interface',
'isset',
'list',
'namespace',
'new',
'or',
'print',
'private',
'protected',
'public',
'require',
'require_once',
'return',
'static',
'switch',
'throw',
'trait',
'try',
'unset',
'use',
'var',
'while',
'xor',
'yield',
);
}
}

View File

@ -0,0 +1,94 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\PhpDocumentor\ClassAndInterfaceTagRetriever;
use Prophecy\PhpDocumentor\MethodTagRetrieverInterface;
/**
* Discover Magical API using "@method" PHPDoc format.
*
* @author Thomas Tourlourat <thomas@tourlourat.com>
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Théo FIDRY <theo.fidry@gmail.com>
*/
class MagicCallPatch implements ClassPatchInterface
{
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);
$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;
}
}

View File

@ -0,0 +1,104 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\ArgumentNode;
/**
* Add Prophecy functionality to the double.
* This is a core class patch for Prophecy.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
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->getReturnType() === 'void') {
$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->setTypeHint('Prophecy\Prophecy\ProphecyInterface');
$prophecySetter->addArgument($prophecyArgument);
$prophecySetter->setCode('$this->objectProphecyClosure = function () use ($prophecy) { return $prophecy; };');
$prophecyGetter = new MethodNode('getProphecy');
$prophecyGetter->setCode('return call_user_func($this->objectProphecyClosure);');
if ($node->hasMethod('__call')) {
$__call = $node->getMethod('__call');
} else {
$__call = new MethodNode('__call');
$__call->addArgument(new ArgumentNode('name'));
$__call->addArgument(new ArgumentNode('arguments'));
$node->addMethod($__call, true);
}
$__call->setCode(<<<PHP
throw new \Prophecy\Exception\Doubler\MethodNotFoundException(
sprintf('Method `%s::%s()` not found.', get_class(\$this), func_get_arg(0)),
\$this->getProphecy(), func_get_arg(0)
);
PHP
);
$node->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;
}
}

View File

@ -0,0 +1,57 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <florian.klein@free.fr>
*/
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)
{
foreach ($node->getMethod('newInstance')->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;
}
}

View File

@ -0,0 +1,123 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class SplFileInfoPatch implements ClassPatchInterface
{
/**
* Supports everything that extends SplFileInfo.
*
* @param ClassNode $node
*
* @return bool
*/
public function supports(ClassNode $node)
{
if (null === $node->getParentClass()) {
return false;
}
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');
} 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;
}
}

View File

@ -0,0 +1,95 @@
<?php
namespace Prophecy\Doubler\ClassPatch;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Exception\Doubler\ClassCreatorException;
class ThrowablePatch implements ClassPatchInterface
{
/**
* Checks if patch supports specific class node.
*
* @param ClassNode $node
* @return bool
*/
public function supports(ClassNode $node)
{
return $this->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)
{
$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)
{
$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;
}
}

View File

@ -0,0 +1,83 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Traversable interface patch.
* Forces classes that implement interfaces, that extend Traversable to also implement Iterator.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
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');
$node->addMethod(new MethodNode('current'));
$node->addMethod(new MethodNode('key'));
$node->addMethod(new MethodNode('next'));
$node->addMethod(new MethodNode('rewind'));
$node->addMethod(new MethodNode('valid'));
}
/**
* Returns patch priority, which determines when patch will be applied.
*
* @return int Priority number (higher - earlier)
*/
public function getPriority()
{
return 100;
}
}

View File

@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface DoubleInterface
{
}

View File

@ -0,0 +1,146 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class Doubler
{
private $mirror;
private $creator;
private $namer;
/**
* @var ClassPatchInterface[]
*/
private $patches = array();
/**
* @var \Doctrine\Instantiator\Instantiator
*/
private $instantiator;
/**
* Initializes doubler.
*
* @param ClassMirror $mirror
* @param ClassCreator $creator
* @param NameGenerator $namer
*/
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 ClassPatchInterface[]
*/
public function getClassPatches()
{
return $this->patches;
}
/**
* Registers new class patch.
*
* @param ClassPatchInterface $patch
*/
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.
*
* @param ReflectionClass $class
* @param ReflectionClass[] $interfaces Array of ReflectionClass instances
* @param array $args Constructor arguments
*
* @return DoubleInterface
*
* @throws \Prophecy\Exception\InvalidArgumentException
*/
public function double(ReflectionClass $class = null, 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.
*
* @param ReflectionClass $class
* @param ReflectionClass[] $interfaces
*
* @return string
*/
protected function createDoubleClass(ReflectionClass $class = null, 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);
}
}
$this->creator->create($name, $node);
return $name;
}
}

View File

@ -0,0 +1,129 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Doubler\Generator;
/**
* Class code creator.
* Generates PHP code for specific class node tree.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ClassCodeGenerator
{
/**
* @var TypeHintReference
*/
private $typeHintReference;
public function __construct(TypeHintReference $typeHintReference = null)
{
$this->typeHintReference = $typeHintReference ?: new TypeHintReference();
}
/**
* 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("class %s extends \%s implements %s {\n",
$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)
{
$php = sprintf("%s %s function %s%s(%s)%s {\n",
$method->getVisibility(),
$method->isStatic() ? 'static' : '',
$method->returnsReference() ? '&':'',
$method->getName(),
implode(', ', $this->generateArguments($method->getArguments())),
$this->getReturnType($method)
);
$php .= $method->getCode()."\n";
return $php.'}';
}
/**
* @return string
*/
private function getReturnType(Node\MethodNode $method)
{
if (version_compare(PHP_VERSION, '7.1', '>=')) {
if ($method->hasReturnType()) {
return $method->hasNullableReturnType()
? sprintf(': ?%s', $method->getReturnType())
: sprintf(': %s', $method->getReturnType());
}
}
if (version_compare(PHP_VERSION, '7.0', '>=')) {
return $method->hasReturnType() && $method->getReturnType() !== 'void'
? sprintf(': %s', $method->getReturnType())
: '';
}
return '';
}
private function generateArguments(array $arguments)
{
$typeHintReference = $this->typeHintReference;
return array_map(function (Node\ArgumentNode $argument) use ($typeHintReference) {
$php = '';
if (version_compare(PHP_VERSION, '7.1', '>=')) {
$php .= $argument->isNullable() ? '?' : '';
}
if ($hint = $argument->getTypeHint()) {
$php .= $typeHintReference->isBuiltInParamTypeHint($hint) ? $hint : '\\'.$hint;
}
$php .= ' '.($argument->isPassedByReference() ? '&' : '');
$php .= $argument->isVariadic() ? '...' : '';
$php .= '$'.$argument->getName();
if ($argument->isOptional() && !$argument->isVariadic()) {
$php .= ' = '.var_export($argument->getDefault(), true);
}
return $php;
}, $arguments);
}
}

View File

@ -0,0 +1,67 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class ClassCreator
{
private $generator;
/**
* Initializes creator.
*
* @param ClassCodeGenerator $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;
}
}

View File

@ -0,0 +1,260 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\InvalidArgumentException;
use Prophecy\Exception\Doubler\ClassMirrorException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
/**
* Class mirror.
* Core doubler class. Mirrors specific class and/or interfaces into class node tree.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ClassMirror
{
private static $reflectableMethods = array(
'__construct',
'__destruct',
'__sleep',
'__wakeup',
'__toString',
'__call',
'__invoke'
);
/**
* Reflects provided arguments into class node.
*
* @param ReflectionClass $class
* @param ReflectionClass[] $interfaces
*
* @return Node\ClassNode
*
* @throws \Prophecy\Exception\InvalidArgumentException
*/
public function reflect(ReflectionClass $class = null, 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;
}
private function reflectClassToNode(ReflectionClass $class, Node\ClassNode $node)
{
if (true === $class->isFinal()) {
throw new ClassMirrorException(sprintf(
'Could not reflect class %s as it is marked final.', $class->getName()
), $class);
}
$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::$reflectableMethods)) {
continue;
}
if (true === $method->isFinal()) {
$node->addUnextendableMethod($method->getName());
continue;
}
$this->reflectMethodToNode($method, $node);
}
}
private function reflectInterfaceToNode(ReflectionClass $interface, Node\ClassNode $node)
{
$node->addInterface($interface->getName());
foreach ($interface->getMethods() as $method) {
$this->reflectMethodToNode($method, $node);
}
}
private function reflectMethodToNode(ReflectionMethod $method, Node\ClassNode $classNode)
{
$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();
}
if (version_compare(PHP_VERSION, '7.0', '>=') && $method->hasReturnType()) {
$returnType = PHP_VERSION_ID >= 70100 ? $method->getReturnType()->getName() : (string) $method->getReturnType();
$returnTypeLower = strtolower($returnType);
if ('self' === $returnTypeLower) {
$returnType = $method->getDeclaringClass()->getName();
}
if ('parent' === $returnTypeLower) {
$returnType = $method->getDeclaringClass()->getParentClass()->getName();
}
$node->setReturnType($returnType);
if (version_compare(PHP_VERSION, '7.1', '>=') && $method->getReturnType()->allowsNull()) {
$node->setNullableReturnType(true);
}
}
if (is_array($params = $method->getParameters()) && count($params)) {
foreach ($params as $param) {
$this->reflectArgumentToNode($param, $node);
}
}
$classNode->addMethod($node);
}
private function reflectArgumentToNode(ReflectionParameter $parameter, Node\MethodNode $methodNode)
{
$name = $parameter->getName() == '...' ? '__dot_dot_dot__' : $parameter->getName();
$node = new Node\ArgumentNode($name);
$node->setTypeHint($this->getTypeHint($parameter));
if ($this->isVariadic($parameter)) {
$node->setAsVariadic();
}
if ($this->hasDefaultValue($parameter)) {
$node->setDefault($this->getDefaultValue($parameter));
}
if ($parameter->isPassedByReference()) {
$node->setAsPassedByReference();
}
$node->setAsNullable($this->isNullable($parameter));
$methodNode->addArgument($node);
}
private function hasDefaultValue(ReflectionParameter $parameter)
{
if ($this->isVariadic($parameter)) {
return false;
}
if ($parameter->isDefaultValueAvailable()) {
return true;
}
return $parameter->isOptional() || $this->isNullable($parameter);
}
private function getDefaultValue(ReflectionParameter $parameter)
{
if (!$parameter->isDefaultValueAvailable()) {
return null;
}
return $parameter->getDefaultValue();
}
private function getTypeHint(ReflectionParameter $parameter)
{
if (null !== $className = $this->getParameterClassName($parameter)) {
return $className;
}
if (true === $parameter->isArray()) {
return 'array';
}
if (version_compare(PHP_VERSION, '5.4', '>=') && true === $parameter->isCallable()) {
return 'callable';
}
if (version_compare(PHP_VERSION, '7.0', '>=') && true === $parameter->hasType()) {
return PHP_VERSION_ID >= 70100 ? $parameter->getType()->getName() : (string) $parameter->getType();
}
return null;
}
private function isVariadic(ReflectionParameter $parameter)
{
return PHP_VERSION_ID >= 50600 && $parameter->isVariadic();
}
private function isNullable(ReflectionParameter $parameter)
{
return $parameter->allowsNull() && null !== $this->getTypeHint($parameter);
}
private function getParameterClassName(ReflectionParameter $parameter)
{
try {
return $parameter->getClass() ? $parameter->getClass()->getName() : null;
} catch (\ReflectionException $e) {
preg_match('/\[\s\<\w+?>\s([\w,\\\]+)/s', $parameter, $matches);
return isset($matches[1]) ? $matches[1] : null;
}
}
}

View File

@ -0,0 +1,102 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class ArgumentNode
{
private $name;
private $typeHint;
private $default;
private $optional = false;
private $byReference = false;
private $isVariadic = false;
private $isNullable = false;
/**
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function getTypeHint()
{
return $this->typeHint;
}
public function setTypeHint($typeHint = null)
{
$this->typeHint = $typeHint;
}
public function hasDefault()
{
return $this->isOptional() && !$this->isVariadic();
}
public function getDefault()
{
return $this->default;
}
public function setDefault($default = null)
{
$this->optional = true;
$this->default = $default;
}
public function isOptional()
{
return $this->optional;
}
public function setAsPassedByReference($byReference = true)
{
$this->byReference = $byReference;
}
public function isPassedByReference()
{
return $this->byReference;
}
public function setAsVariadic($isVariadic = true)
{
$this->isVariadic = $isVariadic;
}
public function isVariadic()
{
return $this->isVariadic;
}
public function isNullable()
{
return $this->isNullable;
}
public function setAsNullable($isNullable = true)
{
$this->isNullable = $isNullable;
}
}

View File

@ -0,0 +1,169 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class ClassNode
{
private $parentClass = 'stdClass';
private $interfaces = array();
private $properties = array();
private $unextendableMethods = array();
/**
* @var MethodNode[]
*/
private $methods = array();
public function getParentClass()
{
return $this->parentClass;
}
/**
* @param string $class
*/
public function setParentClass($class)
{
$this->parentClass = $class ?: 'stdClass';
}
/**
* @return string[]
*/
public function getInterfaces()
{
return $this->interfaces;
}
/**
* @param string $interface
*/
public function addInterface($interface)
{
if ($this->hasInterface($interface)) {
return;
}
array_unshift($this->interfaces, $interface);
}
/**
* @param string $interface
*
* @return bool
*/
public function hasInterface($interface)
{
return in_array($interface, $this->interfaces);
}
public function getProperties()
{
return $this->properties;
}
public function addProperty($name, $visibility = 'public')
{
$visibility = strtolower($visibility);
if (!in_array($visibility, array('public', 'private', 'protected'))) {
throw new InvalidArgumentException(sprintf(
'`%s` property visibility is not supported.', $visibility
));
}
$this->properties[$name] = $visibility;
}
/**
* @return MethodNode[]
*/
public function getMethods()
{
return $this->methods;
}
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;
}
}
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 string[]
*/
public function getUnextendableMethods()
{
return $this->unextendableMethods;
}
/**
* @param string $unextendableMethod
*/
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);
}
}

View File

@ -0,0 +1,198 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\Doubler\Generator\TypeHintReference;
use Prophecy\Exception\InvalidArgumentException;
/**
* Method node.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class MethodNode
{
private $name;
private $code;
private $visibility = 'public';
private $static = false;
private $returnsReference = false;
private $returnType;
private $nullableReturnType = false;
/**
* @var ArgumentNode[]
*/
private $arguments = array();
/**
* @var TypeHintReference
*/
private $typeHintReference;
/**
* @param string $name
* @param string $code
*/
public function __construct($name, $code = null, TypeHintReference $typeHintReference = null)
{
$this->name = $name;
$this->code = $code;
$this->typeHintReference = $typeHintReference ?: new TypeHintReference();
}
public function getVisibility()
{
return $this->visibility;
}
/**
* @param string $visibility
*/
public function setVisibility($visibility)
{
$visibility = strtolower($visibility);
if (!in_array($visibility, array('public', 'private', 'protected'))) {
throw new InvalidArgumentException(sprintf(
'`%s` method visibility is not supported.', $visibility
));
}
$this->visibility = $visibility;
}
public function isStatic()
{
return $this->static;
}
public function setStatic($static = true)
{
$this->static = (bool) $static;
}
public function returnsReference()
{
return $this->returnsReference;
}
public function setReturnsReference()
{
$this->returnsReference = true;
}
public function getName()
{
return $this->name;
}
public function addArgument(ArgumentNode $argument)
{
$this->arguments[] = $argument;
}
/**
* @return ArgumentNode[]
*/
public function getArguments()
{
return $this->arguments;
}
public function hasReturnType()
{
return null !== $this->returnType;
}
/**
* @param string $type
*/
public function setReturnType($type = null)
{
if ($type === '' || $type === null) {
$this->returnType = null;
return;
}
$typeMap = array(
'double' => 'float',
'real' => 'float',
'boolean' => 'bool',
'integer' => 'int',
);
if (isset($typeMap[$type])) {
$type = $typeMap[$type];
}
$this->returnType = $this->typeHintReference->isBuiltInReturnTypeHint($type) ?
$type :
'\\' . ltrim($type, '\\');
}
public function getReturnType()
{
return $this->returnType;
}
/**
* @param bool $bool
*/
public function setNullableReturnType($bool = true)
{
$this->nullableReturnType = (bool) $bool;
}
/**
* @return bool
*/
public function hasNullableReturnType()
{
return $this->nullableReturnType;
}
/**
* @param string $code
*/
public function setCode($code)
{
$this->code = $code;
}
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;
}
public function useParentCode()
{
$this->code = sprintf(
'return parent::%s(%s);', $this->getName(), implode(', ',
array_map(array($this, 'generateArgument'), $this->arguments)
)
);
}
private function generateArgument(ArgumentNode $arg)
{
$argument = '$'.$arg->getName();
if ($arg->isVariadic()) {
$argument = '...'.$argument;
}
return $argument;
}
}

View File

@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface ReflectionInterface
{
}

View File

@ -0,0 +1,46 @@
<?php
namespace Prophecy\Doubler\Generator;
/**
* Tells whether a keyword refers to a class or to a built-in type for the
* current version of php
*/
final class TypeHintReference
{
public function isBuiltInParamTypeHint($type)
{
switch ($type) {
case 'self':
case 'array':
return true;
case 'callable':
return PHP_VERSION_ID >= 50400;
case 'bool':
case 'float':
case 'int':
case 'string':
return PHP_VERSION_ID >= 70000;
case 'iterable':
return PHP_VERSION_ID >= 70100;
case 'object':
return PHP_VERSION_ID >= 70200;
default:
return false;
}
}
public function isBuiltInReturnTypeHint($type)
{
if ($type === 'void') {
return PHP_VERSION_ID >= 70100;
}
return $this->isBuiltInParamTypeHint($type);
}
}

View File

@ -0,0 +1,127 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class LazyDouble
{
private $doubler;
private $class;
private $interfaces = array();
private $arguments = null;
private $double;
/**
* Initializes lazy double.
*
* @param Doubler $doubler
*/
public function __construct(Doubler $doubler)
{
$this->doubler = $doubler;
}
/**
* Tells doubler to use specific class as parent one for double.
*
* @param string|ReflectionClass $class
*
* @throws \Prophecy\Exception\Doubler\ClassNotFoundException
* @throws \Prophecy\Exception\Doubler\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);
}
$this->class = $class;
}
/**
* Tells doubler to implement specific interface with double.
*
* @param string|ReflectionClass $interface
*
* @throws \Prophecy\Exception\Doubler\InterfaceNotFoundException
* @throws \Prophecy\Exception\Doubler\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 $arguments
*/
public function setArguments(array $arguments = null)
{
$this->arguments = $arguments;
}
/**
* Creates double instance or returns already created one.
*
* @return 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;
}
}

View File

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class NameGenerator
{
private static $counter = 1;
/**
* Generates name.
*
* @param ReflectionClass $class
* @param ReflectionClass[] $interfaces
*
* @return string
*/
public function name(ReflectionClass $class = null, 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++);
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
public function __construct($message, ObjectProphecy $objectProphecy,
$methodName, array $arguments)
{
parent::__construct($message, $objectProphecy);
$this->methodName = $methodName;
$this->arguments = $arguments;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
}

View File

@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
public function __construct($message, ClassNode $node)
{
parent::__construct($message);
$this->node = $node;
}
public function getClassNode()
{
return $this->node;
}
}

View File

@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
public function __construct($message, ReflectionClass $class)
{
parent::__construct($message);
$this->class = $class;
}
public function getReflectedClass()
{
return $this->class;
}
}

View File

@ -0,0 +1,33 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
}
public function getClassname()
{
return $this->classname;
}
}

View File

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
}

View File

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
}

View File

@ -0,0 +1,20 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
public function getInterfaceName()
{
return $this->getClassname();
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace Prophecy\Exception\Doubler;
class MethodNotExtendableException extends DoubleException
{
private $methodName;
private $className;
/**
* @param string $message
* @param string $className
* @param string $methodName
*/
public function __construct($message, $className, $methodName)
{
parent::__construct($message);
$this->methodName = $methodName;
$this->className = $className;
}
/**
* @return string
*/
public function getMethodName()
{
return $this->methodName;
}
/**
* @return string
*/
public function getClassName()
{
return $this->className;
}
}

View File

@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Exception\Doubler;
class MethodNotFoundException extends DoubleException
{
/**
* @var string|object
*/
private $classname;
/**
* @var string
*/
private $methodName;
/**
* @var array
*/
private $arguments;
/**
* @param string $message
* @param string|object $classname
* @param string $methodName
* @param null|Argument\ArgumentsWildcard|array $arguments
*/
public function __construct($message, $classname, $methodName, $arguments = null)
{
parent::__construct($message);
$this->classname = $classname;
$this->methodName = $methodName;
$this->arguments = $arguments;
}
public function getClassname()
{
return $this->classname;
}
public function getMethodName()
{
return $this->methodName;
}
public function getArguments()
{
return $this->arguments;
}
}

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
}
public function getClassname()
{
return $this->classname;
}
public function getMethodName()
{
return $this->methodName;
}
}

View File

@ -0,0 +1,26 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface Exception
{
/**
* @return string
*/
public function getMessage();
}

View File

@ -0,0 +1,16 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
}

View File

@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
private $exceptions = array();
private $objectProphecy;
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 PredictionException[]
*/
public function getExceptions()
{
return $this->exceptions;
}
public function setObjectProphecy(ObjectProphecy $objectProphecy)
{
$this->objectProphecy = $objectProphecy;
}
/**
* @return ObjectProphecy
*/
public function getObjectProphecy()
{
return $this->objectProphecy;
}
}

View File

@ -0,0 +1,24 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
class FailedPredictionException extends RuntimeException implements PredictionException
{
}

View File

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
}

View File

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
}

View File

@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\MethodProphecy;
class UnexpectedCallsCountException extends UnexpectedCallsException
{
private $expectedCount;
public function __construct($message, MethodProphecy $methodProphecy, $count, array $calls)
{
parent::__construct($message, $methodProphecy, $calls);
$this->expectedCount = intval($count);
}
public function getExpectedCount()
{
return $this->expectedCount;
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\MethodProphecy;
use Prophecy\Exception\Prophecy\MethodProphecyException;
class UnexpectedCallsException extends MethodProphecyException implements PredictionException
{
private $calls = array();
public function __construct($message, MethodProphecy $methodProphecy, array $calls)
{
parent::__construct($message, $methodProphecy);
$this->calls = $calls;
}
public function getCalls()
{
return $this->calls;
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
public function __construct($message, MethodProphecy $methodProphecy)
{
parent::__construct($message, $methodProphecy->getObjectProphecy());
$this->methodProphecy = $methodProphecy;
}
/**
* @return MethodProphecy
*/
public function getMethodProphecy()
{
return $this->methodProphecy;
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
public function __construct($message, ObjectProphecy $objectProphecy)
{
parent::__construct($message);
$this->objectProphecy = $objectProphecy;
}
/**
* @return ObjectProphecy
*/
public function getObjectProphecy()
{
return $this->objectProphecy;
}
}

View File

@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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
{
}

View File

@ -0,0 +1,69 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\Tag\MethodTag as LegacyMethodTag;
use phpDocumentor\Reflection\DocBlock\Tags\Method;
/**
* @author Théo FIDRY <theo.fidry@gmail.com>
*
* @internal
*/
final class ClassAndInterfaceTagRetriever implements MethodTagRetrieverInterface
{
private $classRetriever;
public function __construct(MethodTagRetrieverInterface $classRetriever = null)
{
if (null !== $classRetriever) {
$this->classRetriever = $classRetriever;
return;
}
$this->classRetriever = class_exists('phpDocumentor\Reflection\DocBlockFactory') && class_exists('phpDocumentor\Reflection\Types\ContextFactory')
? new ClassTagRetriever()
: new LegacyClassTagRetriever()
;
}
/**
* @param \ReflectionClass $reflectionClass
*
* @return LegacyMethodTag[]|Method[]
*/
public function getTagList(\ReflectionClass $reflectionClass)
{
return array_merge(
$this->classRetriever->getTagList($reflectionClass),
$this->getInterfacesTagList($reflectionClass)
);
}
/**
* @param \ReflectionClass $reflectionClass
*
* @return LegacyMethodTag[]|Method[]
*/
private function getInterfacesTagList(\ReflectionClass $reflectionClass)
{
$interfaces = $reflectionClass->getInterfaces();
$tagList = array();
foreach($interfaces as $interface) {
$tagList = array_merge($tagList, $this->classRetriever->getTagList($interface));
}
return $tagList;
}
}

View File

@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <theo.fidry@gmail.com>
*
* @internal
*/
final class ClassTagRetriever implements MethodTagRetrieverInterface
{
private $docBlockFactory;
private $contextFactory;
public function __construct()
{
$this->docBlockFactory = DocBlockFactory::createInstance();
$this->contextFactory = new ContextFactory();
}
/**
* @param \ReflectionClass $reflectionClass
*
* @return Method[]
*/
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();
}
}
}

View File

@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
use phpDocumentor\Reflection\DocBlock\Tag\MethodTag as LegacyMethodTag;
/**
* @author Théo FIDRY <theo.fidry@gmail.com>
*
* @internal
*/
final class LegacyClassTagRetriever implements MethodTagRetrieverInterface
{
/**
* @param \ReflectionClass $reflectionClass
*
* @return LegacyMethodTag[]
*/
public function getTagList(\ReflectionClass $reflectionClass)
{
$phpdoc = new DocBlock($reflectionClass->getDocComment());
return $phpdoc->getTagsByName('method');
}
}

View File

@ -0,0 +1,30 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\Tag\MethodTag as LegacyMethodTag;
use phpDocumentor\Reflection\DocBlock\Tags\Method;
/**
* @author Théo FIDRY <theo.fidry@gmail.com>
*
* @internal
*/
interface MethodTagRetrieverInterface
{
/**
* @param \ReflectionClass $reflectionClass
*
* @return LegacyMethodTag[]|Method[]
*/
public function getTagList(\ReflectionClass $reflectionClass);
}

View File

@ -0,0 +1,86 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Call prediction.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class CallPrediction implements PredictionInterface
{
private $util;
/**
* Initializes prediction.
*
* @param StringUtil $util
*/
public function __construct(StringUtil $util = null)
{
$this->util = $util ?: new StringUtil;
}
/**
* Tests that there was at least one call.
*
* @param Call[] $calls
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @throws \Prophecy\Exception\Prediction\NoCallsException
*/
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);
}
}

View File

@ -0,0 +1,107 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\UnexpectedCallsCountException;
/**
* Prediction interface.
* Predictions are logical test blocks, tied to `should...` keyword.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class CallTimesPrediction implements PredictionInterface
{
private $times;
private $util;
/**
* Initializes prediction.
*
* @param int $times
* @param StringUtil $util
*/
public function __construct($times, StringUtil $util = null)
{
$this->times = intval($times);
$this->util = $util ?: new StringUtil;
}
/**
* Tests that there was exact amount of calls made.
*
* @param Call[] $calls
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @throws \Prophecy\Exception\Prediction\UnexpectedCallsCountException
*/
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);
}
}

View File

@ -0,0 +1,65 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\Exception\InvalidArgumentException;
use Closure;
/**
* Callback prediction.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class CallbackPrediction implements PredictionInterface
{
private $callback;
/**
* Initializes callback prediction.
*
* @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;
}
/**
* Executes preset callback.
*
* @param Call[] $calls
* @param ObjectProphecy $object
* @param MethodProphecy $method
*/
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method)
{
$callback = $this->callback;
if ($callback instanceof Closure && method_exists('Closure', 'bind')) {
$callback = Closure::bind($callback, $object);
}
call_user_func($callback, $calls, $object, $method);
}
}

View File

@ -0,0 +1,68 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\Util\StringUtil;
use Prophecy\Exception\Prediction\UnexpectedCallsException;
/**
* No calls prediction.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class NoCallsPrediction implements PredictionInterface
{
private $util;
/**
* Initializes prediction.
*
* @param null|StringUtil $util
*/
public function __construct(StringUtil $util = null)
{
$this->util = $util ?: new StringUtil;
}
/**
* Tests that there were no calls made.
*
* @param Call[] $calls
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @throws \Prophecy\Exception\Prediction\UnexpectedCallsException
*/
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);
}
}

View File

@ -0,0 +1,37 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Prediction interface.
* Predictions are logical test blocks, tied to `should...` keyword.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
interface PredictionInterface
{
/**
* Tests that double fulfilled prediction.
*
* @param Call[] $calls
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @throws object
* @return void
*/
public function check(array $calls, ObjectProphecy $object, MethodProphecy $method);
}

View File

@ -0,0 +1,66 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Callback promise.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
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;
}
/**
* Evaluates promise callback.
*
* @param array $args
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @return mixed
*/
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
$callback = $this->callback;
if ($callback instanceof Closure && method_exists('Closure', 'bind')) {
$callback = Closure::bind($callback, $object);
}
return call_user_func($callback, $args, $object, $method);
}
}

View File

@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface PromiseInterface
{
/**
* Evaluates promise.
*
* @param array $args
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @return mixed
*/
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method);
}

View File

@ -0,0 +1,61 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Return argument promise.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
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;
}
/**
* Returns nth argument if has one, null otherwise.
*
* @param array $args
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @return null|mixed
*/
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
return count($args) > $this->index ? $args[$this->index] : null;
}
}

View File

@ -0,0 +1,55 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Return promise.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ReturnPromise implements PromiseInterface
{
private $returnValues = array();
/**
* Initializes promise.
*
* @param array $returnValues Array of values
*/
public function __construct(array $returnValues)
{
$this->returnValues = $returnValues;
}
/**
* Returns saved values one by one until last one, then continuously returns last value.
*
* @param array $args
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @return mixed
*/
public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
{
$value = array_shift($this->returnValues);
if (!count($this->returnValues)) {
$this->returnValues[] = $value;
}
return $value;
}
}

View File

@ -0,0 +1,100 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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;
/**
* Throw promise.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ThrowPromise implements PromiseInterface
{
private $exception;
/**
* @var \Doctrine\Instantiator\Instantiator
*/
private $instantiator;
/**
* Initializes promise.
*
* @param string|\Exception|\Throwable $exception Exception class name or instance
*
* @throws \Prophecy\Exception\InvalidArgumentException
*/
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;
}
/**
* Throws predefined exception.
*
* @param array $args
* @param ObjectProphecy $object
* @param MethodProphecy $method
*
* @throws object
*/
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->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);
}
}

View File

@ -0,0 +1,522 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\Prophet;
use Prophecy\Promise;
use Prophecy\Prediction;
use Prophecy\Exception\Doubler\MethodNotFoundException;
use Prophecy\Exception\InvalidArgumentException;
use Prophecy\Exception\Prophecy\MethodProphecyException;
/**
* Method prophecy.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class MethodProphecy
{
private $objectProphecy;
private $methodName;
private $argumentsWildcard;
private $promise;
private $prediction;
private $checkedPredictions = array();
private $bound = false;
private $voidReturnType = false;
/**
* Initializes method prophecy.
*
* @param ObjectProphecy $objectProphecy
* @param string $methodName
* @param null|Argument\ArgumentsWildcard|array $arguments
*
* @throws \Prophecy\Exception\Doubler\MethodNotFoundException If method not found
*/
public function __construct(ObjectProphecy $objectProphecy, $methodName, $arguments = null)
{
$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);
}
if (null !== $arguments) {
$this->withArguments($arguments);
}
if (version_compare(PHP_VERSION, '7.0', '>=') && true === $reflectedMethod->hasReturnType()) {
$type = PHP_VERSION_ID >= 70100 ? $reflectedMethod->getReturnType()->getName() : (string) $reflectedMethod->getReturnType();
if ('void' === $type) {
$this->voidReturnType = true;
}
$this->will(function () use ($type) {
switch ($type) {
case 'void': return;
case 'string': return '';
case 'float': return 0.0;
case 'int': return 0;
case 'bool': return false;
case 'array': return array();
case 'callable':
case 'Closure':
return function () {};
case 'Traversable':
case 'Generator':
// Remove eval() when minimum version >=5.5
/** @var callable $generator */
$generator = eval('return function () { yield; };');
return $generator();
default:
$prophet = new Prophet;
return $prophet->prophesize($type)->reveal();
}
});
}
}
/**
* 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
*
* @return $this
*/
public function willReturn()
{
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(func_get_args()));
}
/**
* @param array $items
*
* @return $this
*
* @throws \Prophecy\Exception\InvalidArgumentException
*/
public function willYield($items)
{
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)
));
}
// Remove eval() when minimum version >=5.5
/** @var callable $generator */
$generator = eval('return function() use ($items) {
foreach ($items as $key => $value) {
yield $key => $value;
}
};');
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|\Exception $exception Exception class or instance
*
* @return $this
*/
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 $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
*/
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
*/
public function shouldHaveBeenCalled()
{
return $this->shouldHave(new Prediction\CallPrediction);
}
/**
* Checks no calls prediction.
*
* @see \Prophecy\Prediction\NoCallsPrediction
*
* @return $this
*/
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.
*/
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 Prediction\PredictionInterface[]
*/
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;
}
private function bindToObjectProphecy()
{
if ($this->bound) {
return;
}
$this->getObjectProphecy()->addMethodProphecy($this);
$this->bound = true;
}
}

View File

@ -0,0 +1,286 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Prophecy;
use SebastianBergmann\Comparator\ComparisonFailure;
use Prophecy\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\Prophecy\MethodProphecyException;
use Prophecy\Exception\Prediction\AggregateException;
use Prophecy\Exception\Prediction\PredictionException;
/**
* Object prophecy.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ObjectProphecy implements ProphecyInterface
{
private $lazyDouble;
private $callCenter;
private $revealer;
private $comparatorFactory;
/**
* @var MethodProphecy[][]
*/
private $methodProphecies = array();
/**
* Initializes object prophecy.
*
* @param LazyDouble $lazyDouble
* @param CallCenter $callCenter
* @param RevealerInterface $revealer
* @param ComparatorFactory $comparatorFactory
*/
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 ?: ComparatorFactory::getInstance();
}
/**
* Forces double to extend specific class.
*
* @param string $class
*
* @return $this
*/
public function willExtend($class)
{
$this->lazyDouble->setParentClass($class);
return $this;
}
/**
* Forces double to implement specific interface.
*
* @param string $interface
*
* @return $this
*/
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
*/
public function reveal()
{
$double = $this->lazyDouble->getInstance();
if (null === $double || !$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
*
* @throws \Prophecy\Exception\Prophecy\MethodProphecyException If method prophecy doesn't
* have arguments wildcard
*/
public function addMethodProphecy(MethodProphecy $methodProphecy)
{
$argumentsWildcard = $methodProphecy->getArgumentsWildcard();
if (null === $argumentsWildcard) {
throw new MethodProphecyException(sprintf(
"Can not add prophecy for a method `%s::%s()`\n".
"as you did not specify arguments wildcard for it.",
get_class($this->reveal()),
$methodProphecy->getMethodName()
), $methodProphecy);
}
$methodName = strtolower($methodProphecy->getMethodName());
if (!isset($this->methodProphecies[$methodName])) {
$this->methodProphecies[$methodName] = array();
}
$this->methodProphecies[$methodName][] = $methodProphecy;
}
/**
* Returns either all or related to single method prophecies.
*
* @param null|string $methodName
*
* @return MethodProphecy[]
*/
public function getMethodProphecies($methodName = null)
{
if (null === $methodName) {
return $this->methodProphecies;
}
$methodName = strtolower($methodName);
if (!isset($this->methodProphecies[$methodName])) {
return array();
}
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);
$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 Call[]
*/
public function findProphecyMethodCalls($methodName, ArgumentsWildcard $wildcard)
{
return $this->callCenter->findCalls($methodName, $wildcard);
}
/**
* Checks that registered method predictions do not fail.
*
* @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 = new ArgumentsWildcard($this->revealer->reveal($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
*/
public function __set($name, $value)
{
$this->reveal()->$name = $this->revealer->reveal($value);
}
}

View File

@ -0,0 +1,27 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface ProphecyInterface
{
/**
* Reveals prophecy object (double) .
*
* @return object
*/
public function reveal();
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface ProphecySubjectInterface
{
/**
* Sets subject prophecy.
*
* @param ProphecyInterface $prophecy
*/
public function setProphecy(ProphecyInterface $prophecy);
/**
* Returns subject prophecy.
*
* @return ProphecyInterface
*/
public function getProphecy();
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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;
}
}

View File

@ -0,0 +1,29 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
interface RevealerInterface
{
/**
* Unwraps value(s).
*
* @param mixed $value
*
* @return mixed
*/
public function reveal($value);
}

View File

@ -0,0 +1,138 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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\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 <ever.zet@gmail.com>
*/
class Prophet
{
private $doubler;
private $revealer;
private $util;
/**
* @var ObjectProphecy[]
*/
private $prophecies = array();
/**
* Initializes Prophet.
*
* @param null|Doubler $doubler
* @param null|RevealerInterface $revealer
* @param null|StringUtil $util
*/
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\HhvmExceptionPatch());
$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
*/
public function prophesize($classOrInterface = null)
{
$this->prophecies[] = $prophecy = new ObjectProphecy(
new LazyDouble($this->doubler),
new CallCenter($this->util),
$this->revealer
);
if ($classOrInterface && class_exists($classOrInterface)) {
return $prophecy->willExtend($classOrInterface);
}
if ($classOrInterface && interface_exists($classOrInterface)) {
return $prophecy->willImplement($classOrInterface);
}
return $prophecy;
}
/**
* Returns all created object prophecies.
*
* @return ObjectProphecy[]
*/
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.
*
* @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;
}
}
}

View File

@ -0,0 +1,210 @@
<?php
namespace Prophecy\Util;
use Prophecy\Prophecy\ProphecyInterface;
use SebastianBergmann\RecursionContext\Context;
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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) {
// However, the fast method does work in HHVM, and exposes the
// internal implementation. Hide it again.
if (property_exists('\SplObjectStorage', '__storage')) {
unset($array['__storage']);
} elseif (property_exists('\SplObjectStorage', 'storage')) {
unset($array['storage']);
}
if (property_exists('\SplObjectStorage', '__key')) {
unset($array['__key']);
}
foreach ($value as $key => $val) {
$array[spl_object_hash($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)',
$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 ($hash = $processed->contains($value)) {
return sprintf('%s:%s Object', $class, $hash);
}
$hash = $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:%s Object (%s)', $class, $hash, $values);
}
return var_export($value, true);
}
}

View File

@ -0,0 +1,99 @@
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
* Marcello Duarte <marcello.duarte@gmail.com>
*
* 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 <ever.zet@gmail.com>
*/
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_hash($value));
}
if (true === $value || false === $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';
}
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));
}
}