Archived
1
0
Fork 0
This repository has been archived on 2026-04-03. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
httpcb/app/library/Services.php

426 lines
12 KiB
PHP

<?php
namespace Httpcb;
use Phalcon\Di\FactoryDefault as DiDefault,
Phalcon\Config\Adapter\Yaml as Config,
Phalcon\Mvc\View,
Phalcon\Mvc\View\Simple as SimpleView,
Phalcon\Assets\Manager as AssetsManager,
Phalcon\Url as UrlResolver,
Phalcon\Mvc\View\Engine\Volt as VoltEngine,
Phalcon\Flash\Direct as FlashDirect,
Phalcon\Mvc\Model\Metadata\Memory as MemoryMetaData,
Phalcon\Mvc\Model\MetaData\Apc as ApcMetaData,
Phalcon\Mvc\ViewBaseInterface,
Phalcon\Cache\Frontend\Data as FrontendDataCache,
Phalcon\Cache\Backend\Apc as BackendApcCache,
Phalcon\Translate\Adapter\NativeArray as TranslateAdapter,
Phalcon\Storage\AdapterFactory as StorageAdapterFactory,
Phalcon\Cache\AdapterFactory as CacheAdapterFactory,
Phalcon\Logger,
Phalcon\Mvc\Router;
use Httpcb\Auth,
Httpcb\OAuth\Client as OAuthClient,
Httpcb\OAuth\Adapter\League as OAuthAdapter,
Httpcb\Acl,
Httpcb\Navigation,
Httpcb\Menu,
Httpcb\Mail as MailService,
Httpcb\ViewHelper\Volt\Extension as ViewHelperVoltExtension;
use App\Listener\AccessListener,
App\Listener\DispatchListener,
App\Listener\ActivityLog,
App\Listener\AuthEmailListener;
class Services extends DiDefault
{
public function __construct()
{
parent::__construct();
$reflection = new \ReflectionObject($this);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PROTECTED);
foreach($methods as $method) {
if (substr($method->getName(),0, 11) == '_initShared') {
$service = lcfirst(substr($method->getName(), 11));
$this->setShared($service, $method->getClosure($this));
}
else if (substr($method->getName(),0, 5) == '_init') {
$service = lcfirst(substr($method->getName(), 5));
$this->set($service, $method->getClosure($this));
}
}
// Simple services
$this->setShared('debugger', '\Phalcon\Debug');
}
protected function _initSharedConfig()
{
// All config files used by the application.
// These will be compiled into a single config object.
//
// The priority is files defined AFTER another
// will override settings if there a multiple keys.
$files = array(
'app.yml',
'routes.yml',
'menu.yml',
'local.yml',
'acl.yml'
);
$basePath = APP_PATH . '/app/config/';
$config = new \Phalcon\Config();
foreach ($files as $file) {
try {
$tmp = new Config($basePath . $file);
$config->merge($tmp);
} catch(\Phalcon\Config\Exception $e) {
// Sometime went wrong. Log here?
}
}
return $config;
}
protected function _initSharedLoader()
{
$config = $this->get('config');
$loader = new \Phalcon\Loader();
$loader->registerNamespaces(array(
'App\Controller' => $config->application->controllersDir,
'App\Listener' => $config->application->listenersDir,
'App\Module' => $config->application->modulesDir,
'App\Model' => $config->application->modelsDir,
'App\Form' => $config->application->formsDir,
'Httpcb' => $config->application->libraryDir,
));
$loader->registerFiles(array(APP_PATH . '/vendor/autoload.php'));
$loader->register();
return $loader;
}
protected function _initSharedDispatcher()
{
$config = $this->get('config');
$eventsManager = new \Phalcon\Events\Manager();
$eventsManager->attach("dispatch", function($event, $dispatcher) {
$actionName = lcfirst(\Phalcon\Text::camelize($dispatcher->getActionName(), '-_'));
$dispatcher->setActionName($actionName);
});
if ($config->application->debug == false) {
$eventsManager->attach('dispatch:beforeException', new DispatchListener());
}
$eventsManager->attach('dispatch:beforeExecuteRoute', new AccessListener());
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$dispatcher->setEventsManager($eventsManager);
$dispatcher->setDefaultNamespace('App\Controller');
return $dispatcher;
}
/**
* Database connection is created based in the parameters defined in the configuration file
*/
protected function _initSharedDb()
{
$dbConfig = $this->get('config')->database->toArray();
$logger = $this->get('logger');
$adapter = $dbConfig['adapter'];
unset($dbConfig['adapter']);
$class = 'Phalcon\Db\Adapter\Pdo\\' . $adapter;
$db = new $class($dbConfig);
$eventsManager = new \Phalcon\Events\Manager();
$eventsManager->attach('db', function ($event, $connection) use ($logger) {
if ($event->getType() == 'beforeQuery') {
$logger->info($connection->getRealSQLStatement());
}
});
$db->setEventsManager($eventsManager);
return $db;
}
/**
* If the configuration specify the use of metadata
* adapter use it or use memory otherwise.
*/
protected function _initSharedModelsMetadata()
{
$config = $this->get('config');
// Use adapter and options from config if defined.
if ($config->get('models-metadata')) {
$mdConfig = $config->get('models-metadata')->toArray();
$options = $mdConfig['options'];
$adapter = $mdConfig['adapter'];
$serializerFactory = new \Phalcon\Storage\SerializerFactory();
$factory = new CacheAdapterFactory($serializerFactory);
$class = 'Phalcon\Mvc\Model\MetaData\\' . $adapter;
return new $class($factory, $options);
}
// Otherwise, default to Memory.
return new \Phalcon\Mvc\Model\MetaData\Memory();
}
protected function _initSession()
{
$config = $this->get('config');
$session = new \Phalcon\Session\Manager();
if (isset($config->session)) {
$data = $config->session->toArray();
$adapter_name = isset($data['adapter']) ? $data['adapter'] : 'Stream';
$options = $data['options'];
$serializerFactory = new \Phalcon\Storage\SerializerFactory();
$factory = new StorageAdapterFactory($serializerFactory);
$class = 'Phalcon\Session\Adapter\\' . $adapter_name;
$adapter = new $class($factory, $options);
}
// Default to Stream
else {
$adapter = new \Phalcon\Session\Adapter\Stream();
}
$session->setAdapter($adapter);
// Start session.
$session->start();
return $session;
}
/**
* Setting up the view component
*/
protected function _initSharedView()
{
$config = $this->get('config');
$view = new View();
$view->setViewsDir([ $config->application->viewsDir ]);
$view->setLayoutsDir('_layouts/');
$view->setPartialsDir('_partials/');
$view->registerEngines(array(
'.volt' => function (ViewBaseInterface $view) use ($config) {
$volt = new VoltEngine($view, $this);
$volt->setOptions(array(
'path' => $config->application->viewCacheDir,
'separator' => '_',
'always' => true,
));
// Register view helpers
$compiler = $volt->getCompiler();
$compiler->addExtension(new ViewHelperVoltExtension($this));
return $volt;
},
'.phtml' => \Phalcon\Mvc\View\Engine\Php::class
));
// Set default main layout.
$view->setMainView('layout');
return $view;
}
protected function _initSharedFlash()
{
return new \Phalcon\Flash\Session();
}
protected function _initSharedAssets()
{
$manager = new AssetsManager();
// CSS
$manager->collection('css')
->setPrefix('css/')
->addCss('application.min.css');
// Javascript
$manager->collection('js')
->setPrefix('js/')
->addJs('application.min.js');
return $manager;
}
/**
* Menu system
*
* @return \Httpcb\Menu
*/
protected function _initMenu()
{
$config = $this->get('config')->menu;
$navigation = new Navigation($config->toArray());
$menu = new Menu($navigation);
$menu->setMenuClass(null);
if ($this->get('auth')->hasIdentity()) {
$type = $this->get('auth')->getIdentity()->getType();
$menu->setAclRole($type);
} else {
$menu->setAclRole(Acl::ROLE_GUEST);
}
return $menu;
}
/**
* The URL component is used to generate all kind of urls in the application
*/
protected function _initSharedUrl()
{
$config = $this->get('config');
$url = new UrlResolver();
$url->setBaseUri($config->application->baseUri);
return $url;
}
protected function _initSharedRouter()
{
$config = $this->get('config')->router;
// Create the router
$router = new Router(false);
$router->removeExtraSlashes($config->get('removeExtraSlashes', false));
foreach($config->routes as $name => $def) {
if (!($def instanceof \Phalcon\Config)) {
continue;
}
$path = $def->get('path', []);
if ($path instanceof \Phalcon\Config) {
$path = $path->toArray();
}
$router->add($def->get('pattern'), $path)
->setName($name);
}
$router->notFound(['controller' => 'error', 'action' => 'show404']);
return $router;
}
protected function _initSharedEventsManager()
{
$activityLog = new ActivityLog();
$eventsManager = new \Phalcon\Events\Manager();
$eventsManager->attach('user', $activityLog);
$eventsManager->attach('auth', $activityLog);
$eventsManager->attach('auth', new AuthEmailListener);
return $eventsManager;
}
protected function _initAuth()
{
return new Auth($this->get('config'));
}
protected function _initAcl()
{
return new Acl($this->get('config')->acl);
}
protected function _initSharedLogger()
{
$path = $this->get('config')->application->logDir;
return new \Phalcon\Logger('default', [
'main' => new \Phalcon\Logger\Adapter\Stream($path . 'app.txt')
]);
}
protected function _initTemplate()
{
$config = $this->get('config');
$view = new SimpleView();
$view->setViewsDir($config->application->templateDir);
$view->registerEngines([
'.volt' => function (ViewBaseInterface $view) use ($config) {
$volt = new VoltEngine($view, $this);
$volt->setOptions(array(
'path' => $config->application->viewCacheDir,
'separator' => '_',
));
return $volt;
},
'.phtml' => \Phalcon\Mvc\View\Engine\Php::class,
]);
return $view;
}
/**
* Register the mail service.
*
* @return MailService
*/
protected function _initSharedMail()
{
$config = $this->get('config');
$sendgrid = new \SendGrid($config->sendgrid->key);
return new MailService($sendgrid);
}
protected function _initOauth($provider)
{
$config = $this->get('config');
if (isset($config->oauth->providers->{$provider})) {
$options = $config->oauth->providers->{$provider};
$options = $options->toArray();
} else {
$options = array();
}
$adapter = new OAuthAdapter($provider, $options);
return new OAuthClient($adapter);
}
}