PHP

PHP – Doctrine – DQL – Select Subquery

0

Whilst working on a recent project I needed the ability to do a subquery look-up as part of a select statement. Basically I needed to count the number of rows, without having to do a group by on the entire result set. After a few minutes of research I noticed there was no real definitive source on how to do do a subquery as a select using DQL, although there were some references to using a subquery within a where clause.

Below is a code snippet which worked for me:

$q = Doctrine_Query::create()
    ->select('t1.*')
    ->addSelect('t2.*');

// You can put this anywhere within the select clauses, but must be done before  you make call to from()        
$subQ = $q->createSubquery()
    ->select('COUNT(*)')
    ->from('Table3 t3')
    ->innerJoin('t3.Table4 t4')
    ->innerJoin('t4.Table5 t5')            
    ->where('t4.status_id = :statusId')
    ->andWhere('t5.id = t2.code_id');
        
$q->addSelect(sprintf('(%s) AS my_count', $subQ->getDql()))
    ->from('Table1 t1')
    ->innerJoin('t1.Table2 t2')
    ->where('t2.user_id = :userId', array('statusId' => $statusId, 'userId' => $userId);

// And you should now be able to access the count value using:
$result = $q->execute();

var_dump($result->my_count);

Note, the table names are abstract for obvious reasons, but the snippet should demonstrate the ability to add a select subquery to a dql statement.

phpLogo

PHP – ZipArchive – 5.3.x – Weird Issue when Unlinking a File Just Added to Archive

0

At work, I was tasked with porting some cronjobs from an old server (php 5.2.x) to a new server (php 5.3.x) and ran into a weird issue. The code to be ported was explicitly unlinking a file which was just added to the ZipArchive, in efforts to keep the filesystem clean, and ran fine on php 5.2.x, but when I ported the same code over to php 5.3.x I couldn’t get the zip file to write in it’s entirety.

Below is the code snippet:

$zip = new ZipArchive;

$zip->open('/path/to/file.zip', ZipArchive::OVERWRITE);

foreach ($files as $file) {

    $zip->addFile((string $file));

    // This is the offending line
    unlink((string) $file);
}

After I commented out the unlink, everything worked as expected. Thought I would bring it up in case anyone else faces the same situation.

phpunit_logov2

PHPUnit – You must not expect the generic exception class

4

While working on updating my unit tests from PHPUnit v3.2 to v3.6, I came across the error message; “You must not expect the generic exception class”, upon first glance it sort of made sense, but after some thought and investigation, it really doesn’t make much sense. My preference is to throw exceptions, and codes, versus throwing specific exceptions, and the code which threw the error was doing just that, throwing a generic exception with an exception code. I spoke with the PHPUnit developer via github, and he stated that a fix is in 3.7 but will not added in 3.6 (current stable). Well I can’t wait for 3.7 to be released so I came up with the following solution:


/**
 * @expectedException Test_Exception
 */
 public function testDivByZero()
 {
     try {
         // Fyi you don't need to do an assert test here, as we are only testing the exception, so just make the call
         $result = $this->object->div(1,0);
     } catch (Exception $e) {
         if ('Exception' === get_class($e)) {
             throw new Test_Exception($e->getMessage(), $e->getCode());
         }
     }
 }

// Test_Exception.php
class Test_Exception extends Exception
{
    public function __construct($message = null, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}

Basically all I did was create my own exception class, then when testing if an api call throws an exception, I would check the class of the exception, and if it was a ‘generic’ (Exception) class, then I would wrap it within the custom, expected Test_Exception.

phpLogo

PHP – Correctly Cast Numeric Strings to Numeric Datatypes

0

Recently I posted an article on how to compare two doctrine objects @ http://melikedev.com/2012/06/13/doctrine-php-compare-two-doctrine_record-objects/ which works well in most cases, but ran into an issue yesterday where floats as strings were being set to 0 due to the (int) cast. This was a problem because on the http://melikedrinks.com website, I store ingredient portions in a float (decimal) format, which means that my object comparisons were not being evaluated correctly if I changed the ingredient portions from .5 to .66 as they would both be cast to int with a value of 0.

So I was working on a possible solution and came across a great little hack in the comments section of the docs for the is_numeric function @ http://us2.php.net/is_numeric, in the comments, a user (dave.marr@gmail.com), pointed out that you can add ‘+0′ to a string which evaluated to true using the is_numeric function and it will correctly cast the value of the string to the proper datatype, which worked well in converting string floats to float floats. So the revised code would look like:

$objectArray1 = array_map(function($value) { return (is_numeric($value)) ? ($value + 0): $value; }, $object1->toArray(false));
phpLogo

PHP – Reflection Class – Determine Parent Method Signature

0

As I was writing unit tests against a new caching wrapper which extends the Memcached API, I ran across an issue when overriding the Memcached::get() method. According to PHP docs regarding the Memcached::get() method, there are three arguments which which must be added to my extended signature, which I added, but kept getting “… should be compatible with that of Memcached::get()” errors. I tried looking for the method signature via source code but didn’t glean anything useful from the PECL documentation, so I turned to PHP’s RelectionClass to see if I could figure out what I was missing from my extending class signature which was causing the aforementioned errors. After a few minutes I ended up with the following code snippet:


$this->cache = Cache::factory(Cache::TYPE_VOLATILE);

$reflector = new ReflectionClass(get_class($this->cache));

foreach ($reflector->getMethod('get')->getParameters() as $param) {
    var_dump((string) $param);
}

Which outputted the following:


string(32) "Parameter #0 [ <required> $key ]"
string(37) "Parameter #1 [ <optional> $cache_cb ]"
string(39) "Parameter #2 [ <optional> &$cas_token ]"

After a few seconds investigating the output, I noticed that I wasn’t passing the third argument ($cas_token) by reference, but before I fixed my version I double checked the PHP docs regarding Memcached::get() and in fact noticed they indicated that $cas_token was indeed being passed by reference (as indicated by the ampersand &). After I altered my extended method to pass the third argument by reference, everything worked as expected. So if you ever need to introspect an API with little to no relevant documentation, try using PHP’s ReflectorClass to get the information you are after.

phpLogo

PHP – Manual Compilation – ld returned 1 exit status

0

If you are compiling PHP manually and compilation prematurely halts due to a “ld returned 1 exit status” try issuing the following command from within the build directory, I was running into the same issue and the command worked for me.

$ -> gmake distclean
phpLogo

PHP – Magento – Zend – Missing Hash Function

0

When it comes to manually configuring compiled applications on my systems, I am a minimalist, meaning that I always try to get away with the bare bones settings. Once in a great while this will come back to haunt me. In starting up a new project, I came across an issue where the Magento install process was throwing a fatal error regarding a ‘hash’ function (Zend Framework actually needed it). So I had to recompile with `–enable-hash` setting. Be sure to run a make clean before configure, otherwise your new setting won’t be picked up.

phpunit_logov2

PHPUnit – How to Run PHPUnit Against a Specific Test

7

The other day I was debugging an error in one of my unit tests, and found it hard to track down because when I ran PHPUnit, it ran all the tests contained in the file where my problem unit test was located. After some Googling and reading the PHPUnit Api Docs, I found that you can specify a test, among other tests, by adding a comment with the @group annotation. Using @group and any group name you wish, you can tell PHPUnit, from the command line, to test only tests belonging to a specific group.

Consider the following:

public function testArrayCount()
{
    $this->assertCount(2, array('foo', 'bar');
}

/**
 * @group grain
 */
public function testArrayPopulated()
{
    $this->assertTrue(empty(array()));
}

Notice how I specified the testArrayPopulated() method with a @group grain annotation, now I can tell PHPUnit to only test tests belonging to the grain group.

./phpunit --colors --group grain path/to/your/tests/

Now, when PHPUnit runs, it will only run tests against those tests to which you have assigned the grain group. This @group annotation is a really cool feature of PHPUnit and helped me a lot with debugging my unit tests.

–UPDATE–

Per Edo’s comments: You can also filter tests by adding ‘–filter testYourTestName’ (two hypens). This will make it so only that test or any test matching the string will be run, same benefits as group, but easier to implement. It does require you to put some thought into how you name the methods within your test.

Per Patrick’s comment: I corrected the order for the command line arguments. The options should ALWAYS go before the path to your tests.

Thanks for the feedback.

phpLogo

PHP – mysql_real_escape_string vs PDO::prepare()

0

I was recently made aware of some subtle differences between mysql_real_escape_string and PDO::prepare and thought I would pass on a great article stating why PDO::prepare() is preferred over m_r_e_s. If you are starting a new project or working on an existing project, and you are not using an ORM, I’d suggest using PDO for native SQL constructs vs the mysql_* family of commands, not only for the reasons stated in the linked article, but also for ease of use, and portability.

phpunit_logov2

PHP – PHPUnit – Use PHPUnit Without PEAR

7

Abstract

PHPUnit is a great tool to protect us developers from introducing new defects when adding new features or re-factoring code. However there is one HUGE downside to PHPUnit; it must be installed using PEAR. Personally, I don’t like ‘auto-installers’, I’d prefer to know what exactly is happening behind the scenes with regards to which libraries are required and how they are being called. So when I needed to use PHPUnit on a recent project I shed a tear thinking I would have to break down and install using PEAR.

PHPUnit is not a mythical creature, it doesn’t have magical powers, and as such, it should not intimidate us. It is PHP code, plain and simple, and like any other PHP API Libraries it can be interwoven into our application. So after breaking down the PHPUnit source code, I realized it could be installed without going through PEAR, and without too much headache.

I wrote this article with the goal that it may help others, and maybe even make it’s way to the lead developer of PHPUnit, where he may start using a better autoloading strategy. However, I must warn you to not hold me responsible for any “issues” that may arise on your system by following this article, as it’s strictly demonstrative at this point. There may come a time where I add this code to a GIT repo and officially support it, but not at this point. If you are ok with that, then read on.

Also, note that you can change any of the following guidelines to suit your specific needs. What I am outlining here worked for me, but may not work for you, so feel free to change what you need to, in order to accomplish your end game.

Base Directories

To make things work, we need a base directories from which to work. As with any setting throughout this article, you can change to meet your needs.

Test directory

This directory will be where we put our actual unit tests:

/home/mpurcell/projects/core/test

Vendor directory

This directory will be the location where we download and extract PHPUnit source code:

/home/mpurcell/projects/vendor

Source Code:

Now that we have our directories in place, lets get PHPUnit source code. Normally you would use PEAR to download, extract, and prepare the source code, but personally I don’t like things of this nature being done for me, I am a big boy, I can handle it myself. So I download each of the core packages manually, then extract them, and set their correct directories in preparation for the next ‘Symlinks‘ step.

The PHPUnit developer uses Github as their version control repo, which is good, but sucks when trying to download packages, as the actual files are abstracted by an intermediary PHP script. What I ended up having to do was download to my local machine, then secure copy them over to the server. Once you have the source files on the server, run the following steps:


$ -> cd ~/projects/vendor

$ -> mkdir phpunit

$ -> cd phpunit

$ -> cp ~/sebastianbergmann-phpunit-3.6.7-9-gf5e159b.zip .

$ -> unzip sebastianbergmann-phpunit-3.6.7-9-gf5e159b.zip

# The unzip will result in a weird hash, so I just rename it to
# the correct version based on the original file name
$ -> mv sebastianbergmann-phpunit-f5e159b/ 3.6.7-9

# Don't need source file anymore
$ -> rm *.zip

# Now, we have phpunit locked into a version which we can quickly
# glean when we inspect symlinks to this library
# Lets get the other necessary packages
$ -> mkdir lib

$ -> cd lib
$ -> pwd
/home/mpurcell/projects/vendor/phpunit/lib

# Setup base dirs for phpunit add-ons
$ -> mkdir codeCoverage fileIterator timer

# Now lets copy our add-ons into their respective dirs
$ -> cp ~/sebastianbergmann-php-code-coverage-1.1.1-14-gdc2a15a.zip codeCoverage
$ -> cp ~/sebastianbergmann-php-timer-1.0.2-5-gb352e92.zip timer

# File iterator lib allows you to set a root directory, and phpunit will traverse the directory looking for unit tests
$ -> cp ~/sebastianbergmann-php-file-iterator-1.3.1-1-gbbaab46.zip fileIterator

# Now that we have the files in our lib directory, lets get them setup
$ -> cd codeCoverage
$ -> pwd
/home/mpurcell/projects/vendor/phpunit/lib/codeCoverage

$ -> unzip sebastianbergmann-php-code-coverage-1.1.1-14-gdc2a15a.zip
$ -> mv sebastianbergmann-php-code-coverage-dc2a15a/ 1.1.1-14
$ -> rm *.zip

$ -> cd ../fileIterator
$ -> pwd
/home/mpurcell/projects/vendor/phpunit/lib/codeCoverage

$ -> unzip sebastianbergmann-php-file-iterator-1.3.1-1-gbbaab46.zip
$ -> mv sebastianbergmann-php-file-iterator-bbaab46/ 1.3.1-1
$ -> rm *.zip

$ -> cd ../timer
$ -> pwd
/home/mpurcell/projects/vendor/phpunit/lib/codeCoverage

$ -> unzip sebastianbergmann-php-timer-1.0.2-5-gb352e92.zip
$ -> mv sebastianbergmann-php-timer-b352e92/ 1.0.2-5
$ -> rm *.zip

Ok, now you should have phpunit and it’s core libraries “installed” on your server. In this context, installed is a loose term, as the code isn’t really installed, it’s now available to be hooked into from your testing environment.

Symlinks

As with any 3rd party APIs introduced into your application, it is always best to abstract away version numbers, so you don’t force your application to require files with version numbers in a file’s uri. For example:

// Good
require_once 'path/to/ThirdParty_Vendor/Api/Class.php';

// Bad
require_once 'path/to/ThirdParty_Vendor-1.1.1-9/Api/Class.php';

Why does this matter? Because, when a new version of the file is released, and you upgrade, you won’t have to update all the code references. Instead, just change the related symlink and your application will work as before, except with the newer version of the file.

So lets make the PHPUnit libraries available to our testing environment:

$ -> cd ~/projects/core/test
$ -> mkdir lib
$ -> cd lib
$ -> pwd
/home/mpurcell/projects/test/lib

$ -> ln -s ~/projects/vendor/phpunit/3.6.7-9/PHPUnit
$ -> ln -s ~/projects/vendor/phpunit/lib/codeCoverage/1.1.1-14/PHP PHPCodeCoverage
$ -> ln -s ~/projects/vendor/phpunit/lib/fileIterator/1.3.1-1/File PHPFileIterator
$ -> ln -s ~/projects/vendor/phpunit/lib/timer/1.0.2-5/PHP PHPTimer

Ok, now we have hooks to phpunit libraries within our testing directory, onto the next step.

Bootstrap

A bootstrapper is meant to prepare a library for usage, and that’s exactly what we are going to do. This bootstrapper will setup include_paths along with a few other settings so we can use run our tests correctly. The code is posted here, otherwise it’s too hard to read in wordpress.

Autoloader

Here’s where the magic lies. This autoloader will know how to map files that PHPUnit is requiring, to their symlinked location. It’s pretty easy to follow, all we do is check for a namespace footprint (PHP_Timer), and if it exists, re-map it to our symlink (PHPTimer). The code is posted here, otherwise it’s too hard to read in wordpress.

Changes to PHPUnit Source code

Now for the ugly. It is NEVER a good idea to edit 3rd party (vendor) code directly, otherwise you update and forget about the changes and your app goes to hell. However in this instance I had no choice, and fortunately I was able to limit the change to just one location in the PHPUnit source code. It is a trivial change, but you should add a README to your ~/projects/vendor/phpunit directory to remind yourself to make this change for future upgrades (assuming the lead developer doesn’t change it himself).

My README file:

ATTENTION!
When upgrading phpunit, 1 change must be made to ensure unit tests work

Why:    This allows us to use our own autloader
File:   PHPUnit/Util/GlobalState.php
Line:   98
Change:
    From:    protected static $phpunitFiles;
    To:      public static $phpunitFiles;

This change makes it so we can override the singleton $phpunitfiles. If we don’t over-ride it, then PHPUnit will attempt to use it’s built-in autoloader, which doesn’t work with our setup. By setting the scope from protected to public, we can over-ride the value with an empty array, as the conditional used in source code check is ‘ === NULL’.

phpunit executable

Now we need to create the phpunit executable which will kick off the unit testing. When I was going through the PHPUnit source code, I noticed that the PEAR installer was just renaming the phpunit.php to phpunit. So, lets copy the phpunit executable which came with PHPUnit to our test directory and make a few minor changes:

$ -> pwd
/home/mpurcell/projects/core/test

$ -> cp ~/projects/vendor/phpunit/3.6.7-9/phpunit.php .

Now, make the following changes:

#!/usr/bin/env php

// Bring in our bootstrap file
require_once substr(__FILE__, 0, strpos(__FILE__, '/test')) . '/test/Bootstrap.php';

// Set our main define
define('PHPUnit_MAIN_METHOD', 'PHPUnit_TextUI_Command::main');

// Remember we set the scope of $phpunitfiles to public?
// Now we can set it to whatever we want, which is just an empty
// array, which allows our autoloader to handle loading files
PHPUnit_Util_GlobalState::$phpunitFiles = array();

// Kick this pig
PHPUnit_TextUI_Command::main();

Home Stretch

Finally, we made it. Now, we can call on the phpunit executable and run tests. First lets create a sample test:

$ -> pwd
/home/mpurcell/projects/core/test

$ -> touch CoreTest/ArrayTest.php

Now lets add an easy test:

<?php
class CoreTest_Api_Array_PackageTest extends PHPUnit_Framework_TestCase{
     public function testCount()
     {
         $this->assertCount(2, array('foo', 'bar'));
     }
}

Now, run the test:

$ -> pwd
/home/mpurcell/projects/core/test

$ -> ./phpunit/CoreTest/

Now your ArrayTest test should run (and pass). Notice that we passed a directory to the ./phpunit executable, you can pass a directory, or a specific test to meet your needs. The PHPFileIterator we setup will parse directories for any files ending in *Test.

Congratulations

Hopefully this article wasn’t too hard to follow, and your unit tests are running though PHPUnit, as if you installed through PEAR. If you wouldn’t mind taking the time to contact the lead developer, and let him know that he should drop PEAR and run an autoloader/bootstrap combo like many other PHP libraries/frameworks, I would greatly appreciate it. He has done a good job, but we need to make PHPUnit easier to install and set-up so others don’t get discouraged and give up unit tests altogether.

Go to Top