Coverage index

src/Plugin/views/filter/CurrentPathValue.php

Lines: 0.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin\views\filter;
6
7
use Drupal\Core\Path\CurrentPathStack;
8
9
/**
10
 * Builds a path from the current request by removing and adding parts.
11
 */
12
class CurrentPathValue {
13
14
  /**
15
   * Constructs a CurrentPathValue object.
16
   *
17
   * @param \Drupal\Core\Path\CurrentPathStack $currentPath
18
   *   The current path.
19
   */
20
  public function __construct(
21
    protected CurrentPathStack $currentPath,
220
  ) {}
23
24
  /**
25
   * Returns the current path after parts are removed and added.
26
   *
27
   * @param int $pop
28
   *   Trailing parts to remove. 1 turns /node/1/visitors into /node/1.
29
   * @param string $append
30
   *   Path parts to add. A leading slash and empty parts are ignored.
31
   *
32
   * @return string
33
   *   The adjusted path, or an empty string when nothing remains.
34
   */
35
  public function path(int $pop, string $append): string {
360
    $path = $this->currentPath->getPath();
370
    if ($pop > 0) {
380
      $parts = explode('/', $path);
390
      $parts = array_slice($parts, 0, -$pop);
400
      $path  = implode('/', $parts);
41
    }
42
430
    $extra = array_values(array_filter(
440
      explode('/', trim($append, '/')),
450
      static fn (string $part): bool => $part !== '',
460
    ));
470
    if ($extra !== []) {
480
      $path = rtrim($path, '/') . '/' . implode('/', $extra);
49
    }
50
510
    return $path === '/' ? '' : $path;
52
  }
53
54
}