Просмотр файла app/helpers.php

Размер файла: 6.96Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. use App\Factories\AppFactory;
  6. use App\Models\User;
  7. use App\Services\BBCode;
  8. use App\Services\Session;
  9. use App\Services\Setting;
  10. use App\Services\Str;
  11. use DI\Container;
  12. use Slim\App;
  13. use Slim\Factory\ServerRequestCreatorFactory;
  14. use Slim\Exception\HttpException;
  15.  
  16. /**
  17. * Escape data
  18. *
  19. * @param mixed $value
  20. * @param bool $doubleEncode
  21. *
  22. * @return array|string
  23. */
  24. function escape(mixed $value, bool $doubleEncode = true): mixed
  25. {
  26. $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401;
  27.  
  28. if (is_array($value)) {
  29. foreach ($value as $key => $val) {
  30. $value[$key] = escape($val, $doubleEncode);
  31. }
  32. } else {
  33. $value = htmlspecialchars((string) $value, $flags, 'UTF-8', $doubleEncode);
  34. }
  35.  
  36. return $value;
  37. }
  38.  
  39.  
  40. /**
  41. * Sanitize
  42. *
  43. * @param string $str
  44. *
  45. * @return string
  46. */
  47. function sanitize(string $str): string
  48. {
  49. // preg_replace('/\R/u', '', $str);
  50. $search = ["\0", "\x00", "\x1A", chr(226) . chr(128) . chr(174)];
  51. $str = str_replace($search, '', $str);
  52.  
  53. return trim($str);
  54. }
  55.  
  56. /**
  57. * BBCode
  58. *
  59. * @param mixed $text
  60. * @param bool $parse
  61. *
  62. * @return string
  63. */
  64. function bbCode(mixed $text, bool $parse = true): string
  65. {
  66. $bbCode = new BBCode();
  67. $checkText = escape($text);
  68.  
  69. if (! $parse) {
  70. return $bbCode->clear($checkText);
  71. }
  72.  
  73. $parseText = $bbCode->parse($checkText);
  74.  
  75. return $bbCode->parseStickers($parseText);
  76. }
  77.  
  78. /**
  79. * Возвращает обрезанный текст с закрытием тегов
  80. *
  81. * @param string $text
  82. * @param int $words
  83. * @param string $end
  84. *
  85. * @return string
  86. */
  87. function bbCodeTruncate(string $text, int $words = 20, string $end = '...'): string
  88. {
  89. $bbCode = new BBCode();
  90.  
  91. $text = Str::words($text, $words, $end);
  92. $text = bbCode($bbCode->closeTags($text));
  93.  
  94. return preg_replace('/\[(.*?)]/', '', $text);
  95. }
  96.  
  97. /**
  98. * Возвращает размер в читаемом формате
  99. *
  100. * @param int $bytes
  101. * @param int $precision
  102. *
  103. * @return string
  104. */
  105. function formatSize(int $bytes, int $precision = 2): string
  106. {
  107. $units = ['B', 'Kb', 'Mb', 'Gb', 'Tb'];
  108. $pow = floor(($bytes ? log($bytes) : 0) / log(1000));
  109. $pow = min($pow, count($units) - 1);
  110.  
  111. $bytes /= (1 << (10 * $pow));
  112.  
  113. return round($bytes, $precision) . $units[$pow];
  114. }
  115.  
  116. /**
  117. * @param string|null $abstract
  118. *
  119. * @return mixed|Container
  120. */
  121. function app(?string $abstract = null): mixed
  122. {
  123. $app = AppFactory::getInstance();
  124.  
  125. if ($abstract === null) {
  126. return $app->getContainer();
  127. }
  128.  
  129. return $app->getContainer()->get($abstract);
  130. }
  131.  
  132. /**
  133. * Get route by name
  134. *
  135. * @param string $routeName
  136. * @param array $data
  137. * @param array $queryParams
  138. *
  139. * @return string
  140. */
  141. function route(string $routeName, array $data = [], array $queryParams = []): string
  142. {
  143. return app(App::class)
  144. ->getRouteCollector()
  145. ->getRouteParser()
  146. ->urlFor($routeName, $data, $queryParams);
  147. }
  148.  
  149. /**
  150. * Get current route
  151. *
  152. * @return string
  153. */
  154. function currentRoute(): string
  155. {
  156. $serverRequestCreator = ServerRequestCreatorFactory::create();
  157. $request = $serverRequestCreator->createServerRequestFromGlobals();
  158.  
  159. return $request->getUri()->getPath();
  160. }
  161.  
  162. /**
  163. * Get session
  164. *
  165. * @param string|null $key
  166. * @param mixed|null $default
  167. *
  168. * @return Session|mixed
  169. */
  170. function session(?string $key = null, mixed $default = null): mixed
  171. {
  172. /** @var Session $session */
  173. $session = app(Session::class);
  174.  
  175. if ($key === null) {
  176. return $session;
  177. }
  178.  
  179. return $session->get($key, $default);
  180. }
  181.  
  182. /**
  183. * Get setting
  184. *
  185. * @param string|null $key
  186. * @param mixed|null $default
  187. *
  188. * @return Setting|mixed
  189. */
  190. function setting(?string $key = null, mixed $default = null): mixed
  191. {
  192. /** @var Setting $setting */
  193. $setting = app(Setting::class);
  194.  
  195. if ($key === null) {
  196. return $setting;
  197. }
  198.  
  199. return $setting->get($key, $default);
  200. }
  201.  
  202. /**
  203. * Check auth
  204. *
  205. * @return User|bool
  206. */
  207. function checkAuth(): User|bool
  208. {
  209. $login = session('login');
  210. $password = session('password');
  211.  
  212. if ($login && $password) {
  213. $user = User::query()->where('login', $login)->first();
  214.  
  215. if ($user && $password === $user->password) {
  216. return $user;
  217. }
  218. }
  219.  
  220. return false;
  221. }
  222.  
  223. /**
  224. * Is user
  225. *
  226. * @return bool
  227. */
  228. function isUser(): bool
  229. {
  230. return (bool) getUser();
  231. }
  232.  
  233. /**
  234. * Get user
  235. *
  236. * @param string $key
  237. *
  238. * @return User|bool|null
  239. */
  240. function getUser(string $key = ''): mixed
  241. {
  242. static $user;
  243.  
  244. if (! $user) {
  245. $user = checkAuth();
  246. }
  247.  
  248. return $key ? ($user->$key ?? null) : $user;
  249. }
  250.  
  251. /**
  252. * Is admin
  253. *
  254. * @param string $role
  255. *
  256. * @return bool
  257. */
  258. function isAdmin(string $role = User::EDITOR): bool
  259. {
  260. $group = array_flip(User::ROLES);
  261.  
  262. return isUser()
  263. && isset($group[$role], $group[getUser('role')])
  264. && $group[getUser('role')] <= $group[$role];
  265. }
  266.  
  267. /**
  268. * Get extension
  269. *
  270. * @param string $filename Имя файла
  271. *
  272. * @return string расширение
  273. */
  274. function getExtension(string $filename): string
  275. {
  276. return pathinfo($filename, PATHINFO_EXTENSION);
  277. }
  278.  
  279. /**
  280. * Get unique name
  281. *
  282. * @param string|null $extension
  283. *
  284. * @return string
  285. */
  286. function uniqueName(string $extension = null): string
  287. {
  288. if ($extension) {
  289. $extension = '.' . $extension;
  290. }
  291.  
  292. return str_replace('.', '', uniqid('', true)) . $extension;
  293. }
  294.  
  295. /**
  296. * Get root path
  297. *
  298. * @param string $path
  299. *
  300. * @return string
  301. */
  302. function basePath(string $path = ''): string
  303. {
  304. return dirname(__DIR__) . '/' . ltrim($path, '/');
  305. }
  306.  
  307. /**
  308. * Get public path
  309. *
  310. * @param string $path
  311. *
  312. * @return string
  313. */
  314. function publicPath(string $path = ''): string
  315. {
  316. return basePath('/public/' . ltrim($path, '/'));
  317. }
  318.  
  319. /**
  320. * Get storage path
  321. *
  322. * @param string $path
  323. *
  324. * @return string
  325. */
  326. function storagePath(string $path = ''): string
  327. {
  328. return basePath('/storage/' . ltrim($path, '/'));
  329. }
  330.  
  331. /**
  332. * Throw an Exception with the given data.
  333. *
  334. * @param int $code
  335. * @param string $message
  336. *
  337. * @return void
  338. */
  339. function abort(int $code, string $message = ''): void
  340. {
  341. $serverRequestCreator = ServerRequestCreatorFactory::create();
  342. $request = $serverRequestCreator->createServerRequestFromGlobals();
  343.  
  344. throw new HttpException($request, $message, $code);
  345. }
  346.  
  347. /**
  348. * Session old
  349. *
  350. * @param string $key
  351. * @param mixed|null $default
  352. *
  353. * @return mixed
  354. */
  355. function old(string $key, mixed $default = null): mixed
  356. {
  357. if (! session('flash.old')) {
  358. return escape($default);
  359. }
  360.  
  361. $old = session('flash.old.' . $key, $default);
  362.  
  363. return escape($old);
  364. }
  365.  
  366. /**
  367. * Session has error
  368. *
  369. * @param string $field
  370. *
  371. * @return string
  372. */
  373. function hasError(string $field): string
  374. {
  375. if (session('flash.errors')) {
  376. return session('flash.errors.' . $field) ? ' is-invalid' : ' is-valid';
  377. }
  378.  
  379. return '';
  380. }
  381.  
  382. /**
  383. * Session get error
  384. *
  385. * @param string $field
  386. *
  387. * @return string
  388. */
  389. function getError(string $field): string
  390. {
  391. return session('flash.errors.' . $field, '');
  392. }