trinion_suo-1.0.x-dev/src/Plugin/rest/resource/MarkLessonRestResource.php

src/Plugin/rest/resource/MarkLessonRestResource.php
<?php

namespace Drupal\trinion_suo\Plugin\rest\resource;

use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "mark_lesson_rest_resource",
 *   label = @Translation("Mark lesson as completed rest resource"),
 *   uri_paths = {
 *     "canonical" = "/lesson-complete/{id}"
 *   }
 * )
 */
class MarkLessonRestResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->logger = $container->get('logger.factory')->get('trinion_suo');
    $instance->currentUser = $container->get('current_user');
    return $instance;
  }

    /**
     * Responds to GET requests.
     *
     * @param string $payload
     *
     * @return \Drupal\rest\ModifiedResourceResponse
     *   The HTTP response object.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function get(int $id) {
      $user = User::load($this->currentUser->id());
      $exist = false;
      foreach ($user->get('field_id_proydennykh_urokov')->getValue() as $val) {
        if ($id == $val['target_id'])
          $exist = true;
      }
      if (!$exist) {
        $user->field_id_proydennykh_urokov[] = $id;
        $user->save();
      }

      return new ModifiedResourceResponse([], 200);
    }

}

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

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