helpers.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. use Composer\Autoload\ClassLoader;
  3. use Michel\Framework\Core\App;
  4. use Michel\RouterInterface;
  5. use Psr\Container\ContainerExceptionInterface;
  6. use Psr\Container\ContainerInterface;
  7. use Psr\Container\NotFoundExceptionInterface;
  8. use Psr\Http\Message\ResponseFactoryInterface;
  9. use Psr\Http\Message\ResponseInterface;
  10. use Psr\Http\Message\ServerRequestFactoryInterface;
  11. use Psr\Http\Message\ServerRequestInterface;
  12. if (!function_exists('michel_composer_loader')) {
  13. /**
  14. * Returns the instance of the Composer class loader.
  15. *
  16. * @return ClassLoader
  17. * @throws LogicException If the MICHEL_COMPOSER_AUTOLOAD_FILE constant is not defined.
  18. */
  19. function michel_composer_loader(): ClassLoader
  20. {
  21. if (!defined('MICHEL_COMPOSER_AUTOLOAD_FILE')) {
  22. throw new LogicException('MICHEL_COMPOSER_AUTOLOAD_FILE const must be defined!');
  23. }
  24. return require MICHEL_COMPOSER_AUTOLOAD_FILE;
  25. }
  26. }
  27. if (!function_exists('send_http_response')) {
  28. /**
  29. * Sends the HTTP response to the client.
  30. *
  31. * @param ResponseInterface $response The HTTP response to send.
  32. */
  33. function send_http_response(ResponseInterface $response)
  34. {
  35. $httpLine = sprintf('HTTP/%s %s %s',
  36. $response->getProtocolVersion(),
  37. $response->getStatusCode(),
  38. $response->getReasonPhrase()
  39. );
  40. if (!headers_sent()) {
  41. header($httpLine, true, $response->getStatusCode());
  42. foreach ($response->getHeaders() as $name => $values) {
  43. foreach ($values as $value) {
  44. header("$name: $value", false);
  45. }
  46. }
  47. }
  48. echo $response->getBody();
  49. }
  50. }
  51. if (!function_exists('container')) {
  52. /**
  53. * Retrieves the application's dependency injection container.
  54. *
  55. * @return ContainerInterface The dependency injection container.
  56. */
  57. function container(): ContainerInterface
  58. {
  59. return App::getContainer();
  60. }
  61. }
  62. if (!function_exists('create_request')) {
  63. /**
  64. * Creates a new HTTP request.
  65. *
  66. * @return ServerRequestInterface The HTTP response.
  67. */
  68. function create_request(): ServerRequestInterface
  69. {
  70. return App::createServerRequest();
  71. }
  72. }
  73. if (!function_exists('request_factory')) {
  74. /**
  75. * Creates a new HTTP request.
  76. *
  77. * @return ServerRequestFactoryInterface The HTTP response.
  78. */
  79. function request_factory(): ServerRequestFactoryInterface
  80. {
  81. return App::getServerRequestFactory();
  82. }
  83. }
  84. if (!function_exists('response_factory')) {
  85. /**
  86. * Retrieves the response factory.
  87. *
  88. * @return ResponseFactoryInterface The response factory.
  89. */
  90. function response_factory(): ResponseFactoryInterface
  91. {
  92. return App::getResponseFactory();
  93. }
  94. }
  95. if (!function_exists('response')) {
  96. /**
  97. * Creates a new HTTP response.
  98. *
  99. * @param string $content The response content.
  100. * @param int $status The HTTP status code.
  101. * @return ResponseInterface The HTTP response.
  102. */
  103. function response(string $content = '', int $status = 200, $contentType = 'text/html'): ResponseInterface
  104. {
  105. $response = response_factory()->createResponse($status);
  106. $response->getBody()->write($content);
  107. return $response->withHeader('Content-Type', $contentType);
  108. }
  109. }
  110. if (!function_exists('json_response')) {
  111. /**
  112. * Creates a new JSON response.
  113. *
  114. * @param array|JsonSerializable $data The data to encode to JSON.
  115. * @param int $status The HTTP status code.
  116. * @param int $flags JSON encoding flags.
  117. * @return ResponseInterface The JSON response.
  118. * @throws InvalidArgumentException If JSON encoding fails.
  119. */
  120. function json_response($data, int $status = 200, int $flags = JSON_HEX_TAG
  121. | JSON_HEX_APOS
  122. | JSON_HEX_AMP
  123. | JSON_HEX_QUOT
  124. | JSON_UNESCAPED_SLASHES): ResponseInterface
  125. {
  126. if (!is_array($data) && !is_subclass_of($data, JsonSerializable::class)) {
  127. throw new InvalidArgumentException(
  128. 'Data must be an array or implement JsonSerializable interface'
  129. );
  130. }
  131. $response = response_factory()->createResponse($status);
  132. $response->getBody()->write(json_encode($data, $flags));
  133. if (json_last_error() !== JSON_ERROR_NONE) {
  134. throw new InvalidArgumentException(
  135. sprintf('Unable to encode data to JSON: %s', json_last_error_msg())
  136. );
  137. }
  138. return $response->withHeader('Content-Type', 'application/json');
  139. }
  140. }
  141. if (!function_exists('redirect')) {
  142. /**
  143. * Creates a redirect response.
  144. *
  145. * @param string $url The URL to redirect to.
  146. * @param int $status The HTTP status code.
  147. * @return ResponseInterface The redirect response.
  148. */
  149. function redirect(string $url, int $status = 302): ResponseInterface
  150. {
  151. $response = response_factory()->createResponse($status);
  152. return $response->withHeader('Location', $url);
  153. }
  154. }
  155. if (!function_exists('redirect_to')) {
  156. /**
  157. * Creates a redirect response to a named route.
  158. *
  159. * @param string $routeName The name of the route registered in the router.
  160. * @param array $parameters Dynamic parameters to build the URI (e.g., ['id' => 1]).
  161. * @param int $status The HTTP status code (default: 302).
  162. * @return ResponseInterface The configured redirect response.
  163. */
  164. function redirect_to(string $routeName, array $parameters = [], int $status = 302): ResponseInterface
  165. {
  166. /** @var RouterInterface $router */
  167. $router = container()->get(RouterInterface::class);
  168. return response_factory()
  169. ->createResponse($status)
  170. ->withHeader('Location', $router->generateUri($routeName, $parameters));
  171. }
  172. }
  173. if (!function_exists('render_view')) {
  174. /**
  175. * Renders a view template with the provided context.
  176. *
  177. * @param string $view The name of the view template.
  178. * @param array $context The context data to pass to the view.
  179. * @return string The rendered view.
  180. * @throws ContainerExceptionInterface
  181. * @throws NotFoundExceptionInterface
  182. */
  183. function render_view(string $view, array $context = []): string
  184. {
  185. if (!container()->has('render')) {
  186. throw new \LogicException('The "render_view" method requires the "michel/pure-plate" package. ' .
  187. 'Try running "composer require michel/pure-plate".');
  188. }
  189. $renderer = container()->get('render');
  190. return $renderer->render($view, $context);
  191. }
  192. }
  193. if (!function_exists('render')) {
  194. /**
  195. * Renders a view template and creates an HTTP response.
  196. *
  197. * @param string $view The name of the view template.
  198. * @param array $context The context data to pass to the view.
  199. * @param int $status The HTTP status code.
  200. * @return ResponseInterface The HTTP response with the rendered view.
  201. */
  202. function render(string $view, array $context = [], int $status = 200): ResponseInterface
  203. {
  204. return response(render_view($view, $context), $status);
  205. }
  206. }
  207. if (!function_exists('url')) {
  208. /**
  209. * Generates Absolute URL for a route.
  210. *
  211. * @param string $name
  212. * @param array $parameters
  213. * @return string The dependency injection container.
  214. * @throws ContainerExceptionInterface
  215. * @throws NotFoundExceptionInterface
  216. */
  217. function url(string $name, array $parameters = []): string
  218. {
  219. /**
  220. * @var RouterInterface $router
  221. */
  222. $router = App::getContainer()->get(RouterInterface::class);
  223. return $router->generateUri($name, $parameters, true);
  224. }
  225. }
  226. if (!function_exists('asset')) {
  227. /**
  228. * Generates a URL for an asset.
  229. *
  230. *
  231. * @param string $path
  232. * @return string The dependency injection container.
  233. */
  234. function asset(string $path): string
  235. {
  236. return '/'.ltrim($path, '/');
  237. }
  238. }