Skip to content

Commit

Permalink
feat: возможность отключения exception chaining
Browse files Browse the repository at this point in the history
Добавлено:

- возможность отключения exception chaining при ошибке кешируемого
  callback  методом
  \WebArch\BitrixCache\Cache::setCallbackExceptionChaining().
  • Loading branch information
webarchitect609 committed Sep 16, 2021
1 parent 28a976f commit f2ba3a8
Show file tree
Hide file tree
Showing 3 changed files with 133 additions and 14 deletions.
10 changes: 9 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
Change Log
==========

1.10.0
------

### Добавлено:

- возможность отключения exception chaining при ошибке кешируемого callback
методом `\WebArch\BitrixCache\Cache::setCallbackExceptionChaining()`.

1.9.3
-----

### Исправлено:

- ограничение `psr/cache: ^1.0` для поддержки `PHP 8.0`.
- ограничение `psr/cache: ^1.0` для поддержки `PHP 8.0`.

### Изменено:

Expand Down
63 changes: 51 additions & 12 deletions src/main/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use DateTimeImmutable;
use DateTimeInterface;
use Psr\SimpleCache\CacheInterface;
use ReflectionException;
use ReflectionFunction;
use Throwable;
use WebArch\BitrixCache\Enum\ErrorCode;
Expand Down Expand Up @@ -84,6 +85,13 @@ class Cache implements CacheInterface
*/
private $closureAbortedCache = false;

/**
* @var bool Использование exception chaining при ошибке в кешируемом callback: выбрасывается
* \WebArch\BitrixCache\Exception\RuntimeException, у которого в $previous сохранено фактически возникшее
* исключение.
*/
private $callbackExceptionChaining = true;

/**
* @var null|BitrixCache
*/
Expand Down Expand Up @@ -117,6 +125,7 @@ public static function create(): Cache
*
* @throws RuntimeException
* @throws LogicException
* @throws ReflectionException
* @return mixed Результат выполнения $callback.
*/
public function callback(callable $callback)
Expand Down Expand Up @@ -148,19 +157,24 @@ public function callback(callable $callback)
$this->closureAbortedCache = false;
$result = $callback();
} catch (Throwable $exception) {
throw new RuntimeException(
sprintf(
'The callback has thrown an exception [%s] %s (%s) in %s:%d',
get_class($exception),
$exception->getMessage(),
$exception->getCode(),
$exception->getFile(),
$exception->getLine()
),
ErrorCode::CALLBACK_THROWS_EXCEPTION,
$exception
);
if ($this->isCallbackExceptionChaining()) {
throw new RuntimeException(
sprintf(
'The callback has thrown an exception [%s] %s (%s) in %s:%d',
get_class($exception),
$exception->getMessage(),
$exception->getCode(),
$exception->getFile(),
$exception->getLine()
),
ErrorCode::CALLBACK_THROWS_EXCEPTION,
$exception
);
}
throw $exception;
}
// Условие может измениться при вызове abort() в кешируемом callback
/** @noinspection PhpConditionAlreadyCheckedInspection */
if (false === $this->closureAbortedCache) {
$this->startTagCache();
$this->endTagCache();
Expand Down Expand Up @@ -675,6 +689,31 @@ public function addTag(string $tag)
return $this;
}

/**
* Возвращает состояние флага использования exception chaining при ошибке в кешируемом callback.
*
* @return bool
*/
public function isCallbackExceptionChaining(): bool
{
return $this->callbackExceptionChaining;
}

/**
* Устанавливает или снимает флаг использования exception chaining при ошибке в кешируемом callback.
*
* @param bool $callbackExceptionChaining
*
* @return $this
* @noinspection PhpMissingReturnTypeInspection
*/
public function setCallbackExceptionChaining(bool $callbackExceptionChaining)
{
$this->callbackExceptionChaining = $callbackExceptionChaining;

return $this;
}

/**
* @param null|DateInterval|int $ttl
*
Expand Down
74 changes: 73 additions & 1 deletion src/test/CacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -279,11 +279,12 @@ public function testCallbackReflectionFunctionFailsByNonExistingFunction()
$this->expectExceptionCode(ErrorCode::ERROR_REFLECTING_CALLBACK);

$this->cache->callback(
[$this,'testCallbackReflectionFunctionFailsByNonExistingFunction']
[$this, 'testCallbackReflectionFunctionFailsByNonExistingFunction']
);
}

/**
* @throws ReflectionException
* @return void
*/
public function testCallbackExceptionAbortsCacheIncludingTagged()
Expand Down Expand Up @@ -348,6 +349,73 @@ function () {
}

/**
* @throws ReflectionException
* @return void
*/
public function testCallbackExceptionChainingDisabled()
{
$this->bitrixCache->expects($this->once())
->method('startDataCache')
->with(
Cache::DEFAULT_TTL,
$this->key,
Cache::DEFAULT_PATH,
[],
Cache::DEFAULT_BASE_DIR
)
->willReturn(true);

$this->bitrixTaggedCache->expects($this->never())
->method('startTagCache')
->with(Cache::DEFAULT_PATH);

$tag = 'tag';
$this->bitrixTaggedCache->expects($this->never())
->method('registerTag')
->with($tag);

$this->bitrixCache->expects($this->never())
->method('abortDataCache');

$this->bitrixTaggedCache->expects($this->never())
->method('abortTagCache');

$this->bitrixCache->expects($this->never())
->method('endDataCache');

$this->bitrixCache->expects($this->never())
->method('getVars');

$this->bitrixCache->expects($this->never())
->method('clean');

$this->bitrixCache->expects($this->never())
->method('cleanDir');

$this->bitrixCache->expects($this->never())
->method('initCache');

$this->bitrixTaggedCache->expects($this->never())
->method('clearByTag');

$this->bitrixTaggedCache->expects($this->never())
->method('endTagCache');

$this->expectException(CommonLogicException::class);
$this->expectExceptionCode(784);

$this->cache->setKey($this->key)
->addTag($tag)
->setCallbackExceptionChaining(false)
->callback(
function () {
throw new CommonLogicException('This is the source exception!', 784);
}
);
}

/**
* @throws ReflectionException
* @return void
*/
public function testCallbackEncountersGetVarsError()
Expand Down Expand Up @@ -992,6 +1060,7 @@ public function testSetMixedTTLWrongType()
}

/**
* @throws ReflectionException
* @return void
*/
public function testBitrixCacheInstantiation()
Expand All @@ -1012,6 +1081,7 @@ public function testBitrixCacheInstantiation()
}

/**
* @throws ReflectionException
* @return void
*/
public function testBitrixCacheInstantiationFails()
Expand All @@ -1031,6 +1101,7 @@ public function testBitrixCacheInstantiationFails()
}

/**
* @throws ReflectionException
* @return void
*/
public function testBitrixTaggedCacheInstantiation()
Expand All @@ -1051,6 +1122,7 @@ public function testBitrixTaggedCacheInstantiation()
}

/**
* @throws ReflectionException
* @return void
*/
public function testBitrixTaggedCacheInstantiationFails()
Expand Down

0 comments on commit f2ba3a8

Please sign in to comment.