contrib_todo_list-1.1.1/src/Controller/TodoController.php

src/Controller/TodoController.php
<?php

namespace Drupal\contrib_todo_list\Controller;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\contrib_todo_list\data\TodoState;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Url;
use Drupal\contrib_todo_list\Service\TodoManagerService;
use Drupal\contrib_todo_list\Entity\Todo;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Controller for Todo entity.
 */
class TodoController extends ControllerBase {

  /**
   * Constructor.
   *
   * @param \Drupal\contrib_todo_list\Service\TodoManagerService $todoManager
   *   The todo manager service.
   */
  public function __construct(
    protected TodoManagerService $todoManagerService
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('contrib_todo_list.todo_manager'),
    );
  }

  /**
   * Adds a new todo.
   *
   * @param Request $request
   *   The request object.
   *
   * @return JsonResponse
   *   JSON response.
   * @throws InvalidPluginDefinitionException
   * @throws PluginNotFoundException
   */
  public function add(Request $request): JsonResponse {
    $content = json_decode($request->getContent(), TRUE);

    if (empty($content['node_id']) || empty($content['todo_text'])) {
      return new JsonResponse(['error' =>  $this->t('Missing required parameters')], 400);
    }

    $node = $this->entityTypeManager()->getStorage('node')->load($content['node_id']);
    if (!$node instanceof NodeInterface) {
      return new JsonResponse(['error' =>  $this->t('Invalid node ID')], 400);
    }

    $todo = $this->todoManagerService->createTodo($node, $content['todo_text']);

    if (!$todo) {
      return new JsonResponse(['error' =>  $this->t('Failed to create todo')], 500);
    }

    return new JsonResponse([
      'message' =>  $this->t('Todo created successfully'),
      'todo_id' => $todo->id(),
      'text' => $todo->get('todo')->value,
    ]);
  }

  /**
   * Updates todo share status.
   *
   * @param Todo $todo
   *   The todo entity.
   * @param Request $request
   *   The request object.
   *
   * @return JsonResponse
   *   JSON response.
   * @throws EntityStorageException
   */
  public function updateShare(Todo $todo, Request $request): JsonResponse {
    $content = json_decode($request->getContent(), TRUE);

    if (!isset($content['share'])) {
      return new JsonResponse(['error' =>  $this->t('Share parameter is required')], 400);
    }

    $success = $this->todoManagerService->updateTodoShare($todo, (bool) $content['share']);

    if (!$success) {
      return new JsonResponse(['error' =>  $this->t('Failed to update share status')], 500);
    }

    return new JsonResponse(['message' =>  $this->t('Share status updated successfully')]);
  }

  /**
   * Updates todo state.
   *
   * @param Todo $todo
   *   The todo entity.
   * @param Request $request
   *   The request object.
   *
   * @return JsonResponse
   *   JSON response.
   * @throws EntityStorageException
   */
  public function updateState(Todo $todo, Request $request): JsonResponse {
    $content = json_decode($request->getContent(), TRUE);

    if (empty($content['state'])) {
      return new JsonResponse(['error' =>  $this->t('State parameter is required')], 400);
    }

    $success = $this->todoManagerService->updateTodoState($todo, $content['state']);

    if (!$success) {
      return new JsonResponse(['error' =>  $this->t('Failed to update state')], 500);
    }

    return new JsonResponse(['message' =>  $this->t('State updated successfully')]);
  }

  /**
   * Delete todo.
   *
   * @param Todo $todo
   *
   * @return JsonResponse
   *   JSON response.
   */
  public function deleteTodo(Todo $todo): JsonResponse {
    $success = $this->todoManagerService->deleteTodo($todo);

    if (!$success) {
      return new JsonResponse(['error' =>  $this->t('Failed to delete todo')], 500);
    }

    return new JsonResponse(['message' =>  $this->t('Todo deleted successfully')]);
  }

  /**
   * Delete a todo in admin
   *
   * @param Todo $todo
   *
   * @return RedirectResponse
   */
  public function deleteTodoInAdmin(Todo $todo): RedirectResponse {
    $success = $this->todoManagerService->deleteTodo($todo);

    if (!$success) {
      $this->messenger()->addMessage($this->t('Failed to delete todo'));
    }
    else {
      $this->messenger()->addMessage($this->t('Todo deleted successfully'));
    }

    $url = Url::fromRoute('contrib_todo_list.view_my_todos');
    return new RedirectResponse($url->toString());
  }

  /**
   * Add a pin in todo.
   *
   * @param Todo $todo
   * @param Request $request
   * @return JsonResponse
   *   JSON response.
   * @throws EntityStorageException
   */
  public function addPin(Todo $todo, Request $request): JsonResponse {
    $content = json_decode($request->getContent(), TRUE);

    if (empty($content['pin'])) {
      return new JsonResponse(['error' =>  $this->t('Pin parameter is required')], 400);
    }

    $success = $this->todoManagerService->addPin($todo, $content['pin']);

    if (!$success) {
      return new JsonResponse(['error' =>  $this->t('Failed to add a pin')], 500);
    }

    return new JsonResponse(['message' =>  $this->t('pin add successfully')]);
  }


  /**
   * list user todos
   *
   * @param Request $request
   *
   * @return array
   * @throws InvalidPluginDefinitionException
   * @throws PluginNotFoundException
   */
  public function listUserTodos(Request $request): array {
    $state_filter = $request->query->get('state');
    $share_filter = $request->query->get('share');
    if (!in_array($state_filter, TodoState::getStateKeys())) {
      $state_filter = null;
    }

    $filters = [
        '#type' => 'container',
        '#attributes' => ['class' => ['todo-filters']],
        'state' => [
            '#type' => 'select',
            '#title' => $this->t('Filter by state'),
            '#options' => [
                '' => $this->t('- Any -'),
                'pending' => $this->t('Pending'),
                'in-progress' => $this->t('In Progress'),
                'completed' => $this->t('Completed'),
            ],
        ],
        'share' => [
            '#type' => 'select',
            '#title' => $this->t('Filter by share status'),
            '#options' => [
                '' => $this->t('- Any -'),
                '1' => $this->t('Shared'),
                '0' => $this->t('Not shared'),
            ],
        ],
        'submit' => [
            '#type' => 'submit',
            '#value' => $this->t('Filter'),
            '#attributes' => ['class' => ['button']],
        ],
        'reset' => [
            '#type' => 'submit',
            '#value' => $this->t('Reset'),
            '#attributes' => ['class' => ['button']],
        ],
    ];

    $header = [
        'node' => $this->t('Node'),
        'todo' => $this->t('Description'),
        'state' => $this->t('State'),
        'pin' => $this->t('Pinned'),
        'shared' => $this->t('Shared'),
        'operations' => $this->t('Operations'),
    ];

    $todos = $this->todoManagerService->getUserTodos($state_filter !== null ? TodoState::getStateFromKey($state_filter) : null, $share_filter);

    $rows = [];
    foreach ($todos as $todo) {
        $url = Url::fromRoute('contrib_todo_list.admin_todo_delete', ['todo' => $todo->id()]);
        $rows[] = [
            'node' => $todo->get('nid')->target_id,
            'todo' => $todo->get('todo')[0]->value,
            'state' => $this->t($todo->get('state')[0]->value),
            'pin' => $todo->get('pin')[0]->value && $todo->get('pin')[0]->value !== '' ? '✔️' : '❌',
            'shared' => $todo->get('share')[0]->value === '1' ? '✔️' : '❌',
            'operations' => [
                'data' => [
                    '#type' => 'operations',
                    '#links' => [
                        'view' => [
                            'title' => $this->t('View'),
                            'url' => Url::fromUri($this->todoManagerService->getNodeUrlByTodo($todo)),
                        ],
                        'delete' => [
                            'title' => $this->t('Delete'),
                            'url' => $url,
                        ],
                    ],
                ],
            ],
        ];
    }

    return [
        '#type' => 'container',
        'filters' => $filters,
        'table' => [
            '#type' => 'table',
            '#header' => $header,
            '#rows' => $rows,
            '#attributes' => [
                'class' => ['table-my-todos'],
            ],
            '#empty' => $this->t('You don\'t have todos yet'),
        ],
        '#attached' => [
            'library' => ['contrib_todo_list/contrib_todo_list'],
            'drupalSettings' => [
                'todoList' => [
                    'currentFilters' => [
                        'state' => $state_filter,
                        'share' => $share_filter,
                    ],
                ],
            ],
        ],
    ];
  }


}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc