Пример #1
0
 /**
  * Constructor
  */
 public function __construct()
 {
     if (empty($this->_configPath)) {
         $class = new \ReflectionClass($this);
         throw new \Engine\Exception('Application has no config path: ' . $class->getFileName());
     }
     $loader = new \Phalcon\Loader();
     $loader->registerNamespaces(['Engine' => ROOT_PATH . '/engine']);
     $loader->register();
     // create default di
     $di = new \Phalcon\DI\FactoryDefault();
     // get config
     $this->_config = (include_once ROOT_PATH . $this->_configPath);
     // Store config in the Di container
     $di->setShared('config', $this->_config);
     parent::__construct($di);
 }
Пример #2
0
 public function setup()
 {
     static::$config = (require __DIR__ . '/../config.php');
     // append biller conf
     static::$config['biller'] = ['key' => self::API_KEY, 'custom_id' => 'id', 'custom_email' => 'email'];
     $di = new \Phalcon\DI\FactoryDefault();
     $di->set('config', static::$config);
     $di->set('db', function () {
         return new \Phalcon\Db\Adapter\Pdo\Mysql(array('host' => '127.0.0.1', 'username' => 'root', 'password' => '', 'dbname' => 'biller_tests', 'charset' => 'utf8'));
     });
     // Session manager
     $di->setShared('session', function () {
         $session = new \Phalcon\Session\Adapter\Files();
         $session->start();
         return $session;
     });
     self::authorize();
     static::$mock = new \Tests\User();
 }
Пример #3
0
 $loader = new \Phalcon\Loader();
 $loader->registerDirs(array('../app/controllers/', '../app/models/', '../app/forms/', '../app/views/', '../app/plugins/', '../app/validators/', '../app/wrappers/'));
 $loader->registerNamespaces(array('Sigmamovil\\Misc' => '../app/misc/'), true);
 $loader->register();
 //Create a DI
 $di = new Phalcon\DI\FactoryDefault();
 //Registering Volt as template engine
 $di->set('view', function () {
     $view = new \Phalcon\Mvc\View();
     $view->setViewsDir('../app/views/');
     $view->registerEngines(array(".volt" => 'volt'));
     return $view;
 });
 $di->setShared('volt', function ($view, $di) {
     $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
     $volt->setOptions(array("compileAlways" => true, "compiledPath" => "../app/compiled-templates/", 'stat' => true));
     $compiler = $volt->getCompiler();
     return $volt;
 });
 $di->set('logger', function () {
     // Archivo de log
     return new \Phalcon\Logger\Adapter\File("../app/logs/debug.log");
 });
 $urlManager = new \Sigmamovil\Misc\UrlManager($config);
 $di->set('urlManager', $urlManager);
 //Setup a base URI so that all generated URIs include the "tutorial" folder
 $di->set('url', function () use($urlManager) {
     $url = new \Phalcon\Mvc\Url();
     $uri = $urlManager->get_base_uri();
     // Adicionar / al inicio y al final
     if (substr($uri, 0, 1) != '/') {
         $uri = '/' . $uri;
Пример #4
0
 public function testCallActionMethod()
 {
     $di = new \Phalcon\DI\FactoryDefault();
     $dispatcher = new \Phalcon\Mvc\Dispatcher();
     $di->setShared("dispatcher", $dispatcher);
     $dispatcher->setDI($di);
     $mainTask = new Test2Controller();
     $mainTask->setDI($di);
     $this->assertEquals($dispatcher->callActionMethod($mainTask, 'anotherTwoAction', [1, 2]), 3);
 }
Пример #5
0
try {
    //    $debug = new \Phalcon\Debug();
    // $debug->listen();
    //Register an autoloader
    //   $loader = new \Phalcon\Loader();
    //   $loader->registerDirs(array(
    //       $config->application->controllersDir,
    // $config->application->pluginsDir,
    // $config->application->libraryDir,
    //       $config->application->modelsDir,
    //   ))->register();
    //Create a DI
    $di = new Phalcon\DI\FactoryDefault();
    //Set the database service
    $di->setShared('db', function () use($config) {
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname));
    });
    // register config
    $di->set('config', function () use($config) {
        return $config;
    });
    // some constants
    $di->set('consts', function () use($consts) {
        return $consts;
    });
    //Set up the flash service
    $di->set('flashSession', function () {
        return new Phalcon\Flash\Session(array('error' => 'alert alert-danger alert-dismissible', 'success' => 'alert alert-success alert-dismissible', 'notice' => 'alert alert-info alert-dismissible', 'warning' => 'alert alert-warning alert-dismissible'));
    });
    //Registering Volt as template engine
    // $di->set('view', function() {
Пример #6
0
     require APPLICATION_PATH . '/config/routes.php';
     $router->removeExtraSlashes(true);
     return $router;
 });
 $di->set('url', function () use($di) {
     $url = new \Phalcon\Mvc\Url();
     $url->setBaseUri('http://' . $_SERVER['HTTP_HOST'] . '/');
     return $url;
 });
 $di->set('view', function () use($config) {
     $view = new \Phalcon\Mvc\View();
     $view->setViewsDir(APPLICATION_PATH . $config->app->viewsDir);
     return $view;
 });
 $di->setShared('db', function () use($config, $di) {
     $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "charset" => $config->database->charset));
     return $connection;
 });
 $di->set('dispatcher', function () use($di) {
     $dispatcher = new \Phalcon\Mvc\Dispatcher();
     $eventsManager = $di->getShared('eventsManager');
     if (ENVIRONMENT == ENVIRONMENT_PRODUCTION) {
         $eventsManager->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) {
             switch ($exception->getCode()) {
                 case 404:
                 case \Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                 case \Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                     $dispatcher->forward(array("namespace" => 'App\\Controllers', 'controller' => 'error', 'action' => 'notFound'));
                     return false;
                     break;
                 default:
                     $dispatcher->forward(array("namespace" => 'App\\Controllers', 'controller' => 'error', 'action' => 'uncaughtException'));
Пример #7
0
    //     ini_set("log_errors", 1);
    //     error_reporting(E_ALL);
    //     break;
    case DIST_ENV:
        ini_set("display_errors", 0);
        ini_set("log_errors", 1);
        error_reporting(E_ALL);
        break;
    default:
        error_log('Error: The application ENV constant is not set correctly.');
        exit(1);
}
// Create the dependency injector for the Phalcon framework
$di = new Phalcon\DI\FactoryDefault();
$di->setShared('config', function () {
    $config = (require __DIR__ . "/config/config.php");
    return $config;
});
$config = $di->get('config');
if (!file_exists($config->path->tmpDir)) {
    mkdir($config->path->tmpDir);
}
// Setup composer autoloading so that it doesn't need to be specified in each Module
require_once $config->path->composerDir . 'autoload.php';
require $config->path->configDir . 'services.php';
require $config->path->configDir . 'services_web.php';
if (DEV) {
    class_alias('\\Webird\\Debug', '\\Dbg', true);
}
// Handle the request and inject DI
$application = new \Phalcon\Mvc\Application($di);
$application->registerModules(['web' => ['className' => 'Webird\\Web\\Module'], 'admin' => ['className' => 'Webird\\Admin\\Module'], 'api' => ['className' => 'Webird\\Api\\Module']]);
Пример #8
0
 //Registering Volt as template engine
 $di->set('view', function () {
     $view = new \Phalcon\Mvc\View();
     $view->setViewsDir('../app/views/');
     $view->registerEngines(array(".volt" => 'Phalcon\\Mvc\\View\\Engine\\Volt'));
     return $view;
 });
 //Setup a base URI so that all generated URIs include the "tutorial" folder
 $di->set('url', function () {
     $url = new \Phalcon\Mvc\Url();
     $url->setBaseUri('/silar/');
     return $url;
 });
 $di->setShared('session', function () {
     $session = new Phalcon\Session\Adapter\Files();
     $session->start();
     return $session;
 });
 $di->set('router', function () {
     $router = new \Phalcon\Mvc\Router\Annotations();
     $router->addResource('Api', '/api');
     return $router;
 });
 $di->set('db', function () use($config) {
     return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname));
 });
 $di->set('dispatcher', function () use($di) {
     $dispatcher = new Phalcon\Mvc\Dispatcher();
     return $dispatcher;
 });
 $di->set('hash', function () {
Пример #9
0
<?php

$di = new \Phalcon\DI\FactoryDefault();
$di->setShared('config', function () use($config) {
    return $config;
});
$di->setShared('session', function () use($config) {
    session_set_cookie_params($config->app->session_lifetime);
    if ($config->app->debug != 1) {
        ini_set('session.cookie_secure', '1');
        ini_set('session.cookie_httponly', '1');
    }
    $session = new Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});
$di->setShared('view', function () use($config) {
    $view = new Phalcon\Mvc\View\Simple();
    $view->setViewsDir(ROOTDIR . '/app/views/');
    $view->registerEngines(array('.phtml' => function ($view) use($config) {
        $volt = new Phalcon\Mvc\View\Engine\Volt($view);
        $volt->setOptions(array('compiledPath' => ROOTDIR . '/tmp/volt/', 'compiledExtension' => '.php', 'compiledSeparator' => '_', 'compileAlways' => true));
        $compiler = $volt->getCompiler();
        $compiler->addFunction('recaptcha_get_html', function () use($config) {
            return "'" . recaptcha_get_html($config->captcha->pub, null, true) . "'";
        });
        return $volt;
    }));
    return $view;
});
$di->setShared('db', function () use($config) {
Пример #10
0
<?php

use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
$di = new Phalcon\DI\FactoryDefault();
$di->setShared('config', function () {
    return new Phalcon\Config(require APP_ROOT . '/config/config.php');
});
$di->setShared('router', function () {
    return require APP_ROOT . '/config/routes.php';
});
$di->setShared('url', function () use($di) {
    $url = new \ApiDocs\Components\Url();
    $url->setBaseUri('/api/');
    return $url;
});
$di->setShared('tag', function () {
    return new \ApiDocs\Components\Tag();
});
$di->setShared('view', function () use($di) {
    $view = new Phalcon\Mvc\View();
    $view->setViewsDir(APP_ROOT . '/views/');
    $view->registerEngines(array('.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php', '.volt' => function ($view, $di) {
        $config = $di->get('config');
        $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di);
        $volt->setOptions((array) $config->voltOptions);
        $volt->getCompiler()->addFunction('tr', function ($key) {
            return "translate({$key})";
        });
        return $volt;
    }));
    return $view;
Пример #11
0
<?php

use filter\Filter;
use kahlan\reporter\coverage\exporter\Coveralls;
$args = $this->args();
$args->argument('coverage', 'default', 3);
Filter::register('phalcon.namespace', function ($chain) {
    $this->_autoloader->addPsr4('Spec\\Models\\', __DIR__ . '/spec/models/');
});
Filter::register('phalcon.coverage-exporter', function ($chain) {
    $reporter = $this->reporters()->get('coverage');
    if (!$reporter) {
        return;
    }
    Coveralls::write(['collector' => $reporter, 'file' => 'coveralls.json', 'service_name' => 'travis-ci', 'service_job_id' => getenv('TRAVIS_JOB_ID') ?: null]);
    return $chain->next();
});
Filter::apply($this, 'namespaces', 'phalcon.namespace');
Filter::apply($this, 'reporting', 'phalcon.coverage-exporter');
$di = new \Phalcon\DI\FactoryDefault();
$di->setShared('db', function () {
    return new \Phalcon\Db\Adapter\Pdo\Sqlite(['dbname' => __DIR__ . '/spec/db.sqlite']);
});
\Phalcon\DI::setDefault($di);
Пример #12
0
<?php

$loader = new \Phalcon\Loader();
$loader->registerNamespaces(['Example\\Models' => __DIR__ . '/../app/models', 'DataTables' => __DIR__ . '/../../src/']);
$loader->register();
$di = new \Phalcon\DI\FactoryDefault();
$di->setShared('db', function () {
    return new \Phalcon\Db\Adapter\Pdo\Sqlite(['dbname' => __DIR__ . '/../db.sqlite']);
});
$di->setShared('view', function () {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir(__DIR__ . '/../app/views/');
    $view->registerEngines(['.volt' => 'Phalcon\\Mvc\\View\\Engine\\Volt']);
    return $view;
});
$app = new \Phalcon\Mvc\Micro($di);
/** @noinspection PhpUndefinedMethodInspection */
$app->getRouter()->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
$app->get('/', function () use($app) {
    $app['view']->render('index.volt', []);
});
$app->post('/example_querybuilder', function () use($app) {
    $builder = $app->getService('modelsManager')->createBuilder()->columns('id, name, email, balance')->from('Example\\Models\\User');
    $dataTables = new \DataTables\DataTable();
    $dataTables->fromBuilder($builder)->sendResponse();
});
$app->get('/example_resultset', function () use($app) {
    $resultset = $app->getService('modelsManager')->createQuery("SELECT * FROM \\Example\\Models\\User")->execute();
    $dataTables = new \DataTables\DataTable();
    $dataTables->fromResultSet($resultset)->sendResponse();
});
Пример #13
0
<?php

use Eve\Components;
$di = new Phalcon\DI\FactoryDefault();
/**
 * Register the global configuration as config
 */
$di->set('config', $config);
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->setShared('url', function () use($config) {
    $url = new Phalcon\Mvc\Url();
    $url->setBaseUri($config->application->baseUri);
    $url->setStaticBaseUri($config->application->staticBaseUri);
    return $url;
});
/************************
 *      Dispatcher      *
 ************************/
$di->setShared('dispatcher', function () use($di) {
    //get the events manager
    $eventsManager = $di->getShared('eventsManager');
    //puts any params in the url into an assoc array in the dispatcher
    //for example given this url
    //	/en/employer/profile/edit/id/5/company/6/email/test@test.com
    //then in the controller
    //	$this->dispatcher->getParam('id') = 5
    //	$this->dispatcher->getParam('company') = 6
    //	$this->dispatcher->getParam('email') = test@test.com
    $eventsManager->attach('dispatch', new Eve\Plugins\Params($di));
Пример #14
0
 //URL	延迟加载
 $di->set('url', function () use($config) {
     return new \Phalcon\Mvc\Url();
 }, true);
 //路由器		延迟加载
 $di->set('router', function () use($config) {
     $router = new \Phalcon\Mvc\Router();
     //加载默认模块
     $key = $config->modules->default;
     if ($key && $config->modules->{$key}->used == 1) {
         $router->setDefaultModule('frontend');
     }
     return $router;
 }, true);
 //session	延迟加载
 $di->setShared('session', new Phalcon\Session\Adapter\Files());
 $di->get('session')->start();
 //加载DB负载均衡
 BalanceDb::config($config->balanceDb->toArray());
 foreach ($config->balanceDb->toArray() as $dbKey => $currentConfig) {
     if ($dbKey == 'default') {
         continue;
     }
     $keyWrite = 'db' . ucfirst($dbKey);
     $keyRead = $keyWrite . '_read';
     $dbWriteConfig = $currentConfig['write']['db'];
     $di->set($keyWrite, function () use($dbWriteConfig) {
         return new Phalcon\Db\Adapter\Pdo\Mysql($dbWriteConfig);
     });
     $dbReadConfig = current($currentConfig['reads']);
     $di->set($keyRead, function () use($dbReadConfig) {
Пример #15
0
}
$autoload_classes = $config->application->autoload->toArray();
foreach ($autoload_classes['psr0'] as $class_key => $class_dir) {
    $autoloader->add($class_key, $class_dir);
}
foreach ($autoload_classes['psr4'] as $class_key => $class_dir) {
    $autoloader->addPsr4($class_key, $class_dir);
}
// Set up Dependency Injection
if (FA_IS_COMMAND_LINE) {
    $di = new \Phalcon\DI\FactoryDefault\CLI();
} else {
    $di = new \Phalcon\DI\FactoryDefault();
}
// Configs
$di->setShared('config', $config);
$di->setShared('module_config', function () use($module_config) {
    return $module_config;
});
$di->setShared('phalcon_modules', function () use($phalcon_modules) {
    return $phalcon_modules;
});
// Router
if (FA_IS_COMMAND_LINE) {
    $router = new \Phalcon\CLI\Router();
    $di->setShared('router', $router);
} else {
    $di->setShared('router', function () use($di) {
        $router = new \FA\Phalcon\Router(false);
        $router->setUriSource(\FA\Phalcon\Router::URI_SOURCE_SERVER_REQUEST_URI);
        $router->setDi($di);
Пример #16
0
<?php

error_reporting(-1);
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
try {
    if (!defined('DIRS')) {
        define('DIRS', DIRECTORY_SEPARATOR);
    }
    if (!defined('ROOTFULLPATH')) {
        define('ROOTFULLPATH', dirname(__DIR__));
    }
    if (!defined('TRACK')) {
        define('TRACK', TRUE);
    }
    require_once ROOTFULLPATH . '/vendor/autoload.php';
    $profiler = new \Fabfuel\Prophiler\Profiler();
    $bootstrap = $profiler->start('Bootstrap', ['lorem' => 'ipsum'], 'Application');
    require_once 'bootstrap/Load.php';
    $di = new \Phalcon\DI\FactoryDefault();
    $di->setShared('profiler', $profiler);
    $Load = new Load($di);
    $app = $Load->run();
    $profiler->stop($bootstrap);
    echo $app->handle()->getContent();
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();
}
$toolbar = new \Fabfuel\Prophiler\Toolbar($profiler);
$toolbar->addDataCollector(new \Fabfuel\Prophiler\DataCollector\Request());
//echo $toolbar->render();
Пример #17
0
 /**
  * This methods registers the services to be used by the application
  */
 protected function _registerServices()
 {
     $di = new \Phalcon\DI\FactoryDefault();
     // Registering a Config shared-service
     $di->setShared('config', function () {
         $config['main'] = (include ROOT_DIR . "/config/main.php");
         $config['db'] = (include ROOT_DIR . "/config/db.php");
         $config['router'] = (include ROOT_DIR . "/config/router.php");
         return new \Phalcon\Config($config);
     });
     $config = $di->get('config');
     // Change FactoryDefault default Router service
     $di->getService('router')->setDefinition(function () use($config) {
         $router = new \Phalcon\Mvc\Router();
         //Setup routes from /config/router.php
         foreach ($config->router->toArray() as $key => $value) {
             $router->add($key, $value);
         }
         // Mount each module routers
         $router->mount(new \App\Frontend\Router());
         $router->mount(new \App\Backend\Router());
         // URI_SOURCE_SERVER_REQUEST_URI
         $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
         // Remove trailing slashes automatically
         $router->removeExtraSlashes(true);
         // Setting a specific default using an array
         // DefaultModule
         // DefaultNamespace
         // DefaultController
         // DefaultAction
         $router->setDefaults(array('modul' => 'frontend', 'namespace' => 'App\\Frontend\\Controllers\\', 'controller' => 'index', 'action' => 'index'));
         // Set 404 paths
         $router->notFound(["controller" => "error", "action" => "error404"]);
         return $router;
     });
     // Registering a View shared-service
     $di->setShared('view', function () {
         return new \Phalcon\Mvc\View();
     });
     // Registering a Mysql shared-service
     $di->setShared('mysql', function () use($config) {
         return new \Phalcon\Db\Adapter\Pdo\Mysql($config->db->mysql->toArray());
     });
     // Registering a Db shared-service
     $di->setShared('db', function () use($di) {
         return $di->get('mysql');
     });
     // Registering a Url shared-service
     $di->setShared('url', function () {
         $url = new \Phalcon\Mvc\Url();
         $url->setBaseUri('/');
         return $url;
     });
     // Start the Session service
     $di->get('session')->start();
     // Setup the Crypt service
     $di->get('crypt')->setMode(MCRYPT_MODE_CFB)->setKey($config->main->crypt_key);
     // Setup the Security service
     $di->get('security')->setWorkFactor(12);
     // Registering a custom authentication shared-service
     $di->setShared('auth', function () {
         return new \App\Common\Libs\Auth();
     });
     $this->setDI($di);
 }
Пример #18
0
    if ($server === $host) {
        $config = new \Phalcon\Config\Adapter\Ini('../config/config_' . $file . '.ini');
    }
}
$routers = new \Phalcon\Config\Adapter\Ini('../config/router.ini');
$di = new \Phalcon\DI\FactoryDefault();
$loader = new \Phalcon\Loader();
if (!empty($config->library)) {
    foreach ($config->library as $name => $patch) {
        $namespace[$name] = '../' . $config->app->library . $patch;
    }
}
$loader->registerNamespaces($namespace);
$loader->register();
$di->setShared('config', function () use($config) {
    return $config;
});
$di->setShared('crypt', function () use($config) {
    $crypt = new \Phalcon\Crypt();
    $crypt->setKey($config->auth->cookie_hash);
    return $crypt;
});
$di->setShared('cookies', function () {
    $cookies = new \Phalcon\Http\Response\Cookies();
    return $cookies;
});
$di->setShared('session', function () {
    $session = new \Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});
Пример #19
0
* The DI is our direct injector.  It will store pointers to all of our services
* and we will insert it into all of our controllers.
* @var DefaultDI
*/
$di = new Phalcon\DI\FactoryDefault();
/**
* Return array of the Collections, which define a group of routes, from
* routes/collections.  These will be mounted into the app itself later.
*/
$di->set('collections', function () {
    return include './Routes/RouteLoader.php';
});
// As soon as we request the session service, it will be started.
$di->setShared('session', function () {
    $session = new \Phalcon\Session\Adapter\Files();
    $session->start();
    $session->set('language', 'id');
    return $session;
});
$di->set('modelsCache', function () {
    //Cache data for one day by default
    $frontCache = new \Phalcon\Cache\Frontend\Data(array('lifetime' => 3600));
    //File cache settings
    $cache = new \Phalcon\Cache\Backend\File($frontCache, array('cacheDir' => __DIR__ . '/Cache/'));
    return $cache;
});
/**
* Database connection is created based in the parameters defined in the configuration file
*/
$di->set('db', function () use($config) {
    try {
        $eventsManager = new Phalcon\Events\Manager();
Пример #20
0
 $di->set('view', function () use($config) {
     $view = new \Phalcon\Mvc\View();
     $view->setViewsDir($config->application->viewsDir);
     $view->registerEngines(array(".phtml" => 'Phalcon\\Mvc\\View\\Engine\\Php', ".volt" => 'volt'));
     return $view;
 });
 //Setup a base URI so that all generated URIs include the "tutorial" folder
 $di->set('url', function () use($config) {
     $url = new \Phalcon\Mvc\Url();
     $url->setBaseUri($config->resource->baseUri);
     return $url;
 });
 //Start the session the first time when some component request the session service
 $di->setShared('session', function () {
     $session = new Phalcon\Session\Adapter\Files();
     $session->start();
     return $session;
 });
 $di->set('elements', function () {
     return new Elements();
 });
 /**
  * Setting up volt
  */
 $di->set('volt', function ($view, $di) use($config) {
     $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
     $volt->setOptions(array("compiledPath" => $config->cache->voltCacheDir));
     return $volt;
 }, true);
 //phalcon Case insesitive routing || url:https://forum.phalconphp.com/discussion/1824/case-insesitive-routing-how-to-
 if (isset($_GET['_url'])) {
<?php

$loader = new \Phalcon\Loader();
$loader->registerNamespaces(["Jowy\\Phrest" => __DIR__ . "/../app"], true)->register();
$di = new \Phalcon\DI\FactoryDefault();
$di->setShared("config", function () {
    require __DIR__ . "/../app/Config/Config.php";
    return new \Phalcon\Config($config);
});
$di->setShared("db", function () use($di) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(["host" => $di["config"]->database->host, "username" => $di["config"]->database->username, "password" => $di["config"]->database->password, "port" => $di["config"]->database->port, "dbname" => $di["config"]->database->dbname]);
});
$di->setShared("apiResponse", function () {
    $response = new \Jowy\Phrest\Core\Response(new \League\Fractal\Manager());
    $response->setPhalconResponse(new \Phalcon\Http\Response());
    return $response;
});
$di->set("router", function () {
    $router = new \Phalcon\Mvc\Router\Annotations(false);
    $files = array_diff(scandir(__DIR__ . "/../app/controllers/"), array('..', '.'));
    foreach ($files as $file) {
        $file = array_slice(preg_split('/(?=[A-Z])/', $file), 1);
        $router->addResource("Jowy\\Phrest\\Controllers\\" . $file[0]);
    }
    return $router;
});
$di->set("view", function () {
    $view = new \Phalcon\Mvc\View();
    $view->disable();
    return $view;
});