Category Archives for php

Install Gearman from source on Ubuntu 18.04

I tried to install Gearman on my Ubuntu 18.04 Docker container and encountered a lot of issues.

This write-up is to save you some valuable time of your life.

TL;DR

apt update
apt install -y g++ uuid-dev gperf libboost-all-dev libevent-dev curl 

cd /tmp
curl -LO https://github.com/gearman/gearmand/releases/download/1.1.18/gearmand-1.1.18.tar.gz
tar xvzf gearmand-1.1.18.tar.gz
cd gearmand-1.1.18
./configure --with-boost-libdir=/usr/lib/x86_64-linux-gnu
make
make test
make install

# Start gearman in the background
gearmand --log-file /var/log/gearmand.log --daemon

To get there, I encountered the following issues:

configure: error: Unable to find libevent

./configure --with-boost-libdir=/usr/lib/x86_64-linux-gnu
...
checking test for a working libevent... no
configure: error: Unable to find libevent

Fix: apt install -y libevent-dev

configure: error: Could not find a version of the library!

./configure --with-boost-libdir=/usr/lib/x86_64-linux-gnu
...
checking whether the Boost::Program_Options library is available... yes
configure: error: Could not find a version of the library!

Fix: apt install -y libboost-all-dev

Installing the PHP client libraries for Gearman

If you intend to use PHP to talk to your Gearman service, use the following to get the libraries installed.

Note: you might not need the last line. This is to enable the Gearman PHP extension in Docker.

cd /tmp \
  && wget https://github.com/wcgallego/pecl-gearman/archive/gearman-2.0.6.tar.gz\
  && tar xvzf gearman-2.0.6.tar.gz \
  && mv pecl-gearman-gearman-2.0.6 pecl-gearman \
  && cd pecl-gearman \
  && phpize \
  && ./configure \
  && make -j$(nproc) \
  && make install \
  && cd / \
  && rm /tmp/gearman-2.0.6.tar.gz \
  && rm -r /tmp/pecl-gearman \
  && docker-php-ext-enable gearman

Slim 2 framework logging

This shows you how to enable logging so you can write stuff like $app->log->debug('this will show up in the error_log');.

<?php

--- snip %< ---

$app = new \Slim\Slim(array(
    'log.enabled' => true,
    'log.level'   => \Slim\Log::DEBUG
));

$app->log->debug('this will show up in your error-log');

--- >% /snip ---

 



XDebug for PHPUnit in Docker with PHPStorm

[ update ]
Set the IP-address to the following DNS-name: docker.for.mac.localhost (yes, literally)!
Working with the IP-address doesn’t work anymore
[ /update ]

Want to get XDebug working for your PHPUnit tests which run in Docker? Or for behat? Or any other CLI application? Follow me!

Roughly this is what you’ll need to do: Continue reading

Change mysql_ to mysqli_ functions

In the process of upgrading PHP5.3 code I had to change all deprecated mysql_* functions to their mysqli_* counterparts.

For a lot of functions the signature stayed the same.

But mysqli_query and mysqli_connect have differences. So you can’t just find and replace them.

Instead of doing this manually, I wanted to find and replace recursively while changing the order of the arguments.

In vim:

# change mysql_query(param1, param2) to: 
# mysqli_query(param2, param1)
:%s/mysql_query(\(.\{-}\),\(.\{-}\))/mysqli_query(\2, \1)/g

Using sed:

# on linux

# mysql_query(param1, param2) to 
# mysqli_query(param2, param1)
sed -i 's|mysql_query(\(.*\),\(.*\))|mysqli_query(\2, \1)|g' devices.php

# on mac (otherwise you get the 'invalid command mode' when 
# you run the sed command)

# mysql_query(param1, param2) to: 
# mysqli_query(param2, param1)
sed -i '' -e 's|mysql_query(\([^,]*\),\([^)]*\))|mysqli_query(\2, \1)|g' devices.php

Recursively changing all files:

# in all files under current directory:
# mysql_query(param1, param2) to: 
# mysqli_query(param2, param1)
fgrep -rl mysql_query . | while read file; do
  sed -i '' -e 's|mysql_query(\([^,]*\),\([^)]*\))|mysqli_query(\2, \1)|g' $file
done

Note that sed cannot do non greedy matching.

That’s why we’re searching for anything but the separator until the separator like this:

# non greedy matching with sed
\([^,]*\),

It basically states: get everything except for the comma until you get a comma (which is the first one to appear).

Disable xdebug for one run

This script disables xdebug for one run. No more error-messages like:

$ composer update
You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug

and:

$ php-cs-fixer fix --dry-run .
You are running PHP CS Fixer with xdebug enabled. This has a major impact on runtime performance.
If you need help while solving warnings, ask at https://gitter.im/PHP-CS-Fixer, we will help you!

This is what you’ll get

We’ll create a script which will:

  • disable xdebug
  • run your command
  • enable xdebug

the script we’ll name php-no-xdebug (or whatever you like)

With Xdebug (note the last line)

$ php --version
PHP 7.1.10 (cli) (built: Oct  6 2017 01:08:19) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    with Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans

Without Xdebug (note the missing last line)

$ php-no-xdebug --version
PHP 7.1.10 (cli) (built: Oct  6 2017 01:08:19) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

The script php-no-xdebug

Create the script /usr/local/bin/php-no-xdebug with the following contents.

# file /usr/local/bin/php-no-xdebug
#!/bin/bash

php=$(which php)

# get the xdebug config
xdebugConfig=$(php -i | grep xdebug | while read line; do echo $line; exit; done)

# no xdebug? Nothing to do!
if [ "$xdebugConfig" == "" ]; then
    $php "$@"
    exit
fi

# get the configfile (which should be the first value)
# so strip off everything after the first space of the xdebug-config
xdebugConfigFile=$(php -i | grep xdebug | while read line; do echo $line; exit; done)

# test whether we got it right
if [ ! -f "$xdebugConfigFile" ]; then
    echo "No XDebug configfile found!"
    exit 1
fi

# disable xdebug by renaming the relevant .ini file
mv ${xdebugConfigFile}{,.temporarily-disabled}

# dissect the argument to extract the first one (which should be a script or an application in $PATH) from the rest
index=0
for arg in $(echo $@ | tr ' ' "\n")
do
    if [ "$index" == "0" ]; then
        firstArg=$arg
    else
      restArg="$restArg $arg"
    fi

   ((index++))
done

# check whether the command to be executed is a local PHP file or something in the $PATH like composer or php-cs-fixer
fullPath="$(which $firstArg)"
if [ "$fullPath" == "" ]; then
    # check whether it's a local file
    if [ ! -f  $firstArg ]; then
        echo "Could not find $firstArg. No such file or directory"
        exit 1
    else
        # just run the commands
        $php $@
    fi
else
    # run the command with the fullpath followed by the rest of the arguments provided
    $php $fullPath $restArg
fi

# execute the command
$php "$@"

# re-enable xdebug
mv ${xdebugConfigFile}{.temporarily-disabled,}

# test whether the conf file is restored correctly
if [ ! -f "$xdebugConfigFile" ]; then
    echo "Something went wrong with restoring the configfile for xdebug!"
    exit 1
fi

and make it executable

$ chmod +x /usr/local/bin/php-no-xdebug

That’s it! Run it like this:

$ php-no-xdebug composer update

Switch between multiple PHP versions on your mac

This article is a slimmed-down, firing-from-the-hips, get right to the action version based on the ones listed below. If you miss some background info or want a more spelled out version, please do visit these articles:

Install multiple PHP versions with fpm

I’d also install the xdebug extension.

versions="php56 php70 php71 php72"
for version in $versions; do
    brew install $version --with-fpm
    brew install $version-xdebug
    brew unlink $version
done

If you receive the error `configure: error: Cannot find libz` you need to install required libraries via XCode:

xcode-select --install
brew upgrade

Switch PHP-version

To switch the active version of PHP use the command sphp (script for this command is further down below):

sphp 71

PHP version 71 found
Unlinking old binaries...
Linking new binaries...
Linking /usr/local/Cellar/php71/7.1.10_21... 17 symlinks created
Linking new modphp addon...
Password:
/usr/local/lib/libphp7.so
Fixing LoadModule...
Updating version file...
Done.

PHP 7.1.10 (cli) (built: Oct  6 2017 01:08:19) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    with Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans

Without arguments, this command returns useful information like which versions are installed and which is the active one right now:

$ sphp
Usage: sphp [phpversion]
Versions installed:
 - phpversion: 56
 - phpversion: 70
 - phpversion: 71
 - phpversion: 72

Currently active version: 56

Create script for easy switching

In order for this to work, create the following script: /usr/local/bin/sphp

#!/bin/bash

# Check if command was ran as root.
if [[ $(id -u) -eq 0 ]]; then
    echo "The command \"sphp\" should not be executed as root or via sudo directly."
    echo "When a service requires root access, you will be prompted for a password as needed."
    exit 1
fi

# Usage
if [ $# -ne 1 ]; then
    echo "Usage: sphp [phpversion]"
    echo "Versions installed:"
    brew list | grep '^php[0-9]\{2,\}$' | grep -o -E '[0-9]+' | while read -r line ; do
        echo " - phpversion: $line"
    done
    exit 1
fi

currentversion="`php -r \"error_reporting(0); echo str_replace('.', '', substr(phpversion(), 0, 3));\"`"
newversion="$1"

majorOld=${currentversion:0:1}
majorNew=${newversion:0:1}
minorNew=${newversion:1:1}

brew list php$newversion 2> /dev/null > /dev/null

if [ $? -eq 0 ]; then
    echo "PHP version $newversion found"

    # Check if new version is already the current version.
    # if [ "${newversion}" == "${currentversion}" ]; then
    #     echo -n "PHP version ${newversion} is already being used. Continue by reloading? (y/n) "
    #     while true; do
    #         read -n 1 yn
    #         case $yn in
    #             [Yy]* ) echo && break;;
    #             [Nn]* ) echo && exit 1;;
    #         esac
    #     done
    # fi

    echo "Unlinking old binaries..."
    brew unlink php$currentversion 2> /dev/null > /dev/null

    echo "Linking new binaries..."
    brew link php$newversion --force

    echo "Linking new modphp addon..."
    sudo ln -sf `brew list php$newversion | grep libphp` /usr/local/lib/libphp${majorNew}.so
    echo /usr/local/lib/libphp${majorNew}.so
    echo "Fixing LoadModule..."
    apacheConf=`httpd -V | grep -i server_config_file | cut -d '"' -f 2`
    sudo sed -i -e "/LoadModule php${majorOld}_module/s/^#*/#/" $apacheConf

    if grep "LoadModule php${majorNew}_module .*php${newversion}" $apacheConf > /dev/null
    then
        sudo sed -i -e "/LoadModule php${majorNew}_module .*php${newversion}/s/^#//" $apacheConf
    else
        sudo sed -i -e "/LoadModule php${majorNew}_module/s/^#//" $apacheConf
    fi

    echo "Updating version file..."

    pgrep -f /usr/sbin/httpd 2> /dev/null > /dev/null
    if [ $? -eq 0 ]; then
        echo "Restarting system Apache..."
        sudo pkill -9 -f /usr/sbin/httpd
        sudo /usr/sbin/apachectl -k restart > /dev/null 2>&1
    fi

    pgrep -f /usr/local/"Cellar|opt"/*/httpd 2> /dev/null > /dev/null
    if [ $? -eq 0 ]; then
        echo "Restarting homebrew Apache..."
        sudo pkill -9 -f /usr/local/"Cellar|opt"/*/httpd
        sudo /usr/local/bin/apachectl -k restart > /dev/null 2>&1
    fi

    # pgrep -x httpd 2> /dev/null > /dev/null
    # if [ $? -eq 0 ]; then
    #     echo "Restarting non-root homebrew Apache..."
    #     httpd -k restart > /dev/null 2>&1
    # fi

    echo "Done."

    # Show PHP CLI version for verification.
    echo && php -v
else
    echo "PHP version $majorNew.$minorNew was not found."
    echo "Try \`brew install php${newversion}\` first."
    exit 1
fi

 

Use events in symfony

The other day I had to add some logic right after an user was saved to the database. I ended up using events to get this done without cluttering the entity.

I first added the logic in the User-entity but I then realised this logic was not really related to the user entity itself. Or the application, for that matters.

In order to seperate concerns, I decided to create a hook after the User save-action. That would allow me to add logic at that particular time without cluttering the User entity with nonrelevant code.

This has a downside though. When you want to debug what the heck happens after the User is saved to the database, you won’t find it in the User entity. This might send you down a long code-hunt. But you will see the dispatching of the event though. So if you’re new to this, remind yourself that there can be a whole different world behind the dispatching of an event.

Setting it up consists of 3 steps:

  1. create an Event class (the one that will be dispatched)
  2. dispatch the event at the right time and place (after the User is saved to the database)
  3. create (and subscribe) the subscriber which will take action upon the dispatched event

symfony events

Create Event

The event is nothing more than a class.

The event is the object which is passed around. Therefore you want to populate the event with all the information the subscriber(s) need.

For that purpose I create a setter and a getter. The code which will dispatch the event will use the setter, the event subscriber will use the getter.

# file src/AppBundle/Event/UserCreatedEvent.php
<?php
namespace AppBundle\Event;

use AppBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;

class UserCreatedEvent extends Event
{
    private $user;

    public function setUser(User $user)
    {
        $this->user = $user;
    }

    public function getUser()
    {
        return $this->user;
    }
}

Dispatch Event

Now we decide in what moment of time we’ll dispatch (fire) the event. In our example this will be right after the user is saved to the database.

# file src/AppBundle/Entity/User.php
/* other code */

public function createUser(User $user)
{

    /* more code */

    // save the user to the database
    $this->em->persist($user);
    $this->em->flush();

    // dispatch an event where others can work with the newly created user
    $eventDispatcher = $this->container->get('event_dispatcher');
    $event = new UserCreatedEvent();
    $event->setUser($user);
    $eventDispatcher->dispatch('user.event.created', $event);

    return $user;
}

Act on event with the subscriber

Create subscriber

The subscriber is the class with the method which gets called once the event gets dispatched.

# file src/AppBundle/EventSubscriber/UserCreatedSubscriber.php
<?php
namespace AppBundle\EventSubscriber;

class UserCreatedSubscriber
{
    public function newUserCreated(UserCreatedEvent $event)
    {
        var_dump($event->getUser());
    }
}

Subscribe the subscriber

Now that we have the code for the subscriber, we need to actually subscribe the subcriber to the event. This is the glue between dispatching an event and acting upon it.

You do this in services.yml as you register it as a service.

# create a listener for the UserCreatedEvent
valuation.event.created:
  class: AppBundle\EventSubscriber\UserCreatedSubscriber
  tags:
    - { name: kernel.event_listener, event: valuation.event.created, method: newUserCreated }

That’s it!

Sources

If you want to read more:

  • Symfony documentation:
    https://symfony.com/doc/current/event_dispatcher.html
  • Nice dense setup: https://stackoverflow.com/a/34162603

Symfony JsTranslationBundle shows javascript translations upon login

In order to benefit from the Symfony3 translations in javascript files, I use BazingaJsTranslationBundle from

I had the weirdest thing: whenever I logged out, cleared my cache, went to the login page and logged in, I got redirected to /translations which showed me the generated JSON file with the translations.

Cause: the login page tried to load the JSON translation because of my <script src="{{ url('bazinga_jstranslation_js', {}) }}?locales=en,nl"></script> script import. But that failed as security did not allow anonymous access to that URI.

Symfony registered the failed URL and, as I’m on the login page, redirected me to the url that first failed once I was logged in.

Solution: allow anonymous access to URI /translations.

In file app/config/security.yml I added the following:

access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/translations, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Behat 3 + Mink + Selenium

Installation

We will be installing the following:

  • Behat version 3 – the testingframework
  • Mink – for controlling real webbrowsers to run your tests
  • PHPUnit – for using the handy ‘assert’ methods PHPUnit provides.
  • Selenium Standalone Server – this will act as a service to accept connections and map them to browsers.

Continue reading

>