-
Notifications
You must be signed in to change notification settings - Fork 5
Examples
Imagine you already experienced the great benefits of tested source code and you want to advance further to test drive the development of your Drupal modules or you want to get a piece of the cake of confidentiality a verified code repository gives you ;) To achieve this and you don't know yet you might want to read the article about how Liip-Teams develop Drupal-Modules.
So the main idea of the class structure behind the LiipDrupalConnectorModule is to provide you with some kind of an adapter enabling you to get rid of global function calls in your OO-style source code and going forward being able to recognize well known principles of OOP (e.g. SOLID).
The following example shows how the one the adapters (the Node adapter) helps you to eliminate global function calls and further enables you to unit test your sources.
<?php
namespace Liip\Drupal\Examples;
use Liip\Drupal\Modules\DrupalConnector\Node;
class NodeManager
{
protected $nodeConnector;
public function __construct(Node $nodeConnector)
{
$this->nodeConnector = $nodeConnector;
}
public function capitalizeTitle($nid)
{
$node = $this->nodeConnector->node_load($nid);
$node->title = ucfirst($node->title);
$this->nodeConnector->node_save($node);
}
}Basically what happens in the example above is a request to receive information about a node from a storage engine, uppercase the first character of it's title, and persist it again.
If you are familiar with the Drupal functions to manipulate a Drupal node and since the connector expresses the same api as Drupal itself. Since we injected the Node connector, it is now possible to mock it completely as in the following example.
Note that mixing the approaches (i.e. using the connectors and accessing the Drupal API directly) will spoil all the advantages you gain from the LiipDrupalConnectorModule.
<?php
class NodeManagerTest extends \PHPUnit_Framework_TestCase
{
public function testCapitalizeTitle()
{
$nodeConnectorMock = $this->getMockBuilder('\\Liip\\Drupal\\Modules\\DrupalConnector\\Node')
->setMethods(array('node_load', 'node_save'))
->getMock();
$nodeConnectorMock
->expects($this->once())
->method('node_load')
->will(
$this->returnValue($this->getNodeFixture(array('title' => 'node title')))
);
$nodeConnectorMock
->expects($this->once())
->method('node_save')
->with(
$this->equalTo($this->getNodeFixture(array('title' => 'Node title')))
);
$manager = new NodeManager($nodeConnectorMock);
$manager->capitalizeTitle(42);
}
}