Skip to main content

Kiểm tra quyền truy cập EntityQuery sẽ được thực thi trong Drupal 10

The \Drupal\Core\Entity\Query\QueryInterface::accessCheck() là function kiểm tra cho phép nhà phát triển chỉ định liệu chỉ những thực thể nội dung mà người dùng hiện tại có quyền xem mới được trả lại khi thực thi truy vấn hay không.

Cho đến Drupal 9.2, nếu ::accessCheck() không được gọi trong truy vấn SQL thì truy vấn sẽ mặc định kiểm tra quyền truy cập, tức là nó sẽ gọi ::accessCheck(TRUE) làm mặc định.

Hành vi này là nguồn gốc của nhiều lỗi, vì các nhà phát triển rất dễ quên rằng điều này xảy ra.

Drupal\Core\Entity\Query\QueryException: Entity queries must explicitly set whether the query should be access checked or not. See Drupal\Core\Entity\Query\QueryInterface::accessCheck(). in Drupal\Core\Entity\Query\Sql\Query->prepare() (line 141 of core/lib/Drupal/Core/Entity/Query/Sql/Query.php).

Đối với Drupal 10, điều này sẽ được thực thi bằng cách đưa ra một ngoại lệ nếu ::accessCheck() không được gọi. Do đó trong câu truy vấn của Drupal 10 cần phải gọi ::accessCheck().

Ví dụ:

Trong Drupal 9.2 

// This gets all articles the current user can view.
$ids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->execute();

// This also gets all articles the current user can view.
$ids = \Drupal::entityQuery('node')
  ->accessCheck(TRUE)
  ->condition('type', 'article')
  ->execute();

// This gets all articles that exist regardless of access.
$ids = \Drupal::entityQuery('node')
  ->accessCheck(FALSE)
  ->condition('type', 'article')
  ->execute();

Trong Drupal 10, chúng ta phải

// This will trigger a deprecation error.
$ids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->execute();

// Unchanged: This gets all articles the current user can view.
$ids = \Drupal::entityQuery('node')
  ->accessCheck(TRUE)
  ->condition('type', 'article')
  ->execute();

// Unchanged: This gets all articles that exist regardless of access.
$ids = \Drupal::entityQuery('node')
  ->accessCheck(FALSE)
  ->condition('type', 'article')
  ->execute();

Thay đổi này không áp dụng với config entitie

Nguồn: https://www.drupal.org/node/3201242