cboissenin
11/14/2016 - 8:18 AM

Custom service

Custom service

<?php

/**
 * @file
 * Contains \Drupal\phenix_core\DefaultService.
 */

namespace Drupal\phenix_core;

use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\eck\Entity\EckEntity;
use Drupal\rng\Entity\Registration;
use Drupal\Core\Database\Connection;

/**
 * Class MyService.
 *
 * @package Drupal\phenix_core
 */
class MyService  {

  protected $entity_query;
  protected $connection;
  protected $entityManager;

  public function __construct(QueryFactory $entity_query, Connection $connection, EntityManager $entityManager) {
    $this->entity_query = $entity_query;
    $this->connexion = $connection;
    $this->entityManager = $entityManager;
  }

  /**
   * Return IDs of registrations
   */
  public function getRegistrations($event_id, $status = [], $pricing_id = 0) {
    $query = $this->entity_query->get('registration')
    ->condition('event__target_id', $event_id);

    if (!empty($status)) {
      $query->condition('field_inscription_status', $status, 'IN');
    }

    if ($pricing_id) {
      $query->condition('field_ref_price', $pricing_id);
    }

    $ids = $query->execute();

    return array_keys($ids);
  }

  /*
   * Count number of registrations
   */
  public function getRegistrationsCount($event_id, $status = [], $pricing_id = 0) {
    $ids = $this->getRegistrations($event_id, $status, $pricing_id);

    return count($ids);
  }

  /**
   * Check if event has enough capacity for a new registration
   * @param $event_id
   * @param $event_quantity
   * @return bool
   */
  public function eventHasCapacity($event_id, $event_quantity) {
    $count_registrations = $this->getRegistrationsCount($event_id, array('confirmed'));

    return $event_quantity > $count_registrations;
  }


  /**
   * Check is a event has a valid option
   * @param $options
   * @param $price_id
   * @return bool
   */
  public function eventHasPricingOption($options, $price_id) {
    foreach ($options as $option) {
      if ($option['target_id'] == $price_id) {
        return true;
      }
    }

    return false;
  }

  /**
   * Check if pricing option is still available
   * @param $event_id
   * @param $option_id
   * @param $option_quantity
   * @return bool
   */
  public function eventHasCapacityForPriceOption($event_id, $option_id, $option_quantity) {
    // If quantity is 0, it is unlimited
    if ($option_quantity === 0) {
      return true;
    }

    $status_to_check = array('confirmed', 'waiting');
    $count_options = $this->getRegistrationsCount($event_id, $status_to_check, $option_id);

    return $option_quantity > $count_options;
  }


  /**
   * Check if current_user has not already a registration for an event
   */
  public function userCanRegister($event_id, $user_id) {
    $query = $this->connexion->select('registrant', 'registrant');
    $query->fields('registrant', array('id'));
    $query->condition('identity__target_id', $user_id);
    $query->join('registration_field_data', 'registration', 'registration.id = registrant.registration');
    $query->condition('registration.event__target_id', $event_id);

    $count = $query->countQuery()->execute()->fetchField();

    return (int)$count === 0;
  }

  /**
   * Return the ID of the selection option for a event
   * @param $event_id
   * @param $user_id
   * @return mixed
   */
  public function getUserRegistrationOption($event_id, $user_id) {
    $query = $this->connexion->select('registration__field_ref_price', 'price');
    $query->fields('price', array('field_ref_price_target_id'));

    $query->join('registration_field_data', 'registration', 'registration.id = price.entity_id');
    $query->condition('registration.event__target_id', $event_id);

    $query->join('registrant', 'registrant', 'registrant.registration = registration.id');
    $query->condition('registrant.identity__target_id', $user_id);

    return $query->execute()->fetchField();
  }


  /**
   * Return a new registration
   */
  public function createRegistration() {
    $registration = Registration::create([
      'type' => 'simple',
    ]);

    return $registration;
  }

  /**
   * Check if a registration has a line item associated with
   */
  public function registrationHasLineItem($registation_id) {
    $query = $this->entity_query->get('line_item')
      ->condition('field_status', 'cancelled', '!=')
      ->condition('field_ref_registration', $registation_id);

    $result = $query->execute();

    return !empty($result);
  }
}
services:
  module_name.example:
    class: Drupal\module_name\ModuleNameExampleServide
    arguments: ['@entity.query', '@database', '@entity.manager']
Get service using static drupal method

$service = \Drupal::service('service_name');

Global access

// Returns a Drupal\Core\Database\Connection object.
$connection = \Drupal::database();
// EQUAL
$connection = \Drupal::service('database');

// Old d7 styles (no global anymore)
global $language
global $user

// New d8 style
Drupal::languageManager()->getLanguage(Language::TYPE_INTERFACE)
Drupal::currentUser()
/**
 * Generate service
 */
 
$ drupal generate:service [options]
$ gs
<?php 
namespace Drupal\module_name\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\module_name\ModuleNameExampleService;
use Symfony\Component\DependencyInjection\ContainerInterface;

class TestController extends ControllerBase {

  protected $myService;

  /**
   * {@inheritdoc}
   */
  public function __construct(ModuleNameExampleService $myService) {
    // Dependency injection
    $this->myService = $myService;
  }
  
  /**
   * {@inheritdoc}
   */
   public static function create(ContainerInterface $container) {
    return new static(
      // Get the service through the service container using the key defined insode the yml
      $container->get('module_name.example')
    );
  }
  
}
//Static method
$current_user = \Drupal::currentUser();

// Dependency injection - Best pratice

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Controller\ControllerBase;

class TestController extends ControllerBase {

  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(AccountInterface $currentUser) {
    $this->currentUser = $currentUser;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }
  
  public function index() {
    $user_id = $this->currentUser->id();
  }
}