1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6/**
7 * This is a port of parser_spec from the http_accept_language gem
8 * https://github.com/iain/http_accept_language/blob/v2.1.1/spec/parser_spec.rb.
9 */
10
11namespace Tests\Libraries\AcceptHttpLanguage;
12
13use App\Libraries\AcceptHttpLanguage\Parser;
14use Tests\TestCase;
15
16class ParserTest extends TestCase
17{
18 private const DEFAULT_HEADER = 'en-us,en-gb;q=0.8,en;q=0.6,es-419';
19
20 public function testShouldReturnEmptyArray()
21 {
22 $this->assertSame([], Parser::parseHeader(null));
23 }
24
25 public function testShouldProperlySplit()
26 {
27 $this->assertSame(
28 ['en-us', 'es-419', 'en-gb', 'en'],
29 Parser::parseHeader('en-us,en-gb;q=0.8,en;q=0.6,es-419'),
30 );
31 }
32
33 public function testShouldIgnoreJambledHeader()
34 {
35 $this->assertSame([], Parser::parseHeader('odkhjf89fioma098jq .,.,'));
36 }
37
38 public function testShouldProperlyRespectWhitespace()
39 {
40 $this->assertSame(
41 ['en-us', 'es-419', 'en-gb', 'en'],
42 Parser::parseHeader('en-us, en-gb; q=0.8,en;q = 0.6,es-419'),
43 );
44 }
45
46 public function testShouldFindFirstCompatibleLanguage()
47 {
48 $this->assertSame(
49 'en-hk',
50 (new Parser(['en-hk']))->languageRegionCompatibleFor(static::DEFAULT_HEADER),
51 );
52
53 $this->assertSame(
54 'en',
55 (new Parser(['en']))->languageRegionCompatibleFor(static::DEFAULT_HEADER),
56 );
57 }
58
59 public function testShouldfindFirstCompatibleFromUserPreferred()
60 {
61 $this->assertSame(
62 'en',
63 (new Parser(['de', 'en']))->languageRegionCompatibleFor('en-us,de-de'),
64 );
65 }
66
67 public function testShouldAcceptAndIgnoreWildcards()
68 {
69 $this->assertSame(
70 'en-us',
71 (new Parser(['en-us']))->languageRegionCompatibleFor('en-US,en,*'),
72 );
73 }
74
75 public function testShouldFindMostCompatibleLanguageFromUserPreferred()
76 {
77 $this->assertSame(
78 'ja-jp',
79 (new Parser(['en-uk', 'en-us', 'ja-jp']))->languageRegionCompatibleFor('ja,en-gb,en-us,fr-fr'),
80 );
81 }
82}