Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4.x - Add check for Slim callable notation if no resolver given #2807

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions Slim/DeferredCallable.php
Expand Up @@ -9,6 +9,7 @@

namespace Slim;

use RuntimeException;
use Slim\Interfaces\CallableResolverInterface;

class DeferredCallable
Expand All @@ -29,6 +30,13 @@ class DeferredCallable
*/
public function __construct($callable, ?CallableResolverInterface $resolver = null)
{
if ($resolver === null && is_string($callable) && preg_match(CallableResolver::$callablePattern, $callable)) {
throw new RuntimeException(sprintf(
'Slim callable notation %s is not allowed without callable resolver.',
$callable
));
}

$this->callable = $callable;
$this->callableResolver = $resolver;
}
Expand Down
38 changes: 38 additions & 0 deletions tests/DeferredCallableTest.php
Expand Up @@ -10,6 +10,7 @@
namespace Slim\Tests;

use Psr\Container\ContainerInterface;
use RuntimeException;
use Slim\CallableResolver;
use Slim\DeferredCallable;
use Slim\Tests\Mocks\CallableTest;
Expand Down Expand Up @@ -68,4 +69,41 @@ public function testItReturnsInvokedCallableResponse()
$response = $deferred($foo);
$this->assertEquals($bar, $response);
}

public function testFunctionNameIfNoResolver()
{
$deferredTrim = new DeferredCallable('trim');
$this->assertSame('foo', $deferredTrim(' foo '));
}

public function testClosureIfNoResolver()
{
$closure = function ($a, $b) {
return $a + $b;
};

$deferredClosure = new DeferredCallable($closure);
$this->assertSame(42, $deferredClosure(31, 11));
}

public static function getFoo(): string
{
return 'foo';
}

public function testClassNameMethodNameNotation()
{
// Test `ClassName::methodName` notation for a static method.
$deferredGetFoo = new DeferredCallable(get_class($this) . '::getFoo');
$this->assertSame('foo', $deferredGetFoo());
}

/**
* @expectedException RuntimeException
* @expectedExceptionMessage Slim callable notation CallableTest:toCall is not allowed without callable resolver.
*/
public function testSlimCallableNotationThrowsExceptionIfNoResolver()
{
new DeferredCallable('CallableTest:toCall');
}
}