Commit 953fe54d authored by Taras Kyryliuk's avatar Taras Kyryliuk
Browse files

User weather display ported, refactored and optimised related code

parent 71059414
Loading
Loading
Loading
Loading
+5 −0
Original line number Diff line number Diff line
@@ -82,6 +82,11 @@ class WeatherDetailedForecastController extends ControllerBase {
      $display_type = 'system-wide';
      $display_number = $destination;
    }
    elseif ($destination == 'u') {
      // Use the user's custom display.
      $display_type = 'user';
      $display_number = $this->currentUser()->id();
    }

    if ($weatherPlace instanceof WeatherPlaceInterface) {
      // Show detailed forecast only if Weather Place
+23 −15
Original line number Diff line number Diff line
@@ -6,12 +6,15 @@ use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Renderer;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
use Drupal\weather\Entity\WeatherDisplayInterface;
use Drupal\weather\Service\HelperService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Returns responses for Weather routes.
@@ -32,6 +35,13 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {
   */
  protected $entityTypeManager;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The controller constructor.
   *
@@ -39,10 +49,13 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {
   *   The weather.helper service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity.type_manager service.
   * @param \Drupal\Core\Render\Renderer $renderer
   *   The renderer service.
   */
  public function __construct(HelperService $weather_helper, EntityTypeManagerInterface $entity_type_manager) {
  public function __construct(HelperService $weather_helper, EntityTypeManagerInterface $entity_type_manager, Renderer $renderer) {
    $this->weatherHelper = $weather_helper;
    $this->entityTypeManager = $entity_type_manager;
    $this->renderer = $renderer;
  }

  /**
@@ -51,7 +64,8 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('weather.helper'),
      $container->get('entity_type.manager')
      $container->get('entity_type.manager'),
      $container->get('renderer')
    );
  }

@@ -59,6 +73,7 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {
   * Builds the response.
   */
  public function content(UserInterface $user) {
    $output = [];
    $weatherDisplayPlaceStorage = $this->entityTypeManager->getStorage('weather_display_place');

    $header = [
@@ -80,18 +95,20 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {
          Link::createFromRoute(
            $location->displayed_name->value,
            'weather.user.weather_display_place.edit_form', [
              'display_number' => $user->id(),
              'user' => $user->id(),
              'weather_display_place' => $location->id(),
            ]),
          $location->weight->value,
        ];
        $this->renderer->addCacheableDependency($output, $location);
      }
    }
    $output["#cache"]["tags"][] = 'weather_display:' . $user->id();

    // Insert link for adding locations into the table as last row.
    $rows[] = [
      [
        'data' => Link::createFromRoute($this->t('Add location to this display'), 'weather.user.weather_display_place.add_form', ['display_number' => $user->id()]),
        'data' => Link::createFromRoute($this->t('Add location to this display'), 'weather.user.weather_display_place.add_form', ['user' => $user->id()]),
        'colspan' => 2,
      ],
    ];
@@ -104,15 +121,6 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {

    // Generate link to Add or Edit user's weather display.
    $url = Url::fromRoute('weather.user.weather_display.add_form', ['user' => $user->id()]);
    $weatherDisplayStorage = $this->entityTypeManager->getStorage('weather_display');
    $userWeatherDisplay = $weatherDisplayStorage->loadByProperties([
      'type' => WeatherDisplayInterface::USER_TYPE,
      'number' => $user->id(),
    ]);
    $userWeatherDisplay = reset($userWeatherDisplay);
    if ($userWeatherDisplay instanceof WeatherDisplayInterface) {
      $url = Url::fromRoute('weather.user.weather_display.edit_form', ['display_number' => $user->id(), 'weather_display' => $userWeatherDisplay->id()]);
    }

    $output['edit_display'] = [
      '#type' => 'link',
@@ -132,9 +140,9 @@ class WeatherUserConfiguredDisplayController extends ControllerBase {
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
  public function access(AccountInterface $account, UserInterface $user) {
    return AccessResult::allowedIf(
      $this->currentUser()->id() == $account->id() &&
      $user->id() == $account->id() &&
      $account->hasPermission('administer custom weather block')
    );
  }
+0 −2
Original line number Diff line number Diff line
@@ -20,8 +20,6 @@ use Drupal\Core\Field\BaseFieldDefinition;
 *   handlers = {
 *     "form" = {
 *       "add" = "Drupal\weather\Form\WeatherDisplayForm",
 *       "add_user" = "Drupal\weather\Form\WeatherDisplayForm",
 *       "default" = "Drupal\weather\Form\WeatherDisplayForm",
 *       "edit" = "Drupal\weather\Form\WeatherDisplayForm",
 *       "delete" = "Drupal\weather\Form\WeatherDisplayDeleteForm",
 *     },
+52 −30
Original line number Diff line number Diff line
@@ -75,39 +75,42 @@ class WeatherDisplayForm extends ContentEntityForm {
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
  public function buildForm(array $form, FormStateInterface $form_state, string $display_type = '') {
    $form = parent::buildForm($form, $form_state);
    $displayNumber = NULL;
    $savedConfig = [];

    // todo: simplify this part, we dont need so many operation types.
    // only add/edit should left, check perms for operations in Entity access.
    switch ($this->operation) {
      case 'add':
        $display_type = WeatherDisplayInterface::SYSTEM_WIDE_TYPE;
        break;

      case 'edit':
        $display_type = $this->entity->type->value;
        $savedConfig = $this->entity->config->getValue()[0];
        break;

      case 'add_user':
        $display_type = WeatherDisplayInterface::USER_TYPE;
        break;
    $savedConfig = [];

      case 'default':
        $display_type = WeatherDisplayInterface::DEFAULT_TYPE;
    // Try to load saved config when we are editing
    // Default or User weather display.
    if ($display_type == WeatherDisplayInterface::DEFAULT_TYPE) {
      $displayNumber = 1;
        break;

      default:
        $display_type = NULL;
      $defaultDisplay = $this->weatherDisplayStorage->loadByProperties([
        'type' => WeatherDisplayInterface::DEFAULT_TYPE,
      ]);
      $defaultDisplay = reset($defaultDisplay);
      if ($defaultDisplay instanceof WeatherDisplayInterface) {
        $savedConfig = $defaultDisplay->config->getValue()[0];
      }
    }
    elseif ($display_type == WeatherDisplayInterface::USER_TYPE) {
      $displayNumber = $this->currentUser()->id();
      $userDisplayExists = $this->weatherDisplayStorage->loadByProperties([
        'type' => WeatherDisplayInterface::USER_TYPE,
        'number' => $this->currentUser()->id(),
      ]);
      $userDisplay = reset($userDisplayExists);
      if ($userDisplay instanceof WeatherDisplayInterface) {
        $savedConfig = $userDisplay->config->getValue()[0];
      }
    }

    // When we are editing system-wide display.
    if (!$this->entity->isNew()) {
      $display_type = $this->entity->type->value;
      $displayNumber = $this->entity->number->value;
      $savedConfig = $this->entity->config->getValue()[0];
    }

    $defaultConfig = $this->weatherHelperService->getDisplayConfig(WeatherDisplayInterface::DEFAULT_TYPE);

    $form['config'] = [
@@ -195,8 +198,8 @@ class WeatherDisplayForm extends ContentEntityForm {
      '#value' => $displayNumber,
    ];

    // Show a 'reset' button if editing the default display.
    if ($this->operation == 'default') {
    // Show a 'reset' button if editing the default or user display.
    if (in_array($display_type, [WeatherDisplayInterface::DEFAULT_TYPE, WeatherDisplayInterface::USER_TYPE])) {
      $form['actions']['reset'] = [
        '#type' => 'submit',
        '#value' => $this->t('Reset'),
@@ -208,7 +211,7 @@ class WeatherDisplayForm extends ContentEntityForm {
    // Use different path for delete form for non-admin user.
    if ($display_type == WeatherDisplayInterface::USER_TYPE) {
      $form["actions"]["delete"]["#url"] = Url::fromRoute('weather.user.weather_display.delete_form', [
        'display_number' => $displayNumber,
        'user' => $displayNumber,
        'weather_display' => $this->entity->id(),
      ]);
    }
@@ -233,9 +236,10 @@ class WeatherDisplayForm extends ContentEntityForm {
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $type = $form_state->getValue('type');

    // Set display number before save.
    if ($form_state->getValue('number') == NULL) {
      $type = $form_state->getValue('type');
      $free_number = $this->getFreeDisplayNumber($type);
      $this->entity->set('number', $free_number);
    }
@@ -243,7 +247,7 @@ class WeatherDisplayForm extends ContentEntityForm {
    $this->entity->set('config', $form_state->getValue('config'));

    // Make sure we have only one instance of display with type 'default'.
    if ($this->operation == 'default') {
    if ($type == WeatherDisplayInterface::DEFAULT_TYPE) {
      $defaultDisplay = $this->weatherDisplayStorage->loadByProperties([
        'type' => WeatherDisplayInterface::DEFAULT_TYPE,
      ]);
@@ -253,6 +257,18 @@ class WeatherDisplayForm extends ContentEntityForm {
        $this->entity->enforceIsNew(FALSE);
      }
    }
    // Make sure only one Display per user.
    elseif ($type == WeatherDisplayInterface::USER_TYPE) {
      $userDisplayExists = $this->weatherDisplayStorage->loadByProperties([
        'type' => WeatherDisplayInterface::USER_TYPE,
        'number' => $this->currentUser()->id(),
      ]);
      $userDisplay = reset($userDisplayExists);
      if ($userDisplay instanceof WeatherDisplayInterface) {
        $this->entity->id = $userDisplay->id();
        $this->entity->enforceIsNew(FALSE);
      }
    }

    $status = parent::save($form, $form_state);
    if ($status == SAVED_NEW) {
@@ -281,6 +297,12 @@ class WeatherDisplayForm extends ContentEntityForm {
   * Finds first free display number for given display type.
   */
  protected function getFreeDisplayNumber(string $displayType) : int {
    // User display ID is always equal UID.
    if ($displayType == WeatherDisplayInterface::USER_TYPE) {
      return $this->currentUser()->id();
    }

    // Find next number for system-wide display.
    $used_numbers = Database::getConnection()
      ->select('weather_display', 'wd')
      ->fields('wd', ['number'])
+15 −1
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@
namespace Drupal\weather\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
@@ -74,6 +75,10 @@ class WeatherDisplayPlaceForm extends ContentEntityForm {
      return $form;
    }

    if ($display_type == WeatherDisplayInterface::USER_TYPE) {
      $display_number = $this->currentUser()->id();
    }

    $form = parent::buildForm($form, $form_state);

    // If we are on edit form, display type and number not passed here.
@@ -159,7 +164,7 @@ class WeatherDisplayPlaceForm extends ContentEntityForm {
    // Use different path for delete form for non-admin user.
    if ($display_type == WeatherDisplayInterface::USER_TYPE && $weather_display_place instanceof WeatherDisplayPlaceInterface) {
      $form["actions"]["delete"]["#url"] = Url::fromRoute('weather.user.weather_display_place.delete_form', [
        'display_number' => $display_number,
        'user' => $display_number,
        'weather_display_place' => $weather_display_place->id(),
      ]);
    }
@@ -173,6 +178,15 @@ class WeatherDisplayPlaceForm extends ContentEntityForm {
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form, $form_state);

    // Invalidate related weather display cache, once place is saved.
    $display_type = $this->entity->display_type->value;
    $display_number = $this->entity->display_number->value;
    $displays = $this->entityTypeManager->getStorage('weather_display')->loadByProperties(['type' => $display_type, 'number' => $display_number]);
    foreach ($displays as $display) {
      Cache::invalidateTags($display->getCacheTags());
    }

    // Show message.
    if ($status == SAVED_NEW) {
      $message = $this->t('Added new place to weather display');
    }
Loading