Loading .gitignore 0 → 100644 +1 −0 Original line number Diff line number Diff line /vendor No newline at end of file index.php +47 −23 Original line number Diff line number Diff line Loading @@ -2,7 +2,9 @@ require_once __DIR__ . '/vendor/autoload.php'; $func = new Hp\Test\Functions(); use Hp\Test\Functions; $func = new Functions(); ?> Loading Loading @@ -37,6 +39,7 @@ $func = new Hp\Test\Functions(); print_r($func->search($array, 54)); ?> <h1>Function 3</h1> <?php $arr = [ Loading @@ -48,6 +51,7 @@ $func = new Hp\Test\Functions(); print_r($func->uniqElements($arr)); ?> <h1>Function 4</h1> <?php $aMenu = [ Loading @@ -71,33 +75,53 @@ $func = new Hp\Test\Functions(); <h1>Function 5</h1> <?php print("<h2>До НГ: </h2>"); print($func->howDaysToNy(new DateTimeImmutable())); print "<h2>До НГ: </h2>"; try { print $func->howDaysToNy(new DateTimeImmutable()); } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 6</h1> <?php print("<h2>Пятницы 13: </h2>"); print "<h2>Пятницы 13: </h2>"; try { foreach ($func->countFriday13(2024) as $date) { print($date->format("Y-m-d l") . "\n"); print $date->format("Y-m-d l") . "\n"; } } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 7</h1> <?php print("<h2>Разница дней: </h2>"); print($func->diffDays(new DateTimeImmutable(), new DateTimeImmutable("2025-01-01"))); print "<h2>Разница дней: </h2>"; print $func->diffDays(new DateTimeImmutable(), new DateTimeImmutable("2025-01-01")); ?> <h1>Function 8</h1> <?php try { $func->readLogFile(__DIR__ . "/public/text.txt"); } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 9</h1> <?php try { foreach($func->readFileLineByLine(__DIR__ . "/public/text.txt") as $line) { print($line); print $line; } } catch (Exception $e) { print $e->getMessage(); } ?> </body> Loading src/Functions.php +161 −118 Original line number Diff line number Diff line <?php declare(strict_types=1); namespace Hp\Test; use DateTimeImmutable; use DateTime; use DateInterval; use DatePeriod; use Exception; use RuntimeException; class Functions { class Functions { /** * Выполняет сортировку массива по убыванию цены * * @param array $array * * Выполняет сортировку массива по убыванию цены * @param array $array * @return array */ function sortPrice(array $array): array { array_multisort(array_column($array, 'price'), SORT_DESC, array_column($array, 'count'), SORT_ASC, $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], ] /** * На выход должна вернуть отсортированный массив по ключу *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 - найденный элемент /** * Найдет элемент с указаным id * @param array $array - массив, содержащий элементы со структурой * [ * 'id' => 30, * 'name' => 'Jhon', * 'age' => 23, * ] * @param $id - ид искомого элемента * @return ?array - найденный элемент */ function search($array, $id): ?array { $rowId = array_search($id, array_column($array, 'id')); public function search(array $array, int $id): ?array { $rowId = array_search($id, array_column($array, 'id'), true); if ($rowId) { return $array[$rowId]; } return null; } /** * Удалить дубликаты, оставив только уникальные значения Loading @@ -45,12 +66,14 @@ class Functions { * @return array */ function uniqElements(array $array): array { public function uniqElements(array $array): array { return array_unique($array, SORT_REGULAR); } //Выходной массив: /** Array ( /** * Выходной массив: * Array ( * [0] => Array([0] => laravel, [1] => php) * [1] => Array([0] => codeigniter, [1] => php) * [3] => Array([0] => c++, [1] => java)) Loading @@ -59,16 +82,17 @@ class Functions { /** * Сгруппировать подразедлы в верхние разделы меню * Дочерние элементы поместить в массив родителя с ключом submenu * * Значение под ключом depth определяет уровень раздела * * Дочерние элементы поместить в массив родителя с ключом submenu * Значение под ключом depth определяет уровень раздела * Массив $aMenu всегда начинается с элемента depth = 0, * все последующие элементы с depth = 1 являются его дочерними * * элементами * * * @param array $aMenu * * * все последующие элементы с depth = 1 являются его дочерними * элементами * @param array $aMenu * @return array */ function prepareMenu(array $aMenu): array { public function prepareMenu(array $aMenu): array { $result = []; foreach ($aMenu as $arr) { if ($arr['depth'] === 0) { Loading @@ -87,7 +111,8 @@ class Functions { return $result; } /** Выходные данные: /** * Выходные данные: * $aMenu = [ * [ * 'name' => 'Смартфоны и гаджеты', Loading @@ -95,9 +120,8 @@ class Functions { * 'submenu' => [ * ['name' => 'Смартфоны, мобильные телефоны','depth' => 1,], * ['name' => 'Планшеты','depth' => 1,], * ['name' => 'Наушники и гарнитуры','depth' => 1,] * ,] * ,], * ['name' => 'Наушники и гарнитуры','depth' => 1,],], * ], * [ * 'name' => 'Компьютеры и ноутбуки', * 'depth' => 0, Loading @@ -111,35 +135,45 @@ class Functions { * 'submenu' => [ * ['name' => 'Техника для уборки','depth' => 1,], * ['name' => 'Товары для ухода за одеждой','depth' => 1,], * ['name' => 'Аксессуары для техники','depth' => 1,],]], * ['name' => 'Аксессуары для техники','depth' => 1,],] * ], * [ * 'name' => 'Товары для дома и кухни','depth' => 0, * 'name' => 'Товары для дома и кухни', * 'depth' => 0, * 'submenu' => [ * ['name' => 'Посуда','depth' => 1,],]], ]; * ['name' => 'Посуда','depth' => 1,],]], * ]; */ /** * Функция рассчитывает кол-во дней до нового года * @param DateTime $date дата от которой, необходимо рассчитать кол-во дней * @param DateTimeImmutable $date дата от которой, необходимо рассчитать кол-во дней * @return int * @throws Exception */ function howDaysToNy(DateTimeImmutable $date): int { public function howDaysToNy(DateTimeImmutable $date): int { $endYear = date("Y-12-31", date_timestamp_get($date)); $dateInterval = date_diff(new DateTimeImmutable($endYear), $date); return $dateInterval->format("%a") + 1; return (int)$dateInterval->format("%a") + 1; } /** * Вернет все пятницы 13 в году * @param int $yaer год, в котором необходимо произвести расчет * @param int $year год, в котором необходимо произвести расчет * @return DateTimeImmutable[] * @throws Exception */ function countFriday13(int $year): iterable { $stardDate = new DateTime("{$year}-01-01 Friday"); $year += 1; $endDate = new DateTime("{$year}-01-01"); 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($stardDate, $interval, $endDate) as $day) { foreach (new DatePeriod($startDate, $interval, $endDate) as $day) { yield new DateTimeImmutable($day->format("Y-m-d")); } } Loading @@ -150,49 +184,58 @@ class Functions { * @param DateTimeImmutable $dateEnd дата окончания * @return int */ function diffDays(DateTimeImmutable $dateStart, DateTimeImmutable $dateEnd): int { public function diffDays(DateTimeImmutable $dateStart, DateTimeImmutable $dateEnd): int { $dateInterval = date_diff($dateStart, $dateEnd); return $dateInterval->format("%a") ; return (int)$dateInterval->format("%a") ; } /** * Переделай своё решение 8 задачи: * замени вывод всего текста из файла разом на * построчный вывод используя yield * Напиши функцию, которая принимает путь до файла, * проверяет, что файл существует и выводит пользователю весь контент файла * (файл можешь создать любой) * @param string $filePath путь до файла * @return void * @throws Exception */ function readLogFile(string $filePath): void { public function readLogFile(string $filePath): void { if (file_exists($filePath)) { $text = ""; $file = fopen($filePath, "r"); $file = fopen($filePath, 'rb'); while(!feof($file)) { $line = fgets($file); $text .= $line; } fclose($file); print($text); print $text; } else { throw new RuntimeException("File not found: $filePath"); } else print("Такого файла не существует."); } /** * Переделай своё решение 8 задачи: * замени вывод всего текста из файла разом на * построчный вывод используя yield * @param string $filePath путь до файла * @return void * @return iterable */ function readFileLineByLine(string $filePath): iterable { public function readFileLineByLine(string $filePath): iterable { if (file_exists($filePath)) { $file = fopen($filePath, "r"); $file = fopen($filePath, 'rb'); while(!feof($file)) { yield fgets($file); } fclose($file); } else yield "Такого файла не существует."; else { throw new RuntimeException("File not found: $filePath"); } } } Loading
.gitignore 0 → 100644 +1 −0 Original line number Diff line number Diff line /vendor No newline at end of file
index.php +47 −23 Original line number Diff line number Diff line Loading @@ -2,7 +2,9 @@ require_once __DIR__ . '/vendor/autoload.php'; $func = new Hp\Test\Functions(); use Hp\Test\Functions; $func = new Functions(); ?> Loading Loading @@ -37,6 +39,7 @@ $func = new Hp\Test\Functions(); print_r($func->search($array, 54)); ?> <h1>Function 3</h1> <?php $arr = [ Loading @@ -48,6 +51,7 @@ $func = new Hp\Test\Functions(); print_r($func->uniqElements($arr)); ?> <h1>Function 4</h1> <?php $aMenu = [ Loading @@ -71,33 +75,53 @@ $func = new Hp\Test\Functions(); <h1>Function 5</h1> <?php print("<h2>До НГ: </h2>"); print($func->howDaysToNy(new DateTimeImmutable())); print "<h2>До НГ: </h2>"; try { print $func->howDaysToNy(new DateTimeImmutable()); } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 6</h1> <?php print("<h2>Пятницы 13: </h2>"); print "<h2>Пятницы 13: </h2>"; try { foreach ($func->countFriday13(2024) as $date) { print($date->format("Y-m-d l") . "\n"); print $date->format("Y-m-d l") . "\n"; } } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 7</h1> <?php print("<h2>Разница дней: </h2>"); print($func->diffDays(new DateTimeImmutable(), new DateTimeImmutable("2025-01-01"))); print "<h2>Разница дней: </h2>"; print $func->diffDays(new DateTimeImmutable(), new DateTimeImmutable("2025-01-01")); ?> <h1>Function 8</h1> <?php try { $func->readLogFile(__DIR__ . "/public/text.txt"); } catch (Exception $e) { print $e->getMessage(); } ?> <h1>Function 9</h1> <?php try { foreach($func->readFileLineByLine(__DIR__ . "/public/text.txt") as $line) { print($line); print $line; } } catch (Exception $e) { print $e->getMessage(); } ?> </body> Loading
src/Functions.php +161 −118 Original line number Diff line number Diff line <?php declare(strict_types=1); namespace Hp\Test; use DateTimeImmutable; use DateTime; use DateInterval; use DatePeriod; use Exception; use RuntimeException; class Functions { class Functions { /** * Выполняет сортировку массива по убыванию цены * * @param array $array * * Выполняет сортировку массива по убыванию цены * @param array $array * @return array */ function sortPrice(array $array): array { array_multisort(array_column($array, 'price'), SORT_DESC, array_column($array, 'count'), SORT_ASC, $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], ] /** * На выход должна вернуть отсортированный массив по ключу *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 - найденный элемент /** * Найдет элемент с указаным id * @param array $array - массив, содержащий элементы со структурой * [ * 'id' => 30, * 'name' => 'Jhon', * 'age' => 23, * ] * @param $id - ид искомого элемента * @return ?array - найденный элемент */ function search($array, $id): ?array { $rowId = array_search($id, array_column($array, 'id')); public function search(array $array, int $id): ?array { $rowId = array_search($id, array_column($array, 'id'), true); if ($rowId) { return $array[$rowId]; } return null; } /** * Удалить дубликаты, оставив только уникальные значения Loading @@ -45,12 +66,14 @@ class Functions { * @return array */ function uniqElements(array $array): array { public function uniqElements(array $array): array { return array_unique($array, SORT_REGULAR); } //Выходной массив: /** Array ( /** * Выходной массив: * Array ( * [0] => Array([0] => laravel, [1] => php) * [1] => Array([0] => codeigniter, [1] => php) * [3] => Array([0] => c++, [1] => java)) Loading @@ -59,16 +82,17 @@ class Functions { /** * Сгруппировать подразедлы в верхние разделы меню * Дочерние элементы поместить в массив родителя с ключом submenu * * Значение под ключом depth определяет уровень раздела * * Дочерние элементы поместить в массив родителя с ключом submenu * Значение под ключом depth определяет уровень раздела * Массив $aMenu всегда начинается с элемента depth = 0, * все последующие элементы с depth = 1 являются его дочерними * * элементами * * * @param array $aMenu * * * все последующие элементы с depth = 1 являются его дочерними * элементами * @param array $aMenu * @return array */ function prepareMenu(array $aMenu): array { public function prepareMenu(array $aMenu): array { $result = []; foreach ($aMenu as $arr) { if ($arr['depth'] === 0) { Loading @@ -87,7 +111,8 @@ class Functions { return $result; } /** Выходные данные: /** * Выходные данные: * $aMenu = [ * [ * 'name' => 'Смартфоны и гаджеты', Loading @@ -95,9 +120,8 @@ class Functions { * 'submenu' => [ * ['name' => 'Смартфоны, мобильные телефоны','depth' => 1,], * ['name' => 'Планшеты','depth' => 1,], * ['name' => 'Наушники и гарнитуры','depth' => 1,] * ,] * ,], * ['name' => 'Наушники и гарнитуры','depth' => 1,],], * ], * [ * 'name' => 'Компьютеры и ноутбуки', * 'depth' => 0, Loading @@ -111,35 +135,45 @@ class Functions { * 'submenu' => [ * ['name' => 'Техника для уборки','depth' => 1,], * ['name' => 'Товары для ухода за одеждой','depth' => 1,], * ['name' => 'Аксессуары для техники','depth' => 1,],]], * ['name' => 'Аксессуары для техники','depth' => 1,],] * ], * [ * 'name' => 'Товары для дома и кухни','depth' => 0, * 'name' => 'Товары для дома и кухни', * 'depth' => 0, * 'submenu' => [ * ['name' => 'Посуда','depth' => 1,],]], ]; * ['name' => 'Посуда','depth' => 1,],]], * ]; */ /** * Функция рассчитывает кол-во дней до нового года * @param DateTime $date дата от которой, необходимо рассчитать кол-во дней * @param DateTimeImmutable $date дата от которой, необходимо рассчитать кол-во дней * @return int * @throws Exception */ function howDaysToNy(DateTimeImmutable $date): int { public function howDaysToNy(DateTimeImmutable $date): int { $endYear = date("Y-12-31", date_timestamp_get($date)); $dateInterval = date_diff(new DateTimeImmutable($endYear), $date); return $dateInterval->format("%a") + 1; return (int)$dateInterval->format("%a") + 1; } /** * Вернет все пятницы 13 в году * @param int $yaer год, в котором необходимо произвести расчет * @param int $year год, в котором необходимо произвести расчет * @return DateTimeImmutable[] * @throws Exception */ function countFriday13(int $year): iterable { $stardDate = new DateTime("{$year}-01-01 Friday"); $year += 1; $endDate = new DateTime("{$year}-01-01"); 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($stardDate, $interval, $endDate) as $day) { foreach (new DatePeriod($startDate, $interval, $endDate) as $day) { yield new DateTimeImmutable($day->format("Y-m-d")); } } Loading @@ -150,49 +184,58 @@ class Functions { * @param DateTimeImmutable $dateEnd дата окончания * @return int */ function diffDays(DateTimeImmutable $dateStart, DateTimeImmutable $dateEnd): int { public function diffDays(DateTimeImmutable $dateStart, DateTimeImmutable $dateEnd): int { $dateInterval = date_diff($dateStart, $dateEnd); return $dateInterval->format("%a") ; return (int)$dateInterval->format("%a") ; } /** * Переделай своё решение 8 задачи: * замени вывод всего текста из файла разом на * построчный вывод используя yield * Напиши функцию, которая принимает путь до файла, * проверяет, что файл существует и выводит пользователю весь контент файла * (файл можешь создать любой) * @param string $filePath путь до файла * @return void * @throws Exception */ function readLogFile(string $filePath): void { public function readLogFile(string $filePath): void { if (file_exists($filePath)) { $text = ""; $file = fopen($filePath, "r"); $file = fopen($filePath, 'rb'); while(!feof($file)) { $line = fgets($file); $text .= $line; } fclose($file); print($text); print $text; } else { throw new RuntimeException("File not found: $filePath"); } else print("Такого файла не существует."); } /** * Переделай своё решение 8 задачи: * замени вывод всего текста из файла разом на * построчный вывод используя yield * @param string $filePath путь до файла * @return void * @return iterable */ function readFileLineByLine(string $filePath): iterable { public function readFileLineByLine(string $filePath): iterable { if (file_exists($filePath)) { $file = fopen($filePath, "r"); $file = fopen($filePath, 'rb'); while(!feof($file)) { yield fgets($file); } fclose($file); } else yield "Такого файла не существует."; else { throw new RuntimeException("File not found: $filePath"); } } }