You are here

public static function CourseEnrollment::preDelete in Course 3.x

Clean up fulfillments after deleting an enrollment.

Overrides EntityBase::preDelete

File

src/Entity/CourseEnrollment.php, line 338

Class

CourseEnrollment
Defines the profile entity class.

Namespace

Drupal\course\Entity

Code

public static function preDelete(EntityStorageInterface $storage, array $entities) {
  foreach ($entities as $course_enrollment) {

    // Find all course objects in this course and delete the fulfillments.
    $coids = array();
    $result = Drupal::database()
      ->query("SELECT coid FROM {course_object} WHERE cid = :cid", array(
      ':cid' => $course_enrollment
        ->getCourse()
        ->id(),
    ));
    while ($row = $result
      ->fetch()) {
      $coids[] = $row->coid;
    }
    if (count($coids)) {
      $sql = "SELECT cofid FROM {course_object_fulfillment} WHERE coid IN (:coids[]) AND uid = :uid";

      // The user is already deleted, so we have to delete by the user ID.
      $cofIds = Drupal::database()
        ->query($sql, array(
        ':coids[]' => $coids,
        ':uid' => $course_enrollment
          ->get('uid')
          ->getString(),
      ))
        ->fetchAllKeyed(0, 0);
      $cofStorage = \Drupal::entityTypeManager()
        ->getStorage('course_object_fulfillment');
      $entities = $cofStorage
        ->loadMultiple($cofIds);
      foreach ($entities as $entity) {
        $entity
          ->delete();
      }
    }
    parent::preDelete($storage, $entities);
  }
}