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

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