Skip to content

Instantly share code, notes, and snippets.

@peterlafferty
peterlafferty / TddController.php
Created October 25, 2017 20:18
basic silex controller for TDD
<?php
namespace pl\tddcontroller;
use Symfony\Component\HttpFoundation\JsonResponse;
class TddController
{
/** @var string */
private $charset;
<?php
//{"id": 10, "code": "U+1F4A9", "value": "💩", "description": "pile of poo", "hasSkinTone": false}
$app->post('/emoji/', function (Request $request) use ($app) {
$constraints = new Assert\Collection([
'id' => [
new Assert\NotNull(),
new Assert\Type("int")
],
'code' => [
new Assert\NotBlank(),
<?php
$app->get(‘/emoji/{id}’, function (int $id) {
// …
})->assert(‘id’, ‘\d+’);
<?php
use Symfony\Component\Validator\Constraint as Assert;
use Silex\Provider\ValidatorServiceProvider;
//...
//register the validator
$app->register(new ValidatorServiceProvider());
<?php
$constraints = new Assert\Collection([
'hasSkinTone' => [
new Assert\NotBlank(),
new Assert\Regex("/true|false/")
],
'idBelow' => [
new Assert\NotBlank(),
new Assert\Regex([
"pattern" => '/\d+/',
<?php
$getQuery = $request->query->all();
$errors = $app['validator']->validate(
$getQuery,
$constraints
);
<?php
if (count($errors) > 0) {
$messages = [];
foreach ($errors as $error) {
$messages[] = $error->getPropertyPath() . ' ' . $error->getMessage();
}
return new Utf8JsonResponse($messages, 400);
}
<?php
//at this point we know the values are present and can convert them
$hasSkinTone = filter_var(
$getQuery['hasSkinTone'],
FILTER_VALIDATE_BOOLEAN
);
$idBelow = (int)$getQuery['idBelow'];
$filterEmoji = [];
foreach ($app['emoji'] as $emoji) {
<?php
require_once __DIR__.'/vendor/autoload.php';
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
$app = new Silex\Application();
$app['emoji'] = json_decode('[
<?xml version="1.0"?>
<ruleset name="Basic Project Ruleset">
<rule ref="rulesets/cleancode.xml" />
<rule ref="rulesets/codesize.xml" />
<rule ref="rulesets/controversial.xml" />
<rule ref="rulesets/design.xml" />
<rule ref="rulesets/naming.xml" />
<rule ref="rulesets/unusedcode.xml" />
</ruleset>