fortnox-8.x-1.x-dev/src/Plugin/ResourceBase.php

src/Plugin/ResourceBase.php
<?php

namespace Drupal\fortnox\Plugin;

use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\fortnox\Form\SupplierInvoicesForm;
use Drupal\fortnox\Services\FortnoxClient;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Base class for Resource plugins.
 */
abstract class ResourceBase extends PluginBase implements ResourceInterface, ContainerFactoryPluginInterface {
  use StringTranslationTrait;

  /**
   * The ID of this resource.
   *
   * @var string
   */
  protected $resourceIDPlural;

  /**
   * The ID of this resource.
   *
   * @var string
   */
  protected $resourceIDSingular;

  /**
   * The name of the property that stores the resource ID.
   *
   * @var string
   */
  protected $resourceIDPropertyName;

  /**
   * The ID of the resource form.
   *
   * @var string
   */
  protected $resourceFormID;

  /**
   * The fortnox client.
   *
   * @var \Drupal\fortnox\Services\FortnoxClient
   */
  protected $fortnoxClient;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The current user service.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Fortnox's API endpoint.
   *
   * @var string
   */
  protected $endpoint = 'https://api.fortnox.se/3/';

  /**
   * Fortnox's resource url.
   *
   * @var string
   */
  protected $url;

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The injected link generator.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $linkGenerator;

  /**
   * The form builder service.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, FortnoxClient $fortnox_client, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, RequestStack $request_stack, MessengerInterface $messenger, LinkGeneratorInterface $link_generator, FormBuilderInterface $form_builder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->fortnoxClient = $fortnox_client;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->requestStack = $request_stack;
    $this->messenger = $messenger;
    $this->linkGenerator = $link_generator;
    $this->formBuilder = $form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('fortnox.client'),
      $container->get('current_user'),
      $container->get('entity_type.manager'),
      $container->get('request_stack'),
      $container->get('messenger'),
      $container->get('link_generator'),
      $container->get('form_builder')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getTableListing() {
    $build = [];
    $response = $this->getResponse($build);
    $meta = $this->getMetaInformation($response);
    $this->addTableValues($response, $build);
    if (isset($meta)) {
      if ($meta > 0) {
        // Initialize the pager using the @totalResources
        // variable from the request response.
        pager_default_initialize($meta, 50);
      }
      elseif ($meta == 0) {
        $build['message'] = [
          '#markup' => $this->t('There are no resources of this type in your fortnox integration!'),
        ];
      }
    }
    // Add the pager.
    $build['pager'] = [
      '#type' => 'pager',
    ];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function getResponse(array &$build, $id = NULL) {
    $response = [];
    // Check if the integration is enabled before making the request.
    if ($this->fortnoxClient->checkIfIntegrationIsEnabled()) {
      // Get the page query parameter so we can request invoices by page.
      $page = $this->requestStack->getCurrentRequest()->get('page') + 1;
      $limit = isset($build['limit']) ? $build['limit'] : 50;
      $page = isset($build['page']) ? $build['page'] : $page;
      $response = $this->fortnoxClient->makeRequest('GET', $this->endpoint . $this->url . '/' . $id, ['query' => ['page' => $page, 'limit' => $limit]]);
    }

    return $response;
  }

  /**
   * Updates an existing resource.
   *
   * @param string $id
   *   The resource to update.
   * @param array $requestParameters
   *   Array containing request parameters.
   *
   * @return array|bool|mixed
   *   The request response.
   */
  public function updateResource($id, array $requestParameters) {
    $response = [];
    // Check if the integration is enabled before making the request.
    if ($this->fortnoxClient->checkIfIntegrationIsEnabled()) {
      $response = $this->fortnoxClient->makeRequest('PUT', $this->endpoint . $this->url . '/' . $id, ['body' => $requestParameters]);
    }
    if (!empty($response)) {
      $this->messenger->addMessage($this->t('Your resource was successfully updated.'));
      return $response;
    }
    else {
      $this->messenger->addError($this->t("The resource couldn't be created. Please check the logs."));
      return FALSE;
    }
  }

  /**
   * Retrieves response's meta information.
   *
   * @param array $response
   *   The response from fortnox.
   *
   * @return int
   *   The meta information.
   */
  protected function getMetaInformation(array &$response) {
    $meta = NULL;
    if (isset($response['MetaInformation']['@TotalResources'])) {
      $meta = $response['MetaInformation']['@TotalResources'];
    }

    return $meta;
  }

  /**
   * {@inheritdoc}
   */
  abstract public function addTableValues(array $values, array &$build);

  /**
   * Returns the form for the current plugin.
   *
   * @return array
   *   The form for the current plugin.
   */
  public function getCreateForm() {
    return $this->formBuilder->getForm(SupplierInvoicesForm::class);
  }

  /**
   * {@inheritdoc}
   */
  public function createFortnoxResource($resource) {
    $requestParameters['body'] = $resource;
    $response = $this->fortnoxClient->makeRequest('POST', $this->endpoint . $this->url, $requestParameters);
    if (!empty($response)) {
      $this->messenger->addMessage($this->t('Your resource was successfully created.'));
      return $response;
    }
    else {
      $this->messenger->addError($this->t("The resource couldn't be created. Please check the logs."));
      return FALSE;
    }
  }

  /**
   * Deletes an resource.
   *
   * @param string $id
   *   The resource id.
   * @param string $param1
   *   Optional parameter.
   * @param string $param2
   *   Options parameter.
   *
   * @return bool|mixed|null
   *   Returns the request response.
   */
  public function deleteResource($id, $param1 = '', $param2 = '') {
    $response = NULL;
    // Check if the integration is enabled before making the request.
    if ($this->fortnoxClient->checkIfIntegrationIsEnabled()) {
      if (!empty($param1) && !empty($param2)) {
        $id .= '/' . $param1 . '/' . $param2;
      }
      $response = $this->fortnoxClient->makeRequest('DELETE', $this->endpoint . $this->url . '/' . $id, []);
    }

    return $response;
  }

  /**
   * Creates a list of resource properties.
   *
   * @return array
   *   The properties array.
   */
  public function getResourceDetails() {
    return [
      'id-plural' => $this->resourceIDPlural,
      'id-singular' => $this->resourceIDSingular,
      'property-name' => $this->resourceIDPropertyName,
    ];
  }

}

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

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