public function setUpRoutes() { $this->app->get('/', function (Request $request, Response $response, array $args) { $response->getBody()->write(file_get_contents(AppConfig::getPathToPublic() . '/app.html')); }); $this->app->any('/api/users/[{id}]', Controller\UsersController::class); $this->app->any('/api/sessions/[{api_key}]', Controller\SessionsController::class); $this->app->any('/api/trips/[{id}]', Controller\TripsController::class); $this->app->any('/api/trips/user/[{user_id}]', Controller\TripsController::class); }
public function __construct(App $app) { $app->group('/empleados/{e_id}/solicitudes_pqr', function () { $this->get('', RetriveLastSolicitudPQRAction::class); $this->post('', CreateNewSolicitudPQRAction::class); $this->delete('/{pqr_id}', DeleteSolicitudPQRAction::class); $this->post('/{pqr_id}/respuesta', ResponderSolicitudPQRAction::class); }); $app->get('/solicitudes_pqr', RetriveSolicitudesPQRAction::class); $app->get('/solicitudes_pqr/{pqr_id}', RetriveOneSolicitudPQRAction::class); }
public static function register(App $app, $config) { $app->getContainer()['imagecache'] = function () use($config) { return new Manager($config); }; $app->get("/{$config['path_web']}/{$config['path_cache']}/{preset}/{file:.*}", (new ImagecacheRegister())->request())->setName('onigoetz.imagecache'); }
public function register(App &$app) { $app->get('/version', function (Request $request, Response $response) { $response->getBody()->write(json_encode("v1.0.0")); return $response->withHeader('Access-Control-Allow-Origin', '*'); }); $app->options('/version', function (Request $request, Response $response, $args) use(&$self) { return $response->withHeader('Access-Control-Allow-Origin', '*')->withHeader('Access-Control-Allow-Headers', 'Content-Type'); }); }
protected function dispatchApplication(array $server, array $pipe = []) { $app = new App(); $app->getContainer()['environment'] = function () use($server) { return new Environment($server); }; $middlewareFactory = new PhpDebugBarMiddlewareFactory(); $middleware = $middlewareFactory(); $app->add($middleware); foreach ($pipe as $pattern => $middleware) { $app->get($pattern, $middleware); } return $app->run(true); }
/** * @param string $method * @param string $route * @param object $routerClass * @param string $callback * @param Secured $secured * @throws \Exception */ private function setRoute($method, $route, $routerClass, $callback, $secured) { $method = strtoupper($method); $easyRoute = new Route($route, $routerClass, $callback, $secured, $this); if ($method === 'GET') { $this->app->get($route, array($easyRoute, 'call')); } elseif ($method === 'PUT') { $this->app->put($route, array($easyRoute, 'call')); } elseif ($method === 'POST') { $this->app->post($route, array($easyRoute, 'call')); } elseif ($method === 'DELETE') { $this->app->delete($route, array($easyRoute, 'call')); } else { throw new \Exception('Unsupported HTTP method ' . $method); } }
public function testMiddlewareIsWorkingAndEditorIsSet() { $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $container = $app->getContainer(); $container['environment'] = function () { return Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); }; $app->get('/foo', function ($req, $res, $args) { return $res; }); $app->add(new WhoopsMiddleware()); // Invoke app $response = $app->run(); // Get added whoops handlers $handlers = $container['whoops']->getHandlers(); $this->assertEquals(2, count($handlers)); $this->assertEquals('subl://open?url=file://test_path&line=169', $handlers[0]->getEditorHref('test_path', 169)); }
/** * * @param App $slim */ public function run(App $slim) { if (!isset($_SERVER['PHP_AUTH_USER'])) { $this->response_401(); } else { if ($_SERVER['PHP_AUTH_USER'] == $this->user && sha1($_SERVER['PHP_AUTH_PW']) == $this->pass) { // Start session just in case if (!isset($_SESSION)) { session_start(); } $token = $this->TokenGenerator->Generate(session_id()); $validation = $this->TokenHandler->GetToken($token, $_SERVER['REMOTE_ADDR']); if ($validation == false) { if ($this->whitelistRetriever->check_whitelist($_SERVER['REMOTE_ADDR'])) { $validation = $this->TokenHandler->SaveCurrentToken($token, $_SERVER['REMOTE_ADDR'], date('Y-m-d H:i')); } else { $this->response_401(); } } if (!$this->whitelistRetriever->check_whitelist($_SERVER['REMOTE_ADDR'])) { $this->response_401(); } $slim->add(function (Request $request, Response $response, $next) use($token) { if (!$this->whitelistRetriever->check_whitelist($_SERVER['REMOTE_ADDR'])) { $this->response_401(); } // TODO: find a way to give a token. }); // TODO: add around every request and check if the tokens match $slim->get('/security', function () use($token) { header("Security token: " . $token); echo $token; return; }); return; } else { $this->response_401(); } } }
/** * Add the controller's routes and relative methods. * Request and response are PSR-7 compliant * @param App $application the Slim application to be configured * @return null */ public static function createRoutes(App $application) { // Note: in the SlimFramework's routing function closures, $this equals to the App's Container. $base = static::$baseUri; // Routes that need the user to be admin if (Utils::isAdmin()) { // Product creation (view) $application->map(['GET', 'POST'], "{$base}/create[/]", function (Request $request, Response $response) { return (new self($this))->handleCreate($request, $response); })->setName('productCreate'); // Products list (view) $application->get("{$base}/list[/]", function (Request $request, Response $response) { return (new self($this))->handleReadList($request, $response); })->setName('productList'); // Product edit (view) $application->map(['GET', 'POST'], "{$base}/{product}/edit[/]", function (Request $request, Response $response, $args) { return (new self($this))->handleEdit($request, $response, intval($args['product'])); })->setName('productEdit'); } // Routes that can be seen by anyone // ... }
return function ($request, $response, $exception) use($container) { //Format of exception to return $data = ['message' => $exception->getMessage()]; return $container->get('response')->withStatus(500)->withHeader('Content-Type', 'application/json')->write(json_encode($data)); }; }; //Register authentication container Dependency $container['auth'] = function ($container) { return new BB8\Emoji\Auth($container); }; //Initialize the slim app $app = new App($container); //Add middleware at app level $app->add('BB8\\Emoji\\Middleware:init'); //Index page $app->get('/', 'BB8\\Emoji\\Controllers\\UserController:index'); //Create new user $app->post('/signup', 'BB8\\Emoji\\Controllers\\UserController:create'); //Login Route $app->post('/auth/login', 'BB8\\Emoji\\Controllers\\UserController:login'); //Logout Route $app->get('/auth/logout', 'BB8\\Emoji\\Controllers\\UserController:logout')->add('BB8\\Emoji\\Middleware:authorize'); //List all emojis Route $app->get('/emojis', 'BB8\\Emoji\\Controllers\\EmojiController:index'); //Gets an emoji $app->get('/emojis/{id}', 'BB8\\Emoji\\Controllers\\EmojiController:show'); //Adds a new Emoji $app->post('/emojis', 'BB8\\Emoji\\Controllers\\EmojiController:create')->add('BB8\\Emoji\\Middleware:authorize'); //Updates an Emoji $app->put('/emojis/{id}', 'BB8\\Emoji\\Controllers\\EmojiController:update')->add('BB8\\Emoji\\Middleware:authorize'); //Updates an Emoji Keyword
<?php require_once __DIR__ . "/../vendor/autoload.php"; use Slim\App; use Slim\Container; use Slim\Views\TwigExtension; $configuration = ['settings' => ['displayErrorDetails' => true]]; $container = new Container($configuration); // Register component on container $container['view'] = function ($c) { $view = new \Slim\Views\Twig(__DIR__ . '/../src/Application/Templating', ['cache' => __DIR__ . '/../cache']); $view->addExtension(new TwigExtension($c['router'], $c['request']->getUri())); return $view; }; $container['debug'] = true; // Create app $app = new App($container); // Render Twig template in route $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'home/index.html.twig'); })->setName('profile'); // Run app $app->run();
/** * @runInSeparateProcess */ public function testExceptionErrorHandlerDisplaysErrorDetails() { $app = new App(['settings' => ['displayErrorDetails' => true]]); // Prepare request and response objects $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app->getContainer()['request'] = $req; $app->getContainer()['response'] = $res; $mw = function ($req, $res, $next) { throw new \Exception('middleware exception'); }; $app->add($mw); $app->get('/foo', function ($req, $res) { return $res; }); $resOut = $app->run(); $this->assertEquals(500, $resOut->getStatusCode()); $this->expectOutputRegex('/.*middleware exception.*/'); }
<?php use Slim\App; use Slim\Views\Twig; require '../vendor/autoload.php'; $app = new App(); $view = new Twig('../resources/views'); $env = $view->getEnvironment(); $env->addGlobal('year', date('Y')); $container = $app->getContainer(); $container->register($view); // Routes $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'index.html.twig', ['page_title' => 'Project Mercury']); })->setName('index'); $app->run();
return $view; }; // Register provider $container['flash'] = function () { return new \Slim\Flash\Messages(); }; $container['pdo'] = function ($c) { $pdo = new ExtendedPdo($c->get('settings')['db']['connection'], $c->get('settings')['db']['username'], $c->get('settings')['db']['password']); return $pdo; }; $app->get('/', function (\Slim\Http\Request $request, \Slim\Http\Response $response, array $args) { $getParams = $request->getQueryParams(); /** @var ExtendedPdo $pdo */ $pdo = $this->get('pdo'); $stm = "SELECT * FROM indiegogo WHERE Email = :email"; $bind = ['email' => $getParams['email']]; $sth = $pdo->perform($stm, $bind); $result = $sth->fetch(PDO::FETCH_ASSOC); /** @var \Slim\Flash\Messages $flash */ $flash = $this->get('flash'); $this->view->render($response, 'pages/osmirewards2016/index.twig', $getParams + ['result' => $result, 'formAction' => $this->router->pathFor('postForm'), 'flash' => $flash->getMessages()]); })->setName('getForm'); $app->post('/', function (\Slim\Http\Request $request, \Slim\Http\Response $response, array $args) { $postParams = $request->getParsedBody(); /** @var \Slim\Flash\Messages $flash */ $flash = $this->get('flash'); try { \Assert\lazy()->that($postParams['email'], 'email')->notEmpty('Email must be provided')->email('Email must be valid')->verifyNow(); } catch (Assert\LazyAssertionException $e) { $flash->addMessage('error', $e->getMessage()); return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('getForm') . '?' . http_build_query(['email' => $postParams['email']])); }
<?php require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; use Slim\App; use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware; $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $app->add(new WhoopsMiddleware()); // Throw exception, Named route does not exist for name: hello $app->get('/', function ($request, $response, $args) { return $this->router->pathFor('hello'); }); // $app->get('/hello', function($request, $response, $args) { // $response->write("Hello Slim"); // return $response; // })->setName('hello'); $app->run();
use Slim\App; use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware; /*** * The slim documents: http://www.slimframework.com/docs/objects/router.html */ // config $debug = false; if (defined("DEBUG")) { $debug = true; } // Make a Slim App // $app = new App($c) $app = new App(['settings' => ['debug' => $debug, 'whoops.editor' => 'sublime']]); $app->add(new WhoopsMiddleware()); // Home $app->get('/', 'App\\Controllers\\HomeController:index'); $app->get('/code', 'App\\Controllers\\HomeController:code'); $app->get('/tos', 'App\\Controllers\\HomeController:tos'); $app->get('/debug', 'App\\Controllers\\HomeController:debug'); $app->post('/debug', 'App\\Controllers\\HomeController:postDebug'); // User Center $app->group('/user', function () { $this->get('', 'App\\Controllers\\UserController:index'); $this->get('/', 'App\\Controllers\\UserController:index'); $this->post('/checkin', 'App\\Controllers\\UserController:doCheckin'); $this->get('/node', 'App\\Controllers\\UserController:node'); $this->get('/node/{id}', 'App\\Controllers\\UserController:nodeInfo'); $this->get('/profile', 'App\\Controllers\\UserController:profile'); $this->get('/invite', 'App\\Controllers\\UserController:invite'); $this->post('/invite', 'App\\Controllers\\UserController:doInvite'); $this->get('/edit', 'App\\Controllers\\UserController:edit');
<?php require_once __DIR__ . '/../vendor/autoload.php'; use Slim\App; use Actuator\Health\OrderedHealthAggregator; use Actuator\Health\Indicator\DiskSpaceHealthIndicator; use Actuator\Health\Indicator\MemcachedHealthIndicator; use Actuator\Slim\Provider\HealthServiceProvider; $memcached = new Memcached(); $memcached->addServer('127.0.0.1', 11211); $indicators = array('memcache' => new MemcachedHealthIndicator($memcached), 'disk' => new DiskSpaceHealthIndicator()); $app = new App(); $container = $app->getContainer(); $container['health.aggregator'] = new OrderedHealthAggregator(); $container['health.indicators'] = $indicators; $container['health'] = function ($container) { return new HealthServiceProvider($container['health.aggregator'], $container['health.indicators']); }; $app->get('/health', function ($req, $res) { return $this->health->getHealth($res); }); $app->run();
<?php use ShippingSteam\LandingPadUI\Controllers\HomeController; use Slim\App; use Slim\Container; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Slim\Views\Twig; require '../vendor/autoload.php'; $container = new Container(); // Register component on container $container['view'] = function ($container) { $view = new Twig(__DIR__ . '/../src/Views', ['cache' => false, 'debug' => true]); $view->addExtension(new \Slim\Views\TwigExtension($container['router'], $container['request']->getUri())); return $view; }; $container[HomeController::class] = function ($container) { return new HomeController($container['view']); }; $app = new App($container); $app->get('/', function (ServerRequestInterface $request, ResponseInterface $response, $args) { $controller = $this->get(HomeController::class); return $controller->index($request, $response, $args); }); $app->run();
<?php require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; use Slim\App; use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware; $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $app->add(new WhoopsMiddleware()); $container = $app->getContainer(); $container['view'] = function ($c) { $view = new \Slim\Views\Twig('./views', ['debug' => true, 'cache' => './cache/views']); $view->addExtension(new Twig_Extension_Debug()); return $view; }; // Work // $app->get('/', function($request, $response, $args) use ($app) { // return $this->view->render($response, 'test.html', [ // 'name' => "Tester" // ]); // }); // Exception $app->get('/', function ($request, $response, $args) use($app) { return $this->view->render($response, 'noExists.html'); }); $app->run();
/** * Integration test IpRestrictMiddleware::_invoke() when the given IP is allowed. */ public function testIpAllow() { // Prepare the Request and the application. $app = new App(); // Setup a demo environment $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.2']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $headers->set('Accept', 'text/html'); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app->getContainer()['request'] = $req; $app->getContainer()['response'] = $res; // Set the options value. $this->options = ['error_code' => 403, 'exception_message' => 'NOT ALLOWED']; $app->add(new IpRestrictMiddleware($this->ipSet, false, $this->options)); $appMessage = 'I am In'; $app->get('/foo', function ($req, $res) use($appMessage) { $res->write($appMessage); return $res; }); $resOut = $app->run(); $body = (string) $resOut->getBody(); $this->assertEquals($appMessage, $body, 'The client is allowed to access the application.'); }
/** * Add a repository to your Slim App * @param App $app * @param Repository $repository * @return App the given app for chaining */ public function bootStrap(App $app, Repository $repository) { $baseUrl = '/' . self::parseRepoName($repository->getEntityClass()->getShortName()); /** * Get the whole collection. */ $app->get($baseUrl, function (Request $request, Response $response) use($repository) { return $response->write(self::output($repository->findAll()))->withHeader('Content-Type', 'application/json'); }); /** * Delete the whole collection. */ $app->delete($baseUrl, function (Request $request, Response $response) use($repository) { $repository->deleteAll(); }); /** * Add a new entity to the collection. */ $app->post($baseUrl, function (Request $request, Response $response) use($repository) { $body = self::getBody($request->getBody(), $repository->getEntityClass(), $response); if ($body instanceof Response) { return $body; } else { // Store the entity $repository->insert($body); return $response->withStatus(Status::CREATED)->withHeader('Content-Type', 'application/json')->write(self::output($body)); } }); if ($this->showCheckPage) { /** * Display the repository check page. */ $app->get($baseUrl . '/check', function (Request $request, Response $response) use($repository) { $repository->checkDatabase(); }); } $entityUrl = $baseUrl . '/{id}'; /** * Get a single entity. */ $app->get($entityUrl, function (Request $request, Response $response, $args) use($repository) { $entity = $repository->get($args['id']); if ($entity) { return $response->write(self::output($entity))->withHeader('Content-Type', 'application/json'); } return $response->withStatus(Status::NOT_FOUND); }); /** * Delete a single entity */ $app->delete($entityUrl, function (Request $request, Response $response, $args) use($repository) { $repository->delete($args['id']); }); /** * Replace a single entity */ $app->put($entityUrl, function (Request $request, Response $response, $args) use($repository) { $body = self::getBody($request->getBody(), $repository->getEntityClass(), $response); if ($body instanceof Response) { return $body; } else { // Store the entity $repository->getIdProperty()->setValue($body, $args['id']); $repository->update($body); return $response->withHeader('Content-Type', 'application/json')->write(self::output($body)); } }); return $app; }
$token = $tokenAuth->findToken($request); /** * Call authentication logic class */ $auth = new \app\Auth(); /** * Verify if token is valid on database * If token isn't valid, must throw an UnauthorizedExceptionInterface */ $auth->getUserByToken($token); }; /** * Add token authentication middleware */ $app->add(new TokenAuthentication(['path' => '/restrict', 'authenticator' => $authenticator])); /** * Public route example */ $app->get('/', function ($request, $response) { $output = ['msg' => 'It is a public area']; $response->withJson($output, 200, JSON_PRETTY_PRINT); }); /** * Restrict route example * Our token is "usertokensecret" */ $app->get('/restrict', function ($request, $response) { $output = ['msg' => 'It\'s a restrict area. Token authentication works!']; $response->withJson($output, 200, JSON_PRETTY_PRINT); }); $app->run();
<?php require "../vendor/autoload.php"; use PeelingPixels\Raktiv\Raktiv; use Slim\App; use Slim\Views\PhpRenderer; $app = new App(['settings' => ['displayErrorDetails' => true]]); $container = $app->getContainer(); $container['renderer'] = function () use($container) { $templatesDir = __DIR__ . '/app/templates/'; return new PhpRenderer($templatesDir); }; $app->get('/', function ($req, $res) { $templatesDir = __DIR__ . '/app/templates/'; $data = ['fullName' => 'James Bond', 'hello' => ['name' => 'Jamie', 'library' => 'Ractive'], 'list' => ['shoppingList' => [['name' => 'Chips'], ['name' => 'Water'], ['name' => 'Milk']]], 'comments' => [['name' => 'Harry', 'text' => 'This is a test to make sure this works.']]]; $comments = Raktiv::extend(['template' => file_get_contents($templatesDir . 'comments.html'), 'data' => ['comments' => $data['comments']]]); Raktiv::make()->addComponent('Comments', $comments); $list = Raktiv::extend(['template' => file_get_contents($templatesDir . 'list.html'), 'data' => $data['list']]); $hello = Raktiv::extend(['template' => file_get_contents($templatesDir . 'hello.html'), 'data' => $data['hello']]); $app = Raktiv::extend(['template' => file_get_contents($templatesDir . 'app.html'), 'components' => ['Hello' => $hello, 'List' => $list], 'data' => $data]); return $this->renderer->render($res, 'index.php', ['content' => $app->render(), 'json_data' => json_encode($data)]); }); $app->run();
public function registerRoute(Slim $app) { $data = $this->getInfo(); $app->get($data['path'], $data['handle'] . ':' . $data['method'])->setName('page.' . $data['name']); }
public static function setupRoutes(SlimApp $app, MapInterface $map) { $app->get('/' . self::getId() . '/do', self::class . ':actionDo'); }
<?php use Slim\App; use App\Controllers; /*** * The slim documents: http://www.slimframework.com/docs/objects/router.html */ $app = new App(); $app->get('/', 'App\\Controllers\\HomeController:home'); $app->get('/hello/:name', function ($name) { echo "Hello, {$name}"; }); // Run Slim Routes for App $app->run();
<?php use Slim\App; use App\Controllers; use App\Middleware\Auth; use App\Middleware\Guest; /*** * The slim documents: http://www.slimframework.com/docs/objects/router.html */ $app = new App(); // Home $app->get('/', 'App\\Controllers\\HomeController:home'); $app->get('/code', 'App\\Controllers\\HomeController:code'); // User Center $app->group('/user', function () { $this->get('/', 'App\\Controllers\\UserController:home'); $this->get('/node', 'App\\Controllers\\UserController:node'); $this->get('/profile', 'App\\Controllers\\UserController:profile'); $this->get('/invite', 'App\\Controllers\\UserController:invite'); $this->get('/sys', 'App\\Controllers\\UserController:sys'); $this->get('/logout', 'App\\Controllers\\UserController:logout'); })->add(new Auth()); // Auth $app->group('/auth', function () { $this->get('/login', 'App\\Controllers\\AuthController:login'); $this->post('/login', 'App\\Controllers\\AuthController:loginHandle'); $this->get('/register', 'App\\Controllers\\AuthController:register'); $this->post('/register', 'App\\Controllers\\AuthController:registerHandle'); $this->get('/logout', 'App\\Controllers\\AuthController:logout'); })->add(new Guest()); // Run Slim Routes for App
<?php require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; use Slim\App; use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware; $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $app->add(new WhoopsMiddleware()); $app->get('/', function () use($app) { // echo "Hello World"; $app->router->urlFor('index'); // Throw exception, not defined route named 'index' }); $app->run();
use Slim\Handlers\Strategies\RequestResponseArgs; use Zelory\DiskonMania\Model\Category; use Zelory\DiskonMania\Model\Comment; use Zelory\DiskonMania\Model\Promo; use Zelory\DiskonMania\Model\User; use Zelory\DiskonMania\Util\ResultWrapper; use Zelory\DiskonMania\Util\Scraper; require 'vendor/autoload.php'; require_once 'src/zelory/diskonmania/DB.php'; $container = new Container(); $container['foundHandler'] = function () { return new RequestResponseArgs(); }; $app = new App($container); $app->get('/', function (Request $request, Response $response) { $response->getBody()->write('<script type="text/javascript">url = window.location.href + "doc"; window.location = url;</script>'); return $response->withStatus(200)->withHeader('Content-Type', 'text/html'); }); $app->post('/login', function (Request $request, Response $response) { try { $params = $request->getQueryParams(); $user = User::login($params['username'], $params['password']); if ($user == null) { throw new Exception("Invalid username or password!"); } return ResultWrapper::getResult($user, $response); } catch (Exception $e) { return ResultWrapper::getError($e->getMessage(), $response); } }); $app->post('/register', function (Request $request, Response $response) { try {
$pathInfo = pathinfo($fileName); $extension = $pathInfo['extension']; // TODO: Do some validation here for extension type $fileConverter = new \PNGify\FileConverter($_FILES['file']['tmp_name'], $extension); $config = (require './config.php'); $fileConverter->setMappings($config['extensions']); try { $image = $fileConverter->toImage(); } catch (\PNGify\Exceptions\InvalidFileExtension $e) { $response = $response->withStatus(400); /** @var \Psr\Http\Message\StreamInterface $body */ $body = $response->getBody(); $body->write(json_encode(['error' => 'Invalid file extension'])); $response = $response->withHeader('Content-Type', 'application/json'); $response = $response->withHeader('Content-Disposition', 'inline; filename="' . $pathInfo['filename'] . '.png"'); $response = $response->withBody($body); return $response; } $response = $response->withHeader('Content-Type', 'image/png'); $body = $response->getBody(); $body->write($image); $response = $response->withBody($body); return $response; }); $app->get('/', function (Request $request, Response $response) { $body = $response->getBody(); $body->write(file_get_contents('./static/templates/index.html')); $response = $response->withBody($body); return $response; }); $app->run();