Skip to content

Commit

Permalink
extract magic method discovery
Browse files Browse the repository at this point in the history
  • Loading branch information
juliangut committed Jun 4, 2017
1 parent 6306434 commit 821f3dc
Showing 1 changed file with 44 additions and 14 deletions.
58 changes: 44 additions & 14 deletions src/RepositoryTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -288,17 +288,33 @@ public function __call($method, $arguments)
));
}

$baseMethod = $this->getSupportedMethod($method);

if ($baseMethod === 'findOneBy' && preg_match('/OrGetNew$/', $method)) {
$field = substr($method, strlen($baseMethod), -8);
$method = 'findOneByOrGetNew';
} else {
$field = substr($method, strlen($baseMethod));
$method = $baseMethod;
}

return $this->callSupportedMethod($method, Inflector::camelize($field), $arguments);
}

/**
* Get supported magic method.
*
* @param string $method
*
* @throws \BadMethodCallException
*
* @return string
*/
private function getSupportedMethod(string $method): string
{
foreach (static::$supportedMethods as $supportedMethod) {
if (strpos($method, $supportedMethod) === 0) {
if ($supportedMethod === 'findOneBy' && preg_match('/OrGetNew$/', $method)) {
$field = substr($method, strlen($supportedMethod), -8);
$method = 'findOneByOrGetNew';
} else {
$field = substr($method, strlen($supportedMethod));
$method = $supportedMethod;
}

return $this->callSupportedMethod($method, Inflector::camelize($field), $arguments);
return $supportedMethod;
}
}

Expand Down Expand Up @@ -356,7 +372,7 @@ protected function runManagerAction(string $action, $objects, bool $flush)
{
$manager = $this->getManager();

if (!is_array($objects) && !$objects instanceof \Traversable) {
if (!$this->isTraversable($objects)) {
$objects = array_filter([$objects]);
}

Expand Down Expand Up @@ -385,11 +401,13 @@ protected function runManagerAction(string $action, $objects, bool $flush)
*/
protected function flushObjects($objects, bool $flush)
{
if ($objects instanceof \Traversable) {
$objects = iterator_to_array($objects);
}

if ($flush || $this->autoFlush) {
// @codeCoverageIgnoreStart
if ($objects instanceof \Traversable) {
$objects = iterator_to_array($objects);
}
// @codeCoverageIgnoreEnd

$this->getManager()->flush($objects);
}
}
Expand Down Expand Up @@ -428,4 +446,16 @@ abstract protected function getManager();
* @return \Doctrine\Common\Persistence\Mapping\ClassMetadata
*/
abstract protected function getClassMetadata();

/**
* Is traversable.
*
* @param mixed $object
*
* @return bool
*/
private function isTraversable($object): bool
{
return is_array($object) || $object instanceof \Traversable;
}
}

0 comments on commit 821f3dc

Please sign in to comment.