From 30785d4f5c76391f9ab3bf4f4d2aa21cf72b6644 Mon Sep 17 00:00:00 2001 From: "a.shamavov" Date: Fri, 12 Apr 2024 16:54:30 +0500 Subject: [PATCH] refactoring --- .gitignore | 1 + src/Action/Functions.php | 219 ++++++++++++++++++++++++++++++ src/Controller/HomeController.php | 32 ++--- 3 files changed, 232 insertions(+), 20 deletions(-) create mode 100644 src/Action/Functions.php diff --git a/.gitignore b/.gitignore index 4daae38..930e1e2 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,4 @@ /public/assets/ /assets/vendor/ ###< symfony/asset-mapper ### +/.idea \ No newline at end of file diff --git a/src/Action/Functions.php b/src/Action/Functions.php new file mode 100644 index 0000000..51b043b --- /dev/null +++ b/src/Action/Functions.php @@ -0,0 +1,219 @@ +12, 'count'=>4], ['price'=>10, 'count'=>2], ['price'=>8, 'count'=>4], + * ['price'=>8, 'count'=>5], ['price'=>5, 'count'=>5],] + */ + + /** + * Найдет элемент с указаным id + * @param array $array - массив, содержащий элементы со структурой + * [ + * 'id' => 30, + * 'name' => 'Jhon', + * 'age' => 23, + * ] + * @param $id - ид искомого элемента + * @return ?array - найденный элемент + */ + + public function search(array $array, int $id): ?array + { + $rowId = array_search($id, array_column($array, 'id'), false); + if ($rowId !== false) { + return $array[$rowId]; + } + return null; + } + + /** + * Удалить дубликаты, оставив только уникальные значения + * @param array $array + * @return array + */ + + public function uniqElements(array $array): array + { + return array_unique($array, SORT_REGULAR); + } + + /** + * Выходной массив: + * Array ( + * [0] => Array([0] => laravel, [1] => php) + * [1] => Array([0] => codeigniter, [1] => php) + * [3] => Array([0] => c++, [1] => java)) + * ) + */ + + /** + * Сгруппировать подразедлы в верхние разделы меню + * Дочерние элементы поместить в массив родителя с ключом submenu + * Значение под ключом depth определяет уровень раздела + * Массив $aMenu всегда начинается с элемента depth = 0, + * все последующие элементы с depth = 1 являются его дочерними + * элементами + * @param array $aMenu + * @return array + */ + + public function prepareMenu(array $aMenu): array + { + $result = []; + foreach ($aMenu as $arr) { + if ($arr['depth'] == 0) { + $result[] = array( + 'name' => $arr['name'], + 'depth' => $arr['depth'], + 'submenu' => [] + ); + continue; + } + $result[array_key_last($result)]['submenu'][] = array( + 'name' => $arr['name'], + 'depth' => $arr['depth'], + ); + } + return $result; + } + + /** + * Выходные данные: + * $aMenu = [ + * [ + * 'name' => 'Смартфоны и гаджеты', + * 'depth' => 0, + * 'submenu' => [ + * ['name' => 'Смартфоны, мобильные телефоны','depth' => 1,], + * ['name' => 'Планшеты','depth' => 1,], + * ['name' => 'Наушники и гарнитуры','depth' => 1,],], + * ], + * [ + * 'name' => 'Компьютеры и ноутбуки', + * 'depth' => 0, + * 'submenu' => [ + * ['name' => 'Ноутбуки и аксессуары','depth' => 1,], + * ['name' => 'Компьютеры и мониторы','depth' => 1,], + * ['name' => 'Компьютерные комплектующие','depth' => 1,],]], + * [ + * 'name' => 'Техника для дома', + * 'depth' => 0, + * 'submenu' => [ + * ['name' => 'Техника для уборки','depth' => 1,], + * ['name' => 'Товары для ухода за одеждой','depth' => 1,], + * ['name' => 'Аксессуары для техники','depth' => 1,],] + * ], + * [ + * 'name' => 'Товары для дома и кухни', + * 'depth' => 0, + * 'submenu' => [ + * ['name' => 'Посуда','depth' => 1,],]], + * ]; + */ + + /** + * Функция рассчитывает кол-во дней до нового года + * @param DateTimeImmutable $date дата от которой, необходимо рассчитать кол-во дней + * @return int + * @throws Exception + */ + + public function howDaysToNy(DateTimeImmutable $date): int + { + $endYear = date("Y-12-31", date_timestamp_get($date)); + $dateInterval = date_diff(new DateTimeImmutable($endYear), $date); + return (int)$dateInterval->format("%a") + 1; + } + + + /** + * Вернет все пятницы 13 в году + * @param int $year год, в котором необходимо произвести расчет + * @return DateTimeImmutable[] + * @throws Exception + */ + + public function countFriday13(int $year): iterable + { + $startDate = new DateTime("$year-01-01 Friday"); + ++$year; + $endDate = new DateTime("$year-01-01"); + $interval = new DateInterval('P7D'); + foreach (new DatePeriod($startDate, $interval, $endDate) as $day) { + yield new DateTimeImmutable($day->format("Y-m-d")); + } + } + + /** + * Вернет кол-во дней между датами + * @param DateTimeImmutable $dateStart дата начала + * @param DateTimeImmutable $dateEnd дата окончания + * @return int + */ + public function diffDays(DateTimeImmutable $dateStart, DateTimeImmutable $dateEnd): int + { + $dateInterval = date_diff($dateStart, $dateEnd); + return (int)$dateInterval->format("%a") ; + } + + /** + * Напиши функцию, которая принимает путь до файла, + * проверяет, что файл существует и выводит пользователю весь контент файла + * (файл можешь создать любой) + * @param string $filePath путь до файла + * @return string + * @throws RuntimeException + */ + + public function readLogFile(string $filePath): string + { + if (file_exists($filePath)) { + $text = ""; + $file = fopen($filePath, 'rb'); + while(!feof($file)) { + $line = fgets($file); + $text .= $line; + } + fclose($file); + return $text; + } + else { + throw new RuntimeException("File not found: $filePath"); + } + } +} + diff --git a/src/Controller/HomeController.php b/src/Controller/HomeController.php index 51d19fa..803667d 100644 --- a/src/Controller/HomeController.php +++ b/src/Controller/HomeController.php @@ -2,36 +2,28 @@ namespace App\Controller; -use DateInterval; -use DatePeriod; -use DateTime; -use DateTimeImmutable; +use App\Action\Functions; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; class HomeController extends AbstractController { - private function readLogFile(string $fileName): string { - $filePath = $this->getParameter('kernel.project_dir') . "/public/files/" . $fileName; - if (file_exists($filePath)) { - $text = ""; - $file = fopen($filePath, "r"); - while(!feof($file)) { - $line = fgets($file); - $text .= $line; - } - fclose($file); - return $text; - } - return "Такого файла не существует."; - } + private Functions $functions; + public function __construct(Functions $functions) + { + $this->functions = $functions; + } #[Route('/{fileName}', name: 'home')] public function home(string $fileName): Response // text.txt { - $text = $this->readLogFile($fileName); - return $this->render('home.html.twig', ['text' => $text]); + $filePath = $this->getParameter('kernel.project_dir') . "/public/files/"; + $text = $this->functions->readLogFile($filePath . $fileName); + $response = new JsonResponse($text); + $response->setEncodingOptions(JSON_UNESCAPED_UNICODE); + return $response; } } -- GitLab