/**
  * Handle a call to the app
  * 
  * @param  string $method  GET/POST
  * @param  string $path    URI
  * @param  array  $options
  */
 public function request($method, $path, $options = [])
 {
     ob_start();
     $settings = (require __DIR__ . '/../../lib/settings.php');
     $container = new \Slim\Container($settings);
     require __DIR__ . '/../../lib/containers.php';
     $container->get('environment')['REQUEST_URI'] = $path;
     $container->get('environment')['REQUEST_METHOD'] = $method;
     // Set up custom 404 so that we can easilly check if the page wasn't found
     $container['notFoundHandler'] = function ($container) {
         return function ($request, $response) use($container) {
             return $container['response']->withStatus(404)->withHeader('Content-Type', 'text/plain')->write('Page not found');
         };
     };
     $sentinel = m::mock('sentinel');
     $container['sentinel'] = function ($container) use($sentinel) {
         return $sentinel;
     };
     $app = new \Slim\App($container);
     // Set up dependencies
     require __DIR__ . '/../../lib/dependencies.php';
     // Register middleware
     require __DIR__ . '/../../lib/middleware.php';
     // Register routes
     require __DIR__ . '/../../lib/routes.php';
     $app->run();
     $this->app = $app;
     $this->request = $app->getContainer()->request;
     $this->response = $app->getContainer()->response;
     $this->page = ob_get_clean();
 }
Exemplo n.º 2
1
<?php

require 'vendor/autoload.php';
require 'plugins/NotORM.php';
require 'config/dbconnect.php';
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Dflydev\FigCookies\Cookie;
use Dflydev\FigCookies\FigRequestCookies;
use Dflydev\FigCookies\SetCookie;
$app = new \Slim\App();
require 'api/v1/Auht.php';
require 'api/v1/Article.php';
require 'api/v1/Offer.php';
require 'api/v1/Categories.php';
require 'api/v1/AppUser.php';
$app->get('/', function ($request, $response) {
    $app = $response->withStatus(200)->withHeader('Content-Type', 'application/json')->withHeader('Access-Control-Allow-Origin', '*');
    $result = 'Сервер запущен';
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    return $app;
});
$app->run();
Exemplo n.º 3
1
<?php

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $file = __DIR__ . $_SERVER['REQUEST_URI'];
    if (is_file($file)) {
        return false;
    }
}
require __DIR__ . '/vendor/autoload.php';
spl_autoload_register(function ($classname) {
    require __DIR__ . "/src/classes/" . $classname . ".php";
});
session_start();
// Instantiate the app
$settings = (require __DIR__ . '/src/settings.php');
$app = new \Slim\App($settings);
// Set up dependencies
require __DIR__ . '/src/dependencies.php';
// Register middleware
require __DIR__ . '/src/middleware.php';
// Register routes
require __DIR__ . '/src/routes.php';
// Run app
$app->run();
Exemplo n.º 4
0
 public static function setUpBeforeClass()
 {
     $app = new \Slim\App();
     $container = $app->getContainer();
     require "./config/slim.php";
     require "./config/deps.php";
     require "./config/validators.php";
     require "./config/db.env.php";
     require "./config/db.php";
     require "./config/routes.php";
     self::$app = $app;
 }
Exemplo n.º 5
0
 public function instantiate($dao)
 {
     // Instantiate a Slim application:
     $app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
     // Routes
     $app->get('/api/posts/{id}', function (ServerRequestInterface $request, ResponseInterface $response, $args) use($dao) {
         $params = $request->getQueryParams();
         $id = $args['id'];
         $post = $dao->getPost($id);
         if (!empty($post[0])) {
             $postResponse = ["post" => $post[0]];
         } else {
             // send an empty json list {} and not []
             $postResponse = ["post" => new ArrayObject()];
         }
         $response->getBody()->write(json_encode($postResponse, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE));
         $response = $response->withHeader('Content-type', 'application/json');
         return $response;
     });
     $app->get('/api/posts', function (ServerRequestInterface $request, ResponseInterface $response) use($dao) {
         $params = $request->getQueryParams();
         if (isset($params['author'])) {
             $author = $params['author'];
         } else {
             $author = null;
         }
         // TODO : move in settings
         $formatDate = 'Y-m-d';
         // Date checking
         if (isset($params['from']) || isset($params['to'])) {
             if (!DateHelper::validateDate($formatDate, $params['from']) || !DateHelper::validateDate($formatDate, $params['to'])) {
                 throw new Exception("'from' date parameter or 'to' date parameter is not correct or missing.");
             } else {
                 // pipe concatenation to set h-m-s at 00:00:00
                 $fromDate = DateTime::createFromFormat($formatDate . '|', $params['from']);
                 $toDate = DateTime::createFromFormat($formatDate . '|', $params['to']);
             }
         } else {
             $fromDate = null;
             $toDate = null;
         }
         $post = $dao->getPosts($author, $fromDate, $toDate);
         $postResponse = ["posts" => $post, "count" => count($post)];
         $response->getBody()->write(json_encode($postResponse, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE));
         $response = $response->withHeader('Content-type', 'application/json');
         return $response;
     });
     return $app;
 }
Exemplo n.º 6
0
 public function testSetup()
 {
     $app = new \Slim\App();
     $c = $app->getContainer();
     $boot = new \Aimeos\Slim\Bootstrap($app, array('apc_enabled' => true));
     $boot->setup('.');
     $this->assertInstanceOf('\\Aimeos\\Bootstrap', $c['aimeos']);
     $this->assertInstanceOf('\\Aimeos\\Slim\\Base\\Config', $c['aimeos_config']);
     $this->assertInstanceOf('\\Aimeos\\Slim\\Base\\Context', $c['aimeos_context']);
     $this->assertInstanceOf('\\Aimeos\\Slim\\Base\\Locale', $c['aimeos_locale']);
     $this->assertInstanceOf('\\Aimeos\\Slim\\Base\\I18n', $c['aimeos_i18n']);
     $this->assertInstanceOf('\\Aimeos\\Slim\\Base\\Page', $c['aimeos_page']);
     $this->assertInstanceOf('\\Aimeos\\Slim\\Base\\View', $c['aimeos_view']);
     $this->assertInstanceOf('\\Swift_Mailer', $c['mailer']);
 }
Exemplo n.º 7
0
 public function call($method, $path, $params = array(), $body = '')
 {
     $app = new \Slim\App(array('settings' => array('determineRouteBeforeAppMiddleware' => true)));
     $settings = array('disableSites' => false, 'routes' => array('admin' => '/{site}/admin', 'account' => '/{site}', 'default' => '/{site}', 'confirm' => '/{site}', 'update' => '/{site}'));
     $boot = new \Aimeos\Slim\Bootstrap($app, $settings);
     $boot->setup(dirname(__DIR__) . '/ext')->routes(dirname(__DIR__) . '/src/aimeos-routes.php');
     $c = $app->getContainer();
     $env = \Slim\Http\Environment::mock(array('REQUEST_METHOD' => $method, 'REQUEST_URI' => $path, 'QUERY_STRING' => http_build_query($params)));
     $c['request'] = \Slim\Http\Request::createFromEnvironment($env);
     $c['request']->getBody()->write($body);
     $c['response'] = new \Slim\Http\Response();
     $twigconf = array('cache' => sys_get_temp_dir() . '/aimeos-slim-twig-cache');
     $c['view'] = new \Slim\Views\Twig(dirname(__DIR__) . '/templates', $twigconf);
     $c['view']->addExtension(new \Slim\Views\TwigExtension($c['router'], $c['request']->getUri()));
     return $app->run(true);
 }
Exemplo n.º 8
0
 public function setUp()
 {
     // =========================
     // Instantiate the app and container
     $settings = (require APPLICATION_PATH . '/config/global.php');
     $this->app = $app = new \Slim\App($settings);
     $this->container = $app->getContainer();
     // =========================
     // Set up dependencies
     require APPLICATION_PATH . '/dependencies.php';
     // =========================
     // Create test stubs
     // In some cases, where services have become "frozen", we need to define
     // mocks before they are loaded
     //  auth service
     $authMock = $this->getMockBuilder('Wordup\\Auth\\Auth')->disableOriginalConstructor()->getMock();
     $this->container['auth'] = $authMock;
     // =========================
     // Register middleware
     require APPLICATION_PATH . '/middleware.php';
     // =========================
     // Register routes
     require APPLICATION_PATH . '/routes.php';
     $this->app = $app;
     // =========================
     // Init mongo
     Connection::getInstance()->init($settings['mongo_testing']);
     // =========================
     // create fixtures
     $this->adminUser = new User(array('first_name' => 'Martyn', 'last_name' => 'Bissett', 'email' => '*****@*****.**', 'password' => 'mypass'));
     $this->adminUser->role = User::ROLE_ADMIN;
     $this->adminUser->save();
     $this->editorUser = new User(array('first_name' => 'Neil', 'last_name' => 'McInness', 'email' => '*****@*****.**', 'password' => 'mypass'));
     $this->editorUser->role = User::ROLE_EDITOR;
     $this->editorUser->save();
     $this->ownerUser = new User(array('first_name' => 'Louise', 'last_name' => 'McInness', 'email' => '*****@*****.**', 'password' => 'mypass'));
     $this->ownerUser->role = User::ROLE_MEMBER;
     $this->ownerUser->save();
     $this->randomUser = new User(array('first_name' => 'Moses', 'last_name' => 'Cat', 'email' => '*****@*****.**', 'password' => 'mypass'));
     $this->randomUser->role = User::ROLE_MEMBER;
     $this->randomUser->save();
     $this->article = new Article(array('title' => 'A long time ago in a galaxy far far away...', 'description' => '...'));
     $this->article->author = $this->ownerUser;
     $this->article->save();
     $this->tag = new Tag(array('name' => 'Travel', 'slug' => 'travel'));
     $this->tag->save();
 }
Exemplo n.º 9
0
 /**
  * Executes the command
  *
  * @param array $argv Associative array from $_SERVER['argv']
  */
 public static function run(array $argv)
 {
     array_shift($argv);
     $options = self::getOptions($argv);
     if (($jobs = array_shift($argv)) === null) {
         throw new \Aimeos\Slim\Command\Exception();
     }
     $sites = array_shift($argv);
     $config = self::getConfig($options);
     $app = new \Slim\App($config);
     $aimeos = new \Aimeos\Slim\Bootstrap($app, $config);
     $aimeos->setup(isset($options['extdir']) ? $options['extdir'] : './ext')->routes(isset($options['routes']) ? $options['routes'] : './src/aimeos-routes.php');
     $container = $app->getContainer();
     $context = self::getContext($container);
     $siteItems = self::getSiteItems($context, $sites);
     self::execute($container->get('aimeos'), $context, $siteItems, $jobs);
 }
Exemplo n.º 10
0
 /**
  * This general method provide impelemenatation classes two oportunities to break the middleware 
  * chain by returning a value from runBeforeNext() or runAfterNext(). 
  * If any of these functions return a value other than null, that value will be returned by the __invoke() itself.
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
 {
     $this->request = $request;
     $this->response = $response;
     $this->slim = \Chubby\AppFactory::getApp()->getSlim();
     $this->container = $this->slim->getContainer();
     $returned = $this->runBeforeNext();
     if ($returned instanceof ResponseInterface) {
         return $returned;
     }
     $this->response = $next($this->request, $this->response);
     $returned = $this->runAfterNext();
     if ($returned instanceof ResponseInterface) {
         return $returned;
     }
     return $this->response;
 }
Exemplo n.º 11
0
 /**
  * @covers mbarquin\SlimDR\Factory::slim
  * @todo   Implement testSlim().
  */
 public function testSlimAcceptsSlimAlreadySetted()
 {
     $slim = new \Slim\App();
     $slim->group('/users', function () {
         $this->get('/reset-password', function ($request, $response, $args) {
             // Code here.
         })->setName('user-password-reset');
     });
     $oFact = Factory::slim($slim);
     $slimProcessed = $oFact->withGroup('admin')->getApp();
     $container = $slimProcessed->getContainer();
     $routes = $container->get('router')->getRoutes();
     $rout = array_values($routes);
     $group = $rout[0]->getGroups();
     $group2 = $rout[1]->getGroups();
     $this->assertAttributeContains('/users', 'pattern', $group[0]);
     $this->assertAttributeContains('/admin', 'pattern', $group2[0]);
 }
Exemplo n.º 12
0
 public static function instance()
 {
     if (self::$slim === null) {
         $configuration = ['settings' => ['displayErrorDetails' => true]];
         $c = new \Slim\Container($configuration);
         $app = new \Slim\App($c);
         $container = $app->getContainer();
         $container['view'] = function ($c) {
             $view = new \Slim\Views\Twig(DOCROOT . 'app/views', []);
             $view->addExtension(new \Slim\Views\TwigExtension($c['router'], $c['request']->getUri()));
             return $view;
         };
         $container['flash'] = function () {
             return new \Slim\Flash\Messages();
         };
         self::$slim = $app;
     }
     return self::$slim;
 }
Exemplo n.º 13
0
 public function getSlimInstance()
 {
     // Prepare a mock environment
     // Instantiate the app
     $settings = (require __DIR__ . '/../src/settings.php');
     $app = new \Slim\App($settings);
     // Set up dependencies
     require __DIR__ . '/../src/dependencies.php';
     $pdo = new PDO('sqlite::memory:');
     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $logger = $app->getContainer()['logger'];
     $db = new DBConnection($pdo, $logger);
     $app->upload = new UploadProcessor($db, $logger);
     $app->dir = new DirectoryHelper($settings['upload'], $logger);
     $app->data = new DataProcessor($db, $logger);
     $app->helper = new RoutesHelper($logger);
     // Routes
     require __DIR__ . '/../src/routes.php';
     return $app;
 }
Exemplo n.º 14
0
 public function testGetSections()
 {
     $app = new \Slim\App(array());
     $basedir = dirname(dirname(__DIR__));
     $settings = (require $basedir . '/src/aimeos-default.php');
     $settings['page']['test'] = array('catalog/filter', 'basket/mini');
     $settings['disableSites'] = false;
     $boot = new \Aimeos\Slim\Bootstrap($app, $settings);
     $boot->setup($basedir . '/ext')->routes($basedir . '/src/aimeos-routes.php');
     $response = new \Slim\Http\Response();
     $request = \Slim\Http\Request::createFromEnvironment(\Slim\Http\Environment::mock());
     $object = new \Aimeos\Slim\Base\Page($app->getContainer());
     $result = $object->getSections('test', $request, $response, array('site' => 'unittest'));
     $this->assertArrayHasKey('aiheader', $result);
     $this->assertArrayHasKey('aibody', $result);
     $this->assertArrayHasKey('catalog/filter', $result['aibody']);
     $this->assertArrayHasKey('catalog/filter', $result['aiheader']);
     $this->assertArrayHasKey('basket/mini', $result['aibody']);
     $this->assertArrayHasKey('basket/mini', $result['aiheader']);
 }
Exemplo n.º 15
0
 function run()
 {
     $config = parse_ini_file('../.config');
     $this->setUpDb();
     $showErrors = isset($config['showErrors']) ? $config['showErrors'] : false;
     $configuration = ['settings' => ['displayErrorDetails' => $showErrors]];
     $c = new \Slim\Container($configuration);
     // create new Slim instance
     $app = new \Slim\App($c);
     // create new Slim instance
     //$app = new \Slim\App();
     $app->db = $this->database;
     $this->flashDB(false);
     $app->auth = false;
     $app->user = '';
     $app->register = $config['registerActive'];
     $app->add(function ($request, $response, $next) use(&$app) {
         if (isset($_SESSION['userID'])) {
             $app->auth = true;
             $app->user = $_SESSION['username'];
         }
         $response = $next($request, $response);
         return $response;
     });
     $container = $app->getContainer();
     $container['view'] = function ($c) {
         // templates location and a settings array
         $view = new \Slim\Views\Twig('../templates', ['cache' => '../cache', 'auto_reload' => true, 'debug' => true]);
         // Instantiate and add Slim specific extension
         $view->addExtension(new Slim\Views\TwigExtension($c['router'], $c['request']->getUri()));
         return $view;
     };
     $route = new Routes($app);
     $app = $route->run($app);
     $this->app = $app;
     // Run app
     $this->app->run();
 }
Exemplo n.º 16
0
 public function request($method, $path, $data, $headers = [])
 {
     // Capture STDOUT
     ob_start();
     // Prepare a mock environment
     $options = ['REQUEST_METHOD' => $method, 'SERVER_PORT' => '8000', 'REQUEST_URI' => $path, 'SERVER_NAME' => 'localhost'];
     foreach ($headers as $key => $value) {
         $options['HTTP_' . $key] = $value;
     }
     $env = Environment::mock($options);
     $request = TestRequest::createFromEnvironment($env, $data);
     $container = new \Slim\Container(["environment" => $env, "request" => $request]);
     // Run the application
     // this creates an Slim $app
     $app = new \Slim\App($container);
     require __DIR__ . '/../app/app.php';
     $this->app = $app;
     $this->request = $app->getContainer()->get("request");
     // We fire the routes
     $this->response = $this->app->run();
     // Return STDOUT
     return ob_get_clean();
 }
Exemplo n.º 17
0
 public function run()
 {
     $configuration = ['settings' => ['displayErrorDetails' => false]];
     $c = new \Slim\Container($configuration);
     $c['notFoundHandler'] = function ($c) {
         return function ($request, $response) use($c) {
             return $c['response']->withStatus(404)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'not_found', 'pretty_error' => 'Could not find the specified endpoint.'), JSON_PRETTY_PRINT));
         };
     };
     $c['errorHandler'] = function ($c) {
         return function ($request, $response) use($c) {
             return $c['response']->withStatus(500)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'internal_error', 'pretty_error' => 'An internal error has occured, please contact the site administrator.'), JSON_PRETTY_PRINT));
         };
     };
     $app = new \Slim\App($c);
     $app->add(new AuthenticationMiddleware());
     $app->get('/oauth/v2/authorize', 'PleioRest\\Controllers\\Authentication::authorize');
     $app->post('/oauth/v2/token', 'PleioRest\\Controllers\\Authentication::getToken');
     $app->get('/api/users/me', 'PleioRest\\Controllers\\User:me');
     $app->post('/api/users/me/register_push', 'PleioRest\\Controllers\\User:registerPush');
     $app->post('/api/users/me/deregister_push', 'PleioRest\\Controllers\\User:deregisterPush');
     $app->post('/api/users/me/generate_token', 'PleioRest\\Controllers\\User:generateToken');
     $app->get('/api/users/me/login_token', 'PleioRest\\Controllers\\User:loginToken');
     $app->get('/api', 'PleioRest\\Controllers\\Version:getVersion');
     $app->get('/api/doc', 'PleioRest\\Controllers\\Documentation:getDocumentation');
     $app->get('/api/doc/swagger', 'PleioRest\\Controllers\\Documentation:getSwagger');
     $app->get('/api/sites', 'PleioRest\\Controllers\\Sites:getAll');
     $app->get('/api/sites/mine', 'PleioRest\\Controllers\\Sites:getMine');
     $app->get('/api/groups', 'PleioRest\\Controllers\\Groups:getAll');
     $app->get('/api/groups/mine', 'PleioRest\\Controllers\\Groups:getMine');
     $app->get('/api/groups/{guid}/activities', 'PleioRest\\Controllers\\Activities:getGroup');
     $app->post('/api/groups/{guid}/activities/mark_read', 'PleioRest\\Controllers\\Activities:markRead');
     $app->get('/api/groups/{guid}/events', 'PleioRest\\Controllers\\Events:getGroup');
     $app->get('/api/groups/{guid}/members', 'PleioRest\\Controllers\\Members:getGroup');
     $app->get('/api/groups/{guid}/files', 'PleioRest\\Controllers\\Files:getGroup');
     $app->run();
 }
Exemplo n.º 18
0
<?php

require 'vendor/autoload.php';
require 'config/env.php';
require 'config/mysql.php';
require 'config/redis.php';
// Create Slim app
$app = new \Slim\App(['settings' => ['debug' => true]]);
// Add whoops to slim because its helps debuggin' and is pretty.
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware());
// Fetch DI Container
$container = $app->getContainer();
// Instantiate and add Slim specific extension
$view = new \Slim\Views\Twig(__DIR__ . '/views', ['cache' => $container->get('settings')['debug'] ? false : __DIR__ . '/cache']);
$view->addExtension(new Slim\Views\TwigExtension($container->get('router'), $container->get('request')->getUri()));
// Register Twig View helper
$container->register($view);
// Write some default variables available to every template
$view->offsetSet('realtime_url', $environment['REALTIME_URL']);
$view->offsetSet('current_watts', is_numeric($redis->get('owlintuition.watts')) ? $redis->get('owlintuition.watts') : '???');
$app->get('/', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    header("Location: /redis");
    exit;
});
$app->get('/redis', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    global $redis;
    $keys = $redis->keys('*');
    $redisKeys = [];
    foreach ($keys as $key) {
        $redisKeys[$key] = ['key' => $key, 'value' => $redis->get($key)];
    }
Exemplo n.º 19
0
};
$container['db'] = function ($c) {
    $dsn = 'mysql:dbname=' . $_ENV['DB_NAME'] . ';host=' . $_ENV['DB_HOST'];
    return new \PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS']);
};
$container['flash'] = function () {
    return new \Slim\Flash\Messages();
};
// Make the session instance
$container['session'] = function () {
    $data = array();
    $sessionFactory = new \Aura\Session\SessionFactory();
    return $sessionFactory->newInstance($data);
};
$container['errorHandler'] = function ($c) {
    return function ($request, $response, $ex) use($c) {
        echo $c['view']->render($response, 'error/index.twig', ['message' => $ex->getMessage()]);
        return $c['response'];
    };
};
//----------------------
$app = new \Slim\App($container);
$app->add(new \Conftrack\Middleware\Auth($container));
// Load the controllers
$dir = new DirectoryIterator(APP_PATH . '/' . APP_NAMESPACE . '/Controller');
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        require_once $fileinfo->getPathname();
    }
}
$app->run();
Exemplo n.º 20
0
<?php

session_start();
require_once 'vendor/autoload.php';
require_once './eagle/database/Connection.php';
$c = new \Slim\Container(include './eagle/config/config.php');
$app = new \Slim\App($c);
$container = $app->getContainer();
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig('./eagle/templates');
    $view->addExtension(new \Slim\Views\TwigExtension($container['router'], $container['request']->getUri()));
    return $view;
};
new Connection();
ini_set('max_execution_time', 60);
require_once './eagle/routes/team.routes.php';
require_once './eagle/routes/event.routes.php';
require_once './eagle/routes/comment.routes.php';
require_once './eagle/routes/scouting.routes.php';
require_once './eagle/routes/base.routes.php';
$app->run();
Exemplo n.º 21
0
*
* @author: Samuel Adeshina <*****@*****.**> <>
* @package KarabowId\Api\
* @since: 1/2/2016.
* @license: 
* @version 0.1
*/
# IMPORT
require __DIR__ . "/vendor/autoload.php";
use KarabowId\Api\Orm\OrmManager;
use KarabowId\Api\ParamHandler;
use KarabowId\Api\Messages;
# SETUP
$configuration = ['settings' => ['displayErrorDetails' => true]];
$config = new \Slim\Container($configuration);
$app = new Slim\App($config);
$ormManager = new OrmManager();
$app->any("/", function ($request, $response, $args) {
    $reponse->getBody()->write("No Request Made. Should we throw an exception? or just tell the user to go learn how to consume this api?");
});
# CREATE NEW USER
$app->post("/user/new", function ($request, $response, $args) use($app) {
    return $response;
});
# GET USER INFO
$app->get("/user", function ($request, $response, $args) use($app) {
    return $response;
});
# MODIFY USER INFO
$app->put("/user/edit", function ($request, $response, $args) use($app) {
    return $response;
Exemplo n.º 22
0
<?php

require_once '../vendor/autoload.php';
$config = ['settings' => ['addContentLengthHeader' => false]];
$app = new \Slim\App($config);
// Define app routes
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->write("Hello " . $args['name']);
});
$app->get('/samplejson', function () {
    $json = (array) simplexml_load_file('http://shoggoth.net/?feed=rss2');
    return json_encode($json);
});
$app->get('/info', function () {
    phpinfo();
    return null;
});
$app->get('/', function () {
    return file_get_contents('../templates/index.html');
});
// Run app
$app->run();
Exemplo n.º 23
0
<?php

require 'vendor/autoload.php';
include_once 'db/dbConnect.php';
include_once 'functions/getters.php';
include_once 'functions/dataHandler.php';
$app = new \Slim\App();
// Default -> redirect on selection page
$app->get("/", function ($request, $response, $args) {
    return $response->withStatus(200)->withHeader('Location', 'rest.php');
});
// select one country, using it's id
$app->get("/country/{id}/", function ($request, $response, $args) use($link) {
    $country = getId($args['id'], 'countries');
    if ($country) {
        return $response->withJson(array("status" => 1, "Id" => $country['id'], "Name" => $country['name']));
    } else {
        $response->withJson(array("status" => 0, "message" => "Country Id {$args['id']} does not exists"));
    }
});
// select one city, using it's id
$app->get("/city/{id}/", function ($request, $response, $args) use($link) {
    $city = getId($args['id'], 'cities');
    if ($city) {
        return $response->withJson(array("status" => 0, "Id" => $city['id'], "Name" => $city['name']));
    } else {
        $response->withJson(array("status" => 1, "message" => "City Id {$args['id']} does not exists"));
    }
});
// select one language, using it's id
$app->get("/language/{id}/", function ($request, $response, $args) use($link) {
Exemplo n.º 24
0
<?php

require __DIR__ . "/vendor/autoload.php";
use App\Todo;
use App\TodoTransformer;
use League\Fractal\Manager;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\Collection;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Serializer\DataArraySerializer;
date_default_timezone_set("UTC");
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$app = new Slim\App(["settings" => ["displayErrorDetails" => true]]);
require __DIR__ . "/config/logger.php";
require __DIR__ . "/config/database.php";
$app->add(new \Tuupola\Middleware\Cors(["origin" => "*", "methods" => ["GET", "POST", "PATCH", "DELETE"], "headers.allow" => ["Content-Type", "Accept"], "credentials" => true, "cache" => 86400]));
$app->get("/", function ($request, $response, $arguments) {
    return $response->withStatus(301)->withHeader("Location", "/todos");
});
$app->get("/todos", function ($request, $response, $arguments) {
    $todos = $this->spot->mapper("App\\Todo")->all();
    $fractal = new Manager();
    $fractal->setSerializer(new ArraySerializer());
    $resource = new Collection($todos, new TodoTransformer());
    $data = $fractal->createData($resource)->toArray();
    /* Fractal collections are always namespaced. Apparently a feature and */
    /* not a bug. Thus we need to return $data["data"] for TodoMVC examples. */
    /* https://github.com/thephpleague/fractal/issues/110 */
    return $response->withStatus(200)->withHeader("Content-Type", "application/json")->write(json_encode($data["data"], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
Exemplo n.º 25
0
<?php

$container = (require 'Container.php');
$app = new \Slim\App($container);
$app->group('/api/v1', function () use($app) {
    $app->any('/data/{table}[/{id}]', function ($req, $res, $args) {
        $middleware = $this->get('retrieveData');
        return $middleware($req, $res);
    })->add('parser');
});
$app->run();
<?php

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write("Page d'accueil");
    return $response;
});
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, {$name}");
    return $response;
});
$app->run();
<?php

require '../vendor/autoload.php';
require 'bootEloquent.php';
use Slim\Views\PhpRenderer;
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
$container = $app->getContainer();
$container['view'] = new PhpRenderer(__DIR__ . '/../views/');
$app->get('/', function ($request, $response, $args) {
    return $this->view->render($response, 'hello.php', ['pessoas' => Pessoa::all()]);
});
$app->post('/pessoas', function ($request, $response, $args) {
    $pessoa = new Pessoa();
    $pessoa->nome = $request->getParam('nome');
    $pessoa->save();
    return $response->withRedirect('/');
});
$app->run();
Exemplo n.º 28
0
/**
 * Created by PhpStorm.
 * User: Benjaco
 * Date: 12-01-2016
 * Time: 16:36
 */
require "../../vendor/autoload.php";
$c = new \Slim\Container();
//Create Your container
//Override the default Not Found Handler
$c['notFoundHandler'] = function ($c) {
    return function ($request, $response) use($c) {
        return $c['response']->withStatus(404)->withHeader('Content-Type', 'text/json')->write('{"status":404}');
    };
};
$app = new \Slim\App($c);
$app->group('/discussion', function () {
    include "../../requirements/sqli.php";
    $sqli = new sqli(array("127.0.0.1", "", "", "test"));
    $this->get('', function ($request, $response, $args) use($sqli) {
        echo json_encode($sqli->pull_multiple("select * from diskotioner")->data);
    });
    $this->post('', function ($request, $response, $args) use($sqli) {
        if (isset($_POST['title'])) {
            $insert = $sqli->push("insert into diskotioner (title) VALUES (?)", "s", $_POST['title']);
            if ($insert->affected_rows == 1) {
                return $response->withStatus(201)->write($insert->insert_id);
            }
            return $response->withStatus(400);
        }
        return $response->withStatus(400);
Exemplo n.º 29
0
<?php

/**
 * Created by Paris on 21-01-16.
 */
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App();
/*
exemple de route slim 
$app->get('/', function (Request $request, Response $response) { 
    $response->getBody()->write("{'nom':'Durand','age':'28'}");

    return $response;
});*/
$app->get('/api/wines', function (Request $request, Response $response) {
    try {
        $db = thisConnection();
        $stmt = $db->query("SELECT* FROM wine ORDER BY name");
        $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
        $response->getBody()->write('{"vins": ' . json_encode($wines) . '}');
    } catch (PDOException $e) {
        $response->getBody()->write('{"error":' . $e->getMessage() . '}');
        die;
    }
    return $response;
});
$app->get('/api/wines/{id}', function (Request $request, Response $response, $args) {
    try {
        $id = $args['id'];
Exemplo n.º 30
0
<?php

/**
 * redports is a continuous integration platform for FreeBSD ports.
 *
 * @author     Bernhard Froehlich <*****@*****.**>
 * @copyright  2015 Bernhard Froehlich
 * @license    BSD License (2 Clause)
 *
 * @link       https://freebsd.github.io/redports/
 */
namespace Redports\Web;

require_once __DIR__ . '/vendor/autoload.php';
$session = new Session();
$app = new \Slim\App(new \Slim\Container(Config::get('slimconfig')));
/* init php-view */
$container = $app->getContainer();
$container['view'] = function ($container) {
    return new \Slim\Views\PhpRenderer(__DIR__ . '/templates/');
};
/* landing page */
$app->get('/', function ($request, $response, $args) use($session) {
    return $this->view->render($response, 'index.html', $args);
});
/* GitHub OAuth login */
$app->get('/login', function ($request, $response) use($session) {
    $credentials = new \OAuth\Common\Consumer\Credentials(Config::get('github.oauth.key'), Config::get('github.oauth.secret'), Config::get('github.oauth.redirecturl'));
    $serviceFactory = new \OAuth\ServiceFactory();
    $gitHub = $serviceFactory->createService('GitHub', $credentials, new \OAuth\Common\Storage\Session(), array('user:email', 'public_repo', 'repo:status', 'admin:repo_hook'));
    $queryParams = $request->getQueryParams();