/** * @return RestModeHandler this */ public function handle() { $nameSpace = $this->getNameSpace(); if (!class_exists($nameSpace)) { return $this->error(404); } $requestMethod = strtolower($this->getRequestMethod()); if ($requestMethod === null) { return $this->error(405); } $object = new $nameSpace($this->config); if (!$object instanceof AbstractRestPage) { Logger::error('class `' . $nameSpace . '` is not instance of `' . AbstractRestPage::class . '`'); return $this->error(500); } if ($object->access() !== true) { return $this->error(403); } if (isset($this->request->getInputList()[0])) { $method = $requestMethod . ucfirst(strtolower($this->request->getInputList()[0])); if (method_exists($object, $method)) { $responseCode = $object->{$method}($this->request); } } if (!isset($responseCode)) { $method = $requestMethod . 'Index'; if (method_exists($object, $method)) { $responseCode = $object->{$method}($this->request); } } if (!isset($responseCode)) { return $this->error(501); } if ($responseCode === true) { $responseCode = 200; } elseif ($responseCode === false) { $responseCode = 400; } if (!HttpConst::isStatus($responseCode)) { $dataText = var_export($responseCode, true); $callText = get_class($object) . '::' . (isset($method) ? $method : ''); Logger::error('invalid response `' . $dataText . '` of `' . $callText . '`'); return $this->error(500); } echo $object->getResponse()->toJson(); http_response_code($responseCode); return $this; }
/** * @param int $code * @return AbstractModeHandler this */ protected function error($code) { if (!HttpConst::isStatus($code)) { throw new RuntimeException('unknown HTTP-Status Code `' . $code . '`'); } http_response_code($code); # pipe to URL if (isset($this->settings['err' . $code . '-pipe'])) { $target = new MAPUrl($this->settings['err' . $code . '-pipe'], $this->config); if ($target->get() === $this->request->get()) { Logger::error('endless pipe-loop (status: `' . $code . '`) - interrupted with HTTP-Status `508`'); return $this->error(508); } $this->setLocation(new Url($this->settings['err' . $code . '-pipe'])); return $this; } # default error output if (defined('peer\\http\\HttpConst::STATUS_' . $code)) { $message = constant('peer\\http\\HttpConst::STATUS_' . $code); } else { $message = 'N/A'; } $this->setContentType('text/plain'); echo '[' . $code . '] ' . $message; return $this; }