public function __construct() { if (basename(__DIR__) !== __NAMESPACE__) { throw new \LogicException(sprintf('%s: `%s` is an invalid framework filesystem directory! Must be `%s`.', __CLASS__, basename(__DIR__), __NAMESPACE__), 1322213425); } $this->registerNamespace(__DIR__); $this->urlParts = $this->guessUrlParts(); $nsMap =& $this->namespaceMap; $urlParts =& $this->urlParts; $dc = new \Pimple\Container(); $dc['main.default_module'] = ''; $dc['login.forced_redirect'] = ''; $dc['decorator.xhtml.template'] = 'Nethgui\\Template\\Main'; $dc['user.authenticate'] = $dc->protect(function ($user, $password, &$credentials) use($dc) { $dc['Log']->warning(sprintf("%s: user.authenticate is not set! Could not authenticate user `%s`.", __CLASS__, $user)); return FALSE; }); $dc['l10n.available_languages'] = function ($c) { $langs = array(); foreach ($c['namespaceMap'] as $ns => $prefix) { $path = "{$prefix}/{$ns}/Language/*"; $langs = array_unique(array_merge($langs, array_map('basename', $c['PhpWrapper']->glob($path, GLOB_ONLYDIR)))); } return $langs; }; $dc['l10n.preferred_locales'] = array('en'); $dc['l10n.catalog_resolver'] = $dc->protect(function ($lang, $catalog) use($dc) { $languages = array_merge(array($lang), $dc['l10n.preferred_locales']); foreach ($languages as $lang) { foreach ($dc['namespaceMap'] as $ns => $prefix) { $path = "{$prefix}/{$ns}/Language/{$lang}/{$catalog}.php"; if ($dc['PhpWrapper']->file_exists($path)) { return $path; } } } return ''; }); $dc['Log'] = function ($c) { return new \Nethgui\Log\Syslog($c['log.level']); }; $dc['PhpWrapper'] = function ($c) { $p = new \Nethgui\Utility\PhpWrapper(); $p->setLog($c['Log']); return $p; }; $dc['namespaceMap'] = function ($c) use(&$nsMap) { return $nsMap; }; $dc['Session'] = function ($c) { $s = new \Nethgui\Utility\Session(); $s->setLog($c['Log']); return $s; }; $dc['Pdp'] = function ($c) { $pdp = new \Nethgui\Authorization\JsonPolicyDecisionPoint($c['FilenameResolver']); $pdp->setLog($c['Log']); foreach ($c['namespaceMap'] as $nsName => $nsPath) { $pdp->loadPolicy($nsName . '\\Authorization\\*.json'); } return $pdp; }; $dc['User'] = function ($dc) { $user = $dc['objectInjector'](new \Nethgui\Authorization\User($dc['Session'], $dc['Log'])); $user->setAuthenticationValidator($dc['user.authenticate']); return $user; }; $objectInjector = function ($o) use($dc) { if ($o instanceof \Nethgui\Component\DependencyInjectorAggregate) { $o->setDependencyInjector($dc['objectInjector']); } if ($o instanceof \Nethgui\Component\DependencyConsumer) { foreach ($o->getDependencySetters() as $key => $setter) { if (!isset($dc[$key])) { continue; } call_user_func($setter, $dc[$key]); } } if ($o instanceof \Nethgui\Log\LogConsumerInterface) { $o->setLog($dc['Log']); } if ($o instanceof \Nethgui\Utility\SessionConsumerInterface) { $o->setSession($dc['Session']); } if ($o instanceof Authorization\PolicyEnforcementPointInterface) { $o->setPolicyDecisionPoint($dc['Pdp']); } if ($o instanceof \Nethgui\System\PlatformConsumerInterface) { $o->setPlatform($dc['Platform']); } return $o; }; $dc['objectInjector'] = $dc->protect($objectInjector); $dc['StaticFiles'] = function ($c) { return $c['objectInjector'](new \Nethgui\Model\StaticFiles(), $c); }; $dc['UserNotifications'] = function ($c) { return $c['objectInjector'](new \Nethgui\Model\UserNotifications(), $c); }; $dc['ValidationErrors'] = function ($c) { return $c['objectInjector'](new \Nethgui\Model\ValidationErrors(), $c); }; $dc['SystemTasks'] = function ($c) { return $c['objectInjector'](new \Nethgui\Model\SystemTasks($c['Log']), $c); }; $dc['FilenameResolver'] = $this->getFileNameResolver(); $dc['ModuleSet'] = function ($c) { $moduleSet = new \Nethgui\Module\ModuleLoader($c['objectInjector']); foreach ($c['namespaceMap'] as $nsName => $nsRoot) { if ($nsName === 'Nethgui') { $nsRoot = FALSE; } $moduleSet->setNamespace($nsName . '\\Module', $nsRoot); } return $c['objectInjector'](new \Nethgui\Authorization\AuthorizedModuleSet($moduleSet, $c['User']), $c); }; $dc['Platform'] = function ($c) { return $c['objectInjector'](new \Nethgui\System\NethPlatform($c['User'], $c['SystemTasks']), $c); }; $dc['Translator'] = function ($c) { return $c['objectInjector'](new \Nethgui\View\Translator($c['OriginalRequest']->getLanguageCode(), $c['l10n.catalog_resolver'], array_keys($c['namespaceMap'])), $c); }; $dc['HttpResponse'] = function ($c) { return new \Nethgui\Utility\HttpResponse(); }; $dc['Main.factory'] = $dc->factory(function ($c) { return $c['objectInjector'](new \Nethgui\Module\Main($c['ModuleSet'], $c['main.default_module']), $c); }); $dc['View'] = function ($c) use(&$urlParts) { $rootView = $c['objectInjector'](new \Nethgui\View\View($c['OriginalRequest']->getFormat(), $c['Main'], $c['Translator'], $urlParts), $c); $rootView->setTemplate(FALSE); /* * FIXME: remove deprecated features in version 2.0 */ $rootView->commands = $c['objectInjector'](new \Nethgui\View\LegacyCommandBag($rootView, $c), $c); /* * */ return $rootView; }; $dc['decorator.xhtml.params'] = function ($dc) { return new \ArrayObject(array('disableHeader' => FALSE, 'disableMenu' => FALSE, 'disableFooter' => TRUE)); }; $dc['main.xhtml.template'] = $dc->protect(function (\Nethgui\Renderer\Xhtml $renderer, $T, \Nethgui\Utility\HttpResponse $httpResponse) use($dc, &$urlParts) { $decoratorView = $dc['objectInjector'](new \Nethgui\View\View($dc['OriginalRequest']->getFormat(), $dc['Main'], $dc['Translator'], $urlParts), $dc); $decoratorView->setTemplate($dc['decorator.xhtml.template']); $decoratorView->copyFrom($renderer); $decoratorView->copyFrom($dc['decorator.xhtml.params']); $decoratorView['lang'] = $dc['Translator']->getLanguageCode(); $decoratorView['username'] = $dc['User']->asAuthorizationString(); $decoratorView['currentModuleOutput'] = 'currentModule'; // Override helpAreaOutput $decoratorView['helpAreaOutput'] = (string) $renderer->panel($renderer::STATE_UNOBTRUSIVE)->setAttribute('class', 'HelpArea')->insert($renderer->panel()->setAttribute('class', 'wrap')->insert($renderer->buttonList($renderer::BUTTONSET)->insert($renderer->button('Hide', $renderer::BUTTON_CANCEL)))); $currentModule = $renderer['moduleView']->getModule(); // Override currentModuleOutput // - We must render CurrentModule before NotificationArea to catch notifications if ($currentModule instanceof \Nethgui\Module\ModuleCompositeInterface) { $decoratorView['currentModuleOutput'] = (string) $renderer->inset('moduleView'); } else { $decoratorView['currentModuleOutput'] = (string) $renderer->panel()->setAttribute('class', 'Controller')->insert($renderer->inset('moduleView', $renderer::INSET_FORM | $renderer::INSET_WRAP)->setAttribute('class', 'Action')->setAttribute('receiver', $currentModule->getIdentifier())); } $decoratorView['trackerOutput'] = (string) $renderer->inset('Tracker', $renderer::STATE_UNOBTRUSIVE); // Override menuOutput $decoratorView['menuOutput'] = (string) $renderer->inset('Menu'); // Override notificationOutput. Render Notification at the end, to catch notifications from other modules. $decoratorView['notificationOutput'] = (string) $renderer->inset('Notification'); $decoratorView['moduleTitle'] = $dc['Translator']->translate($currentModule, $currentModule->getAttributesProvider()->getTitle()); //read css from db $db = $dc['Main']->getPlatform()->getDatabase('configuration'); $colors = $db->getProp('httpd-admin', 'colors'); if ($colors) { $colors = explode(',', $colors); $decoratorView['colors'] = $colors; } $logo = $db->getProp('httpd-admin', 'logo'); $decoratorView['logo'] = $decoratorView->getPathUrl() . ($logo ? sprintf('images/%s', $logo) : 'images/logo.png'); $decoratorView['company'] = $db->getProp('OrganizationContact', 'Company'); $decoratorView['address'] = $db->getProp('OrganizationContact', 'Street') . ", " . $db->getProp('OrganizationContact', 'City'); $favicon = $db->getProp('httpd-admin', 'favicon'); $decoratorView['favicon'] = $decoratorView->getPathUrl() . ($favicon ? sprintf('images/%s', $favicon) : 'images/favicon.png'); return $renderer->spawnRenderer($decoratorView)->render(); }); $dc['main.css.template'] = $dc->protect(function (\Nethgui\Renderer\TemplateRenderer $renderer, $T, \Nethgui\Utility\HttpResponse $httpResponse) use($dc) { $content = ''; foreach ($renderer as $value) { if ($value instanceof \Nethgui\View\ViewInterface) { $content .= $renderer->spawnRenderer($value)->render(); } else { $content .= (string) $value; } } return $content; }); $dc['main.js.template'] = $dc['main.css.template']; $dc['main.txt.template'] = $dc['main.css.template']; $dc['Renderer'] = function ($dc) { $filenameResolver = $dc['FilenameResolver']; $targetFormat = $dc['OriginalRequest']->getFormat(); // Set the default root view template if (isset($dc[sprintf('main.%s.template', $targetFormat)])) { $dc['View']->setTemplate($dc[sprintf('main.%s.template', $targetFormat)]); } if ($targetFormat === 'json') { $renderer = new \Nethgui\Renderer\Json($dc['View']); } elseif ($targetFormat === 'xhtml') { $renderer = new \Nethgui\Renderer\Xhtml($dc['View'], $filenameResolver, 0); } else { if ($targetFormat === 'js') { $renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'application/javascript', 'UTF-8'); } elseif ($targetFormat === 'css') { $renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'text/css', 'UTF-8'); } else { $renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'text/plain', 'UTF-8'); } } $dc['HttpResponse']->addHeader(sprintf('Content-Type: %s', $renderer->getContentType()) . ($renderer->getCharset() ? sprintf('; charset=%s', $renderer->getCharset()) : '')); return $dc['objectInjector']($renderer, $dc); }; $this->dc = $dc; }
public function register(Pimple\Container $c) { include __DIR__ . '/../local/config.php'; foreach ($env as $envk => $envval) { $c["config/{$envk}"] = $envval; } $c['routes'] = ['/' => 'route/index', '/test', '/index', '/form', '/exception']; $c['entityManager'] = function ($c) { $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/orm"), $c['config/devVersion']); $conn = $c['config/databases']['default']; return Doctrine\ORM\EntityManager::create($conn, $config); }; $c['dispatcher'] = function ($c) { $routes = $c['routes']; $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use($routes) { foreach ($routes as $k => $v) { if (is_int($k)) { $k = $v; $v = "route{$v}"; } $r->addRoute('*', $k, $v); } }); return $dispatcher; }; $c['request'] = function ($c) { $req = Zend\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $c['logger']->notice('Started ' . $req->getMethod() . ' ' . $req->getUri()->getPath()); return $req; }; $c['resource'] = function ($c) { $dispatcher = $c['dispatcher']; $request = $c['request']; $uri = $request->getUri(); $path = $uri->getPath(); if (preg_match("|^(.+)\\..+\$|", $path, $matches)) { //if path ends in .json, .html, etc, ignore it $path = $matches[1]; } $res = $dispatcher->dispatch('*', $path); if ($res[0] == FastRoute\Dispatcher::NOT_FOUND) { throw new WebAppRouteNotFoundException("Route '{$path}' not found on routing table"); } $reqParameters = $res[2]; $c['requestParameters'] = $reqParameters; $entry = $res[1]; if (!isset($c[$entry])) { throw new WebAppResourceNotFoundException("Resource '{$entry}' not found on DI container"); } $res = $c[$entry]; $c['logger']->notice("Resource Selected ({$entry}): " . get_class($res)); return $res; }; $c['response'] = function ($c) { try { $resource = $c['resource']; return $resource->exec(); } catch (Exception $e) { return $c['handleException']($e); } }; $c['templaterFactory'] = function ($c) { $temp = new ExampleApp\templater\SampleTemplaterFactory(); $temp->globalContext = ['url' => $c['config/publicUrl'], 'assetsUrl' => $c['config/assetsUrl']]; return $temp; }; $c['responseFactory'] = function ($c) { $respFactory = new Resourceful\ResponseFactory(); $respFactory->templaterFactory = $c['templaterFactory']; return $respFactory; }; $c['responseEmitter'] = function ($c) { return new Zend\Diactoros\Response\SapiEmitter(); }; $c['session'] = function ($c) { $sess = new Resourceful\SessionStorage("ExampleApp"); $sess->startSession(); return $sess; }; $c['logger'] = function ($c) { $handler = new Monolog\Handler\ErrorLogHandler(Monolog\Handler\ErrorLogHandler::SAPI, Monolog\Logger::NOTICE); $formatter = new Monolog\Formatter\LineFormatter(); $formatter->includeStacktraces(true); $handler->setFormatter($formatter); $log = new Monolog\Logger('webapp'); $log->pushHandler($handler); return $log; }; $c['handleException'] = $c->protect(function ($e) use($c) { $c['logger']->error($e); $exceptionBuilder = new \Resourceful\Exception\ExceptionResponseBuilder(); $exceptionBuilder->includeStackTrace = $c['config/devVersion']; $exceptionBuilder->responseFactory = $c['responseFactory']; $request = null; try { $request = $c['request']; } catch (Exception $e) { //ignore and just use a null request } $resp = $exceptionBuilder->buildResponse($e, $request); return $resp; }); $mkres = function ($cls) use($c) { return function ($c) use($cls) { $res = new $cls(); $res->request = $c['request']; $res->parameters = $c['requestParameters']; $res->responseFactory = $c['responseFactory']; $res->session = $c['session']; return $res; }; }; $c['route/index'] = $mkres('ExampleApp\\Home\\Control\\IndexResource'); $c['route/form'] = $mkres('ExampleApp\\Home\\Control\\FormResource'); $c['route/exception'] = $mkres('ExampleApp\\Home\\Control\\ExceptionResource'); }
<?php include __DIR__ . '/vendor/autoload.php'; $app = new Pimple\Container(); foreach (include __DIR__ . '/app/config.php' as $option => $value) { $app[$option] = $value; } $app['db'] = function () use($app) { $pdo = new PDO("mysql:host=" . $app["db.host"] . ";dbname=" . $app["db.name"], $app["db.user"], $app["db.pass"], [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; }; $app['validate_name'] = $app->protect(function ($name) { return 1 == preg_match("/^[a-zA-ZłśćńóźżęąŁŚĆŃÓŻŹĘĄ-]+\$/", $name); }); $app['validate_worker'] = $app->protect(function (&$entry) use($app) { $errors = array(); $validate_name = $app['validate_name']; if (empty($entry["name"])) { $errors["name"] = "Imie nie może być puste"; } else { if (!$validate_name($entry["name"])) { $errors["name"] = "Musisz podać poprawne imie"; $entry["name"] = NULL; } } if (empty($entry["last_name"])) { $errors["last_name"] = "Nazwisko nie może być puste"; } else { if (!$validate_name($entry["last_name"])) { $errors["last_name"] = "Musisz podać poprawne nazwisko";
$container['comment_service_api'] = function () use($config) { $configuration = (new Jacobemerick\CommentService\Configuration())->setUsername($config->comments->user)->setPassword($config->comments->password)->addDefaultHeader('Content-Type', 'application/json')->setHost($config->comments->host)->setCurlTimeout($config->comments->timeout); $client = new Jacobemerick\CommentService\ApiClient($configuration); return new Jacobemerick\CommentService\Api\DefaultApi($client); }; // setup mail handler $container['mail'] = $container->factory(function ($c) { return (new Jacobemerick\Archangel\Archangel())->setLogger($c['logger']); }); // setup the logger $container['setup_logger'] = $container->protect(function ($name) use($container) { $logger = new Monolog\Logger($name); $logPath = __DIR__ . "/logs/{$name}.log"; $streamHandler = new Monolog\Handler\StreamHandler($logPath, Monolog\Logger::INFO); // todo - make this more useful // $streamHandler->setFormatter( // new Monolog\Formatter\LineFormatter("[%datetime%] %channel%.%level_name%: %message%\n") // ); $logger->pushHandler($streamHandler); Monolog\ErrorHandler::register($logger); $container['logger'] = $logger; }); // adds profiler $console = new Particletree\Pqp\Console(); $profiler = new Particletree\Pqp\PhpQuickProfiler($startTime); $profiler->setConsole($console); $container['console'] = $console; $container['profiler'] = $profiler; $container['console']->logMemory($startMemory, 'PHP - Pre-bootstrap memory', true); // sets up logger, modifes with profiler handler $pqpHandler = new Jacobemerick\MonologPqp\PqpHandler($container['console']); $container['setup_logger']($namespace);