Skip to content
This repository has been archived by the owner on Jan 30, 2020. It is now read-only.

Callback filter consumes string class name via ::class resolution #40

Closed
wants to merge 1 commit 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions doc/book/standard-filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,19 @@ $filter = new Zend\Filter\Callback(array('MyClass', 'reverse'));
print $filter->filter('Hello!');
```

As of PHP 5.5 you can use ::class resolution for given callback class:

```php
class MyClass
{
public function __invoke($param);
}

// The filter definition
$filter = new Zend\Filter\Callback(MyClass::class);
print $filter->filter('Hello!');
```

To get the actual set callback use `getCallback()` and to set another callback
use `setCallback()`.

Expand Down
6 changes: 5 additions & 1 deletion src/Callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Callback extends AbstractFilter
*/
public function __construct($callbackOrOptions = [], $callbackParams = [])
{
if (is_callable($callbackOrOptions)) {
if (is_callable($callbackOrOptions) || is_string($callbackOrOptions)) {
$this->setCallback($callbackOrOptions);
$this->setCallbackParams($callbackParams);
} else {
Expand All @@ -44,6 +44,10 @@ public function __construct($callbackOrOptions = [], $callbackParams = [])
*/
public function setCallback($callback)
{
if (is_string($callback) && class_exists($callback)) {
$callback = new $callback();
}

if (!is_callable($callback)) {
throw new Exception\InvalidArgumentException(
'Invalid parameter for callback: must be callable'
Expand Down
11 changes: 11 additions & 0 deletions test/CallbackTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ public function testStaticCallback()
$this->assertEquals('staticCallback-test', $filter('test'));
}

public function testStringClassCallback()
{
$filter = new CallbackFilter(self::class);
$this->assertEquals('stringClassCallback-test', $filter('test'));
}

public function testSettingDefaultOptions()
{
$filter = new CallbackFilter([$this, 'objectCallback'], 'param');
Expand Down Expand Up @@ -77,6 +83,11 @@ public static function staticCallback($value)
return 'staticCallback-' . $value;
}

public function __invoke($value)
{
return 'stringClassCallback-' . $value;
}

public function objectCallbackWithParams($value, $param = null)
{
return 'objectCallbackWithParams-' . $value . '-' . $param;
Expand Down