xero_sync-8.x-1.x-dev/tests/src/Kernel/MockItemManager.php
tests/src/Kernel/MockItemManager.php
<?php
namespace Drupal\Tests\xero_sync\Kernel;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\xero\XeroItemManager;
use Drupal\xero\TypedData\XeroComplexItemInterface;
/**
* A mock item manager.
*
* It that simply remembers how it was called and supplies
* specified return values, instead of actually using the Xero API.
*/
class MockItemManager extends XeroItemManager {
/**
* The calls this mock item manager has received.
*
* @var array
*/
protected static $calls = [];
/**
* The values this mock item manager should return.
*
* @var array
*/
protected static $returns = [];
/**
* {@inheritDoc}
*/
public function createItem(XeroComplexItemInterface $item) {
return $this->handleCall(__FUNCTION__, func_get_args());
}
/**
* {@inheritDoc}
*/
public function updateItem(XeroComplexItemInterface $item) {
return $this->handleCall(__FUNCTION__, func_get_args());
}
/**
* {@inheritDoc}
*/
public function reloadItem(XeroComplexItemInterface $item) {
return $this->handleCall(__FUNCTION__, func_get_args());
}
/**
* {@inheritDoc}
*/
public function findItem($type, array $conditions, $unique = FALSE) {
return $this->handleCall(__FUNCTION__, func_get_args());
}
/**
* Get the calls that have been made to this mock item manager.
*/
public function getCalls() {
return self::$calls;
}
/**
* Specify the values to return when this mock item manager is called.
*/
public function setReturns($returns) {
self::$calls = [];
self::$returns = $returns;
}
/**
* Handle a call to this mock item manager.
*
* @param string $function
* The call.
* @param array $args
* The argument provided to the call.
*
* @return mixed
* Return the value specified for this call.
*
* @throws \Exception
*/
protected function handleCall($function, array $args) {
self::$calls[] = [
'method' => $function,
'arguments' => $args,
];
$nextReturnIndex = count(self::$calls) - 1;
$returnsCount = count(self::$returns);
if ($returnsCount <= $nextReturnIndex) {
$message = (string) new FormattableMarkup("The mock item manager was called @calls times but only @returns mock returns were provided.\nCalls\n@methods", [
'@calls' => count(self::$calls),
'@returns' => count(self::$returns),
'@methods' => print_r(array_column(self::$calls, 'method'), TRUE),
]);
throw new \Exception($message);
}
return self::$returns[$nextReturnIndex];
}
}
