Welcome to Abdul Malik Ikhsan's Blog

Testing Zend Expressive 2 with kahlan 3

Posted in testing, Tutorial PHP, Zend Framework by samsonasik on March 15, 2017

Zend\Expressive ^2.0 has different default approach for piping and routing middleware which is programmatically way. In this post, I am going to show you how you can test Zend\Expressive ^2.0 application, with assumption, you use its skeleton with kahlan 3.

First, of course, install the Expressive ^2.0 skeleton, for example, install into directory named “expressive2”:

$ composer create-project zendframework/zend-expressive-skeleton:^2.0 expressive2
Installing zendframework/zend-expressive-skeleton (2.0.0)
  - Installing zendframework/zend-expressive-skeleton (2.0.0) Downloading: 100%
Created project in expressive2
> ExpressiveInstaller\OptionalPackages::install
Setting up optional packages
Setup data and cache dir
Removing installer development dependencies

  What type of installation would you like?
  [1] Minimal (no default middleware, templates, or assets; configuration only)
  [2] Flat (flat source code structure; default selection)
  [3] Modular (modular source code structure; recommended)
  Make your selection (2): 3

Now, install kahlan:

$ cd expressive2
$ composer require kahlan/kahlan:^3.1

We are going to need the $app variable inside tests, for example, when testing functionality for each routed middlewares. To simplify and avoid repetitive code, we can register it into kahlan-config.php in root application:

// ./kahlan-config.php
use Kahlan\Filter\Filter;
use Zend\Expressive\Application;

Filter::register('initialize app', function($chain) {

    $root = $this->suite();

    ob_start();

    $root->beforeAll(function ($var) {

        ob_start();

        $var->app = $app
                  = (require 'config/container.php')->get(Application::class);

        require 'config/pipeline.php';
        require 'config/routes.php';

    });

    return $chain->next();

});
Filter::apply($this, 'run', 'initialize app');

By assign $app into “$var->app” like above, the “$app” is accessible from entire tests via “$this->app”, so, we can write test like the following:

// ./src/App/spec/Action/HomePageActionSpec.php
namespace AppSpec\Action;

use Zend\Diactoros\ServerRequest;

describe('HomePageAction', function () {

    describe('/', function () {

        it('contains welcome message', function () {

            $serverRequest = new ServerRequest([], [], '/', 'GET');
            $this->app->run($serverRequest);
            $actual = ob_get_clean();

            expect($actual)->toContain('Welcome to <span class="zf-green">zend-expressive</span>');

        });

    });

});

Now, let’s run the tests:

$ vendor/bin/kahlan --spec=src/App/spec/
            _     _
  /\ /\__ _| |__ | | __ _ _ __
 / //_/ _` | '_ \| |/ _` | '_ \
/ __ \ (_| | | | | | (_| | | | |
\/  \/\__,_|_| |_|_|\__,_|_| | |

The PHP Test Framework for Freedom, Truth and Justice.

Working Directory: /Users/samsonasik/www/expressive2

.                                                                   1 / 1 (100%)



Expectations   : 1 Executed
Specifications : 0 Pending, 0 Excluded, 0 Skipped

Passed 1 of 1 PASS in 0.375 seconds (using 8Mo)

That’s it 😉

Querying PostgreSQL’s JSONB with Zend\Db

Posted in Tutorial PHP by samsonasik on March 13, 2017

PostgreSQL is one of Databases that has json support. If you have table(s) that has json column(s), we can query it with Zend\Db in your php application layer.

For example, we have the following data:

CREATE TABLE album (id serial primary key, data jsonb);

INSERT INTO album VALUES
   (1, '{ "title": "Hello", "singer": "Adelle" }'),
   (2, '{ "title": "September", "singer": "Justin Timberlake" }')
;

We then want to produce SQL like :

select * from album where data ->> 'title' = 'Hello'

There is Zend\Db\Sql\Predicate\Expression for that. So, you can build select with:

use Zend\Db\Sql\Select;
use Zend\Db\Sql\Predicate\Expression;

$select = new Select();
$select->from('album')
       ->where([new Expression("data ->> 'title' = ?", 'Hello')]);

That’s easy! Let’s make it more complicated. We then want to produce SQL with subset of jsonb like:

select * from album where data @> '{"singer": "Adelle"}'

In this case, as it is not a common sql operation across DBs, you need to pass the filter as $expression, the first parameter of Zend\Db\Sql\Predicate\Expression::__construct:

use Zend\Db\Sql\Select;
use Zend\Db\Sql\Predicate\Expression;

$expression = <<<expr
data @> '{"singer": "Adelle"}'
expr;

$select = new Select();
$select->from('album')
       ->where([new Expression($expression)]);

That’s it 😉