Slide 1

Slide 1 text

Advanced

Slide 2

Slide 2 text

• Symfony2 • Silex • Composer igorw @igorwesome

Slide 3

Slide 3 text

require 'vendor/autoload.php'; $app = new Silex\Application(); $app->get('/', function () { return 'Worlds largest microf'; }); $app->run();

Slide 4

Slide 4 text

Trashbin

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

# composer.json { "minimum-stability": "dev", "require": { "silex/silex": "1.0.*@dev" } }

Slide 9

Slide 9 text

$ php composer.phar install

Slide 10

Slide 10 text

require_once __DIR__.'/../vendor/autoload.php'; $app = new Silex\Application(); // ... $app->run();

Slide 11

Slide 11 text

{ "minimum-stability": "dev", "require": { "silex/silex": "1.0.*@dev", "twig/twig": "1.6.0", "predis/service-provider": "dev-master" } }

Slide 12

Slide 12 text

$app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../views', )); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Predis\Silex\PredisServiceProvider());

Slide 13

Slide 13 text

•GET / •POST / •GET /{id}

Slide 14

Slide 14 text

$app->get('/', function () use ($app) { $id = $app['request']->get('parent'); $parentPaste = null; if ($id) { $parentPaste = $app['predis']->hgetall($id); } return $app['twig']->render('index.html', array( 'paste' => $parentPaste, )); }) ->bind('homepage');

Slide 15

Slide 15 text

$app->post('/', function (Request $request) use ($app) { $content = $request->get('content', ''); $id = substr(hash('sha512', mt_rand()), 0, 8); $paste = array( 'content' => $content, 'language' => $request->get('language', ''), 'created_at' => time(), ); if ('' === trim($paste['content'])) { $page = $app['twig']->render('index.html', array( 'errors' => array('you must enter some content'), 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste); return $app->redirect($app['url_generator']->generate('view', array( 'id' => $id, ))); }) ->bind('create');

Slide 16

Slide 16 text

$app->get('/{id}', function ($id) use ($app) { $paste = $app['predis']->hgetall($id); if (!$paste) { return $app->abort(404, 'paste not found'); } $copy_url = $app['url_generator']->generate('homepage', array( 'parent' => $id, )); return $app['twig']->render('view.html', array( 'copy_url' => $copy_url, 'paste' => $paste, )); }) ->bind('view') ->assert('id', '[0-9a-f]{8}');

Slide 17

Slide 17 text

register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../views', 'twig.options' => array('cache' => __DIR__.'/../cache/twig'), )); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Predis\Silex\PredisServiceProvider()); $app['app.languages'] = $app->share(function () { $languages = array(); $finder = new Finder(); foreach ($finder->name('*.min.js')->in(__DIR__.'/../web/shjs/lang') as $file) { if (preg_match('#sh_(.+).min.js#', basename($file), $matches)) { $languages[] = $matches[1]; } } return $languages; }); $app->before(function () use ($app) { // set up some template globals $app['twig']->addGlobal('base_path', $app['request']->getBasePath()); $app['twig']->addGlobal('index_url', $app['url_generator']->generate('homepage')); $app['twig']->addGlobal('create_url', $app['url_generator']->generate('create')); $app['twig']->addGlobal('languages', $app['app.languages']); }); $app->get('/', function () use ($app) { $parentPasteId = $app['request']->get('parent'); $parentPaste = null; if ($parentPasteId) { $parentPaste = $app['predis']->hgetall($id); } return $app['twig']->render('index.html', array( 'paste' => $parentPaste, )); }) ->bind('homepage'); $app->get('/create', function () use ($app) { return $app->redirect($app['url_generator']->generate('homepage')); }); $app->post('/create', function (Request $request) use ($app) { $content = $request->get('content', ''); $content = $this->normalizeContent($content); $id = $this->generateId($content); $paste = array( 'content' => $content, ); $language = $request->get('language', ''); if (in_array($language, $this->languages)) { $paste['language'] = $language; } $paste['created_at'] = time(); $errors = array(); if ('' === trim($paste['content'])) { $errors[] = 'you must enter some content'; } if ($errors) { $page = $app['twig']->render('index.html', array( 'errors' => $errors, 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste) return $app->redirect($app['url_generator']->generate('view', array('id' => $id))); }) ->bind('create'); $app->get('/about', function () use ($app) { return $app['twig']->render('about.html'); }); $app->get('/{id}', function ($id) use ($app) { $paste = $app['predis']->hgetall($id); if (!$paste) { throw new NotFoundHttpException('paste not found'); } return $app['twig']->render('view.html', array( 'copy_url' => $app['url_generator']->generate('homepage', array(' 'paste' => $paste, )); }) ->bind('view') ->assert('id', '[0-9a-f]{8}'); $app->error(function (Exception $e) use ($app) { $code = ($e instanceof HttpException) ? $e->getStatusCode() : 500; return new Response($app['twig']->render('error.html', array( 'message' => $e->getMessage(), )), $code); }); $app->run();

Slide 18

Slide 18 text

What a freaking mess!

Slide 19

Slide 19 text

ᵓᴷᴷ composer.json ᵓᴷᴷ README.md ᵓᴷᴷ phpunit.xml.dist ᵓᴷᴷ src ᴹ ᵋᴷᴷ app.php ᵓᴷᴷ tests ᵓᴷᴷ views ᵋᴷᴷ web ᵋᴷᴷ index.php

Slide 20

Slide 20 text

ᵓᴷᴷ composer.json ᵓᴷᴷ README.md ᵓᴷᴷ phpunit.xml.dist ᵓᴷᴷ src ᴹ ᵋᴷᴷ app.php ᵓᴷᴷ tests ᵓᴷᴷ views ᵋᴷᴷ web ᵋᴷᴷ index.php

Slide 21

Slide 21 text

ᵓᴷᴷ composer.json ᵓᴷᴷ README.md ᵓᴷᴷ phpunit.xml.dist ᵓᴷᴷ src ᴹ ᵋᴷᴷ app.php ᵓᴷᴷ tests ᵓᴷᴷ views ᵋᴷᴷ web ᵋᴷᴷ index.php

Slide 22

Slide 22 text

$app = new Silex\Application(); // ... return $app;

Slide 23

Slide 23 text

$app = require __DIR__.'/../src/app.php'; $app->run();

Slide 24

Slide 24 text

$app->post('/', function (Request $request) use ($app) { $content = $request->get('content', ''); $id = substr(hash('sha512', mt_rand()), 0, 8); $paste = array( 'content' => $content, 'language' => $request->get('language', ''), 'created_at' => time(), ); if ('' === trim($paste['content'])) { $page = $app['twig']->render('index.html', array( 'errors' => array('you must enter some content'), 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste); return $app->redirect($app['url_generator']->generate('view', array( 'id' => $id, ))); }) ->bind('create');

Slide 25

Slide 25 text

$app->post('/', function (Request $request) use ($app) { $content = $request->get('content', ''); $id = substr(hash('sha512', mt_rand()), 0, 8); $paste = array( 'content' => $content, 'language' => $request->get('language', ''), 'created_at' => time(), ); if ('' === trim($paste['content'])) { $page = $app['twig']->render('index.html', array( 'errors' => array('you must enter some content'), 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste); return $app->redirect($app['url_generator']->generate('view', array( 'id' => $id, ))); }) ->bind('create'); Parsing

Slide 26

Slide 26 text

$app->post('/', function (Request $request) use ($app) { $content = $request->get('content', ''); $id = substr(hash('sha512', mt_rand()), 0, 8); $paste = array( 'content' => $content, 'language' => $request->get('language', ''), 'created_at' => time(), ); if ('' === trim($paste['content'])) { $page = $app['twig']->render('index.html', array( 'errors' => array('you must enter some content'), 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste); return $app->redirect($app['url_generator']->generate('view', array( 'id' => $id, ))); }) ->bind('create'); Validation

Slide 27

Slide 27 text

$app->post('/', function (Request $request) use ($app) { $content = $request->get('content', ''); $id = substr(hash('sha512', mt_rand()), 0, 8); $paste = array( 'content' => $content, 'language' => $request->get('language', ''), 'created_at' => time(), ); if ('' === trim($paste['content'])) { $page = $app['twig']->render('index.html', array( 'errors' => array('you must enter some content'), 'paste' => $paste, )); return new Response($page, 400); } $app['predis']->hmset($id, $paste); return $app->redirect($app['url_generator']->generate('view', array( 'id' => $id, ))); }) ->bind('create'); Storage

Slide 28

Slide 28 text

SRP

Slide 29

Slide 29 text

ᵓᴷᴷ src ᵓᴷᴷ app.php ᵓᴷᴷ bootstrap.php ᵋᴷᴷ Igorw ᵋᴷᴷ Trashbin ᵋᴷᴷ *.php

Slide 30

Slide 30 text

{ "require": { "silex/silex": ">=1.0.0-dev", "symfony/finder": ">=2.1-dev", "twig/twig": "1.6.0", "predis/service-provider": "dev-master" }, "autoload": { "psr-0": { "Igorw\\Trashbin": "src" } } }

Slide 31

Slide 31 text

• Parsing • Validation • Storage

Slide 32

Slide 32 text

• Parsing => Trashbin\Parser • Validation => Trashbin\Validator • Storage => Trashbin\Storage

Slide 33

Slide 33 text

namespace Igorw\Trashbin; class Parser { // ... }

Slide 34

Slide 34 text

public function createPasteFromRequest(Request $request) { $content = $request->get('content', ''); $content = $this->normalizeContent($content); $id = $this->generateId(); $paste = array( 'content' => $content, ); $language = $request->get('language', ''); if (in_array($language, $this->languages)) { $paste['language'] = $language; } $paste['created_at'] = time(); return array($id, $paste); }

Slide 35

Slide 35 text

public function createPasteFromRequest(Request $request) { $content = $request->get('content', ''); $content = $this->normalizeContent($content); $id = $this->generateId(); $paste = array( 'content' => $content, ); $language = $request->get('language', ''); if (in_array($language, $this->languages)) { $paste['language'] = $language; } $paste['created_at'] = time(); return array($id, $paste); } Bad

Slide 36

Slide 36 text

public function createPasteFromRequest(Request $request) { $content = $request->get('content', ''); $content = $this->normalizeContent($content); $id = $this->generateId(); $paste = array( 'content' => $content, ); $language = $request->get('language', ''); if (in_array($language, $this->languages)) { $paste['language'] = $language; } $paste['created_at'] = $request->server->get('REQUEST_TIME'); return array($id, $paste); }

Slide 37

Slide 37 text

• header() • setcookie() • var_dump() • echo, print • exit, die • include • time() Bad

Slide 38

Slide 38 text

private $languages; public function __construct(array $languages) { $this->languages = $languages; } public function normalizeContent($content) { return preg_replace(array('#\r?\n#', '#\r#'), "\n", $content); } public function generateId() { return substr(hash('sha512', mt_rand()), 0, 8); }

Slide 39

Slide 39 text

namespace Igorw\Trashbin; class Validator { public function validate(array $paste) { $errors = array(); if ('' === trim($paste['content'])) { $errors[] = 'you must enter some content'; } return $errors; } }

Slide 40

Slide 40 text

namespace Igorw\Trashbin; use Predis\Client; class Storage { private $redis; public function __construct(Client $redis) { $this->redis = $redis; } public function get($id) { return $this->redis->hgetall($id); } public function set($id, array $data) { return $this->redis->hmset($id, $data); } }

Slide 41

Slide 41 text

$app['app.parser'] = $app->share(function () use ($app) { return new Parser($app['app.languages']); }); $app['app.validator'] = $app->share(function () { return new Validator(); }); $app['app.storage'] = $app->share(function () use ($app) { return new Storage($app['predis']); });

Slide 42

Slide 42 text

$app->post('/', function () use ($app) { list($id, $paste) = $app['app.parser'] ->createPasteFromRequest($app['request']); $errors = $app['app.validator']->validate($paste); if ($errors) { $page = $app['twig']->render('index.html', array( 'errors' => $errors, 'paste' => $paste, )); return new Response($page, 400); } $app['app.storage']->set($id, $paste); $url = $app['url_generator']->generate('view', array('id' => $id)); return $app->redirect($url); }) ->bind('create');

Slide 43

Slide 43 text

ᵓᴷᴷ composer.json ᵓᴷᴷ README.md ᵓᴷᴷ phpunit.xml.dist ᵓᴷᴷ src ᵓᴷᴷ tests ᵓᴷᴷ views ᵋᴷᴷ web

Slide 44

Slide 44 text

Slide 45

Slide 45 text

Slide 46

Slide 46 text

Functional tests vs Unit tests

Slide 47

Slide 47 text

use Igorw\Trashbin\Validator; class ValidatorTest extends PHPUnit_Framework_TestCase { /** * @dataProvider provideValidate */ public function testValidate($expected, $input) { $validator = new Validator(); $this->assertEquals($expected, $validator->validate($input)); } public function provideValidate() { return array( array(array('you must enter some content'), array('content' => '')), array(array('you must enter some content'), array('content' => ' ')), array(array('you must enter some content'), array('content' => "\t")), array(array('you must enter some content'), array('content' => "\t \n")), array(array(), array('content' => 'hello')), array(array(), array('content' => 'foobar! ')), array(array(), array('content' => 'äöü~')), ); } }

Slide 48

Slide 48 text

BrowserKit CssSelector DomCrawler

Slide 49

Slide 49 text

{ "require": { "silex/silex": ">=1.0.0-dev", "symfony/finder": ">=2.1-dev", "twig/twig": "1.6.0", "predis/service-provider": "dev-master" }, "require-dev": { "symfony/browser-kit": "2.1.*@dev", "symfony/css-selector": "2.1.*@dev", "symfony/dom-crawler": "2.1.*@dev" }, "autoload": { "psr-0": { "Igorw\\Trashbin": "src" } } }

Slide 50

Slide 50 text

use Silex\WebTestCase; class FunctionalTest extends WebTestCase { public function createApplication() { $app = require __DIR__.'/../src/app.php'; $app['app.storage'] = $this ->getMockBuilder('Igorw\Trashbin\Storage') ->disableOriginalConstructor() ->getMock(); unset($this->app['exception_handler']); return $app; } // ... }

Slide 51

Slide 51 text

public function testCreatePaste() { }

Slide 52

Slide 52 text

$paste = array('content' => 'foobar', 'created_at' => 1337882841); $this->app['app.storage'] ->expects($this->once()) ->method('set') ->with($this->isType('string'), $paste); $this->app['app.storage'] ->expects($this->once()) ->method('get') ->with($this->isType('string')) ->will($this->returnValue($paste));

Slide 53

Slide 53 text

$client = $this->createClient(); $client->setServerParameters(array('REQUEST_TIME' => 1337882841)); $crawler = $client->request('GET', '/'); $form = $crawler->filter('form')->form(); $form['content'] = 'foobar'; $crawler = $client->submit($form); $crawler = $client->followRedirect(); $response = $client->getResponse(); $this->assertTrue($response->isOk()); $this->assertContains('foobar', $response->getContent());

Slide 54

Slide 54 text

public function testCreatePasteWithoutContentShouldFail() { $client = $this->createClient(); $crawler = $client->request('GET', '/'); $form = $crawler->filter('form')->form(); $form['content'] = ''; $client->submit($form); $response = $client->getResponse(); $this->assertSame(400, $response->getStatusCode()); }

Slide 55

Slide 55 text

public function testViewPaste() { $paste = array('content' => 'foobar', 'created_at' => 1337882841); $this->app['app.storage'] ->expects($this->once()) ->method('get') ->with('abcdef12') ->will($this->returnValue($paste)); $client = $this->createClient(); $client->request('GET', '/abcdef12'); $response = $client->getResponse(); $this->assertTrue($response->isOk()); $this->assertContains('foobar', $response->getContent()); }

Slide 56

Slide 56 text

public function testViewPasteWithInvalidId() { $this->app['app.storage'] ->expects($this->once()) ->method('get') ->with('00000000') ->will($this->returnValue(null)); $client = $this->createClient(); $client->request('GET', '/00000000'); $response = $client->getResponse(); $this->assertSame(404, $response->getStatusCode()); $this->assertContains('paste not found', $response->getContent()); }

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

Recap • Clean code principles still apply • Decouple • Write tests

Slide 59

Slide 59 text

on github igorw/trashbin

Slide 60

Slide 60 text

Ω

Slide 61

Slide 61 text

Questions? joind.in/6586 @igorwesome speakerdeck.com /u/igorw