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

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

namespace Drupal\trinion_suo\Plugin\rest\resource;

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

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "subscription_rest_resource",
 *   label = @Translation("Subscription rest resource"),
 *   uri_paths = {
 *     "create" = "/subscribe"
 *   }
 * )
 */
class SubscriptionRestResource 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 POST requests.
     *
     * @param string $payload
     *
     * @return \Drupal\rest\ModifiedResourceResponse
     *   The HTTP response object.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post($payload) {
//        if (!$this->currentUser->hasPermission('access content')) {
//            throw new AccessDeniedHttpException();
//        }

        $result = ['result' => 'error'];

        $query = \Drupal::database()->select('trinion_suo_subscribers', 's');
        $query->condition('s.email', $payload['email']);
        $exist = $query->countQuery()->execute()->fetchField();

        if ($exist) {
          $result = ['result' => 'exist'];
        }
        else {
          $query = \Drupal::database()->insert('trinion_suo_subscribers');
          $query->fields([
            'email' => strtolower($payload['email']),
            'timestamp' => time(),
          ]);
          $res = $query->execute();
          if (is_numeric($res))
            $result = ['result' => 'ok'];
        }

        return new ModifiedResourceResponse($result, 200);
    }

}

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

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