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

[WIP] Static construction of objects #95

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions src/PHPSpec2/Console/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ public function __construct($version)
return new Listener\ClassNotFoundListener($c('io'));
});

$c->extend('event_dispatcher.listeners', function($c) {
return new Listener\FactoryMethodNotFoundListener($c('io'));
});

$c->extend('event_dispatcher.listeners', function($c) {
return new Listener\MethodNotFoundListener($c('io'));
});
Expand Down
34 changes: 34 additions & 0 deletions src/PHPSpec2/Exception/FactoryMethodNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace PHPSpec2\Exception;

class FactoryMethodNotFoundException extends Exception
{
private $subject;
private $method;
private $arguments;

public function __construct($message, $subject, $method, array $arguments = array())
{
parent::__construct($message);

$this->subject = $subject;
$this->method = $method;
$this->arguments = $arguments;
}

public function getSubject()
{
return $this->subject;
}

public function getMethod()
{
return $this->method;
}

public function getArguments()
{
return $this->arguments;
}
}
70 changes: 70 additions & 0 deletions src/PHPSpec2/Listener/FactoryMethodNotFoundListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace PHPSpec2\Listener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use PHPSpec2\Event\ExampleEvent;
use PHPSpec2\Console\IO;
use PHPSpec2\Exception\FactoryMethodNotFoundException;

class FactoryMethodNotFoundListener implements EventSubscriberInterface
{
private $io;
private $proposedMethods = array();

public function __construct(IO $io)
{
$this->io = $io;
}

public static function getSubscribedEvents()
{
return array('afterExample' => 'afterExample');
}

public function afterExample(ExampleEvent $event)
{
$exception = $event->getException();
if (null !== $exception && $exception instanceof FactoryMethodNotFoundException) {
if (null === $ioTemp = $this->io->cutTemp()) {
if ("\n" !== $this->io->getLastWrittenMessage()) {
$this->io->writeln();
}
}
$shortcut = $exception->getSubject().'::'.$exception->getMethod();
if (in_array($shortcut, $this->proposedMethods)) {
return;
}
$this->proposedMethods[] = $shortcut;

if ($this->io->askConfirmation('Do you want me to create this factory method for you?')) {
$class = new \ReflectionClass($exception->getSubject());
$method = $exception->getMethod();

$content = file_get_contents($class->getFileName());
$content = preg_replace(
'/}[ \n]*$/', $this->getMethodContentFor($method) ."\n}\n", $content
);

file_put_contents($class->getFileName(), $content);

$this->io->writeln(sprintf(
"\n<info>Factory Method <value>%s::%s()</value> has been created.</info>",
$class->getName(), $method
), 6);
}

$this->io->writeln();
if (null !== $ioTemp) {
$this->io->writeTemp($ioTemp);
}
}
}

protected function getMethodContentFor($method)
{
$template = file_get_contents(__DIR__.'/../Resources/templates/factorymethod.php');

return rtrim(strtr($template, array('%method%' => $method)));
}
}
15 changes: 15 additions & 0 deletions src/PHPSpec2/Prophet/ObjectProphet.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@

class ObjectProphet implements ArrayAccess, ProphetInterface
{
/**
* @var \PHPSpec2\Subject\LazySubjectInterface
*/
private $subject;

private $matchers;
private $unwrapper;
private $presenter;
Expand Down Expand Up @@ -74,6 +78,17 @@ public function beConstructedWith()
$this->subject->setConstructorArguments($this->unwrapper->unwrapAll(func_get_args()));
}

/**
* Set a Factory to instantiate the object
*
* @param $factory string|Callable Either a static factory method on the class under spec, or a callable to a factory
* method, such as array('Class', 'method')
*/
public function beConstructedThrough($factory)
{
$this->subject->setFactory($factory);
}

public function should($name = null, array $arguments = array())
{
if (null === $name) {
Expand Down
6 changes: 6 additions & 0 deletions src/PHPSpec2/Resources/templates/factorymethod.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

public static function %method%()
{
// TODO: implement
return new static();
}
25 changes: 20 additions & 5 deletions src/PHPSpec2/Subject/LazyObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use PHPSpec2\Exception\Exception;
use PHPSpec2\Exception\ClassNotFoundException;
use PHPSpec2\Exception\FactoryMethodNotFoundException;
use PHPSpec2\Formatter\Presenter\PresenterInterface;

class LazyObject implements LazySubjectInterface
Expand All @@ -14,6 +15,7 @@ class LazyObject implements LazySubjectInterface
private $arguments;
private $presenter;
private $instance;
private $factory = '__construct';

public function __construct($classname = null, array $arguments = array(),
PresenterInterface $presenter)
Expand Down Expand Up @@ -62,12 +64,25 @@ public function getInstance()
), $this->classname);
}

$reflection = new ReflectionClass($this->classname);

if (!empty($this->arguments)) {
return $this->instance = $reflection->newInstanceArgs($this->arguments);
if ($this->factory == '__construct') {
$reflection = new ReflectionClass($this->classname);
$this->instance = $reflection->newInstanceArgs($this->arguments);
} elseif (is_string($this->factory)) {
if (!method_exists($this->classname, $this->factory)) {
throw new FactoryMethodNotFoundException(sprintf(
'Method %s::%s does not exists.', $this->presenter->presentString($this->classname), $this->presenter->presentString($this->factory)
), $this->classname, $this->factory);
}
$this->instance = call_user_func_array(array($this->classname, $this->factory), $this->arguments);
} elseif (is_callable($this->factory)) {
$this->instance = call_user_func_array($this->factory, $this->arguments);
}

return $this->instance = $reflection->newInstance();
return $this->instance;
}

public function setFactory($factory)
{
$this->factory = $factory;
}
}