Skip to content

Commit

Permalink
Avoid calls to Container::has() that can be avoided (#12)
Browse files Browse the repository at this point in the history
For performance reasons.
  • Loading branch information
mnapoli authored Jul 14, 2016
1 parent 4140c38 commit 1f4ca63
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/CallableResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Invoker;

use Interop\Container\ContainerInterface;
use Interop\Container\Exception\NotFoundException;
use Invoker\Exception\NotCallableException;

/**
Expand Down Expand Up @@ -70,29 +71,30 @@ private function resolveFromContainer($callable)

// The callable is a container entry name
if (is_string($callable)) {
if ($this->container->has($callable)) {
try {
return $this->container->get($callable);
} else {
} catch (NotFoundException $e) {
throw NotCallableException::fromInvalidCallable($callable, true);
}
}

// The callable is an array whose first item is a container entry name
// e.g. ['some-container-entry', 'methodToCall']
if (is_array($callable) && is_string($callable[0])) {
if ($this->container->has($callable[0])) {
try {
// Replace the container entry name by the actual object
$callable[0] = $this->container->get($callable[0]);
return $callable;
} elseif ($isStaticCallToNonStaticMethod) {
throw new NotCallableException(sprintf(
'Cannot call %s::%s() because %s() is not a static method and "%s" is not a container entry',
$callable[0],
$callable[1],
$callable[1],
$callable[0]
));
} else {
} catch (NotFoundException $e) {
if ($isStaticCallToNonStaticMethod) {
throw new NotCallableException(sprintf(
'Cannot call %s::%s() because %s() is not a static method and "%s" is not a container entry',
$callable[0],
$callable[1],
$callable[1],
$callable[0]
));
}
throw new NotCallableException(sprintf(
'Cannot call %s on %s because it is not a class nor a valid container entry',
$callable[1],
Expand Down
4 changes: 4 additions & 0 deletions tests/Mock/ArrayContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ public function __construct(array $entries = array())

public function get($id)
{
if (!array_key_exists($id, $this->entries)) {
throw new NotFound;
}

return $this->entries[$id];
}

Expand Down
10 changes: 10 additions & 0 deletions tests/Mock/NotFound.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
declare(strict_types = 1);

namespace Invoker\Test\Mock;

use Interop\Container\Exception\NotFoundException;

class NotFound extends \Exception implements NotFoundException
{
}

0 comments on commit 1f4ca63

Please sign in to comment.