Commit 767286c9 authored by Joshua Fernandes's avatar Joshua Fernandes
Browse files

Issue #3264498 by joshua1234511: Add block configuration from to override...

Issue #3264498 by joshua1234511: Add block configuration from to override number of products to show for each block. 
parent aafe5b83
Loading
Loading
Loading
Loading

composer.json

0 → 100644
+30 −0
Original line number Diff line number Diff line
{
  "name": "drupal/urvp",
  "description": "Display recently viewed products.",
  "type": "drupal-module",
  "homepage": "https://www.drupal.org/project/urvp",
  "license": "GPL-2.0-or-later",
  "minimum-stability": "dev",
  "authors": [
    {
      "name": "Joshua Fernandes",
      "email": "contact@fernandesjoshua.com"
    }
  ],
  "support": {
    "issues": "https://www.drupal.org/project/issues/urvp",
    "source": "http://cgit.drupalcode.org/urvp"
  },
  "repositories": {
    "drupal": {
      "type": "composer",
      "url": "https://packages.drupal.org/8"
    }
  },
  "require": {
    "drupal/core": "^8 || ^9"
  },
  "require-dev": {
    "drupal/ubercart": "^4"
  }
}
+34 −9
Original line number Diff line number Diff line
@@ -6,22 +6,40 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Configure uvrp Subscriber for this site.
 */
class RVPSubscriber implements EventSubscriberInterface {

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

  /**
   * Constructs an event subscriber.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * Redirect pattern based url.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The event to process.
   *   The response event, which contains the current request.
   */
  public function rvp(GetResponseEvent $event) {
    $session = $this->uvrpSession();
    if (!$session) {
      $session_id    = $this->drupalHashBase64(uniqid(mt_rand(), TRUE));
      $session_id    = $this->drupalHashBase64();
      $cookie_domain = ini_get('session.cookie_domain');
      setcookie('uvrp', $session_id, \Drupal::time()->getRequestTime() + 2592000, '/', $cookie_domain, 1, 1);
    }
@@ -29,9 +47,10 @@ class RVPSubscriber implements EventSubscriberInterface {
    $node = uvrp_get_current_node();
    if ($node instanceof NodeInterface) {
      if ($node->getType() == 'product') {
        $uvrp_cookie = $this->requestStack->getCurrentRequest()->cookies->get('uvrp');
        \Drupal::database()->merge('uvrp')->key([
          'nid' => $node->id(),
          'sid' => isset($_COOKIE['uvrp']) ? $_COOKIE['uvrp'] : session_id(),
          'sid' => $uvrp_cookie ?? session_id(),
          'uid' => uvrp_current_user_id(),
        ])->fields([
          'ip' => uvrp_client_ip(),
@@ -43,9 +62,13 @@ class RVPSubscriber implements EventSubscriberInterface {

  /**
   * Hash the data value.
   *
   * @return string
   *   The hash base64 string value.
   */
  private function drupalHashBase64($data) {
    $hash = base64_encode(hash('sha256', $data, TRUE));
  private function drupalHashBase64() {
    $uniqid = uniqid(mt_rand(), TRUE);
    $hash = base64_encode(hash('sha256', $uniqid, TRUE));
    // Modify the hash so it's safe to use in URLs.
    return strtr($hash, ['+' => '-', '/' => '_', '=' => '']);
  }
@@ -54,19 +77,21 @@ class RVPSubscriber implements EventSubscriberInterface {
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['rvp'];
    return $events;
    return [
      KernelEvents::REQUEST => 'rvp',
    ];
  }

  /**
   * Check if cookie variable is set.
   */
  private function uvrpSession() {
    if (isset($_COOKIE['uvrp']) && !empty($_COOKIE['uvrp'])) {
    $uvrp_cookie = $this->requestStack->getCurrentRequest()->cookies->get('uvrp');
    if (isset($uvrp_cookie) && !empty($uvrp_cookie)) {
      return TRUE;
    }
    else {
      $_COOKIE['uvrp'] = '';
      $this->requestStack->getCurrentRequest()->cookies->set('uvrp', '');
      return FALSE;
    }
  }
+5 −3
Original line number Diff line number Diff line
@@ -22,7 +22,7 @@ class RVPSettingsForm extends ConfigFormBase {
   */
  protected function getEditableConfigNames() {
    return [
      'uvrp.settings',
      'urvp.settings',
    ];
  }

@@ -30,7 +30,7 @@ class RVPSettingsForm extends ConfigFormBase {
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('uvrp.settings');
    $config = $this->config('urvp.settings');

    $form['uvrp_expire_interval'] = [
      '#type' => 'textfield',
@@ -40,6 +40,7 @@ class RVPSettingsForm extends ConfigFormBase {
      '#title' => $this->t('Products Expire time'),
      '#default_value' => $config->get('uvrp_expire_interval', 86400),
      '#description' => $this->t("Specify the time (in sec) for which viewed products should remain in database."),
      '#required' => TRUE,
    ];

    $form['uvrp_limit'] = [
@@ -50,6 +51,7 @@ class RVPSettingsForm extends ConfigFormBase {
      '#title' => $this->t('Number of products to show'),
      '#default_value' => $config->get('uvrp_limit', 4),
      '#description' => $this->t("Specify the number of products to show."),
      '#required' => TRUE,
    ];

    return parent::buildForm($form, $form_state);
@@ -61,7 +63,7 @@ class RVPSettingsForm extends ConfigFormBase {
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Retrieve the configuration.
    $this->configFactory()->getEditable('uvrp.settings')
    $this->configFactory()->getEditable('urvp.settings')
    // Set the submitted configuration setting.
      ->set('uvrp_expire_interval', $form_state->getValue('uvrp_expire_interval'))
    // You can set multiple configurations at once by making
+44 −1
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ namespace Drupal\uvrp\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Ubercart Recently Viewed Products' Block.
@@ -15,12 +16,54 @@ use Drupal\Core\Block\BlockPluginInterface;
 */
class RVPBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();
    $global_config = \Drupal::config('urvp.settings');
    $limit = $global_config->get('uvrp_limit');

    $form['uvrp_limit'] = [
      '#type' => 'textfield',
      '#attributes' => [
        ' type' => 'number',
      ],
      '#title' => $this->t('Number of products to show'),
      '#default_value' => $config['uvrp_limit'] ?? $limit ?? 4,
      '#description' => $this->t("Specify the number of products to show."),
      '#required' => TRUE,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $this->configuration['uvrp_limit'] = $form_state->getValue('uvrp_limit');
  }

  /**
   * {@inheritdoc}
   */
  public function blockValidate($form, FormStateInterface $form_state) {
    if ($form_state->getValue('uvrp_limit') <= 0) {
      $form_state->setErrorByName('uvrp_limit', $this->t('Enter only positive integers.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form['#markup'] = uvrp_block_display();
    $config = $this->getConfiguration();
    $limit = $config['uvrp_limit'];
    $form['#markup'] = uvrp_block_display($limit);
    $form['#cache']['max-age'] = 0;
    return $form;

+6 −9
Original line number Diff line number Diff line
@@ -3,8 +3,6 @@
/**
 * @file
 * Allows users to see recently viewed products.
 *
 * Module port to Drupal 8 done by Joshua Fernandes.
 */

use Drupal\Core\Routing\RouteMatchInterface;
@@ -12,10 +10,9 @@ use Drupal\Core\Routing\RouteMatchInterface;
/**
 * Get recently viewed products based on user from database.
 */
function uvrp_get() {
function uvrp_get(int $limit) {
  $nids = [];
  $config = \Drupal::config('uvrp.settings');
  $limit = $config->get('uvrp_limit');
  $uvrp_cookie = \Drupal::request()->cookies->get('uvrp');
  $query = \Drupal::database()->select('uvrp', 'rp');
  $query->innerJoin('node_field_data', 'n', 'n.nid = rp.nid');
  $query->distinct();
@@ -24,7 +21,7 @@ function uvrp_get() {
    $query->condition('rp.uid', \Drupal::currentUser()->id());
  }
  else {
    $query->condition('rp.sid', $_COOKIE['uvrp']);
    $query->condition('rp.sid', $uvrp_cookie);
    $query->condition('rp.uid', 0);
  }
  $query->condition('n.status', 1);
@@ -41,9 +38,9 @@ function uvrp_get() {
/**
 * Output block view.
 */
function uvrp_block_display() {
function uvrp_block_display(int $limit) {
  $output = '';
  $nodeIds = uvrp_get();
  $nodeIds = uvrp_get($limit);
  if (!empty($nodeIds)) {
    foreach ($nodeIds as $nodeId) {
      $node = \Drupal::service('entity_type.manager')->getStorage('node')->load($nodeId->nid);
@@ -64,7 +61,7 @@ function uvrp_block_display() {
 * Implements hook_cron().
 */
function uvrp_cron() {
  $config = \Drupal::config('uvrp.settings');
  $config = \Drupal::config('urvp.settings');
  $expireInterval = $config->get('uvrp_expire_interval');
  $expireTime = \Drupal::time()->getRequestTime() - (int) $expireInterval;

Loading