Exemplo n.º 1
0
 /**
  * create php errorhandler, which also logs to php error_log
  *
  * @param Monolog\Logger $app
  */
 private static function registerErrorHandler($app)
 {
     // get base logger
     $logger = clone $app;
     // add extra handler
     $handler = new Monolog\Handler\ErrorLogHandler();
     // set formatter without datetime
     $handler->setFormatter(new Monolog\Formatter\LineFormatter('%channel%.%level_name%: %message% %context% %extra%'));
     $logger->pushHandler($handler);
     // attach php errorhandler to app logger
     Monolog\ErrorHandler::register($logger);
 }
Exemplo n.º 2
0
 /**
  * @param BaseApp $app
  */
 public function register(BaseApp $app)
 {
     $app->set('errorLogger', function (BaseApp $app) {
         $logger = new \Monolog\Logger('errorLogger');
         $handler = new \Monolog\Handler\ErrorLogHandler();
         if (!$app->isCli()) {
             $handler->pushProcessor(new \Monolog\Processor\WebProcessor());
             $format = '%level_name%: %message% %extra.server%%extra.url%';
         } else {
             $format = '%level_name%: %message%';
         }
         $handler->setFormatter(new \Monolog\Formatter\LineFormatter($format, null, true));
         $logger->pushHandler($handler);
         return $logger;
     });
     $app->set('whoopsDebugErrorPageHandler', function (BaseApp $app) {
         $prettyPageHandler = new \Whoops\Handler\PrettyPageHandler();
         if ($app->getConfig()->has('editor')) {
             $prettyPageHandler->setEditor($app->getConfig()->get('editor'));
         }
         return $prettyPageHandler;
     });
     $app->set('whoopsErrorHandler', function (BaseApp $app) {
         $plainTextHandler = new \Whoops\Handler\PlainTextHandler();
         $plainTextHandler->setLogger($app->get('errorLogger'));
         if (!$app->isCli()) {
             $plainTextHandler->loggerOnly(true);
         }
         return $plainTextHandler;
     });
     $app->set('whoops', function (BaseApp $app) {
         $whoops = new \Whoops\Run();
         if (ini_get('display_errors')) {
             $whoops->pushHandler($app->get('whoopsDebugErrorPageHandler'));
         }
         // Handles cli output and logging
         $whoops->pushHandler($app->get('whoopsErrorHandler'));
         return $whoops;
     });
     $app->get('whoops')->register();
 }
Exemplo n.º 3
0
 * @throws AMQPExchangeException if exchange does not exists
 */
$exchange = $broker->declareExchange(AMQP_DURABLE, "some-exchange", AMQP_EX_TYPE_TOPIC);
/**
 * Listen on shared queue and bind queue to exchange
 *
 * @throws AMQPQueueException if queue does not exists
 */
//$consumer->listen($queue, $exchange);
/**
 * Error handling
 * You can register listener to `kemer.error` event to handle exceptions.
 * Add Monolog to log everything
 */
$dispatcher->addSubscriber(new AmqpAddons\MonologSubscriber($logger = new Monolog\Logger("AMQP")));
$logger->pushHandler($handler = new Monolog\Handler\ErrorLogHandler());
$handler->setFormatter(new Monolog\Formatter\LineFormatter($output = " %level_name% %message% %context% ", $dateFormat = "g:i" . false, false));
$dispatcher->addSubscriber(new AmqpAddons\Command\QueueGetCommand($broker, $logger));
/**
 * postpone message on RuntimeException
 */
$dispatcher->addListener('kemer.error', function (GenericEvent $event, $eventName, $dispatcher) {
    if ($event["error"] instanceof \RuntimeException) {
        $dispatcher->dispatch(AmqpAddons\AddonsEvent::POSTPONE, $event->getSubject());
    }
}, -1);
/**
 * reject message + requeue (if not requeued before) on error
 */
$dispatcher->addListener('kemer.error', function (GenericEvent $event, $eventName, $dispatcher) {
    $subject = $event->getSubject();
Exemplo n.º 4
0
 /**
  * Constructor
  *
  * @param string $dir Directory containing config files
  */
 public function __construct($dir)
 {
     $that = $this;
     $this->dir = rtrim($dir, '/\\');
     $this->cache = function (App $app) use($that) {
         $config = $app->config;
         if ($config->cachePath instanceof \Minify_CacheInterface) {
             return $config->cachePath;
         }
         if (!$config->cachePath || is_string($config->cachePath)) {
             return new \Minify_Cache_File($config->cachePath, $config->cacheFileLocking, $app->logger);
         }
         $type = $that->typeOf($config->cachePath);
         throw new \RuntimeException('$min_cachePath must be a path or implement Minify_CacheInterface.' . " Given {$type}");
     };
     $this->config = function (App $app) {
         $config = (require $app->configPath);
         if ($config instanceof \Minify\Config) {
             return $config;
         }
         // copy from vars into properties
         $config = new \Minify\Config();
         $propNames = array_keys(get_object_vars($config));
         $prefixer = function ($name) {
             return "min_{$name}";
         };
         $varNames = array_map($prefixer, $propNames);
         $vars = compact($varNames);
         foreach ($varNames as $varName) {
             if (isset($vars[$varName])) {
                 $config->{substr($varName, 4)} = $vars[$varName];
             }
         }
         return $config;
     };
     $this->configPath = "{$this->dir}/config.php";
     $this->controller = function (App $app) use($that) {
         $config = $app->config;
         if (empty($config->factories['controller'])) {
             $ctrl = new \Minify_Controller_MinApp($app->env, $app->sourceFactory, $app->logger);
         } else {
             $ctrl = call_user_func($config->factories['controller'], $app);
         }
         if ($ctrl instanceof \Minify_ControllerInterface) {
             return $ctrl;
         }
         $type = $that->typeOf($ctrl);
         throw new \RuntimeException('$min_factories["controller"] callable must return an implementation' . " of Minify_CacheInterface. Returned {$type}");
     };
     $this->docRoot = function (App $app) {
         $config = $app->config;
         if (empty($config->documentRoot)) {
             return $app->env->getDocRoot();
         }
         return $app->env->normalizePath($config->documentRoot);
     };
     $this->env = function (App $app) {
         $config = $app->config;
         $envArgs = empty($config->envArgs) ? array() : $config->envArgs;
         return new \Minify_Env($envArgs);
     };
     $this->errorLogHandler = function (App $app) {
         $format = "%channel%.%level_name%: %message% %context% %extra%";
         $handler = new \Monolog\Handler\ErrorLogHandler();
         $handler->setFormatter(new \Monolog\Formatter\LineFormatter($format));
         return $handler;
     };
     $this->groupsConfig = function (App $app) {
         return require $app->groupsConfigPath;
     };
     $this->groupsConfigPath = "{$this->dir}/groupsConfig.php";
     $this->logger = function (App $app) use($that) {
         $value = $app->config->errorLogger;
         if ($value instanceof \Psr\Log\LoggerInterface) {
             return $value;
         }
         $logger = new \Monolog\Logger('minify');
         if (!$value) {
             return $logger;
         }
         if ($value === true || $value instanceof \FirePHP) {
             $logger->pushHandler($app->errorLogHandler);
             $logger->pushHandler(new \Monolog\Handler\FirePHPHandler());
             return $logger;
         }
         if ($value instanceof \Monolog\Handler\HandlerInterface) {
             $logger->pushHandler($value);
             return $logger;
         }
         // BC
         if (is_object($value) && is_callable(array($value, 'log'))) {
             $handler = new \Minify\Logger\LegacyHandler($value);
             $logger->pushHandler($handler);
             return $logger;
         }
         $type = $that->typeOf($value);
         throw new \RuntimeException('If set, $min_errorLogger must be a PSR-3 logger or a Monolog handler.' . " Given {$type}");
     };
     $this->minify = function (App $app) use($that) {
         $config = $app->config;
         if (empty($config->factories['minify'])) {
             return new \Minify($app->cache, $app->logger);
         }
         $minify = call_user_func($config->factories['minify'], $app);
         if ($minify instanceof \Minify) {
             return $minify;
         }
         $type = $that->typeOf($minify);
         throw new \RuntimeException('$min_factories["minify"] callable must return a Minify object.' . " Returned {$type}");
     };
     $this->serveOptions = function (App $app) {
         $config = $app->config;
         $env = $app->env;
         $ret = $config->serveOptions;
         $ret['minifierOptions']['text/css']['docRoot'] = $app->docRoot;
         $ret['minifierOptions']['text/css']['symlinks'] = $config->symlinks;
         $ret['minApp']['symlinks'] = $config->symlinks;
         // auto-add targets to allowDirs
         foreach ($config->symlinks as $uri => $target) {
             $ret['minApp']['allowDirs'][] = $target;
         }
         if ($config->allowDebugFlag) {
             $ret['debug'] = \Minify_DebugDetector::shouldDebugRequest($env);
         }
         if ($config->concatOnly) {
             $ret['concatOnly'] = true;
         }
         // check for URI versioning
         if ($env->get('v') !== null || preg_match('/&\\d/', $app->env->server('QUERY_STRING'))) {
             $ret['maxAge'] = 31536000;
         }
         // need groups config?
         if ($env->get('g') !== null) {
             $ret['minApp']['groups'] = $app->groupsConfig;
         }
         return $ret;
     };
     $this->sourceFactory = function (App $app) {
         return new \Minify_Source_Factory($app->env, $app->sourceFactoryOptions, $app->cache);
     };
     $this->sourceFactoryOptions = function (App $app) {
         $serveOptions = $app->serveOptions;
         $ret = array();
         // translate legacy setting to option for source factory
         if (isset($serveOptions['minApp']['noMinPattern'])) {
             $ret['noMinPattern'] = $serveOptions['minApp']['noMinPattern'];
         }
         if (isset($serveOptions['minApp']['allowDirs'])) {
             $ret['allowDirs'] = $serveOptions['minApp']['allowDirs'];
         }
         if (isset($serveOptions['checkAllowDirs'])) {
             $ret['checkAllowDirs'] = $serveOptions['checkAllowDirs'];
         }
         if (is_numeric($app->config->uploaderHoursBehind)) {
             $ret['uploaderHoursBehind'] = $app->config->uploaderHoursBehind;
         }
         return $ret;
     };
 }
Exemplo n.º 5
0
 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');
 }