Commit bb48b0b9 authored by Адлан Шамавов's avatar Адлан Шамавов
Browse files

refactoring

parent 9d3fbd3f
Loading
Loading
Loading
Loading

.gitignore

0 → 100644
+1 −0
Original line number Diff line number Diff line
/vendor
 No newline at end of file
+32 −19
Original line number Diff line number Diff line
@@ -2,8 +2,9 @@

require_once __DIR__ . '/vendor/autoload.php';

$func = new Hp\Test\Functions();
use Hp\Test\Functions;

$func = new Functions();
?>

<!DOCTYPE html>
@@ -37,6 +38,7 @@ $func = new Hp\Test\Functions();
        print_r($func->search($array, 54));
    ?>


    <h1>Function 3</h1>
    <?php
        $arr = [
@@ -48,6 +50,7 @@ $func = new Hp\Test\Functions();
        print_r($func->uniqElements($arr));
    ?>


    <h1>Function 4</h1>
    <?php
        $aMenu = [
@@ -71,22 +74,32 @@ $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"));
    ?>
</body>
</html>
 No newline at end of file

public/text.txt

deleted100644 → 0
+0 −2
Original line number Diff line number Diff line
Раз, два, три, четыре,
Пять, шесть, семь, восемь.
 No newline at end of file
+133 −99
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;

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;
    }

    /**
     * Удалить дубликаты, оставив только уникальные значения
@@ -45,12 +65,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))
@@ -59,16 +81,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) {
@@ -87,7 +110,8 @@ class Functions {
        return $result;
    }

    /** Выходные данные: 
    /**
     * Выходные данные:
     * $aMenu = [
     * [
     *  'name' => 'Смартфоны и гаджеты',
@@ -95,9 +119,8 @@ class Functions {
     *  'submenu' => [
     *      ['name' => 'Смартфоны, мобильные телефоны','depth' => 1,],
     *      ['name' => 'Планшеты','depth' => 1,],
        *      ['name' => 'Наушники и гарнитуры','depth' => 1,]
        * ,]
    * ,],
     *      ['name' => 'Наушники и гарнитуры','depth' => 1,],],
     * ],
     * [
     *  'name' => 'Компьютеры и ноутбуки',
     *  'depth' => 0,
@@ -111,35 +134,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"));
        }
    }
@@ -150,9 +183,10 @@ 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") ;
    }
}