Skip to content

Conversation

@ArtyomYaprintsev
Copy link

Выполнил все задания из ридми, всё в рабочем состоянии

public function list(Request $request): Response
{
$user = $this -> getUser();
$project_repository = $this -> getDoctrine() -> getManager() -> getRepository(Project::class);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Разделение пробелами следует убрать, такой способ форматирования не используется ни в одном известном Code Style Guide.
  2. underscore (использование подчеркивания при именовании переменных) в целом в рамках PHP имеет место быть. Но в рамках Symfony принят формат с camelCase

Подробнее про Code Style тут https://symfony.com/doc/current/contributing/code/standards.html

$user = $this -> getUser();
$project_repository = $this -> getDoctrine() -> getManager() -> getRepository(Project::class);

if (in_array("ROLE_ADMIN", $user -> getRoles())) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Проверку на роль лучше делать через метод $this->isGranted('ROLE_ADMIN')

  2. Выделить в отдельный метод репозитория для получения списка доступных объектов.


return $this -> render("projects/create.html.twig", [
"form" => $form -> createView(),
"action" => "creating"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут подойдет Create.
ing - это продолжительное действие (например, loading, creating, waiting - загрузка, создание, ожидание) и тп
лучше использовать для действия инфинитив, Create, Show, Delete, Get и тп

* @Route("/projects/{slug}", name="project_info")
* @return Response
*/
public function info($slug, Request $request): Response

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Когда есть контроллер для вывода конкретной сущности лучше использовать устоявщиеся названия методов:
Например:
get
show
present

Тогда логино выглядит $projectController::show($slug) или get($slug)

{
$project = $this -> getDoctrine() -> getManager() -> find(Project::class, $slug);

$tasks = $this -> getDoctrine() -> getRepository(Task::class) -> findBy(["project" => $project]);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше использовать более короткий и выразительный вариант:
$tasks = $project->getTasks()

$project_repository = $this -> getDoctrine() -> getRepository(Project::class);
$task_repository = $this->getDoctrine()->getRepository(Task::class);

$projects_list = $user_is_admin ?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынести в метод репозитория (выше про это было)

$filter = $taskFilterForm->getData();
if ($filter['isCompleted'] === null) {
unset($filter['isCompleted']);
$data = $taskFilterForm->getData();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Все что ниже нужно скрыть в самом методе фильтрации репозитория.

$project_repository = $this -> getDoctrine() -> getRepository(Project::class);

$form = $this->createForm(TaskType::class, data: $task, options: [
"projects_list" => in_array("ROLE_ADMIN", $user -> getRoles()) ?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В отдельный метод

* @param string $role
* @return bool
*/
public function checkRole(string $role): bool

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hasRole лучше

/**
* @throws Exception
*/
public function getTasksByProjectOwnerId(int $id) : array

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такая реализация имеет место быть, но несколько нивелирует преимущества использования ORM:

  • во-первых возвращается ассоциативный массив, то есть мы не можем использовать функции Collection/и методы сущностей Task/Project.
  • во-вторых в случае добавления полей в БД/удаления/Переименования придется изменить все SQL запросы

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Изменить реализацию через QueryBuilder

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

@selezenev selezenev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно добавить в контроллерах и шаблонах проверку на доступность.
Реализовать через Voter

* @Route("/projects/{slug}", name="project_show")
* @return Response
*/
public function show($slug, Request $request): Response

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет проверки что проект доступен пользователю.
Нужно добавить, реализовать через Voter

https://symfony.com/doc/4.4/security/voters.html

* @param Request $request
* @return Response
*/
public function edit($slug, Request $request): Response

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Также нет проверки на доступность

*/
public function edit($id, Request $request): Response
{
$task = $this->getDoctrine()->getManager()->find(Task::class, $id);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет проверок на доступность и права

$projectsList = $projectRepository -> findByUserRole($user -> getId());
$projectsIdList = array_map(function ($item) { return $item->getId(); }, $projectsList);

$taskFilterForm = $this->createForm(TaskFilterType::class, options: [

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай заменим ChoiceType на EntityType чтобы скрыть логику получения списков из контроллера в форму


$form = $this->createForm(TaskType::class, $task, [
"projectsList" => $projectRepository -> findByUserRole($user -> getId()),
// 'userId' => 4,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Закомменитированный код ненужно оставлять

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants