Skip to content
Permalink
Browse files

added Helpers

  • Loading branch information...
dg committed Nov 3, 2019
1 parent c133e18 commit f1dc08536b040d5b569ee63354343145cbe6c591
@@ -83,7 +83,7 @@ public static function mergeTree(array $arr1, array $arr2): array
public static function searchKey(array $arr, $key): ?int
{
$foo = [$key => null];
return ($tmp = array_search(key($foo), array_keys($arr), true)) === false ? null : $tmp;
return Helpers::falseToNull(array_search(key($foo), array_keys($arr), true));
}
@@ -0,0 +1,35 @@
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Utils;
class Helpers
{
/**
* Captures PHP output into a string.
*/
public static function capture(callable $func): string
{
ob_start(function () {});
try {
$func();
return ob_get_clean();
} catch (\Throwable $e) {
ob_end_clean();
throw $e;
}
}
public static function falseToNull($val)
{
return $val === false ? null : $val;
}
}
@@ -502,9 +502,9 @@ public function save(string $file, int $quality = null, int $type = null): void
*/
public function toString(int $type = self::JPEG, int $quality = null): string
{
ob_start(function () {});
$this->output($type, $quality);
return ob_get_clean();
return Helpers::capture(function () use ($type, $quality) {
$this->output($type, $quality);
});
}
@@ -423,7 +423,7 @@ private static function pos(string $haystack, string $needle, int $nth = 1): ?in
$pos--;
}
}
return $pos === false ? null : $pos;
return Helpers::falseToNull($pos);
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
use Nette\Utils\Helpers;
use Tester\Assert;
require __DIR__ . '/../bootstrap.php';
Assert::same('', Helpers::capture(function () {}));
Assert::same('hello', Helpers::capture(function () { echo 'hello'; }));
$level = ob_get_level();
Assert::exception(function () {
Helpers::capture(function () {
undefined();
});
}, Error::class, 'Call to undefined function undefined()');
Assert::same($level, ob_get_level());
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
use Nette\Utils\Helpers;
use Tester\Assert;
require __DIR__ . '/../bootstrap.php';
Assert::same(null, Helpers::falseToNull(null));
Assert::same(true, Helpers::falseToNull(true));
Assert::same(null, Helpers::falseToNull(false));
Assert::same([], Helpers::falseToNull([]));

0 comments on commit f1dc085

Please sign in to comment.
You can’t perform that action at this time.