From d4230faa9be76e8d348606e2c4cf77ee207319eb Mon Sep 17 00:00:00 2001 From: "a.shamavov" <a.shamavov@iqdev.digital> Date: Fri, 12 Apr 2024 12:58:53 +0500 Subject: [PATCH] refactoring --- .gitignore | 1 + src/Action/Functions.php | 180 ++++++++++++++++++++++++++++++ src/Controller/HomeController.php | 31 +++-- 3 files changed, 195 insertions(+), 17 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..b0b3de9 --- /dev/null +++ b/src/Action/Functions.php @@ -0,0 +1,180 @@ +<?php + +declare(strict_types=1); + +namespace App\Action; + +use DateTimeImmutable; +use DateTime; +use DateInterval; +use DatePeriod; +use Exception; + +class Functions +{ + /** + * ВыполнÑет Ñортировку маÑÑива по убыванию цены + * @param array $array + * @return array + */ + + public function sortPrice(array $array): array + { + $prices = array_column($array, 'price'); + $counts = array_column($array, 'count'); + array_multisort( + $prices, + SORT_DESC, + $counts, + SORT_ASC, $array + ); + return $array; + } + + /** + * Ðа выход должна вернуть отÑортированный маÑÑив по ключу *price* DESC + * и во вторую очередь по *count* ASC: + * [['price'=>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")); + } + } +} + diff --git a/src/Controller/HomeController.php b/src/Controller/HomeController.php index 3436029..2b459b6 100644 --- a/src/Controller/HomeController.php +++ b/src/Controller/HomeController.php @@ -2,34 +2,31 @@ 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\Response; use Symfony\Component\Routing\Attribute\Route; class HomeController extends AbstractController { - private function countFriday13(int $year): iterable { - $stardDate = new DateTime("{$year}-01-01 Friday"); - $year += 1; - $endDate = new DateTime("{$year}-01-01"); - $interval = new DateInterval('P7D'); - foreach(new DatePeriod($stardDate, $interval, $endDate) as $day) { - yield new DateTimeImmutable($day->format("Y-m-d")); - } - } + private Functions $functions; + public function __construct(Functions $functions) + { + $this->functions = $functions; + } - #[Route('/{year}', name: 'home')] + #[Route('/{year}', name: 'home', methods: ['GET'])] public function home(int $year): Response { $fridays = array(); - foreach($this->countFriday13($year) as $date) { - $fridays[] = $date->format("Y-m-d l"); + try { + foreach ($this->functions->countFriday13($year) as $date) { + $fridays[] = $date->format("Y-m-d l"); + } + } catch (\Exception $e) { + return new Response($e->getMessage()); } - return $this->render('home.html.twig', ['fridays' => $fridays]); + return $this->json($fridays); } } -- GitLab