A simple PHP implementation of the JSend specification.
use JSend\JSendResponse;
$success = new JSendResponse('success', $data);
$fail = new JSendResponse('fail', $data);
$error = new JSendResponse('error', $data, 'Not cool.', 9001);
$success = JSendResponse::success($data);
$fail = JSendResponse::fail($data);
$error = JSendResponse::error('Not cool.', 9001, $data);
Note: an InvalidJSendException
is thrown if the status is invalid or if you're creating an error
without a message
.
__toString()
is overridden to encode JSON automatically.
$json = $success->encode();
$json = (string) $success;
As JSendResponse is JsonSerializable
, you can use the object directly in json_encode
json_encode($success);
You can set flags if needed:
$success->setEncodingOptions(\JSON_PRETTY_PRINT | \JSON_BIGINT_AS_STRING);
$json = $success->encode();
try {
$response = JSendResponse::decode($json);
} catch (InvalidJSendException $e) {
echo "You done gone passed me invalid JSend.";
}
This sets the Content-Type
header to application/json
and spits out the JSON.
$jsend = new JSendResponse('success', $data);
$jsend->respond();
$isSuccess = $response->isSuccess();
$isError = $response->isError();
$isFail = $response->isFail();
$status = $response->getStatus();
$data = $response->getData();
$array = $response->asArray();
Additionally, you can call the following methods on an error. A BadMethodCallException
is thrown if the status is not error
, so check first.
if ($response->isError()) {
$code = $response->getErrorCode;
$message = $response->getErrorMessage;
}
For your convenience, there is a dockerfile with the right dependencies (php, composer) available. Please use those
to run various things (composer, phpunit, etc). You will need docker
installed, but you don't
need PHP
or composer
or any of the other dependencies.
To start using the local environment for testing and debugging all you have to is open a shell in the root folder of where this project is checked out. Then run the following command.
make build install
This command should be run occasionally to keep the local environment up to date. For instance when the composer dependencies are changed.
To open a shell in the docker container run the following command.
make shell
Available commands are in /bin
We use a variety of tools to keep the code quality of the library high. To run one the tools you only need to run
make <tool_name>
Available tools:
phpstan
PHPStan is static analyser tool that can detect various code issues.phpunit
PHPUnit is the unit testing framework we use for this library.codeclimate
CodeClimate
- Note that the
composer.lock
file is ignored.
The library was written by Jamie Schembri. It has been transfered to the current account Nanne Huiges in december 2015.