/** * Processes the error, fatal and exceptions */ protected function report() { # - let monolog handle the logging in the errors, # unless you want it to, you can refer to method # handleExceptionError() MonologErrorHandler::register(di()->get('log')); # - register all the the loggers we have register_shutdown_function([$this, 'handleFatalError']); set_error_handler([$this, 'handleError']); set_exception_handler([$this, 'handleExceptionError']); }
public function __construct() { $this->request = di()->get('request'); $this->session = di()->get('session'); $this->response = di()->get('response'); $this->security = di()->get('security'); }
public function __get($name) { if (di()->has($name) === false) { throw new InvalidArgumentException("Dependency Injection [{$name}] not found"); } return di()->get($name); }
/** * Loads all services. * * return void */ public function boot() { $providers_loaded = array_map(function ($provider) { # check if module function exists if (method_exists($provider, 'module')) { di('module')->setModule($provider->getAlias(), function ($di) use($provider) { call_user_func_array([$provider, 'module'], [$di]); }); } # callRegister should return an empty or an object or array # then we could manually update the register if ($register = $provider->callRegister()) { di()->set($provider->getAlias(), $register, $provider->getShared()); } return $provider; }, $this->providers); # this happens when some application services relies on other service, # iterate the loaded providers and call the boot() function foreach ($providers_loaded as $provider) { $boot = $provider->boot(); if ($boot && !di()->has($provider->getAlias())) { di()->set($provider->getAlias(), $boot, $provider->getShared()); } } }
public function testHandle() { $app = $this->setUp(); $resolver = di('resolver'); $resolver->set('dispatch:controller', function () { return '\\Engine\\Tests\\Application\\Sample'; }); $resolver->set('dispatch:forward', function ($controller, $module) { return '\\Engine\\Tests\\Application\\Another'; }); $sources = ['/blog/add' => ['action' => 'add', 'response' => 'test'], '/blog/view' => ['action' => 'view', 'exception' => 'Phalcon\\Mvc\\Dispatcher\\Exception'], '/blog/forward' => ['action' => 'forward', 'response' => 'my_action']]; $router = di('router'); foreach ($sources as $uri => $source) { $router->add($uri, "Blog::Index::{$source['action']}"); try { $app->handle($uri); $response = di('dispatcher')->getReturnedValue(); $this->assertEquals($source['response'], $response); } catch (\Exception $e) { if (isset($source['exception'])) { $this->assertInstanceOf($source['exception'], $e); } else { echo $e->getMessage(); dd($e->getTraceAsString()); } } } }
public function initialize() { # - the code below is hard-coded, you can add it by fetching your # database table and loop into it and change the 'guest' to something # that you've stored. di()->get('acl')->addRole(new PhalconRole('guest')); }
public function tearDown() { $compiled_file = 'storage/slayer/compiled.php'; if (file_exists($compiled_file)) { di()->get('flysystem')->delete($compiled_file); } }
public function boot() { $app = di()->get('application'); $event_manager = new EventsManager(); $event_manager->attach('application', new ApplicationEventListener()); $app->setEventsManager($event_manager); }
public function boot() { $dispatcher = di()->get('dispatcher'); $event_manager = new EventsManager(); $event_manager->attach('dispatch', new DispatcherEventListener()); $dispatcher->setEventsManager($event_manager); }
/** * validate message */ protected function _validateMessage($message) { if (!$message) { di('log')->record("message not found at " . date('Y-m-d H:i:s')); exit; } // 已處理過的 message 將不再處理 if ($message->getIsUsed()) { di('log')->record("message {$id} is used"); exit; } // 回應的 chat_id 必須在白名單之內 $chatId = $message->getChatId(); $allowIds = conf('bot.allow_chat_ids'); if (!in_array($chatId, $allowIds)) { di('log')->record("message can not allow send to {$chatId} ({$message->getName()})"); // debug -> 如果不在予許的名單內, 發送警告訊息 if (isTraining()) { $userId = $message->getUserId(); $text = '您不在白名單之內 by BOT'; BotHelper::sendMessage($userId, $text); } exit; } }
public function render($path, $params = []) { $path = str_replace($this->getView()->getViewsDir(), '', $path); $path = str_replace('.blade.php', '', $path); $blade = new Blade($this->getView()->getViewsDir(), storage_path('views') . '/'); di()->get('view')->setContent($blade->make($path, $params)->render()); }
/** * * @return bool */ public function checkViewPath($path) { $full_path = di()->get('view')->getViewsDir() . $path; $result = glob($full_path . '.*'); if (!$result) { throw new ViewFileNotFoundException('Views file path(' . $full_path . ') not found.'); } }
public function handle($e) { $content = di()->get('view')->take('errors.whoops', ['e' => $e]); $response = di('response'); $response->setContent($content); $response->setStatusCode(self::STATUS_CODE); return $response->send(); }
public function onBoot() { // TODO: Implement onBoot() method. $this->getDI()->set(ViewContract::class, View::class); $this->getDI()->setShared('view', function () { return di(ViewContract::class); }); }
/** * {@inheridoc}. */ public function register() { $manager = $this->manager(); di()->set('flysystem_manager', function () use($manager) { return $manager; }, true); return $manager->getFilesystem(config()->app->flysystem); }
public function testImplementContract() { $modelsManager = new ModelsManager(); di()->setShared('modelsManager', $modelsManager); $model = new SampleModel(); $this->assertInstanceOf(ModelContract::class, $model); return $model; }
/** * {@inheritdoc} */ public function boot() { if (!di()->has($this->alias)) { $db = $this->getDefaultConnection(); di()->set($this->alias, function () use($db) { return $db; }, $this->shared); } }
public function boot() { $event_manager = di()->get('eventsManager'); $event_manager->attach('view:afterRender', function (Event $event, View $dispatcher, $exception) { $dispatcher->getDI()->get('flash')->session()->clear(); }); di()->get('view')->setEventsManager($event_manager); return $this; }
public function beforeDispatchLoop($event, Dispatcher $dispatcher) { $resolver = di('resolver'); $dispatcher->setControllerName($resolver->run('dispatch:controller', function () { $router = di('router'); $moduleName = $router->getModuleName(); $ctlName = ucfirst($router->getControllerName()); return "\\App\\Modules\\{$moduleName}\\Controllers\\{$ctlName}"; })); }
/** * Handles a MVC request * * @param string uri * @return \Phalcon\Http\ResponseInterface|boolean * @throws NullPointerException */ public function handle($uri = null) { $di = di(); if (is_null($di)) { throw new NullPointerException('Dependency Injector must be defined'); } $em = $this->getEventsManager(); if (is_null($em)) { throw new NullPointerException('EventsManager must be defined'); } // Fire application:boot event if ($em->fire('application:boot', $this) === false) { return false; } // Fire application:ready event if ($em->fire('application:ready', $this) === false) { return false; } // Handle Router $router = $di->getShared('router'); $router->handle($uri); // Handle Request $request = $di->getShared('request'); $request->setRouter($router); // Pass the processed router parameters to the dispatcher $dispatcher = $di->getShared('dispatcher'); $dispatcher->setModuleName($router->getModuleName()); $dispatcher->setNamespaceName($router->getNamespaceName()); $dispatcher->setControllerName($router->getControllerName()); $dispatcher->setActionName($router->getActionName()); $dispatcher->setParams($router->getParams()); // Fire application:beforeHandleRequest event if ($em->fire('application:beforeHandleRequest', $this, $dispatcher) === false) { return false; } // Dispatch the request if ($dispatcher->dispatch()) { // There should be a response $response = null; $returnedValue = $dispatcher->getReturnedValue(); if ($returnedValue instanceof View) { $response = $di->get(ResponseInterface::class); $response->setContent($returnedValue->getContent()); } elseif ($returnedValue instanceof ResponseInterface) { $response = $returnedValue; } if ($response instanceof ResponseInterface) { $response->send(); } } // Fire application:afterDispatch event if ($em->fire('application:afterHandleRequest', $this, $dispatcher) === false) { return false; } }
/** * {@inheridoc}. */ public function boot() { $dispatcher = di()->get('dispatcher'); $event_manager = new EventsManager(); $event_manager->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) { if ($exception instanceof DispatchException) { throw new ControllerNotFoundException($exception->getMessage()); } }); $dispatcher->setEventsManager($event_manager); }
/** * {@inheritdoc} */ public function slash() { foreach (di()->getServices() as $service) { if (!method_exists($def = $service->getDefinition(), 'afterModuleRun')) { continue; } $def->afterModuleRun(); } $table = $this->table(['Method', 'Path', 'Controller', 'Action', 'Assigned Name'], $this->extractRoutes(Route::getRoutes())); $table->render(); }
public function tearDown() { $test_module_index = 'public/test_module.php'; if (file_exists($test_module_index)) { di()->get('flysystem')->delete($test_module_index); } $test_module = 'app/TestModule'; if (is_dir($test_module)) { di()->get('flysystem')->deleteDir($test_module); } }
/** * {@inheritdoc} */ public function slash() { # load non-loaded routes based for each module foreach (di('module')->all() as $module_name => $module) { $path = Kernel::buildRoute($module_name); if (file_exists($path)) { require_once $path; } } $table = $this->table(['Method', 'Path', 'Controller', 'Action', 'Assigned Name'], $this->extractRoutes(Route::getRoutes())); $table->render(); }
private function optimizeConfigs() { $path = $this->basePath . '/storages/apps/config.php'; $configs = di('config')->getConfig(); //Arr::except(di('config')->getConfig(), ['router']); $basePath = $this->basePath; $dump = var_export($configs, true); $dump = $this->replaceStorageAbsolutePath($dump, $basePath); $dump = $this->replaceResourceAbsolutePath($dump, $basePath); $dump = $this->replaceAppAbsolutePath($dump, $basePath); file_put_contents($path, "<?php \n\n return " . $dump . ";\n"); }
/** * @inheritdoc */ public function connect(array $config) { $session = new SessionAdapter(); $id = di('crypt')->encrypt($config['app']['key']); $name = $config['session']['cookie']; //$session->setId($id); session_name($name); $session->setOptions(['uniqueId' => $id]); if (!$session->isStarted()) { $session->start(); } return $session; }
public function fire() { $defaultKey = di('config')->get('app.key'); $key = Str::random(32); $path = base_path('.env'); if (file_exists($path)) { file_put_contents($path, str_replace($defaultKey, $key, file_get_contents($path))); // set the new application key to config service. di('config')->set('app.key', $key); } $this->callOptimize(); $this->showInfo($key); }
function pr($data, $writeLog = false) { if (is_object($data) || is_array($data)) { print_r($data); if ($writeLog) { di('log')->record(print_r($data, true)); } } else { echo $data; echo "\n"; if ($writeLog) { di('log')->record($data); } } }
/** * di loader * @see https://github.com/symfony/dependency-injection * @see http://symfony.com/doc/current/components/dependency_injection/factories.html * @see http://symfony.com/doc/current/components/dependency_injection/introduction.html */ public function diLoader() { $basePath = conf('app.path'); $di = di(); $di->setParameter('app.path', $basePath); /* $di->register('abc', 'Lib\Abc') ->addArgument('%app.path%'); // __construct ->setProperty('setDb', [new Reference('db')]); // ?? */ // log & log folder $di->register('log', 'Bridge\\Log')->addMethodCall('init', ['%app.path%/var']); // cache $di->register('cache', 'Bridge\\Cache')->addMethodCall('init', ['%app.path%/var/cache']); }
public function handle($e) { # errors coming from ACL or anything that throws from # AccessNotAllowedException class. # # handle it by providing a page that there is no privilege # to access the website. # # the code below prints the exception message, # you can point it to your views folder or log the message # internally. $content = di()->get('view')->take('errors.whoops', ['e' => $e]); $response = di('response'); $response->setContent($content); $response->setStatusCode(self::STATUS_CODE); return $response->send(); }