Skip to content

Commit

Permalink
Match type
Browse files Browse the repository at this point in the history
  • Loading branch information
timkelty committed Dec 23, 2024
1 parent 80f6456 commit b7bd20d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
9 changes: 9 additions & 0 deletions src/enums/MatchType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace craft\enums;

enum MatchType: string
{
case Exact = 'exact';
case Regex = 'regex';
}
28 changes: 24 additions & 4 deletions src/web/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,33 @@
namespace craft\web;

use Craft;
use craft\enums\MatchType;
use League\Uri\Http;

class Redirect extends \yii\base\BaseObject
{
public string $to;
public string $from;
public int $statusCode = 302;
public \Closure|string $match;
public MatchType $matchType;
public int $statusCode = 302;
public bool $caseSensitive = true;
private string $delimiter = '`';
private array $matches = [];

public function __construct($config = [])
{
$this->match = $config['match'] ?? Craft::$app->getRequest()->getFullPath();
$matchType = $config['matchType'] ?? MatchType::Exact;

$this->matchType = match (true) {
$matchType instanceof MatchType => $matchType,
default => MatchType::tryFrom($matchType),
};

unset($config['match']);
unset($config['matchType']);

parent::__construct($config);
}

Expand All @@ -44,8 +56,16 @@ private function findMatch(): bool
{
$url = Http::new(Craft::$app->getRequest()->getAbsoluteUrl());
$match = is_callable($this->match) ? ($this->match)($url) : $this->match;
$regexFlags = $this->caseSensitive ? '' : 'i';
$pattern = "{$this->delimiter}{$this->from}{$this->delimiter}{$regexFlags}";
return preg_match($pattern, $match, $this->matches);

if ($this->matchType === MatchType::Regex) {
$regexFlags = $this->caseSensitive ? '' : 'i';
$pattern = "{$this->delimiter}{$this->from}{$this->delimiter}{$regexFlags}";

return preg_match($pattern, $match, $this->matches);
}

return $this->caseSensitive ?
strcmp($this->from, $match) === 0 :
strcasecmp($this->from, $match) === 0;
}
}

0 comments on commit b7bd20d

Please sign in to comment.