inline_feedback-1.0.x-dev/src/Controller/InlineFeedbackController.php

src/Controller/InlineFeedbackController.php
<?php

namespace Drupal\inline_feedback\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\inline_feedback\Entity\InlineFeedback;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountProxyInterface;

class InlineFeedbackController extends ControllerBase {

  protected $configFactory;
  protected $currentUser;

  public function __construct(ConfigFactoryInterface $configFactory, AccountProxyInterface $currentUser) {
    $this->configFactory = $configFactory;
    $this->currentUser = $currentUser;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('current_user')
    );
  }

  public function submit(Request $request) {
    $data = json_decode($request->getContent(), TRUE);
    if (empty($data['label']) || empty($data['description']) || empty($data['selector']) || empty($data['node'])) {
      return new JsonResponse(['error' => 'Missing required fields.'], 400);
    }

    $feedback = InlineFeedback::create([
      'label' => $data['label'],
      'description' => $data['description'],
      'selector' => $data['selector'],
      'node' => $data['node'],
      'uid' => $this->currentUser()->id(),
    ]);

    $feedback->save();

    return new JsonResponse(['status' => 'success']);
  }

  public function delete($id) {
    $entity = \Drupal::entityTypeManager()->getStorage('inline_feedback')->load($id);
    if (!$entity) {
      return new JsonResponse(['success' => false, 'message' => 'Feedback not found'], 404);
    }

    // Get allowed roles to delete feedbacks
    $config = $this->configFactory->get('inline_feedback.settings');
    $allowed_roles = array_filter($config->get('allowed_roles_to_delete') ?? []);

    // Current user roles
    $user_roles = $this->currentUser->getRoles();

    // Verify if user has permission
    $has_permission = !empty(array_intersect($user_roles, $allowed_roles));

    if (!$has_permission) {
      return new JsonResponse(['success' => false, 'message' => 'Access denied'], 403);
    }

    try {
      $entity->delete();
      return new JsonResponse(['success' => true]);
    }
    catch (\Exception $e) {
      \Drupal::logger('inline_feedback')->error('Error deleting feedback: @message', ['@message' => $e->getMessage()]);
      return new JsonResponse(['success' => false, 'message' => 'Error deleting feedback.'], 500);
    }
  }
}

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

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