Fix some bugs and add PHPUnit tests