/**
  * 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();
 }
Esempio n. 2
0
 /**
  * Inicia a configuração do Systema
  */
 public static function configure()
 {
     include_once __DIR__ . '/wow/Loader.php';
     wow\Loader::load();
     self::definePathConstants();
     self::$slimObj = new Slim\App();
     unset(self::$slimObj->getContainer()['errorHandler']);
     include_once wow\Storange::getPathFile(\wow\Config::get('path')->configfile);
     self::connectDb();
 }
Esempio n. 3
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;
 }
Esempio 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;
 }
Esempio n. 5
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']);
 }
Esempio n. 6
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);
 }
Esempio n. 7
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();
 }
Esempio n. 8
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);
 }
Esempio n. 9
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;
 }
Esempio n. 10
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;
 }
Esempio n. 11
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']);
 }
Esempio n. 12
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();
 }
Esempio n. 13
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();
 }
Esempio n. 14
0
 protected function getSlimTest(string $method, string $url, array $headers = []) : ResponseInterface
 {
     $slim = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
     // add the CORs middleware
     $cors = $this->getCors($slim->getContainer());
     $slim->add($cors);
     // finish adding the CORs middleware
     // add our own error handler.
     $errorHandler = function (ContainerInterface $container) : callable {
         $handler = function (ServerRequestInterface $request, ResponseInterface $response, \Exception $e) : ResponseInterface {
             $body = new Body(fopen('php://temp', 'r+'));
             $body->write('Error Handler caught exception type ' . get_class($e) . ': ' . $e->getMessage());
             $return = $response->withStatus(500)->withBody($body);
             return $return;
         };
         return $handler;
     };
     // add the error handler.
     $slim->getContainer()['errorHandler'] = $errorHandler;
     // add dummy routes
     $slim->get('/foo', function (Request $req, Response $res) {
         $res->write('getted hi');
         return $res;
     });
     $slim->post('/foo', function (Request $req, Response $res) {
         $res->write('postted hi');
         return $res;
     });
     // Prepare request and response objects
     $uri = Uri::createFromString($url);
     $slimHeaders = new Headers($headers);
     $body = new RequestBody();
     $request = new Request($method, $uri, $slimHeaders, [], [], $body);
     $response = new Response();
     // override the Slim request and responses with our dummies
     $slim->getContainer()['request'] = $request;
     $slim->getContainer()['response'] = $response;
     // invoke Slim
     /* @var \Slim\Http\Response $result */
     $result = $slim->run(true);
     // check we got back what we expected
     $this->assertInstanceOf('\\Psr\\Http\\Message\\ResponseInterface', $result);
     $this->assertInstanceOf('\\Slim\\Http\\Response', $result);
     return $result;
 }
<?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();
Esempio n. 16
0
<?php

require __DIR__ . '/../c3.php';
require_once __DIR__ . '/../vendor/autoload.php';
$config = (require __DIR__ . '/../config.php');
$settings = (require __DIR__ . '/../src/settings.php');
$app = new \Slim\App($settings);
/* Inject our own Response object. */
$app->getContainer()['response'] = function ($container) {
    return new \Gsandbox\Response(200);
};
require __DIR__ . '/../src/routes.php';
$app->run();
Esempio n. 17
0
<?php

use App\Exception\StatusException;
use App\Helper\ResponseDataFormatter;
use App\Resource\AbstractResource;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Http\Response;
require_once __DIR__ . '/vendor/autoload.php';
$app = new Slim\App(include __DIR__ . '/config/settings.php');
(new \App\Configurator())->loadDependencyDefaults($app->getContainer());
$app->getContainer()->get('logger');
// Get
$app->get('/{resource}[/{id}]', function (ServerRequestInterface $request, Response $response, $resource, $id = null) {
    /**
     * @var ResponseDataFormatter $formatter
     */
    $formatter = $this->get('dataFormatter');
    try {
        $resource = AbstractResource::load($resource, $request, $response, $this);
        return $response->withJson($formatter->getSuccess($resource->get($id)));
    } catch (StatusException $e) {
        return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode());
    } catch (Exception $e) {
        return $response->withStatus(500);
    }
});
// Post
$app->post('/{resource}', function (ServerRequestInterface $request, Response $response, $resource) {
    /**
     * @var ResponseDataFormatter $formatter
     */
Esempio n. 18
0
<?php

// All file paths relative to root
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
session_start();
if (file_exists('app/settings.php')) {
    $settings = (require 'app/settings.php');
} else {
    $settings = (require 'app/settings.php.dist');
}
// Instantiate Slim
$app = new \Slim\App($settings);
require 'app/src/dependencies.php';
require 'app/src/middleware.php';
// Register the routes
require 'app/src/routes.php';
// Register the database connection with Eloquent
$capsule = $app->getContainer()->get('capsule');
$capsule->bootEloquent();
$app->run();
Esempio n. 19
0
<?php

// All file paths relative to root
// chdir(dirname(__DIR__));
if (!defined('LAYOUT')) {
    define('LAYOUT', 'layout.twig');
}
if (!defined('CACHEROOT')) {
    define('CACHEROOT', getenv('TEMP'));
}
if (!defined('CONFROOT')) {
    define('CONFROOT', DOCROOT . '/app/Bookshelf/Conf/');
}
require DOCROOT . '/vendor/autoload.php';
session_start();
if (file_exists(CONFROOT . 'settings.php')) {
    $settings = (require CONFROOT . 'settings.php');
} else {
    $settings = (require CONFROOT . 'settings.php.dist');
}
// Instantiate Slim
$app = new \Slim\App($settings);
require CONFROOT . 'dependencies.php';
require CONFROOT . 'middleware.php';
// Register the routes
require CONFROOT . 'routes.php';
// Register the database connection with PdoLite
$pdolite = $app->getContainer()->get('pdolite');
$app->run();
Esempio n. 20
0
require_once ROOT_PATH . 'vendor/autoload.php';
function getJavascriptTemplates()
{
    $templateDirectory = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR;
    $result = array();
    if (file_exists($templateDirectory)) {
        foreach (scandir($templateDirectory) as $file) {
            if ($file != '.' && $file != '..') {
                array_push($result, array('name' => basename($file, '.jade'), 'content' => file_get_contents($templateDirectory . $file)));
            }
        }
    }
    return $result;
}
$app = new \Slim\App(array('settings' => array('view' => array('template_path' => TEMPLATE_PATH, 'twig' => array('cache' => CACHE_PATH, 'auto_reload' => true)))));
$app->getContainer()['view'] = function ($c) {
    $settings = $c->get('settings');
    $view = new \Slim\Views\Twig($settings['view']['template_path'], $settings['view']['twig']);
    $view->addExtension(new Slim\Views\TwigExtension($c->get('router'), $c->get('request')->getUri()));
    $view->addExtension(new Twig_Extension_Debug());
    return $view;
};
$routePath = ROOT_PATH . 'routes' . DIRECTORY_SEPARATOR;
$helperPath = ROOT_PATH . 'helper' . DIRECTORY_SEPARATOR;
$interfacePath = ROOT_PATH . 'interface' . DIRECTORY_SEPARATOR;
$prototypePath = ROOT_PATH . 'prototype' . DIRECTORY_SEPARATOR;
$controllerPath = ROOT_PATH . 'controller' . DIRECTORY_SEPARATOR;
foreach (scandir($interfacePath) as $file) {
    if ($file != '.' && $file != '..') {
        include_once $interfacePath . $file;
    }
Esempio n. 21
0
/**
 * Echoing json response to client
 * @param String $status_code Http response code
 * @param Int $response Json response
 */
function setResponse($status_code = 200, $message = array())
{
    // App
    $app = new \Slim\App();
    // Register with container
    $container = $app->getContainer();
    $response = $container->get('response');
    // Http Status - ContentType
    $response->withStatus($status_code)->withHeader('Content-Type', 'application/json');
    echo json_encode($message);
    exit;
}
Esempio n. 22
0
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$app['config'] = function (Container $c) {
    $fp = $c['fileParser'];
    // Populate Config wrapper
    $config = new Config($fp->read(_CONFIG_ . 'system.yml'));
    // Load user config
    // Append user config to Config wrapper (override if exists)
    $userConfig = $fp->read(_CONFIG_ . $config->get('userConfig'));
    $config->append((array) $userConfig);
    return $config;
};
$app['router'] = function (Container $c) {
    $slimConf = ['settings' => ['displayErrorDetails' => $c['config']->get('debug', false)], 'api' => new Parvula\Router\APIRender(), 'logger' => $c['loggerHandler']];
    $router = new Slim\App($slimConf);
    $container = $router->getContainer();
    $router->add(new \Slim\Middleware\JwtAuthentication(['path' => '/api', 'secure' => !$c['config']->get('debug', false), 'passthrough' => ['/api/0/login', '/api/0/public'], 'rules' => [function ($arr) {
        $path = trim($arr->getUri()->getPath(), '/');
        if ($arr->isGet() && preg_match('~^api/0/pages~', $path)) {
            return false;
        }
    }], 'secret' => $c['config']->get('secretToken'), 'callback' => function ($request, $response, $arguments) use($container) {
        $container['token'] = $arguments['decoded'];
    }]));
    // Remove Slim handler, we want to use our own
    unset($router->getContainer()['errorHandler']);
    return $router;
};
// Log errors in _LOG_ folder
$app['loggerHandler'] = function ($c) {
    if (class_exists('\\Monolog\\Logger')) {
<?php

require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App();
$app->get('/', new Acme\Action\DefaultAction($app->getContainer()));
$app->run();
Esempio n. 24
0
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/cloud.php';
/*
 * A simple Slim based sample application
 *
 * See Slim documentation:
 * http://www.slimframework.com/docs/
 */
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use LeanCloud\LeanClient;
use LeanCloud\Storage\CookieStorage;
use LeanCloud\Engine\SlimEngine;
$app = new \Slim\App();
// 禁用 Slim 默认的 handler,使得错误栈被日志捕捉
unset($app->getContainer()['errorHandler']);
LeanClient::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY"));
// 将 sessionToken 持久化到 cookie 中,以支持多实例共享会话
LeanClient::setStorage(new CookieStorage());
SlimEngine::enableHttpsRedirect();
$app->add(new SlimEngine());
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, {$name}");
    return $response;
});
// compute a random integer between min and max
$app->post('/randomInt', function (Request $request, Response $response) {
    // parse min and max from request body
    $body = $request->getBody();
    $json = json_decode($body, true);