From f81cefefbe0b5888779bd9abccfd1bc4f57dc4ca Mon Sep 17 00:00:00 2001 From: Vladimir Bryzgalov Date: Tue, 12 May 2026 19:58:19 +0500 Subject: [PATCH] feat(wpmc S3): Helpers::current_town URI-match path Co-Authored-By: Claude Sonnet 4.6 --- includes/class-helpers.php | 47 ++++++++++++++++++++++++++++++++++++++ tests/HelpersTest.php | 15 ++++++++++++ 2 files changed, 62 insertions(+) diff --git a/includes/class-helpers.php b/includes/class-helpers.php index 4ecf607..cbb2765 100644 --- a/includes/class-helpers.php +++ b/includes/class-helpers.php @@ -25,4 +25,51 @@ final class Helpers $term = \get_term_by('slug', $slug, $taxonomy); return self::$term_cache[$key] = ($term instanceof \WP_Term) ? $term : null; } + + public static function current_town(): ?string + { + if (self::$current_town_resolved) { + return self::$current_town_memo; + } + + $uri = $_SERVER['REQUEST_URI'] ?? '/'; + $first_segment = self::first_path_segment($uri); + + $resolved = null; + if ($first_segment !== null) { + $terms = \get_terms('town', [ + 'hide_empty' => false, + 'fields' => 'id=>slug', + ]); + if (is_array($terms) && in_array($first_segment, $terms, true)) { + $resolved = $first_segment; + } + } + + if ($resolved === null) { + $resolved = \apply_filters('wpmc_main_town_slug', null); + if (!is_string($resolved) || $resolved === '') { + $resolved = null; + } + } + + $resolved = \apply_filters('wpmc_current_town_slug', $resolved); + if (!is_string($resolved) || $resolved === '') { + $resolved = null; + } + + self::$current_town_memo = $resolved; + self::$current_town_resolved = true; + return $resolved; + } + + private static function first_path_segment(string $uri): ?string + { + $path = strtok($uri, '?'); + if ($path === false) { + return null; + } + $parts = array_values(array_filter(explode('/', $path), static fn(string $p) => $p !== '')); + return $parts[0] ?? null; + } } diff --git a/tests/HelpersTest.php b/tests/HelpersTest.php index df247c2..09c8669 100644 --- a/tests/HelpersTest.php +++ b/tests/HelpersTest.php @@ -50,4 +50,19 @@ final class HelpersTest extends TestCase // Mockery ->once() at teardown verifies the cache stopped repeated calls. self::assertTrue(true); } + + public function test_current_town_returns_slug_when_uri_matches_existing_town(): void + { + $_SERVER['REQUEST_URI'] = '/tyumen/some-service/'; + + \Brain\Monkey\Functions\expect('get_terms') + ->once() + ->with('town', \Mockery::on(function ($args) { + return ($args['hide_empty'] ?? null) === false + && ($args['fields'] ?? null) === 'id=>slug'; + })) + ->andReturn([10 => 'spb', 11 => 'tyumen']); + + self::assertSame('tyumen', Helpers::current_town()); + } }