7 Continuous Integration Tools for PHP Laravel Developers

Image for post
Image for post

In this article we’ll learn about 7 tools that you can use to set up a rock-solid continuous integration (CI) process for your PHP project. Together, these tools increase code quality, reduce development time, easily reveal errors and will generally make your life easier.

We will learn how we can setup a Semaphore CI continuous integration pipeline for a PHP Laravel application.

The game plan is to setup various tests for our code, without having to provision or maintain any servers. Having a quick feedback cycle, we’ll be able to catch errors early and fix them before they grow.

Sounds good? Let’s get started.

Code analysis tests

Code analysis consists of scanning the source for certain structures that may point to deeper problems, such as design flaws and bad coding practices, usually called code smells.

Some code analysis tools focus on finding out bad patterns: functions with too many parameters, fat classes or too deeply nested structures. While others check for style: indentation rules, name conventions, etc.

Every analysis must start with some standard to follow. These rules are, at the end of the day, subjective but informed by previous experience. The rules can be generally configured and customized.

PHP Mess Detector

PHP Mess Detector (phpmd) checks for code smells: awkward, overcomplicated or unused code. It is inspired by the PMD project.

phpmd ships with several rulesets than can be enabled or disabled independently.

Basic usage:

Built-in rules are:

  • cleancode: enforce clean code base rules.
  • codesize: complexity rules, excessively long classes, etc.
  • controversial: camelcase rules, globals, etc.
  • design: forbid eval, goto, exit. Also coupling and depth rules.
  • naming: long and short identifier names, method name rules.
  • unusedcode: dead code and unused variables rules.

What does it look like?

If you’ve never done any code analysis on your project before, it is likely to make you want to pull your hairs out. Don’t worry and be patient, after we have gotten our code in order our lives will be easier.

Instead of setting the rules by command line, we can create an xml file that can be checked in source control:

PHP Code Sniffer

PHP Code sniffer (phpcs) is a style checker. If you’ve ever used a linter (jshint, pylint, checkstyle, etc) you already know what it does. phpcs can check for indentation, missing comments, naming conventions, etc.

PHP Code sniffer ships with various popular PHP styles such as PEAR, PSR2 and Zend among others. We can also make our own rules or mix and match checks from existing ones.

The typical invocation goes:

PHP Code Sniffer also includes phpcbf, a program than can automatically fix some problems.

PHP Copy Paste Detector

PHP Copy Paste Detector (phpcpd) does what it says on the tin: finds duplicate code inside your project.

Having duplicate code usually signals the need for refactoring, the repeated parts should find a new home in a shared library or component. Duplicates also force developers to make shotgun surgery: a single change must be repeated multiple times.

Basic usage:

We can tell phpcpd how many lines must be repeated to be considered an error:

Unit testing ensures that our implementation does what it has been designed to do. Units are the smallest testable pieces of code, e.g. a class method, a function, an API call.

Unit tests also act as a form of living documentation, by reading what they do we can infer how the tested parts should work, what inputs do they take and what outputs should them provide. They also validate that code still valid after refactoring.

As new code is being written, we should also be creating tests to validate its behavior.

We’ll be using phpunit, the most popular testing framework for PHP, to drive our test cases. Fortunately Semaphore has a great resource to get you started:

After our tests are in place, we call phpunit to get an error report:

Browser tests: Laravel Dusk

PHPUnit’s biggest problem is its inability to test javascript on the frontend. Dusk is a browser automation tool that overcomes this limitation by testing the application on an actual browser.

Dusk interfaces with a real Chrome browser to programatically browse sites, perform actions, select elements and do assertions.

In order to test with Dusk, we need to start our application with Laravel’s artisan tool:

Security tests: Sensiolabs

With SensioLabs security checker, we can scan our project dependencies for known vulnerabilities. It scans our composer file for dependencies and runs them down through a vulnerabilities database:

Running Continuous Integration with Semaphore

Continuous Integration (CI) allows to test early and test often.

We can set up a CI pipeline to build the application on every push. The pipeline can drive the tests and optionally deploy the application.

Semaphore is a cloud hosted continuous integration and delivery service. It’s easy to use, really fast and there is no need to install any software, manage any servers or maintain any systems. Semaphore fully supports Linux and macOS applications. The best thing is we can setup the whole process from a single config file.

Getting started with Semaphore is a breeze: first create an account on semaphoreci.com We can login with our GitHub account and Semaphore will have access to the repositories. If you don’t have any repositories you may fork Semaphore’s PHP Laravel Demo.

To create a project click on Projects -> New…. Semaphore will show a list of our GitHub repos. Click on the “Add Repository” button to get started.

Alternatively we create our project with the command line tool. To install it, click on the little cursor icon on the upper right side. Open the Install sem CLI & connect section and copy/paste the commands on your machine:

Image for post
Image for post

Once connected, cd into the local copy of your project and:

If we haven’t used Semaphore before, a sample config will be automatically created on .semaphore/semaphore.yml to get you started. After making a push we should see the pipeline running in our dashboard.

Image for post
Image for post

The Semaphore pipeline

The semaphore file is found at .semaphore/semapore.yml. This is the configuration we'll be using:

Let us walk through a pipeline that includes all the tools we have discussed so far.

Naming the pipeline

At the beginning we have the Semaphore version (v1.0) and the name for our pipeline.

Selecting a server and OS

Next we define the agent. The agent is the environment in which our code will run, which includes virtual machine and operating system. The machine type sets the virtual machine type to be provisioned and os_image its operating system. Semaphore automatically provisions machines on demand.

Here we’re using e1-standard-2 machine (2 vCPUs, 4GB, 25GB disk) paired with an Ubuntu 18.04 LTS image.

Blocks, tasks and jobs

Now we have arrived at the heart of the pipeline: blocks, tasks and jobs.

A pipeline is made of blocks. Blocks can have a name and must contain a task. A task contain jobs, and jobs are just a list of commands to execute.

Blocks are started sequentially, one after the other. Within a block, jobs are executed in parallel. Each block only starts after all the jobs on the previous blocks have finished.

Install dependencies

First things first, we need to install all our dependencies or we won’t get anywhere.

Fortunately Semaphore’s Ubuntu image includes php, composer and npm to handle packages.

Let’s see how the first block looks:

Lots of things are happening here:

  • The env variable APP_ENV is set to "prod", this is applied to all jobs on the task.
  • The code is cloned from our GitHub repo with checkout.
  • composer install and npm install handles the PHP and Javascript dependencies installations.
  • cache is being used to persist files between jobs.

We need to use cache to store and retrieve files between job executions.

To store files we use:

The files or directories are associated to a KEY or comma-separated list of KEYS

To retrieve them:

In our example pipeline, we’re storing the our dependencies under many key names. This helps use find them later.

Code analysis

The second block runs all our code analysis.

Since the tools don’t actually execute our application, we can run all of them in parallel and save us some precious time.

We’re taking advantage of the prologue feature. Commands in the prologue and epilogue sections are executed before and after each job, respectively.

We then define a job for each tool: phpmd, phpcs and phpcpd. The first two were installed by composer on the first block, whereas phpcd is downloaded from the website directly.

Unit tests

The fourth block executes the unit tests:

Nothing new here. Do you see the pattern? checkout to get the code and cache restore to get the dependencies. Then execute the tests.

Browser tests

We’ll continue our round of tests with Laravel dusk:

This job is a bit longer because we need to set up a few things beforehand.

Our application uses a database, Semaphore supports many database services out of the box, so we could choose to use one of them. However, to keep things simple, we can get away with an sqlite db, so lets do that.

We use php artisan serve to start application and the browser testing is done with php artisan dusk

Did you notice that we didn’t install any browsers? That’s because Semaphore’s OS images already include several browsers..

Security tests

And for the final round of tests we’ll do a quick security checkup using sensiolabs:

You know the drill by now, checkout then cache restore. Then we clone the security checker code, install additional dependencies and run the security test.

Let the code flow

To get the pipeline running, make a push to the repository. Semaphore will pick it up and automatically start driving the pipeline.

Image for post
Image for post

We can click on any individual job to read its log.

If any job fails to run, we can easily hop into its session to snoop around. Click on the debug button on the upper right side of the log.

Image for post
Image for post

Semaphore gives us a command to ssh into the job session:

Wrap up

With great continuous integration tools for PHP working well together, we can focus on our code with a peace of mind that code quality is ensured.

With a few clicks and lines of code we’ve come a long way. And we’re just scratching the surface on what Semaphore can do.

Originally published at https://semaphoreci.com.

Written by

Supporting developers with insights and tutorials on delivering good software. · https://semaphoreci.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store