PHPUnit: Assert/mock a method for consecutive calls

I’m testing a class that is calling a method twice and with different parameters. I want to assert that this method (addSourceLinkAndUpdateCounts) is called twice and with the expected parameters.

The matcher to use is the “InvokedAtIndex”. See PHPUnit 3.6 documentation

Here and example (the method addSourceLinkAndUpdateCounts is mocked and I assert that is called twice. The first time with arguments (http://www.link1.com, 12), and the second time with arguments (http://www.link2.com, 12)

// assert save function is called twice and with the two args
        $this->object
             ->expects($this->exactly(2))
             ->method('addSourceLinkAndUpdateCounts')
        ;

        // assert calls return the two links
        $this->object
             ->expects($this->at(1))
             ->method('addSourceLinkAndUpdateCounts')
             ->with('http://www.link1.com', 12)
        ;

        $this->object
             ->expects($this->at(2))
             ->method('addSourceLinkAndUpdateCounts')
             ->with('http://www.link2.com', 12)
        ;

How to create phpunit mock objects from namespaced classes

If the autoloader is enabled:

$mock = $this->getMockBuilder('MyNamespace\sub\ClassToMock')
                   ->setMethods(array('methodToMock', 'methodToMock2'))
                   //->disableOriginalConstructor()
                   ->getMock();

works in phpunit 3.6.7, with or without a namespace specified at the top of the test class.

Clean code talk

 

Clean code talks about testing, by Google

Raw query on Zend framework

\Zend_Db_Table_Abstract::getDefaultAdapter()->query($sql);
\Zend_Db_Table_Abstract::getDefaultAdapter()->query($sql)->fetch(); //if you need to fetch results

if it does not work, use the db handler Pdo), and call – for example – exec()

\Zend_Db_Table_Abstract::getDefaultAdapter()->getConnection()->exec($sql);

How to set apache to skip a directory before a catch-all RewriteRule

Most of PHP applications use internal PHP routing (any MVC framework like ZF, CakePHP… , including wordpress) use a catch-all rewrite rule.

In case a directory needs to be ignored from that (to avoid broken urls falling back to that catch-all route), use a RewriteCond

 

#.htaccess. Redirect all the URLs to index.php, except the ones  starting with /admin

RewriteCond %{REQUEST_URI} !^/admin
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ index.php [NC,L]

PHP Command line interface, set and read ENV variables

When a variable on the console is set

export VARIABLE=VALUE;

You can get it from PHP Command line (CLI) using

getenv(‘VARIABLE’)

 

Example

#script.php
<?php
var_dump(getenv('VAR'));
?>

From command line

php -f script.php //bool(false)
export VAR=a; php -f script.php //string(1) "a"

 

Git pre-commit hook to check PHP syntax

Similarly to SVN, Git supports hook scripts. They are located under

<workcopy>/.git/hooks/

applypatch-msg.sample  post-update.sample     prepare-commit-msg.sample
commit-msg.sample      pre-applypatch.sample  pre-rebase.sample
post-commit.sample     pre-commit             update.sample
post-receive.sample    pre-commit.sample

To check the syntax before committing, I found an interesting script

https://github.com/ReekenX/git-php-syntax-checker/blob/master/pre-commit

Works great for me,

save into .git/hooks/pre-commit

Useful options for PHP Command line interface

I find PHP command line interface very useful, for CRON jobs, testing and whenever apache is not necessary. Basic commands here: CLI php.net manual. In this article I’m writing some CL flags and few lines of related functions / PHP code I find useful

  • To make script interactive and read the line from the console
    $var = readline("text");
  • Prints reflection of a function (params and required values). Can be used as a guide
    php -rf json_encode
  • save highlited code into a html file
    php -s file.php > fileWithCodeHighlited.phtml
  • Display a ini setting containing “log_” (e.g. error_log)
    php -i | grep "log_"
  • Run one command (without entering in interactive mode with php -a)
    php -r "echo time();";
  • Set a INI option before executing
    php -d max_execution_time=20 ...
  • Read from STDIN (when piped)
    $handle = fopen('php://stind', 'r');
    while (!feof($handle)) {
    	$line = trim(fgets($handle));
    	if(strlen($line) > 0){
    	echo strrev($line).PHP_EOL;
    	}
    }
    fclose($handle);
  • Get options using getopt
    $arg = getopt('ab:c::') // "a" as flag "b" required, "c" optional

Mysqldump on a remote machine

Mydump and gzip of database dbuser:pass@localhost/dbname into remote machine “destination.com”, file ~/dbname.sql.gz

mysqldump -h localhost -u root -ppass dbname | gzip \
| ssh user@destination.com "cat > ~/dbname.sql.gz"

Free software alarm for Windows

Some years ago, at University, I used to play with AutoIt, a simple and handy language to make executable for Windows, perfect for automation on Windows machines, including interaction with web applications / REST services.

With that language I made a simple software (ELCITimer) to perform actions (Windows API / display message / close window by title / terminate process from list) at a specified time/interval or when an event is triggered (windows by title appears  / URL contains a specified text).

Download the software, free version for Windows (it was tested on Windows 2k/XP, not sure it works on vista and W7), beta version EXE 300kb, no DLL needed. Click here to download and here to make a small donation if you want