You are here

class StringSorter in Views XML Backend 8

Provides sorting for strings.

Hierarchy

Expanded class hierarchy of StringSorter

5 files declare their use of StringSorter
Standard.php in src/Plugin/views/sort/Standard.php
Contains \Drupal\views_xml_backend\Plugin\views\sort\Standard.
Standard.php in src/Plugin/views/field/Standard.php
Contains \Drupal\views_xml_backend\Plugin\views\field\Standard.
StandardTest.php in tests/src/Unit/Plugin/views/sort/StandardTest.php
Contains \Drupal\Tests\views_xml_backend\Unit\Plugin\views\sort\StandardTest.
StandardTest.php in tests/src/Unit/Plugin/views/field/StandardTest.php
Contains \Drupal\Tests\views_xml_backend\Unit\Plugin\views\field\StandardTest.
StringSorterTest.php in tests/src/Unit/Sorter/StringSorterTest.php

File

src/Sorter/StringSorter.php, line 15
Contains \Drupal\views_xml_backend\Sorter\StringSorter.

Namespace

Drupal\views_xml_backend\Sorter
View source
class StringSorter implements SorterInterface {

  /**
   * The direction to sort.
   *
   * @var string
   */
  protected $direction;

  /**
   * The field of the result to sort.
   *
   * @var string
   */
  protected $field;

  /**
   * Constructs a StringSorter object.
   *
   * @param string $field
   *   The field to sort.
   * @param string $direction
   *   The direction to sort.
   */
  public function __construct($field, $direction) {
    $this->field = $field;
    $this->direction = strtoupper($direction);
  }

  /**
   * {@inheritdoc}
   */
  public function __invoke(array &$result) {

    // Notice the order of the arguments to strcasecmp().
    switch ($this->direction) {
      case 'ASC':
        usort($result, function (ResultRow $a, ResultRow $b) {
          $compare = strcasecmp(reset($a->{$this->field}), reset($b->{$this->field}));
          if ($compare === 0) {
            return $a->index < $b->index ? -1 : 1;
          }
          return $compare;
        });
        break;
      case 'DESC':
        usort($result, function (ResultRow $a, ResultRow $b) {
          $compare = strcasecmp(reset($b->{$this->field}), reset($a->{$this->field}));
          if ($compare === 0) {
            return $a->index < $b->index ? -1 : 1;
          }
          return $compare;
        });
        break;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
StringSorter::$direction protected property The direction to sort.
StringSorter::$field protected property The field of the result to sort.
StringSorter::__construct public function Constructs a StringSorter object.
StringSorter::__invoke public function Sorts a views result. Overrides SorterInterface::__invoke 2