repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidFormatExceptionTest.php | tests/Carbon/Exceptions/InvalidFormatExceptionTest.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidFormatException;
use Tests\AbstractTestCase;
class InvalidFormatExceptionTest extends AbstractTestCase
{
public function testInvalidFormatException(): void
{
$exception = new InvalidFormatException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidIntervalExceptionTest.php | tests/Carbon/Exceptions/InvalidIntervalExceptionTest.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidIntervalException;
use Tests\AbstractTestCase;
class InvalidIntervalExceptionTest extends AbstractTestCase
{
public function testInvalidIntervalException(): void
{
$exception = new InvalidIntervalException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/NotACarbonClassExceptionTest.php | tests/Carbon/Exceptions/NotACarbonClassExceptionTest.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Exceptions;
use Carbon\Exceptions\NotACarbonClassException;
use Tests\AbstractTestCase;
class NotACarbonClassExceptionTest extends AbstractTestCase
{
public function testNotACarbonClassException(): void
{
$exception = new NotACarbonClassException($className = 'foo');
$this->assertSame($className, $exception->getClassName());
$this->assertSame('Given class does not implement Carbon\CarbonInterface: foo', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/BadFluentConstructorExceptionTest.php | tests/Carbon/Exceptions/BadFluentConstructorExceptionTest.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Exceptions;
use Carbon\Exceptions\BadFluentConstructorException;
use Tests\AbstractTestCase;
class BadFluentConstructorExceptionTest extends AbstractTestCase
{
public function testBadFluentConstructorException(): void
{
$exception = new BadFluentConstructorException($method = 'foo');
$this->assertSame($method, $exception->getMethod());
$this->assertSame("Unknown fluent constructor 'foo'.", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Fixtures/FooBar.php | tests/Carbon/Fixtures/FooBar.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Fixtures;
trait FooBar
{
public function super($string)
{
return 'super'.$string.' / '.$this->format('l').' / '.($this->isMutable() ? 'mutable' : 'immutable');
}
public function me()
{
return $this;
}
public static function noThis()
{
return isset(${'this'});
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Fixtures/NoLocaleTranslator.php | tests/Carbon/Fixtures/NoLocaleTranslator.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Fixtures;
use Carbon\Exceptions\NotLocaleAwareException;
use ReflectionMethod;
use Symfony\Component\Translation;
use Symfony\Contracts\Translation\TranslatorInterface;
$transMethod = new ReflectionMethod(
class_exists(TranslatorInterface::class)
? TranslatorInterface::class
: Translation\Translator::class,
'trans',
);
if ($transMethod->hasReturnType()) {
class NoLocaleTranslator implements TranslatorInterface
{
public function trans(string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string
{
return $id;
}
public function getLocale(): string
{
throw new NotLocaleAwareException($this);
}
}
return;
}
class NoLocaleTranslator implements TranslatorInterface
{
public function trans($id, array $parameters = [], $domain = null, $locale = null)
{
return $id;
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Fixtures/DumpCarbon.php | tests/Carbon/Fixtures/DumpCarbon.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Fixtures;
use Carbon\Carbon;
use Exception;
final class DumpCarbon extends Carbon
{
private $dump;
private $formatBroken = false;
/**
* @SuppressWarnings(DevelopmentCodeFragment)
*/
public function __construct($time = null, $timezone = null)
{
ob_start();
var_dump($this);
$this->dump = ob_get_contents() ?: '';
ob_end_clean();
parent::__construct($time, $timezone);
}
public function getDump(): string
{
return $this->dump;
}
public function breakFormat(): void
{
$this->formatBroken = true;
}
public function format(string $format): string
{
if ($this->formatBroken) {
throw new Exception('Broken');
}
return parent::format($format);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Fixtures/MyCarbon.php | tests/Carbon/Fixtures/MyCarbon.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Fixtures;
use Carbon\Carbon;
class MyCarbon extends Carbon
{
public function addTwoHours(): static
{
return $this->addHours(2);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Fixtures/BadIsoCarbon.php | tests/Carbon/Fixtures/BadIsoCarbon.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Fixtures;
use Carbon\Carbon;
class BadIsoCarbon extends Carbon
{
public static function getIsoUnits(): array
{
return [
'MMM' => ['fooxyz', ['barxyz']],
];
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Fixtures/Mixin.php | tests/Carbon/Fixtures/Mixin.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Carbon\Fixtures;
use Carbon\CarbonInterface;
class Mixin
{
public $timezone;
public function __construct($timezone)
{
$this->timezone = $timezone;
}
public function setUserTimezone()
{
$mixin = $this;
return function ($timezone) use ($mixin) {
$mixin->timezone = $timezone;
};
}
public function userFormat()
{
$mixin = $this;
return function ($format) use ($mixin) {
/** @var CarbonInterface $date */
$date = $this;
if ($mixin->timezone) {
$date->setTimezone($mixin->timezone);
}
return $date->format($format);
};
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Language/LanguageTest.php | tests/Language/LanguageTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Language;
use Carbon\Language;
use Tests\AbstractTestCase;
class LanguageTest extends AbstractTestCase
{
public function testAll()
{
$all = Language::all();
$this->assertIsArray($all);
$this->assertArrayHasKey('en', $all);
$this->assertIsArray($all['en']);
$this->assertArrayHasKey('isoName', $all['en']);
$this->assertSame('English', $all['en']['isoName']);
}
public function testRegions()
{
$regions = Language::regions();
$this->assertIsArray($regions);
$this->assertArrayHasKey('US', $regions);
$this->assertSame('United States of America', $regions['US']);
}
public function testGetNames()
{
$ar = new Language('ar');
$this->assertSame([
'isoName' => 'Arabic',
'nativeName' => 'العربية',
], $ar->getNames());
}
public function testGetId()
{
$ar = new Language('ar');
$this->assertSame('ar', $ar->getId());
$ar = new Language('ar_DZ');
$this->assertSame('ar_DZ', $ar->getId());
$ar = new Language('ar_Shakl');
$this->assertSame('ar_Shakl', $ar->getId());
}
public function testGetCode()
{
$ar = new Language('ar');
$this->assertSame('ar', $ar->getCode());
$ar = new Language('ar_DZ');
$this->assertSame('ar', $ar->getCode());
$ar = new Language('ar_Shakl');
$this->assertSame('ar', $ar->getCode());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('sr', $sr->getCode());
}
public function testGetVariant()
{
$ar = new Language('ar');
$this->assertNull($ar->getVariant());
$ar = new Language('ar_DZ');
$this->assertNull($ar->getVariant());
$ar = new Language('ar_Shakl');
$this->assertSame('Shakl', $ar->getVariant());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('Cyrl', $sr->getVariant());
}
public function testGetRegion()
{
$ar = new Language('ar');
$this->assertNull($ar->getRegion());
$ar = new Language('ar_DZ');
$this->assertSame('DZ', $ar->getRegion());
$ar = new Language('ar_Shakl');
$this->assertNull($ar->getRegion());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('ME', $sr->getRegion());
}
public function testGetRegionName()
{
$ar = new Language('ar');
$this->assertNull($ar->getRegionName());
$ar = new Language('ar_DZ');
$this->assertSame('Algeria', $ar->getRegionName());
$ar = new Language('ar_Shakl');
$this->assertNull($ar->getRegionName());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('Montenegro', $sr->getRegionName());
}
public function testGetFullIsoName()
{
$ar = new Language('ca');
$this->assertSame('Catalan, Valencian', $ar->getFullIsoName());
$this->assertSame('Catalan, Valencian', $ar->getFullIsoName());
$ar = new Language('ar_DZ');
$this->assertSame('Arabic', $ar->getFullIsoName());
$gom = new Language('gom_Latn');
$this->assertSame('Konkani, Goan', $gom->getFullIsoName());
$foo = new Language('foo_Latn');
$this->assertSame('foo', $foo->getFullIsoName());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('Serbian', $sr->getFullIsoName());
}
public function testGetFullNativeName()
{
$ar = new Language('ca');
$this->assertSame('català, valencià', $ar->getFullNativeName());
$this->assertSame('català, valencià', $ar->getFullNativeName());
$ar = new Language('ar_DZ');
$this->assertSame('العربية', $ar->getFullNativeName());
$gom = new Language('gom_Latn');
$this->assertSame('ಕೊಂಕಣಿ', $gom->getFullNativeName());
$foo = new Language('foo_Latn');
$this->assertSame('foo', $foo->getFullNativeName());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('српски језик', $sr->getFullNativeName());
}
public function testGetIsoName()
{
$ar = new Language('ca');
$this->assertSame('Catalan', $ar->getIsoName());
$this->assertSame('Catalan', $ar->getIsoName());
$ar = new Language('ar_DZ');
$this->assertSame('Arabic', $ar->getIsoName());
$gom = new Language('gom_Latn');
$this->assertSame('Konkani', $gom->getIsoName());
$foo = new Language('foo_Latn');
$this->assertSame('foo', $foo->getIsoName());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('Serbian', $sr->getIsoName());
}
public function testGetNativeName()
{
$ar = new Language('ca');
$this->assertSame('català', $ar->getNativeName());
$this->assertSame('català', $ar->getNativeName());
$ar = new Language('ar_DZ');
$this->assertSame('العربية', $ar->getNativeName());
$gom = new Language('gom_Latn');
$this->assertSame('ಕೊಂಕಣಿ', $gom->getNativeName());
$foo = new Language('foo_Latn');
$this->assertSame('foo', $foo->getNativeName());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('српски језик', $sr->getNativeName());
}
public function testGetIsoDescription()
{
$ar = new Language('ca');
$this->assertSame('Catalan', $ar->getIsoDescription());
$this->assertSame('Catalan', $ar->getIsoDescription());
$ar = new Language('ar_DZ');
$this->assertSame('Arabic (Algeria)', $ar->getIsoDescription());
$gom = new Language('gom_Latn');
$this->assertSame('Konkani (Latin)', $gom->getIsoDescription());
$foo = new Language('foo_Latn');
$this->assertSame('foo (Latin)', $foo->getIsoDescription());
$foo->setNativeName('Foobar, Barbiz');
$this->assertSame('foo (Latin)', $foo->getIsoDescription());
$foo->setIsoName('Foobar, Barbiz');
$this->assertSame('Foobar (Latin)', $foo->getIsoDescription());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('Serbian (Montenegro) (Cyrillic)', $sr->getIsoDescription());
}
public function testGetNativeDescription()
{
$ar = new Language('ca');
$this->assertSame('català', $ar->getNativeDescription());
$this->assertSame('català', $ar->getNativeDescription());
$ar = new Language('ar_DZ');
$this->assertSame('العربية (Algeria)', $ar->getNativeDescription());
$gom = new Language('gom_Latn');
$this->assertSame('ಕೊಂಕಣಿ (Latin)', $gom->getNativeDescription());
$foo = new Language('foo_Latn');
$this->assertSame('foo (Latin)', $foo->getNativeDescription());
$foo->setIsoName('Foobar, Barbiz');
$this->assertSame('foo (Latin)', $foo->getNativeDescription());
$foo->setNativeName('Foobar, Barbiz');
$this->assertSame('Foobar (Latin)', $foo->getNativeDescription());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('српски језик (Montenegro) (Cyrillic)', $sr->getNativeDescription());
}
public function testGetFullIsoDescription()
{
$ar = new Language('ca');
$this->assertSame('Catalan, Valencian', $ar->getFullIsoDescription());
$this->assertSame('Catalan, Valencian', $ar->getFullIsoDescription());
$ar = new Language('ar_DZ');
$this->assertSame('Arabic (Algeria)', $ar->getFullIsoDescription());
$gom = new Language('gom_Latn');
$this->assertSame('Konkani, Goan (Latin)', $gom->getFullIsoDescription());
$foo = new Language('foo_Latn');
$this->assertSame('foo (Latin)', $foo->getFullIsoDescription());
$foo->setNativeName('Foobar, Barbiz');
$this->assertSame('foo (Latin)', $foo->getFullIsoDescription());
$foo->setIsoName('Foobar, Barbiz');
$this->assertSame('Foobar, Barbiz (Latin)', $foo->getFullIsoDescription());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('Serbian (Montenegro) (Cyrillic)', $sr->getFullIsoDescription());
}
public function testGetFullNativeDescription()
{
$ar = new Language('ca');
$this->assertSame('català, valencià', $ar->getFullNativeDescription());
$this->assertSame('català, valencià', $ar->getFullNativeDescription());
$ar = new Language('ar_DZ');
$this->assertSame('العربية (Algeria)', $ar->getFullNativeDescription());
$gom = new Language('gom_Latn');
$this->assertSame('ಕೊಂಕಣಿ (Latin)', $gom->getFullNativeDescription());
$foo = new Language('foo_Latn');
$this->assertSame('foo (Latin)', $foo->getFullNativeDescription());
$foo->setIsoName('Foobar, Barbiz');
$this->assertSame('foo (Latin)', $foo->getFullNativeDescription());
$foo->setNativeName('Foobar, Barbiz');
$this->assertSame('Foobar, Barbiz (Latin)', $foo->getFullNativeDescription());
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('српски језик (Montenegro) (Cyrillic)', $sr->getFullNativeDescription());
}
public function testToString()
{
$ar = new Language('ar');
$this->assertSame('ar', (string) $ar);
$ar = new Language('ar_DZ');
$this->assertSame('ar_DZ', (string) $ar);
$ar = new Language('ar_Shakl');
$this->assertSame('ar_Shakl', (string) $ar);
}
public function testToJson()
{
$ar = new Language('ca');
$this->assertSame('"Catalan"', json_encode($ar));
$this->assertSame('"Catalan"', json_encode($ar));
$ar = new Language('ar_DZ');
$this->assertSame('"Arabic (Algeria)"', json_encode($ar));
$gom = new Language('gom_Latn');
$this->assertSame('"Konkani (Latin)"', json_encode($gom));
$foo = new Language('foo_Latn');
$this->assertSame('"foo (Latin)"', json_encode($foo));
$foo->setNativeName('Foobar, Barbiz');
$this->assertSame('"foo (Latin)"', json_encode($foo));
$foo->setIsoName('Foobar, Barbiz');
$this->assertSame('"Foobar (Latin)"', json_encode($foo));
$sr = new Language('sr_Cyrl_ME');
$this->assertSame('"Serbian (Montenegro) (Cyrillic)"', json_encode($sr));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Language/TranslatorTest.php | tests/Language/TranslatorTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Language;
use Carbon\AbstractTranslator;
use Carbon\Carbon;
use Carbon\Exceptions\ImmutableException;
use Carbon\Exceptions\NotLocaleAwareException;
use Carbon\Translator;
use Carbon\TranslatorImmutable;
use ReflectionMethod;
use Tests\AbstractTestCase;
class TranslatorTest extends AbstractTestCase
{
public function testSetLocale()
{
$currentLocale = setlocale(LC_TIME, '0');
$currentLocaleAll = setlocale(LC_ALL, '0');
$translator = new Translator('en_FooBar');
$translator->setLocale('auto');
$this->assertSame('en', $translator->getLocale());
$translator = new Translator('en');
$translator->setLocale('en_iso');
$this->assertSame('en_ISO', $translator->getLocale());
$translator = new Translator('fr');
if (setlocale(LC_ALL, 'en_US.UTF-8', 'en_US.utf8', 'en_US', 'en_GB', 'en') === false ||
setlocale(LC_TIME, 'en_US.UTF-8', 'en_US.utf8', 'en_US', 'en_GB', 'en') === false) {
$this->markTestSkipped('testSetLocale test need en_US.UTF-8.');
}
$translator->setLocale('auto');
$this->assertStringStartsWith('en', $translator->getLocale());
setlocale(LC_ALL, $currentLocaleAll);
setlocale(LC_TIME, $currentLocale);
}
public function testMethodsPriorities()
{
Carbon::setLocale('nl');
$text = Carbon::parse('2019-08-06')->locale('en')->isoFormat('dddd D MMMM');
$this->assertSame('Tuesday 6 August', $text);
}
public function testCompareChunkLists()
{
$method = new ReflectionMethod(AbstractTranslator::class, 'compareChunkLists');
$this->assertSame(20, $method->invoke(null, ['a', 'b'], ['a', 'b']));
$this->assertSame(10, $method->invoke(null, ['a', 'b'], ['a', 'c']));
$this->assertSame(10, $method->invoke(null, ['a'], ['a', 'c']));
$this->assertSame(11, $method->invoke(null, ['a', 'b'], ['a']));
$this->assertSame(10, $method->invoke(null, ['a'], ['a']));
}
public function testNotLocaleAwareException()
{
$exception = new NotLocaleAwareException('foobar');
$this->assertSame(
'string does neither implements Symfony\Contracts\Translation\LocaleAwareInterface nor getLocale() method.',
$exception->getMessage(),
);
}
public function testTranslatorImmutable()
{
$this->expectExceptionObject(
new ImmutableException('setTranslations not allowed on '.TranslatorImmutable::class)
);
TranslatorImmutable::get('en')->setTranslations([]);
}
public function testSerializationKeepLocale()
{
$translator = TranslatorImmutable::get('de');
$this->assertEquals('de', unserialize(serialize($translator))->getLocale());
$past = new Carbon('-3 Days');
$today = new Carbon('today');
$interval = $today->diffAsCarbonInterval($past);
$translator = $interval->getLocalTranslator();
$this->assertEquals('en', unserialize(serialize($translator))->getLocale());
$past = new Carbon('-3 Days');
$today = new Carbon('today');
$interval = $today->locale('zh')->diffAsCarbonInterval($past);
$translator = $interval->getLocalTranslator();
$this->assertEquals('zh', unserialize(serialize($translator))->getLocale());
}
public function testUnserializeV2Object()
{
$interval = unserialize(<<<'EOS'
O:21:"Carbon\CarbonInterval":22:{s:1:"y";i:0;s:1:"m";i:2;s:1:"d";i:0;s:1:"h";i:0;s:1:"i";i:0;s:1:"s";i:0;s:1:"f";d:5.4E-5;s:6:"invert";i:0;s:4:"days";b:0;s:11:"from_string";b:0;s:9:" * tzName";N;s:7:" * step";N;s:22:" * localMonthsOverflow";N;s:21:" * localYearsOverflow";N;s:25:" * localStrictModeEnabled";N;s:24:" * localHumanDiffOptions";N;s:22:" * localToStringFormat";N;s:18:" * localSerializer";N;s:14:" * localMacros";N;s:21:" * localGenericMacros";N;s:22:" * localFormatFunction";N;s:18:" * localTranslator";N;}
EOS);
$this->assertCarbonInterval($interval, 0, 2, 0, 0, 0, 0, 54);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPStan/FeaturesTest.php | tests/PHPStan/FeaturesTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\PHPStan;
use PHPUnit\Framework\Attributes\Large;
use RuntimeException;
use Tests\AbstractTestCase;
#[Large]
class FeaturesTest extends AbstractTestCase
{
/**
* @SuppressWarnings(LongVariable)
*/
protected string $phpStanPreviousDirectory = '.';
protected function setUp(): void
{
parent::setUp();
$this->phpStanPreviousDirectory = getcwd();
chdir(__DIR__.'/../..');
}
protected function tearDown(): void
{
chdir($this->phpStanPreviousDirectory);
parent::tearDown();
}
public function testAnalysesWithoutErrors(): void
{
$this->assertStringContainsString(
'[OK] No errors',
$this->analyze(__DIR__.'/project.neon'),
);
}
public function testAnalysesWithAnError(): void
{
$this->assertStringContainsString(
'22 Static call to instance method Carbon\Carbon::foo().',
$this->analyze(__DIR__.'/bad-project.neon'),
);
}
private function analyze(string $file): string
{
$output = shell_exec(implode(' ', [
implode(DIRECTORY_SEPARATOR, ['.', 'vendor', 'bin', 'phpstan']),
'analyse',
'--configuration='.escapeshellarg(realpath($file)),
'--no-progress',
'--no-interaction',
'--level=0',
escapeshellarg(realpath(__DIR__.'/Fixture.php')),
]));
if (!\is_string($output)) {
throw new RuntimeException('Executing phpstan returned '.var_export($output, true));
}
return $output;
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPStan/bootstrap-non-static.php | tests/PHPStan/bootstrap-non-static.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Carbon\Carbon;
Carbon::macro('foo', function ($someArg): string {
return 'foo';
});
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPStan/MixinClass.php | tests/PHPStan/MixinClass.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\PHPStan;
class MixinClass
{
// Declaring final won't apply for macro, sub-class will always be able to override macros.
final public static function foo(): string
{
return 'foo';
}
public static function bar(): string
{
return 'bar';
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPStan/MacroExtensionTest.php | tests/PHPStan/MacroExtensionTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\PHPStan;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterval;
use Carbon\PHPStan\MacroExtension;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Testing\PHPStanTestCase;
use PHPStan\Type\ClosureTypeFactory;
use PHPStan\Type\VerbosityLevel;
use PHPUnit\Framework\Attributes\RequiresPhp;
/**
* PHPStan is calling deprecated ->setAccessible() method, they already fixed it,
* but did not release a new version with the fix.
*
* Disabling this test for PHP 8.5 until the patch is out.
*/
#[RequiresPhp('< 8.5')]
class MacroExtensionTest extends PHPStanTestCase
{
private ReflectionProvider $reflectionProvider;
private MacroExtension $extension;
protected function setUp(): void
{
parent::setUp();
$this->reflectionProvider = $this->createReflectionProvider();
$this->extension = new MacroExtension(
$this->reflectionProvider,
self::getContainer()->getByType(ClosureTypeFactory::class)
);
}
public function testHasMacro()
{
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$this->assertFalse($this->extension->hasMethod($carbon, 'foo'));
Carbon::macro('foo', function ($someArg) {
});
$carbonInterval = $this->reflectionProvider->getClass(CarbonInterval::class);
$this->assertTrue($this->extension->hasMethod($carbon, 'foo'));
$this->assertFalse($this->extension->hasMethod($carbonInterval, 'foo'));
$this->assertFalse($this->extension->hasMethod($carbonInterval, 'foo'));
}
public function testGetMacro()
{
Carbon::macro('foo', function (): CarbonInterval {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'foo');
$variant = $method->getVariants()[0];
$this->assertSame(
CarbonInterval::class,
$variant->getReturnType()->describe(VerbosityLevel::typeOnly()),
);
}
public function testIsStatic()
{
Carbon::macro('calendarBerlin', static function (): string {
return self::this()->tz('Europe/Berlin')->calendar();
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'calendarBerlin');
$this->assertTrue($method->isStatic());
Carbon::macro('calendarBerlinNonStatic', function (): string {
return $this->tz('Europe/Berlin')->calendar();
});
$method = $this->extension->getMethod($carbon, 'calendarBerlinNonStatic');
$this->assertFalse($method->isStatic());
}
public function testGetDeclaringClass()
{
Carbon::macro('lower', 'strtolower');
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'lower');
$this->assertSame(Carbon::class, $method->getDeclaringClass()->getName());
CarbonImmutable::macro('lowerImmutable', 'strtolower');
$carbonImmutable = $this->reflectionProvider->getClass(CarbonImmutable::class);
$method = $this->extension->getMethod($carbonImmutable, 'lowerImmutable');
$this->assertSame(CarbonImmutable::class, $method->getDeclaringClass()->getName());
}
public function testIsPrivate()
{
Carbon::macro('lowerVisibility', 'strtolower');
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'lowerVisibility');
$this->assertFalse($method->isPrivate());
}
public function testIsPublic()
{
Carbon::macro('lowerVisibility', 'strtolower');
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'lowerVisibility');
$this->assertTrue($method->isPublic());
}
public function testIsFinal()
{
$mixinClass = new class() {
// Declaring final won't apply for macro, sub-class will always be able to override macros.
final public static function foo(): string
{
return 'foo';
}
public static function bar(): string
{
return 'bar';
}
};
$carbon = $this->reflectionProvider->getClass(Carbon::class);
Carbon::macro('foo', [$mixinClass, 'foo']);
$method = $this->extension->getMethod($carbon, 'foo');
$this->assertTrue($method->isFinal()->yes());
Carbon::macro('bar', [$mixinClass, 'bar']);
$method = $this->extension->getMethod($carbon, 'bar');
$this->assertTrue($method->isFinal()->no());
}
public function testIsInternal()
{
Carbon::macro('lowerVisibility', 'strtolower');
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'lowerVisibility');
$this->assertFalse($method->isInternal()->yes());
}
public function testGetDocComment()
{
Carbon::macro(
'closureWithDocComment',
/**
* Foo.
*/
function () {
return 'foo';
},
);
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'closureWithDocComment');
$this->assertSame(
"/**\n* Foo.\n*/",
preg_replace('/^[\t ]+/m', '', $method->getDocComment()),
);
}
public function testGetName()
{
Carbon::macro('lowerVisibility', 'strtolower');
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'lowerVisibility');
$this->assertSame('lowerVisibility', $method->getName());
}
public function testGetParameters()
{
Carbon::macro('noParameters', function () {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'noParameters');
$variant = $method->getVariants()[0];
$this->assertSame([], $variant->getParameters());
Carbon::macro('twoParameters', function (string $a, $b = 9) {
});
$method = $this->extension->getMethod($carbon, 'twoParameters');
$variant = $method->getVariants()[0];
$parameters = $variant->getParameters();
$this->assertCount(2, $parameters);
$this->assertSame('a', $parameters[0]->getName());
$this->assertNull($parameters[0]->getDefaultValue());
$this->assertSame('string', $parameters[0]->getType()->describe(VerbosityLevel::typeOnly()));
$this->assertSame('b', $parameters[1]->getName());
$this->assertNotNull($parameters[1]->getDefaultValue());
$this->assertSame('9', $parameters[1]->getDefaultValue()->describe(VerbosityLevel::value()));
$this->assertSame('mixed', $parameters[1]->getType()->describe(VerbosityLevel::typeOnly()));
}
public function testGetReturnType()
{
Carbon::macro('noReturnType', function () {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'noReturnType');
$variant = $method->getVariants()[0];
$this->assertSame('mixed', $variant->getReturnType()->describe(VerbosityLevel::typeOnly()));
Carbon::macro('carbonReturnType', function (): Carbon {
});
$method = $this->extension->getMethod($carbon, 'carbonReturnType');
$variant = $method->getVariants()[0];
$this->assertSame(Carbon::class, $variant->getReturnType()->describe(VerbosityLevel::typeOnly()));
}
public function testIsDeprecated()
{
Carbon::macro(
'deprecated',
/**
* @deprecated since 3.0.0
*/
function () {
},
);
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'deprecated');
$this->assertTrue($method->isDeprecated()->yes());
$this->assertNull($method->getDeprecatedDescription());
Carbon::macro(
'discouraged',
/**
* @discouraged since 3.0.0
*/
function () {
},
);
$method = $this->extension->getMethod($carbon, 'discouraged');
$this->assertFalse($method->isDeprecated()->yes());
$this->assertNull($method->getDeprecatedDescription());
}
public function testIsVariadic()
{
Carbon::macro('variadic', function (...$params) {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'variadic');
$variant = $method->getVariants()[0];
$this->assertTrue($variant->isVariadic());
Carbon::macro('notVariadic', function ($params) {
});
$method = $this->extension->getMethod($carbon, 'notVariadic');
$variant = $method->getVariants()[0];
$this->assertFalse($variant->isVariadic());
}
public function testGetPrototype()
{
Carbon::macro('prototype', function () {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'prototype');
$this->assertSame($method, $method->getPrototype());
}
public function testGetThrowType()
{
Carbon::macro('throwType', function () {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'throwType');
$this->assertNull($method->getThrowType());
}
public function testHasSideEffects()
{
Carbon::macro('hasSideEffects', function () {
});
$carbon = $this->reflectionProvider->getClass(Carbon::class);
$method = $this->extension->getMethod($carbon, 'hasSideEffects');
$this->assertTrue($method->hasSideEffects()->maybe());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPStan/bootstrap.php | tests/PHPStan/bootstrap.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Carbon\Carbon;
Carbon::macro('foo', static function ($someArg): string {
return 'foo';
});
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPStan/Fixture.php | tests/PHPStan/Fixture.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\PHPStan;
use Carbon\Carbon;
class Fixture
{
public function testCarbonMacroCalledStatically(): string
{
return Carbon::foo(15);
}
public function testCarbonMacroCalledDynamically(): string
{
return Carbon::now()->foo(42);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Cli/InvokerTest.php | tests/Cli/InvokerTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Cli;
use Carbon\Cli;
use Carbon\Cli\Invoker;
use Tests\AbstractTestCase;
class InvokerTest extends AbstractTestCase
{
public function testInvoke()
{
$invoker = new Invoker();
$lastCommand = null;
$exec = function ($command) use (&$lastCommand) {
$lastCommand = $command;
};
ob_start();
$return = $invoker('file', 'install', $exec);
$contents = ob_get_contents();
ob_end_clean();
$this->assertSame('composer require carbon-cli/carbon-cli --no-interaction', $lastCommand);
$this->assertSame('Installation succeeded.', $contents);
$this->assertTrue($return);
include_once __DIR__.'/Cli.php';
$invoker = new Invoker();
$lastCommand = null;
ob_start();
$return = $invoker('file', 'install', $exec);
$contents = ob_get_contents();
ob_end_clean();
$this->assertNull($lastCommand);
$this->assertSame('', $contents);
$this->assertTrue($return);
$this->assertSame(['file', 'install', $exec], Cli::$lastParameters);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Cli/Cli.php | tests/Cli/Cli.php | <?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon;
class Cli
{
public static $lastParameters = [];
public function __invoke(...$parameters)
{
static::$lastParameters = $parameters;
return true;
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/Translator.php | tests/Laravel/Translator.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Illuminate\Translation;
class Translator extends \Symfony\Component\Translation\Translator
{
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/App.php | tests/Laravel/App.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Laravel;
use ArrayAccess;
use Symfony\Component\Translation\Translator;
class App implements ArrayAccess
{
/**
* @var string
*/
protected $locale = 'en';
/**
* @var string
*/
protected $fallbackLocale = 'en';
/**
* @var string
*/
protected static $version;
/**
* @var Translator
*/
public $translator;
/**
* @var \Illuminate\Events\EventDispatcher
*/
public $events;
public function register()
{
include_once __DIR__.'/EventDispatcher.php';
$this->locale = 'de';
$this->fallbackLocale = 'fr';
$this->translator = new Translator($this->locale);
}
public function setEventDispatcher($dispatcher)
{
$this->events = $dispatcher;
}
public static function version($version = null)
{
if ($version !== null) {
static::$version = $version;
}
return static::$version;
}
public static function getLocaleChangeEventName()
{
return version_compare((string) static::version(), '5.5') >= 0
? 'Illuminate\Foundation\Events\LocaleUpdated'
: 'locale.changed';
}
public function setLocaleWithoutEvent(string $locale)
{
$this->locale = $locale;
$this->translator->setLocale($locale);
}
public function setLocale(string $locale)
{
$this->setLocaleWithoutEvent($locale);
$this->events->dispatch(static::getLocaleChangeEventName());
}
public function setFallbackLocale(string $fallbackLocale)
{
$this->fallbackLocale = $fallbackLocale;
}
public function getLocale()
{
return $this->locale;
}
public function getFallbackLocale()
{
return $this->fallbackLocale;
}
public function bound($service)
{
return isset($this->{$service});
}
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->$offset);
}
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->$offset;
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
// noop
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
// noop
}
public function removeService($offset)
{
$this->$offset = null;
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/Dispatcher.php | tests/Laravel/Dispatcher.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Illuminate\Events;
use Tests\Laravel\EventDispatcherBase;
class Dispatcher extends EventDispatcherBase
{
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/EventDispatcher.php | tests/Laravel/EventDispatcher.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Illuminate\Events;
use Tests\Laravel\EventDispatcherBase;
class EventDispatcher extends EventDispatcherBase
{
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/ServiceProvider.php | tests/Laravel/ServiceProvider.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Illuminate\Support;
use Illuminate\Events\EventDispatcher;
use Tests\Laravel\App;
class ServiceProvider
{
/**
* @var App
*/
public $app;
public function __construct($dispatcher = null)
{
$this->app = new App();
$this->app->setEventDispatcher($dispatcher ?: new EventDispatcher());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/ServiceProviderTest.php | tests/Laravel/ServiceProviderTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Laravel;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;
use Carbon\Laravel\ServiceProvider;
use Generator;
use Illuminate\Events\Dispatcher;
use Illuminate\Events\EventDispatcher;
use Illuminate\Support\Carbon as SupportCarbon;
use Illuminate\Support\Facades\Date;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use stdClass;
class ServiceProviderTest extends TestCase
{
public static function dataForDispatchers(): Generator
{
if (!class_exists(Dispatcher::class)) {
include_once __DIR__.'/Dispatcher.php';
}
if (!class_exists(EventDispatcher::class)) {
include_once __DIR__.'/EventDispatcher.php';
}
yield [new Dispatcher()];
yield [new EventDispatcher()];
}
#[DataProvider('dataForDispatchers')]
public function testBoot(EventDispatcherBase $dispatcher)
{
// Reset language
Carbon::setLocale('en');
CarbonImmutable::setLocale('en');
CarbonPeriod::setLocale('en');
CarbonInterval::setLocale('en');
Carbon::setFallbackLocale('en');
CarbonImmutable::setFallbackLocale('en');
CarbonPeriod::setFallbackLocale('en');
CarbonInterval::setFallbackLocale('en');
$service = new ServiceProvider($dispatcher);
$this->assertSame('en', Carbon::getLocale());
$this->assertSame('en', CarbonImmutable::getLocale());
$this->assertSame('en', CarbonPeriod::getLocale());
$this->assertSame('en', CarbonInterval::getLocale());
$this->assertSame('en', Carbon::getFallbackLocale());
$this->assertSame('en', CarbonImmutable::getFallbackLocale());
$this->assertSame('en', CarbonPeriod::getFallbackLocale());
$this->assertSame('en', CarbonInterval::getFallbackLocale());
$service->boot();
$this->assertSame('en', Carbon::getLocale());
$this->assertSame('en', CarbonImmutable::getLocale());
$this->assertSame('en', CarbonPeriod::getLocale());
$this->assertSame('en', CarbonInterval::getLocale());
$this->assertSame('en', Carbon::getFallbackLocale());
$this->assertSame('en', CarbonImmutable::getFallbackLocale());
$this->assertSame('en', CarbonPeriod::getFallbackLocale());
$this->assertSame('en', CarbonInterval::getFallbackLocale());
$service->app->register();
$service->boot();
$this->assertSame('de', Carbon::getLocale());
$this->assertSame('de', CarbonImmutable::getLocale());
$this->assertSame('de', CarbonPeriod::getLocale());
$this->assertSame('de', CarbonInterval::getLocale());
$this->assertSame('fr', Carbon::getFallbackLocale());
$this->assertSame('fr', CarbonImmutable::getFallbackLocale());
$this->assertSame('fr', CarbonPeriod::getFallbackLocale());
$this->assertSame('fr', CarbonInterval::getFallbackLocale());
$service->app->setLocale('fr');
$this->assertSame('fr', Carbon::getLocale());
$this->assertSame('fr', CarbonImmutable::getLocale());
$this->assertSame('fr', CarbonPeriod::getLocale());
$this->assertSame('fr', CarbonInterval::getLocale());
$this->assertNull($service->register());
// Reset language
Carbon::setLocale('en');
Carbon::setFallbackLocale('en');
$service->app->removeService('events');
$this->assertNull($service->boot());
}
public function testListenerWithoutLocaleUpdatedClass()
{
if (class_exists('Illuminate\Foundation\Events\LocaleUpdated')) {
$this->markTestSkipped('This test cannot be run with Laravel 5.5 classes available via autoload.');
}
$dispatcher = new Dispatcher();
$service = new ServiceProvider($dispatcher);
Carbon::setLocale('en');
CarbonImmutable::setLocale('en');
CarbonPeriod::setLocale('en');
CarbonInterval::setLocale('en');
Carbon::setFallbackLocale('en');
CarbonImmutable::setFallbackLocale('en');
CarbonPeriod::setFallbackLocale('en');
CarbonInterval::setFallbackLocale('en');
$service->boot();
$service->app->register();
$service->app->setLocaleWithoutEvent('fr');
$service->app->setFallbackLocale('it');
$dispatcher->dispatch('locale.changed');
$this->assertSame('fr', Carbon::getLocale());
$this->assertSame('fr', CarbonImmutable::getLocale());
$this->assertSame('fr', CarbonPeriod::getLocale());
$this->assertSame('fr', CarbonInterval::getLocale());
$this->assertSame('en', Carbon::getFallbackLocale());
$this->assertSame('en', CarbonImmutable::getFallbackLocale());
$this->assertSame('en', CarbonPeriod::getFallbackLocale());
$this->assertSame('en', CarbonInterval::getFallbackLocale());
}
public function testListenerWithLocaleUpdatedClass()
{
if (!class_exists('Illuminate\Foundation\Events\LocaleUpdated')) {
eval('namespace Illuminate\Foundation\Events; class LocaleUpdated {}');
}
$dispatcher = new Dispatcher();
$service = new ServiceProvider($dispatcher);
Carbon::setLocale('en');
CarbonImmutable::setLocale('en');
CarbonPeriod::setLocale('en');
CarbonInterval::setLocale('en');
Carbon::setFallbackLocale('en');
CarbonImmutable::setFallbackLocale('en');
CarbonPeriod::setFallbackLocale('en');
CarbonInterval::setFallbackLocale('en');
$service->boot();
$service->app->register();
$service->app->setLocaleWithoutEvent('fr');
$service->app->setFallbackLocale('it');
$app = new App();
$app->register();
$app->setLocaleWithoutEvent('de_DE');
$app->setFallbackLocale('es_ES');
$dispatcher->dispatch('Illuminate\Foundation\Events\LocaleUpdated');
$this->assertSame('fr', Carbon::getLocale());
$this->assertSame('fr', CarbonImmutable::getLocale());
$this->assertSame('fr', CarbonPeriod::getLocale());
$this->assertSame('fr', CarbonInterval::getLocale());
$this->assertSame('en', Carbon::getFallbackLocale());
$this->assertSame('en', CarbonImmutable::getFallbackLocale());
$this->assertSame('en', CarbonPeriod::getFallbackLocale());
$this->assertSame('en', CarbonInterval::getFallbackLocale());
$service->setAppGetter(static fn () => $app);
$this->assertSame('fr', Carbon::getLocale());
$service->updateLocale();
$this->assertSame('de_DE', Carbon::getLocale());
$service->setLocaleGetter(static fn () => 'ckb');
$this->assertSame('de_DE', Carbon::getLocale());
$service->updateLocale();
$this->assertSame('ckb', Carbon::getLocale());
$service->setLocaleGetter(null);
$service->setAppGetter(static fn () => null);
$service->updateLocale();
$this->assertSame('ckb', Carbon::getLocale());
$service->setAppGetter(static fn () => $app);
$this->assertSame('en', Carbon::getFallbackLocale());
$service->updateFallbackLocale();
$this->assertSame('es_ES', Carbon::getFallbackLocale());
$service->setFallbackLocaleGetter(static fn () => 'ckb');
$this->assertSame('es_ES', Carbon::getFallbackLocale());
$service->updateFallbackLocale();
$this->assertSame('ckb', Carbon::getFallbackLocale());
$service->setFallbackLocaleGetter(null);
$service->setAppGetter(static fn () => null);
$service->updateFallbackLocale();
$this->assertSame('ckb', Carbon::getFallbackLocale());
}
public function testUpdateLocale()
{
if (class_exists('Illuminate\Support\Carbon')) {
$this->markTestSkipped('This test cannot be run with Laravel 5.5 classes available via autoload.');
}
eval('
namespace Illuminate\Support;
class Carbon
{
public static $locale;
public static $fallbackLocale;
public static function setLocale($locale)
{
static::$locale = $locale;
}
public static function setFallbackLocale($locale)
{
static::$fallbackLocale = $locale;
}
}
');
eval('
namespace Illuminate\Support\Facades;
use Exception;
class Date
{
public static $locale;
public static $fallbackLocale;
public static function getFacadeRoot()
{
return new static();
}
public function setLocale($locale)
{
static::$locale = $locale;
if ($locale === "fr") {
throw new Exception("stop");
}
}
public function setFallbackLocale($locale)
{
static::$fallbackLocale = $locale;
if ($locale === "es") {
throw new Exception("stop");
}
}
}
');
$dispatcher = new Dispatcher();
$service = new ServiceProvider($dispatcher);
$service->boot();
$service->app->register();
$this->assertSame('en', SupportCarbon::$locale);
$this->assertSame('en', Date::$locale);
$this->assertSame('en', SupportCarbon::$fallbackLocale);
$this->assertSame('en', Date::$fallbackLocale);
$service->updateLocale();
$this->assertSame('de', SupportCarbon::$locale);
$this->assertSame('de', Date::$locale);
$this->assertSame('en', SupportCarbon::$fallbackLocale);
$this->assertSame('en', Date::$fallbackLocale);
$service->updateFallbackLocale();
$this->assertSame('de', SupportCarbon::$locale);
$this->assertSame('de', Date::$locale);
$this->assertSame('fr', SupportCarbon::$fallbackLocale);
$this->assertSame('fr', Date::$fallbackLocale);
$service->app->setLocale('fr');
$service->app->setFallbackLocale('gl');
$service->updateLocale();
$this->assertSame('fr', SupportCarbon::$locale);
$this->assertSame('fr', Date::$locale);
$this->assertSame('fr', SupportCarbon::$fallbackLocale);
$this->assertSame('fr', Date::$fallbackLocale);
$service->updateFallbackLocale();
$this->assertSame('gl', SupportCarbon::$fallbackLocale);
$this->assertSame('gl', Date::$fallbackLocale);
eval('
use Illuminate\Events\Dispatcher;
use Tests\Laravel\App;
function app($id)
{
$app = new App();
$app->setEventDispatcher(new Dispatcher());
$app->register();
$app->setLocale("it");
return $app;
}
');
$service->app = new stdClass();
$service->updateLocale();
$this->assertSame('it', SupportCarbon::$locale);
$this->assertSame('it', Date::$locale);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Laravel/EventDispatcherBase.php | tests/Laravel/EventDispatcherBase.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Laravel;
class EventDispatcherBase
{
/**
* @var array
*/
protected $listeners;
public function listen($name, $listener)
{
$this->listeners[$name] ??= [];
$this->listeners[$name][] = $listener;
}
public function dispatch($name, $event = null)
{
foreach (($this->listeners[$name] ?? []) as $listener) {
$listener($event);
}
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Factory/WrapperClockTest.php | tests/Factory/WrapperClockTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Factory;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\Factory;
use Carbon\FactoryImmutable;
use Carbon\WrapperClock;
use DateTime;
use DateTimeImmutable;
use DateTimeZone;
use Psr\Clock\ClockInterface;
use RuntimeException;
use Tests\AbstractTestCase;
class WrapperClockTest extends AbstractTestCase
{
public function testWrapperClock(): void
{
$now = new DateTimeImmutable('now UTC');
$clock = new WrapperClock($now);
$this->assertSame($now, $clock->now());
$this->assertSame($now, $clock->unwrap());
$carbon = $clock->getFactory()->now();
$this->assertSame(CarbonImmutable::class, $carbon::class);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $carbon->format('Y-m-d H:i:s.u e'));
$carbon = $clock->nowAs(Carbon::class, 'Europe/Berlin');
$this->assertSame(Carbon::class, $carbon::class);
$this->assertSame(
$now->setTimezone(new DateTimeZone('Europe/Berlin'))->format('Y-m-d H:i:s.u e'),
$carbon->format('Y-m-d H:i:s.u e'),
);
$carbon = $clock->nowAsCarbon();
$this->assertSame(CarbonImmutable::class, $carbon::class);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $carbon->format('Y-m-d H:i:s.u e'));
$clock = new WrapperClock($carbon);
$this->assertSame($clock->nowAsCarbon(), $carbon);
}
public function testWrapperClockMutable(): void
{
$now = new DateTime('now UTC');
$clock = new WrapperClock($now);
$result = $clock->now();
$unwrapped = $clock->unwrap();
$this->assertNotSame($now, $result);
$this->assertSame($now, $unwrapped);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $result->format('Y-m-d H:i:s.u e'));
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $unwrapped->format('Y-m-d H:i:s.u e'));
$carbon = $clock->getFactory()->now();
$this->assertSame(Carbon::class, $carbon::class);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $carbon->format('Y-m-d H:i:s.u e'));
}
public function testWrapperClockPsrLink(): void
{
$now = new DateTimeImmutable('now UTC');
$psrClock = new class($now) implements ClockInterface {
public function __construct(private readonly DateTimeImmutable $currentTime)
{
}
public function now(): DateTimeImmutable
{
return $this->currentTime;
}
};
$clock = new WrapperClock($psrClock);
$result = $clock->now();
$unwrapped = $clock->unwrap();
$unwrappedNow = $unwrapped->now();
$this->assertSame($now, $result);
$this->assertSame($psrClock, $unwrapped);
$this->assertSame($now, $unwrappedNow);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $result->format('Y-m-d H:i:s.u e'));
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $unwrappedNow->format('Y-m-d H:i:s.u e'));
$carbon = $clock->getFactory()->now();
$this->assertSame(CarbonImmutable::class, $carbon::class);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $carbon->format('Y-m-d H:i:s.u e'));
}
public function testSleep(): void
{
$factory = new FactoryImmutable();
$factory->setTestNowAndTimezone(new DateTimeImmutable('2024-01-18 00:00 UTC'));
$clock = new WrapperClock($factory);
$clock->sleep(2.5);
$carbon = $clock->now();
$this->assertSame(CarbonImmutable::class, $carbon::class);
$this->assertSame('2024-01-18 00:00:02.500000 UTC', $carbon->format('Y-m-d H:i:s.u e'));
$present = new DateTimeImmutable('2024-01-18 00:00 UTC');
$clock = new WrapperClock($present);
$clock->sleep(2.5);
$now = $clock->now();
$this->assertSame(DateTimeImmutable::class, $now::class);
$this->assertSame('2024-01-18 00:00:02.500000 UTC', $now->format('Y-m-d H:i:s.u e'));
$future = new DateTimeImmutable('2224-01-18 00:00 UTC');
$seconds = $future->getTimestamp() - $present->getTimestamp() + 0.000_001;
$clock->sleep($seconds);
$now = $clock->now();
$this->assertSame('2224-01-18 00:00:02.500001 UTC', $now->format('Y-m-d H:i:s.u e'));
$present = new DateTime('2024-01-18 00:00 UTC');
$clock = new WrapperClock($present);
$clock->sleep(2.5);
$now = $clock->now();
$this->assertSame(CarbonImmutable::class, $now::class);
$this->assertSame('2024-01-18 00:00:02.500000 UTC', $now->format('Y-m-d H:i:s.u e'));
$this->assertSame('2024-01-18 00:00:00.000000 UTC', $present->format('Y-m-d H:i:s.u e'));
$clock->sleep(0);
$clock->sleep(0.0);
$now = $clock->now();
$this->assertSame('2024-01-18 00:00:02.500000 UTC', $now->format('Y-m-d H:i:s.u e'));
$clock = new WrapperClock(new class() implements ClockInterface {
public function now(): DateTimeImmutable
{
return new DateTimeImmutable('2024-01-18 00:00 UTC');
}
});
$clock->sleep(2.5);
$now = $clock->now();
$this->assertSame(DateTimeImmutable::class, $now::class);
$this->assertSame('2024-01-18 00:00:02.500000 UTC', $now->format('Y-m-d H:i:s.u e'));
}
public function testSleepNegative(): void
{
$this->expectExceptionObject(new RuntimeException(
'Expected positive number of seconds, -1.0E-6 given',
));
$present = new DateTimeImmutable('2024-01-18 00:00 UTC');
$clock = new WrapperClock($present);
$clock->sleep(-0.000_001);
}
public function testWithTimezoneOnFactory(): void
{
$factory = new FactoryImmutable();
$factory->setTestNowAndTimezone(new DateTimeImmutable('2024-01-18 00:00 UTC'));
$clock = new WrapperClock($factory);
$clock->sleep(2.5);
$carbon = $clock->now();
$this->assertSame(CarbonImmutable::class, $carbon::class);
$this->assertSame('2024-01-18 00:00:02.500000 UTC', $carbon->format('Y-m-d H:i:s.u e'));
}
public function testWithTimezone(): void
{
$factory = new FactoryImmutable();
$factory->setTestNowAndTimezone(new DateTimeImmutable('2024-01-18 00:00 UTC'));
$clock = new WrapperClock($factory);
$now = $clock->withTimeZone('Pacific/Auckland')->now();
$this->assertSame(CarbonImmutable::class, $now::class);
$this->assertSame(
'2024-01-18 13:00:00.000000 Pacific/Auckland',
$now->format('Y-m-d H:i:s.u e'),
);
$factory = new Factory();
$factory->setTestNowAndTimezone(Carbon::parse('2024-01-18 00:00 UTC'));
$clock = new WrapperClock($factory);
$now = $clock->withTimeZone('Pacific/Auckland')->now();
$this->assertSame(CarbonImmutable::class, $now::class);
$this->assertSame(
'2024-01-18 13:00:00.000000 Pacific/Auckland',
$now->format('Y-m-d H:i:s.u e'),
);
$clock = new WrapperClock(new DateTimeImmutable('2024-01-18 00:00 UTC'));
$now = $clock->withTimeZone('Pacific/Auckland')->now();
$this->assertSame(DateTimeImmutable::class, $now::class);
$this->assertSame(
'2024-01-18 13:00:00.000000 Pacific/Auckland',
$now->format('Y-m-d H:i:s.u e'),
);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Factory/FactoryTest.php | tests/Factory/FactoryTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Factory;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Carbon\Factory;
use Carbon\FactoryImmutable;
use DateTimeImmutable;
use Psr\Clock\ClockInterface;
use ReflectionFunction;
use RuntimeException;
use Tests\AbstractTestCase;
use Tests\Carbon\Fixtures\MyCarbon;
class FactoryTest extends AbstractTestCase
{
public function testFactory()
{
$factory = new Factory();
$this->assertInstanceOf(Carbon::class, $factory->parse('2018-01-01'));
$this->assertSame('01/01/2018', $factory->parse('2018-01-01')->format('d/m/Y'));
$factory = new Factory([
'locale' => 'fr',
]);
$this->assertSame('fr', $factory->parse('2018-01-01')->locale);
$factory = new Factory([
'locale' => 'fr',
], MyCarbon::class);
$this->assertInstanceOf(MyCarbon::class, $factory->parse('2018-01-01'));
$this->assertSame('01/01/2018', $factory->parse('2018-01-01')->format('d/m/Y'));
$factory = new FactoryImmutable([
'locale' => 'fr',
]);
$this->assertInstanceOf(CarbonImmutable::class, $factory->parse('2018-01-01'));
$this->assertSame('01/01/2018', $factory->parse('2018-01-01')->format('d/m/Y'));
}
public function testFactoryModification()
{
$factory = new Factory();
$this->assertSame(Carbon::class, $factory->className());
$this->assertSame($factory, $factory->className(MyCarbon::class));
$this->assertSame(MyCarbon::class, $factory->className());
$this->assertSame([], $factory->settings());
$this->assertSame($factory, $factory->settings([
'locale' => 'fr',
]));
$this->assertSame([
'locale' => 'fr',
], $factory->settings());
$this->assertSame($factory, $factory->mergeSettings([
'timezone' => 'Europe/Paris',
]));
$this->assertSame([
'locale' => 'fr',
'timezone' => 'Europe/Paris',
], $factory->settings());
$this->assertSame($factory, $factory->settings([
'timezone' => 'Europe/Paris',
]));
$this->assertSame([
'timezone' => 'Europe/Paris',
], $factory->settings());
}
public function testFactoryTimezone()
{
Carbon::setTestNowAndTimezone(Carbon::parse('2020-09-04 03:39:04.123456', 'UTC'));
$factory = new Factory();
$date = $factory->now();
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame('2020-09-04 03:39:04.123456 UTC', $date->format('Y-m-d H:i:s.u e'));
$factory = new Factory([
'timezone' => 'Europe/Paris',
]);
$this->assertSame('2020-09-04 05:39:04.123456 Europe/Paris', $factory->now()->format('Y-m-d H:i:s.u e'));
$this->assertSame('2020-09-04 00:00:00.000000 Europe/Paris', $factory->today()->format('Y-m-d H:i:s.u e'));
$this->assertSame('2020-09-05 00:00:00.000000 Europe/Paris', $factory->tomorrow()->format('Y-m-d H:i:s.u e'));
$this->assertSame('2020-09-04 09:39:04.123456 Europe/Paris', $factory->parse('2020-09-04 09:39:04.123456')->format('Y-m-d H:i:s.u e'));
$factory = new Factory([
'timezone' => 'America/Toronto',
]);
$this->assertSame('2020-09-03 23:39:04.123456 America/Toronto', $factory->now()->format('Y-m-d H:i:s.u e'));
$this->assertSame('2020-09-03 00:00:00.000000 America/Toronto', $factory->today()->format('Y-m-d H:i:s.u e'));
$this->assertSame('2020-09-04 00:00:00.000000 America/Toronto', $factory->tomorrow()->format('Y-m-d H:i:s.u e'));
$this->assertSame('2020-09-04 09:39:04.123456 America/Toronto', $factory->parse('2020-09-04 09:39:04.123456')->format('Y-m-d H:i:s.u e'));
$factory = new Factory([
'timezone' => 'Asia/Shanghai',
]);
$baseDate = Carbon::parse('2021-08-01 08:00:00', 'UTC');
$date = $factory->createFromTimestamp($baseDate->getTimestamp());
$this->assertSame('2021-08-01T16:00:00+08:00', $date->format('c'));
$date = $factory->make('2021-08-01 08:00:00');
$this->assertSame('2021-08-01T08:00:00+08:00', $date->format('c'));
$date = $factory->make($baseDate);
$this->assertSame('2021-08-01T16:00:00+08:00', $date->format('c'));
$date = $factory->create($baseDate);
$this->assertSame('2021-08-01T16:00:00+08:00', $date->format('c'));
$date = $factory->parse($baseDate);
$this->assertSame('2021-08-01T16:00:00+08:00', $date->format('c'));
$date = $factory->instance($baseDate);
$this->assertSame('2021-08-01T16:00:00+08:00', $date->format('c'));
$date = $factory->make('2021-08-01 08:00:00+00:20');
$this->assertSame('2021-08-01T08:00:00+00:20', $date->format('c'));
$date = $factory->parse('2021-08-01T08:00:00Z');
$this->assertSame('2021-08-01T08:00:00+00:00', $date->format('c'));
$date = $factory->create('2021-08-01 08:00:00 UTC');
$this->assertSame('2021-08-01T08:00:00+00:00', $date->format('c'));
$date = $factory->make('2021-08-01 08:00:00 Europe/Paris');
$this->assertSame('2021-08-01T08:00:00+02:00', $date->format('c'));
}
public function testPsrClock()
{
FactoryImmutable::setCurrentClock(null);
FactoryImmutable::getDefaultInstance()->setTestNow(null);
$initial = Carbon::now('UTC');
$factory = new FactoryImmutable();
$factory->setTestNow($initial);
$this->assertInstanceOf(ClockInterface::class, $factory);
$this->assertInstanceOf(DateTimeImmutable::class, $factory->now());
$this->assertInstanceOf(CarbonImmutable::class, $factory->now());
$this->assertSame('America/Toronto', $factory->now()->tzName);
$this->assertSame('UTC', $factory->now('UTC')->tzName);
$timezonedFactory = $factory->withTimeZone('Asia/Tokyo');
$this->assertInstanceOf(CarbonImmutable::class, $timezonedFactory->now());
$this->assertSame('Asia/Tokyo', $timezonedFactory->now()->tzName);
$this->assertSame('America/Toronto', $timezonedFactory->now('America/Toronto')->tzName);
$this->assertSame(
$initial->format('Y-m-d H:i:s.u'),
$factory->now('UTC')->format('Y-m-d H:i:s.u'),
);
$before = microtime(true);
$factory->sleep(5);
$factory->sleep(20);
$after = microtime(true);
$this->assertLessThan(0.1, $after - $before);
$this->assertSame(
$initial->copy()->addSeconds(25)->format('Y-m-d H:i:s.u'),
$factory->now('UTC')->format('Y-m-d H:i:s.u'),
);
$factory = new FactoryImmutable();
$factory->setTestNow(null);
$before = new DateTimeImmutable('now UTC');
$now = $factory->now('UTC');
$after = new DateTimeImmutable('now UTC');
$this->assertGreaterThanOrEqual($before, $now);
$this->assertLessThanOrEqual($after, $now);
$before = new DateTimeImmutable('now UTC');
$factory->sleep(0.5);
$after = new DateTimeImmutable('now UTC');
$this->assertSame(
5,
(int) round(10 * ((float) $after->format('U.u') - ((float) $before->format('U.u')))),
);
}
public function testIsolation(): void
{
CarbonImmutable::setTestNow('1990-07-31 23:59:59');
$libAFactory = new FactoryImmutable();
$libAFactory->setTestNow('2000-02-05 15:20:00');
$libBFactory = new FactoryImmutable();
$libBFactory->setTestNow('2050-12-01 00:00:00');
$this->assertSame('2000-02-05 15:20:00', (string) $libAFactory->now());
$this->assertSame('2050-12-01 00:00:00', (string) $libBFactory->now());
$this->assertSame('1990-07-31 23:59:59', (string) CarbonImmutable::now());
CarbonImmutable::setTestNow();
}
public function testClosureMock(): void
{
$factory = new Factory();
$now = Carbon::parse('2024-01-18 00:00:00');
$factory->setTestNow(static fn () => $now);
$result = $factory->now();
$this->assertNotSame($now, $result);
$this->assertSame($now->format('Y-m-d H:i:s.u e'), $result->format('Y-m-d H:i:s.u e'));
}
public function testClosureMockTypeFailure(): void
{
$factory = new Factory();
$closure = static fn () => 42;
$factory->setTestNow($closure);
$function = new ReflectionFunction($closure);
$this->expectExceptionObject(new RuntimeException(
'The test closure defined in '.$function->getFileName().
' at line '.$function->getStartLine().' returned integer'.
'; expected '.CarbonInterface::class.'|null',
));
$factory->now();
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Factory/CallbackTest.php | tests/Factory/CallbackTest.php | <?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Factory;
use Carbon\Callback;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;
use Carbon\CarbonTimeZone;
use DateInterval;
use DatePeriod;
use DateTimeImmutable;
use DateTimeZone;
use Tests\AbstractTestCase;
class CallbackTest extends AbstractTestCase
{
public function testGetReflectionFunction(): void
{
$closure = static fn () => 4;
$callback = Callback::fromClosure($closure);
$function = $callback->getReflectionFunction();
$this->assertSame($function, $callback->getReflectionFunction());
$this->assertSame($closure, $function->getClosure());
}
public function testCall(): void
{
$closure = static function (CarbonInterface $date, CarbonInterval $interval, string $text, ?CarbonTimeZone $timezone, CarbonPeriod $period): string {
return implode(', ', [$text, $date->monthName, $interval->seconds, $timezone?->getName(), $period->getRecurrences()]);
};
$callback = Callback::fromClosure($closure);
$result = $callback->call(
new DateTimeImmutable('2024-01-18'),
new DateInterval('PT1M30S'),
'foo',
new DateTimeZone('CET'),
new DatePeriod(
new DateTimeImmutable('2012-07-01T00:00:00'),
new DateInterval('P1D'),
7,
),
);
$this->assertSame('foo, January, 30, CET, 7', $result);
$result = $callback->call(
interval: new DateInterval('PT1M21S'),
date: new DateTimeImmutable('2024-02-18'),
period: new DatePeriod(
new DateTimeImmutable('2012-07-01T00:00:00'),
new DateInterval('P1D'),
4,
),
timezone: null,
text: 'bar',
);
$this->assertSame('bar, February, 21, , 4', $result);
}
public function testParameter(): void
{
$closure = static function (CarbonInterface $date, CarbonInterval $interval, string $text, ?CarbonTimeZone $timezone, CarbonPeriod $period): string {
return implode(', ', [$text, $date->monthName, $interval->seconds, $timezone?->getName(), $period->getRecurrences()]);
};
$interval = new DateInterval('P1D');
$this->assertSame($interval, Callback::parameter($closure, $interval));
$this->assertSame($interval, Callback::parameter($closure, $interval, 0));
$this->assertSame($interval, Callback::parameter($closure, $interval, 5));
$this->assertSame($interval, Callback::parameter($closure, $interval, 'diff'));
$this->assertSame($interval, Callback::parameter($closure, $interval, 'date'));
$this->assertSame($interval, Callback::parameter($interval, $interval, 1));
$this->assertSame($interval, Callback::parameter(static fn (FooBar $foo) => 42, $interval));
$result = Callback::parameter($closure, $interval, 'interval');
$this->assertSame(CarbonInterval::class, $result::class);
$this->assertSame('1 day', $result->forHumans());
$result = Callback::parameter($closure, $interval, 1);
$this->assertSame(CarbonInterval::class, $result::class);
$this->assertSame('1 day', $result->forHumans());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/EmailLexer.php | src/EmailLexer.php | <?php
namespace Egulias\EmailValidator;
use Doctrine\Common\Lexer\AbstractLexer;
use Doctrine\Common\Lexer\Token;
/** @extends AbstractLexer<int, string> */
class EmailLexer extends AbstractLexer
{
//ASCII values
public const S_EMPTY = -1;
public const C_NUL = 0;
public const S_HTAB = 9;
public const S_LF = 10;
public const S_CR = 13;
public const S_SP = 32;
public const EXCLAMATION = 33;
public const S_DQUOTE = 34;
public const NUMBER_SIGN = 35;
public const DOLLAR = 36;
public const PERCENTAGE = 37;
public const AMPERSAND = 38;
public const S_SQUOTE = 39;
public const S_OPENPARENTHESIS = 40;
public const S_CLOSEPARENTHESIS = 41;
public const ASTERISK = 42;
public const S_PLUS = 43;
public const S_COMMA = 44;
public const S_HYPHEN = 45;
public const S_DOT = 46;
public const S_SLASH = 47;
public const S_COLON = 58;
public const S_SEMICOLON = 59;
public const S_LOWERTHAN = 60;
public const S_EQUAL = 61;
public const S_GREATERTHAN = 62;
public const QUESTIONMARK = 63;
public const S_AT = 64;
public const S_OPENBRACKET = 91;
public const S_BACKSLASH = 92;
public const S_CLOSEBRACKET = 93;
public const CARET = 94;
public const S_UNDERSCORE = 95;
public const S_BACKTICK = 96;
public const S_OPENCURLYBRACES = 123;
public const S_PIPE = 124;
public const S_CLOSECURLYBRACES = 125;
public const S_TILDE = 126;
public const C_DEL = 127;
public const INVERT_QUESTIONMARK = 168;
public const INVERT_EXCLAMATION = 173;
public const GENERIC = 300;
public const S_IPV6TAG = 301;
public const INVALID = 302;
public const CRLF = 1310;
public const S_DOUBLECOLON = 5858;
public const ASCII_INVALID_FROM = 127;
public const ASCII_INVALID_TO = 199;
/**
* US-ASCII visible characters not valid for atext (@link http://tools.ietf.org/html/rfc5322#section-3.2.3)
*
* @var array<string, int>
*/
protected $charValue = [
'{' => self::S_OPENCURLYBRACES,
'}' => self::S_CLOSECURLYBRACES,
'(' => self::S_OPENPARENTHESIS,
')' => self::S_CLOSEPARENTHESIS,
'<' => self::S_LOWERTHAN,
'>' => self::S_GREATERTHAN,
'[' => self::S_OPENBRACKET,
']' => self::S_CLOSEBRACKET,
':' => self::S_COLON,
';' => self::S_SEMICOLON,
'@' => self::S_AT,
'\\' => self::S_BACKSLASH,
'/' => self::S_SLASH,
',' => self::S_COMMA,
'.' => self::S_DOT,
"'" => self::S_SQUOTE,
"`" => self::S_BACKTICK,
'"' => self::S_DQUOTE,
'-' => self::S_HYPHEN,
'::' => self::S_DOUBLECOLON,
' ' => self::S_SP,
"\t" => self::S_HTAB,
"\r" => self::S_CR,
"\n" => self::S_LF,
"\r\n" => self::CRLF,
'IPv6' => self::S_IPV6TAG,
'' => self::S_EMPTY,
'\0' => self::C_NUL,
'*' => self::ASTERISK,
'!' => self::EXCLAMATION,
'&' => self::AMPERSAND,
'^' => self::CARET,
'$' => self::DOLLAR,
'%' => self::PERCENTAGE,
'~' => self::S_TILDE,
'|' => self::S_PIPE,
'_' => self::S_UNDERSCORE,
'=' => self::S_EQUAL,
'+' => self::S_PLUS,
'¿' => self::INVERT_QUESTIONMARK,
'?' => self::QUESTIONMARK,
'#' => self::NUMBER_SIGN,
'¡' => self::INVERT_EXCLAMATION,
];
public const INVALID_CHARS_REGEX = "/[^\p{S}\p{C}\p{Cc}]+/iu";
public const VALID_UTF8_REGEX = '/\p{Cc}+/u';
public const CATCHABLE_PATTERNS = [
'[a-zA-Z]+[46]?', //ASCII and domain literal
'[^\x00-\x7F]', //UTF-8
'[0-9]+',
'\r\n',
'::',
'\s+?',
'.',
];
public const NON_CATCHABLE_PATTERNS = [
'[\xA0-\xff]+',
];
public const MODIFIERS = 'iu';
/** @var bool */
protected $hasInvalidTokens = false;
/**
* @var Token<int, string>
*/
protected Token $previous;
/**
* The last matched/seen token.
*
* @var Token<int, string>
*/
public Token $current;
/**
* @var Token<int, string>
*/
private Token $nullToken;
/** @var string */
private $accumulator = '';
/** @var bool */
private $hasToRecord = false;
public function __construct()
{
/** @var Token<int, string> $nullToken */
$nullToken = new Token('', self::S_EMPTY, 0);
$this->nullToken = $nullToken;
$this->current = $this->previous = $this->nullToken;
$this->lookahead = null;
}
public function reset(): void
{
$this->hasInvalidTokens = false;
parent::reset();
$this->current = $this->previous = $this->nullToken;
}
/**
* @param int $type
* @throws \UnexpectedValueException
* @return boolean
*
*/
public function find($type): bool
{
$search = clone $this;
$search->skipUntil($type);
if (!$search->lookahead) {
throw new \UnexpectedValueException($type . ' not found');
}
return true;
}
/**
* moveNext
*
* @return boolean
*/
public function moveNext(): bool
{
if ($this->hasToRecord && $this->previous === $this->nullToken) {
$this->accumulator .= $this->current->value;
}
$this->previous = $this->current;
if ($this->lookahead === null) {
$this->lookahead = $this->nullToken;
}
$hasNext = parent::moveNext();
$this->current = $this->token ?? $this->nullToken;
if ($this->hasToRecord) {
$this->accumulator .= $this->current->value;
}
return $hasNext;
}
/**
* Retrieve token type. Also processes the token value if necessary.
*
* @param string $value
* @throws \InvalidArgumentException
* @return integer
*/
protected function getType(&$value): int
{
$encoded = $value;
if (mb_detect_encoding($value, 'auto', true) !== 'UTF-8') {
$encoded = mb_convert_encoding($value, 'UTF-8', 'Windows-1252');
}
if ($this->isValid($encoded)) {
return $this->charValue[$encoded];
}
if ($this->isNullType($encoded)) {
return self::C_NUL;
}
if ($this->isInvalidChar($encoded)) {
$this->hasInvalidTokens = true;
return self::INVALID;
}
return self::GENERIC;
}
protected function isValid(string $value): bool
{
return isset($this->charValue[$value]);
}
protected function isNullType(string $value): bool
{
return $value === "\0";
}
protected function isInvalidChar(string $value): bool
{
return !preg_match(self::INVALID_CHARS_REGEX, $value);
}
protected function isUTF8Invalid(string $value): bool
{
return preg_match(self::VALID_UTF8_REGEX, $value) !== false;
}
public function hasInvalidTokens(): bool
{
return $this->hasInvalidTokens;
}
/**
* getPrevious
*
* @return Token<int, string>
*/
public function getPrevious(): Token
{
return $this->previous;
}
/**
* Lexical catchable patterns.
*
* @return string[]
*/
protected function getCatchablePatterns(): array
{
return self::CATCHABLE_PATTERNS;
}
/**
* Lexical non-catchable patterns.
*
* @return string[]
*/
protected function getNonCatchablePatterns(): array
{
return self::NON_CATCHABLE_PATTERNS;
}
protected function getModifiers(): string
{
return self::MODIFIERS;
}
public function getAccumulatedValues(): string
{
return $this->accumulator;
}
public function startRecording(): void
{
$this->hasToRecord = true;
}
public function stopRecording(): void
{
$this->hasToRecord = false;
}
public function clearRecorded(): void
{
$this->accumulator = '';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/EmailParser.php | src/EmailParser.php | <?php
namespace Egulias\EmailValidator;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Parser\LocalPart;
use Egulias\EmailValidator\Parser\DomainPart;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\EmailTooLong;
use Egulias\EmailValidator\Result\Reason\NoLocalPart;
class EmailParser extends Parser
{
public const EMAIL_MAX_LENGTH = 254;
/**
* @var string
*/
protected $domainPart = '';
/**
* @var string
*/
protected $localPart = '';
public function parse(string $str): Result
{
$result = parent::parse($str);
$this->addLongEmailWarning($this->localPart, $this->domainPart);
return $result;
}
protected function preLeftParsing(): Result
{
if (!$this->hasAtToken()) {
return new InvalidEmail(new NoLocalPart(), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function parseLeftFromAt(): Result
{
return $this->processLocalPart();
}
protected function parseRightFromAt(): Result
{
return $this->processDomainPart();
}
private function processLocalPart(): Result
{
$localPartParser = new LocalPart($this->lexer);
$localPartResult = $localPartParser->parse();
$this->localPart = $localPartParser->localPart();
$this->warnings = [...$localPartParser->getWarnings(), ...$this->warnings];
return $localPartResult;
}
private function processDomainPart(): Result
{
$domainPartParser = new DomainPart($this->lexer);
$domainPartResult = $domainPartParser->parse();
$this->domainPart = $domainPartParser->domainPart();
$this->warnings = [...$domainPartParser->getWarnings(), ...$this->warnings];
return $domainPartResult;
}
public function getDomainPart(): string
{
return $this->domainPart;
}
public function getLocalPart(): string
{
return $this->localPart;
}
private function addLongEmailWarning(string $localPart, string $parsedDomainPart): void
{
if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) {
$this->warnings[EmailTooLong::CODE] = new EmailTooLong();
}
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/MessageIDParser.php | src/MessageIDParser.php | <?php
namespace Egulias\EmailValidator;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Parser\IDLeftPart;
use Egulias\EmailValidator\Parser\IDRightPart;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\EmailTooLong;
use Egulias\EmailValidator\Result\Reason\NoLocalPart;
class MessageIDParser extends Parser
{
public const EMAILID_MAX_LENGTH = 254;
/**
* @var string
*/
protected $idLeft = '';
/**
* @var string
*/
protected $idRight = '';
public function parse(string $str): Result
{
$result = parent::parse($str);
$this->addLongEmailWarning($this->idLeft, $this->idRight);
return $result;
}
protected function preLeftParsing(): Result
{
if (!$this->hasAtToken()) {
return new InvalidEmail(new NoLocalPart(), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function parseLeftFromAt(): Result
{
return $this->processIDLeft();
}
protected function parseRightFromAt(): Result
{
return $this->processIDRight();
}
private function processIDLeft(): Result
{
$localPartParser = new IDLeftPart($this->lexer);
$localPartResult = $localPartParser->parse();
$this->idLeft = $localPartParser->localPart();
$this->warnings = [...$localPartParser->getWarnings(), ...$this->warnings];
return $localPartResult;
}
private function processIDRight(): Result
{
$domainPartParser = new IDRightPart($this->lexer);
$domainPartResult = $domainPartParser->parse();
$this->idRight = $domainPartParser->domainPart();
$this->warnings = [...$domainPartParser->getWarnings(), ...$this->warnings];
return $domainPartResult;
}
public function getLeftPart(): string
{
return $this->idLeft;
}
public function getRightPart(): string
{
return $this->idRight;
}
private function addLongEmailWarning(string $localPart, string $parsedDomainPart): void
{
if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAILID_MAX_LENGTH) {
$this->warnings[EmailTooLong::CODE] = new EmailTooLong();
}
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/EmailValidator.php | src/EmailValidator.php | <?php
namespace Egulias\EmailValidator;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Validation\EmailValidation;
class EmailValidator
{
/**
* @var EmailLexer
*/
private $lexer;
/**
* @var Warning\Warning[]
*/
private $warnings = [];
/**
* @var ?InvalidEmail
*/
private $error;
public function __construct()
{
$this->lexer = new EmailLexer();
}
/**
* @param string $email
* @param EmailValidation $emailValidation
* @return bool
*/
public function isValid(string $email, EmailValidation $emailValidation)
{
$isValid = $emailValidation->isValid($email, $this->lexer);
$this->warnings = $emailValidation->getWarnings();
$this->error = $emailValidation->getError();
return $isValid;
}
/**
* @return boolean
*/
public function hasWarnings()
{
return !empty($this->warnings);
}
/**
* @return array
*/
public function getWarnings()
{
return $this->warnings;
}
/**
* @return InvalidEmail|null
*/
public function getError()
{
return $this->error;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser.php | src/Parser.php | <?php
namespace Egulias\EmailValidator;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
abstract class Parser
{
/**
* @var Warning\Warning[]
*/
protected $warnings = [];
/**
* @var EmailLexer
*/
protected $lexer;
/**
* id-left "@" id-right
*/
abstract protected function parseRightFromAt(): Result;
abstract protected function parseLeftFromAt(): Result;
abstract protected function preLeftParsing(): Result;
public function __construct(EmailLexer $lexer)
{
$this->lexer = $lexer;
}
public function parse(string $str): Result
{
$this->lexer->setInput($str);
if ($this->lexer->hasInvalidTokens()) {
return new InvalidEmail(new ExpectingATEXT("Invalid tokens found"), $this->lexer->current->value);
}
$preParsingResult = $this->preLeftParsing();
if ($preParsingResult->isInvalid()) {
return $preParsingResult;
}
$localPartResult = $this->parseLeftFromAt();
if ($localPartResult->isInvalid()) {
return $localPartResult;
}
$domainPartResult = $this->parseRightFromAt();
if ($domainPartResult->isInvalid()) {
return $domainPartResult;
}
return new ValidEmail();
}
/**
* @return Warning\Warning[]
*/
public function getWarnings(): array
{
return $this->warnings;
}
protected function hasAtToken(): bool
{
$this->lexer->moveNext();
$this->lexer->moveNext();
return !$this->lexer->current->isA(EmailLexer::S_AT);
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/EmailTooLong.php | src/Warning/EmailTooLong.php | <?php
namespace Egulias\EmailValidator\Warning;
use Egulias\EmailValidator\EmailParser;
class EmailTooLong extends Warning
{
public const CODE = 66;
public function __construct()
{
$this->message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/NoDNSMXRecord.php | src/Warning/NoDNSMXRecord.php | <?php
namespace Egulias\EmailValidator\Warning;
class NoDNSMXRecord extends Warning
{
public const CODE = 6;
public function __construct()
{
$this->message = 'No MX DSN record was found for this email';
$this->rfcNumber = 5321;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6Deprecated.php | src/Warning/IPV6Deprecated.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6Deprecated extends Warning
{
public const CODE = 13;
public function __construct()
{
$this->message = 'Deprecated form of IPV6';
$this->rfcNumber = 5321;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/TLD.php | src/Warning/TLD.php | <?php
namespace Egulias\EmailValidator\Warning;
class TLD extends Warning
{
public const CODE = 9;
public function __construct()
{
$this->message = "RFC5321, TLD";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/DomainLiteral.php | src/Warning/DomainLiteral.php | <?php
namespace Egulias\EmailValidator\Warning;
class DomainLiteral extends Warning
{
public const CODE = 70;
public function __construct()
{
$this->message = 'Domain Literal';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/CFWSWithFWS.php | src/Warning/CFWSWithFWS.php | <?php
namespace Egulias\EmailValidator\Warning;
class CFWSWithFWS extends Warning
{
public const CODE = 18;
public function __construct()
{
$this->message = 'Folding whites space followed by folding white space';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/ObsoleteDTEXT.php | src/Warning/ObsoleteDTEXT.php | <?php
namespace Egulias\EmailValidator\Warning;
class ObsoleteDTEXT extends Warning
{
public const CODE = 71;
public function __construct()
{
$this->rfcNumber = 5322;
$this->message = 'Obsolete DTEXT in domain literal';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/CFWSNearAt.php | src/Warning/CFWSNearAt.php | <?php
namespace Egulias\EmailValidator\Warning;
class CFWSNearAt extends Warning
{
public const CODE = 49;
public function __construct()
{
$this->message = "Deprecated folding white space near @";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6ColonStart.php | src/Warning/IPV6ColonStart.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6ColonStart extends Warning
{
public const CODE = 76;
public function __construct()
{
$this->message = ':: found at the start of the domain literal';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/QuotedPart.php | src/Warning/QuotedPart.php | <?php
namespace Egulias\EmailValidator\Warning;
use UnitEnum;
class QuotedPart extends Warning
{
public const CODE = 36;
/**
* @param UnitEnum|string|int|null $prevToken
* @param UnitEnum|string|int|null $postToken
*/
public function __construct($prevToken, $postToken)
{
if ($prevToken instanceof UnitEnum) {
$prevToken = $prevToken->name;
}
if ($postToken instanceof UnitEnum) {
$postToken = $postToken->name;
}
$this->message = "Deprecated Quoted String found between $prevToken and $postToken";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6DoubleColon.php | src/Warning/IPV6DoubleColon.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6DoubleColon extends Warning
{
public const CODE = 73;
public function __construct()
{
$this->message = 'Double colon found after IPV6 tag';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/Comment.php | src/Warning/Comment.php | <?php
namespace Egulias\EmailValidator\Warning;
class Comment extends Warning
{
public const CODE = 17;
public function __construct()
{
$this->message = "Comments found in this email";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/DeprecatedComment.php | src/Warning/DeprecatedComment.php | <?php
namespace Egulias\EmailValidator\Warning;
class DeprecatedComment extends Warning
{
public const CODE = 37;
public function __construct()
{
$this->message = 'Deprecated comments';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6GroupCount.php | src/Warning/IPV6GroupCount.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6GroupCount extends Warning
{
public const CODE = 72;
public function __construct()
{
$this->message = 'Group count is not IPV6 valid';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6MaxGroups.php | src/Warning/IPV6MaxGroups.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6MaxGroups extends Warning
{
public const CODE = 75;
public function __construct()
{
$this->message = 'Reached the maximum number of IPV6 groups allowed';
$this->rfcNumber = 5321;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/Warning.php | src/Warning/Warning.php | <?php
namespace Egulias\EmailValidator\Warning;
abstract class Warning
{
/**
* @var int CODE
*/
public const CODE = 0;
/**
* @var string
*/
protected $message = '';
/**
* @var int
*/
protected $rfcNumber = 0;
/**
* @return string
*/
public function message()
{
return $this->message;
}
/**
* @return int
*/
public function code()
{
return self::CODE;
}
/**
* @return int
*/
public function RFCNumber()
{
return $this->rfcNumber;
}
/**
* @return string
*/
public function __toString(): string
{
return $this->message() . " rfc: " . $this->rfcNumber . "internal code: " . static::CODE;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/QuotedString.php | src/Warning/QuotedString.php | <?php
namespace Egulias\EmailValidator\Warning;
class QuotedString extends Warning
{
public const CODE = 11;
/**
* @param string|int $prevToken
* @param string|int $postToken
*/
public function __construct($prevToken, $postToken)
{
$this->message = "Quoted String found between $prevToken and $postToken";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/LocalTooLong.php | src/Warning/LocalTooLong.php | <?php
namespace Egulias\EmailValidator\Warning;
class LocalTooLong extends Warning
{
public const CODE = 64;
public const LOCAL_PART_LENGTH = 64;
public function __construct()
{
$this->message = 'Local part is too long, exceeds 64 chars (octets)';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6ColonEnd.php | src/Warning/IPV6ColonEnd.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6ColonEnd extends Warning
{
public const CODE = 77;
public function __construct()
{
$this->message = ':: found at the end of the domain literal';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/AddressLiteral.php | src/Warning/AddressLiteral.php | <?php
namespace Egulias\EmailValidator\Warning;
class AddressLiteral extends Warning
{
public const CODE = 12;
public function __construct()
{
$this->message = 'Address literal in domain part';
$this->rfcNumber = 5321;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Warning/IPV6BadChar.php | src/Warning/IPV6BadChar.php | <?php
namespace Egulias\EmailValidator\Warning;
class IPV6BadChar extends Warning
{
public const CODE = 74;
public function __construct()
{
$this->message = 'Bad char in IPV6 domain literal';
$this->rfcNumber = 5322;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/LocalPart.php | src/Parser/LocalPart.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\LocalTooLong;
use Egulias\EmailValidator\Result\Reason\DotAtEnd;
use Egulias\EmailValidator\Result\Reason\DotAtStart;
use Egulias\EmailValidator\Result\Reason\ConsecutiveDot;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Parser\CommentStrategy\LocalComment;
class LocalPart extends PartParser
{
public const INVALID_TOKENS = [
EmailLexer::S_COMMA => EmailLexer::S_COMMA,
EmailLexer::S_CLOSEBRACKET => EmailLexer::S_CLOSEBRACKET,
EmailLexer::S_OPENBRACKET => EmailLexer::S_OPENBRACKET,
EmailLexer::S_GREATERTHAN => EmailLexer::S_GREATERTHAN,
EmailLexer::S_LOWERTHAN => EmailLexer::S_LOWERTHAN,
EmailLexer::S_COLON => EmailLexer::S_COLON,
EmailLexer::S_SEMICOLON => EmailLexer::S_SEMICOLON,
EmailLexer::INVALID => EmailLexer::INVALID
];
/**
* @var string
*/
private $localPart = '';
public function parse(): Result
{
$this->lexer->clearRecorded();
$this->lexer->startRecording();
while (!$this->lexer->current->isA(EmailLexer::S_AT) && !$this->lexer->current->isA(EmailLexer::S_EMPTY)) {
if ($this->hasDotAtStart()) {
return new InvalidEmail(new DotAtStart(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_DQUOTE)) {
$dquoteParsingResult = $this->parseDoubleQuote();
//Invalid double quote parsing
if ($dquoteParsingResult->isInvalid()) {
return $dquoteParsingResult;
}
}
if (
$this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS) ||
$this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)
) {
$commentsResult = $this->parseComments();
//Invalid comment parsing
if ($commentsResult->isInvalid()) {
return $commentsResult;
}
}
if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new ConsecutiveDot(), $this->lexer->current->value);
}
if (
$this->lexer->current->isA(EmailLexer::S_DOT) &&
$this->lexer->isNextToken(EmailLexer::S_AT)
) {
return new InvalidEmail(new DotAtEnd(), $this->lexer->current->value);
}
$resultEscaping = $this->validateEscaping();
if ($resultEscaping->isInvalid()) {
return $resultEscaping;
}
$resultToken = $this->validateTokens(false);
if ($resultToken->isInvalid()) {
return $resultToken;
}
$resultFWS = $this->parseLocalFWS();
if ($resultFWS->isInvalid()) {
return $resultFWS;
}
$this->lexer->moveNext();
}
$this->lexer->stopRecording();
$this->localPart = rtrim($this->lexer->getAccumulatedValues(), '@');
if (strlen($this->localPart) > LocalTooLong::LOCAL_PART_LENGTH) {
$this->warnings[LocalTooLong::CODE] = new LocalTooLong();
}
return new ValidEmail();
}
protected function validateTokens(bool $hasComments): Result
{
if (isset(self::INVALID_TOKENS[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT('Invalid token found'), $this->lexer->current->value);
}
return new ValidEmail();
}
public function localPart(): string
{
return $this->localPart;
}
private function parseLocalFWS(): Result
{
$foldingWS = new FoldingWhiteSpace($this->lexer);
$resultFWS = $foldingWS->parse();
if ($resultFWS->isValid()) {
$this->warnings = [...$this->warnings, ...$foldingWS->getWarnings()];
}
return $resultFWS;
}
private function hasDotAtStart(): bool
{
return $this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->getPrevious()->isA(EmailLexer::S_EMPTY);
}
private function parseDoubleQuote(): Result
{
$dquoteParser = new DoubleQuote($this->lexer);
$parseAgain = $dquoteParser->parse();
$this->warnings = [...$this->warnings, ...$dquoteParser->getWarnings()];
return $parseAgain;
}
protected function parseComments(): Result
{
$commentParser = new Comment($this->lexer, new LocalComment());
$result = $commentParser->parse();
$this->warnings = [...$this->warnings, ...$commentParser->getWarnings()];
return $result;
}
private function validateEscaping(): Result
{
//Backslash found
if (!$this->lexer->current->isA(EmailLexer::S_BACKSLASH)) {
return new ValidEmail();
}
if ($this->lexer->isNextToken(EmailLexer::GENERIC)) {
return new InvalidEmail(new ExpectingATEXT('Found ATOM after escaping'), $this->lexer->current->value);
}
return new ValidEmail();
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/FoldingWhiteSpace.php | src/Parser/FoldingWhiteSpace.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Warning\CFWSNearAt;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Result\Reason\CRNoLF;
use Egulias\EmailValidator\Result\Reason\AtextAfterCFWS;
use Egulias\EmailValidator\Result\Reason\CRLFAtTheEnd;
use Egulias\EmailValidator\Result\Reason\CRLFX2;
use Egulias\EmailValidator\Result\Reason\ExpectingCTEXT;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
class FoldingWhiteSpace extends PartParser
{
public const FWS_TYPES = [
EmailLexer::S_SP,
EmailLexer::S_HTAB,
EmailLexer::S_CR,
EmailLexer::S_LF,
EmailLexer::CRLF
];
public function parse(): Result
{
if (!$this->isFWS()) {
return new ValidEmail();
}
$previous = $this->lexer->getPrevious();
$resultCRLF = $this->checkCRLFInFWS();
if ($resultCRLF->isInvalid()) {
return $resultCRLF;
}
if ($this->lexer->current->isA(EmailLexer::S_CR)) {
return new InvalidEmail(new CRNoLF(), $this->lexer->current->value);
}
if ($this->lexer->isNextToken(EmailLexer::GENERIC) && !$previous->isA(EmailLexer::S_AT)) {
return new InvalidEmail(new AtextAfterCFWS(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_LF) || $this->lexer->current->isA(EmailLexer::C_NUL)) {
return new InvalidEmail(new ExpectingCTEXT(), $this->lexer->current->value);
}
if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous->isA(EmailLexer::S_AT)) {
$this->warnings[CFWSNearAt::CODE] = new CFWSNearAt();
} else {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
}
return new ValidEmail();
}
protected function checkCRLFInFWS(): Result
{
if (!$this->lexer->current->isA(EmailLexer::CRLF)) {
return new ValidEmail();
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) {
return new InvalidEmail(new CRLFX2(), $this->lexer->current->value);
}
//this has no coverage. Condition is repeated from above one
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) {
return new InvalidEmail(new CRLFAtTheEnd(), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function isFWS(): bool
{
if ($this->escaped()) {
return false;
}
return in_array($this->lexer->current->type, self::FWS_TYPES);
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/DoubleQuote.php | src/Parser/DoubleQuote.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\QuotedString;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Result\Reason\UnclosedQuotedString;
use Egulias\EmailValidator\Result\Result;
class DoubleQuote extends PartParser
{
public function parse(): Result
{
$validQuotedString = $this->checkDQUOTE();
if ($validQuotedString->isInvalid()) {
return $validQuotedString;
}
$special = [
EmailLexer::S_CR => true,
EmailLexer::S_HTAB => true,
EmailLexer::S_LF => true
];
$invalid = [
EmailLexer::C_NUL => true,
EmailLexer::S_HTAB => true,
EmailLexer::S_CR => true,
EmailLexer::S_LF => true
];
$setSpecialsWarning = true;
$this->lexer->moveNext();
while (!$this->lexer->current->isA(EmailLexer::S_DQUOTE) && !$this->lexer->current->isA(EmailLexer::S_EMPTY)) {
if (isset($special[$this->lexer->current->type]) && $setSpecialsWarning) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
$setSpecialsWarning = false;
}
if ($this->lexer->current->isA(EmailLexer::S_BACKSLASH) && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) {
$this->lexer->moveNext();
}
$this->lexer->moveNext();
if (!$this->escaped() && isset($invalid[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->current->value);
}
}
$prev = $this->lexer->getPrevious();
if ($prev->isA(EmailLexer::S_BACKSLASH)) {
$validQuotedString = $this->checkDQUOTE();
if ($validQuotedString->isInvalid()) {
return $validQuotedString;
}
}
if (!$this->lexer->isNextToken(EmailLexer::S_AT) && !$prev->isA(EmailLexer::S_BACKSLASH)) {
return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function checkDQUOTE(): Result
{
$previous = $this->lexer->getPrevious();
if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous->isA(EmailLexer::GENERIC)) {
$description = 'https://tools.ietf.org/html/rfc5322#section-3.2.4 - quoted string should be a unit';
return new InvalidEmail(new ExpectingATEXT($description), $this->lexer->current->value);
}
try {
$this->lexer->find(EmailLexer::S_DQUOTE);
} catch (\Exception $e) {
return new InvalidEmail(new UnclosedQuotedString(), $this->lexer->current->value);
}
$this->warnings[QuotedString::CODE] = new QuotedString($previous->value, $this->lexer->current->value);
return new ValidEmail();
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/DomainLiteral.php | src/Parser/DomainLiteral.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\IPV6BadChar;
use Egulias\EmailValidator\Result\Reason\CRNoLF;
use Egulias\EmailValidator\Warning\IPV6ColonEnd;
use Egulias\EmailValidator\Warning\IPV6MaxGroups;
use Egulias\EmailValidator\Warning\ObsoleteDTEXT;
use Egulias\EmailValidator\Warning\AddressLiteral;
use Egulias\EmailValidator\Warning\IPV6ColonStart;
use Egulias\EmailValidator\Warning\IPV6Deprecated;
use Egulias\EmailValidator\Warning\IPV6GroupCount;
use Egulias\EmailValidator\Warning\IPV6DoubleColon;
use Egulias\EmailValidator\Result\Reason\ExpectingDTEXT;
use Egulias\EmailValidator\Result\Reason\UnusualElements;
use Egulias\EmailValidator\Warning\DomainLiteral as WarningDomainLiteral;
class DomainLiteral extends PartParser
{
public const IPV4_REGEX = '/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
public const OBSOLETE_WARNINGS = [
EmailLexer::INVALID,
EmailLexer::C_DEL,
EmailLexer::S_LF,
EmailLexer::S_BACKSLASH
];
public function parse(): Result
{
$this->addTagWarnings();
$IPv6TAG = false;
$addressLiteral = '';
do {
if ($this->lexer->current->isA(EmailLexer::C_NUL)) {
return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->current->value);
}
$this->addObsoleteWarnings();
if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENBRACKET, EmailLexer::S_OPENBRACKET))) {
return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->current->value);
}
if ($this->lexer->isNextTokenAny(
array(EmailLexer::S_HTAB, EmailLexer::S_SP, EmailLexer::CRLF)
)) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
$this->parseFWS();
}
if ($this->lexer->isNextToken(EmailLexer::S_CR)) {
return new InvalidEmail(new CRNoLF(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_BACKSLASH)) {
return new InvalidEmail(new UnusualElements($this->lexer->current->value), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_IPV6TAG)) {
$IPv6TAG = true;
}
if ($this->lexer->current->isA(EmailLexer::S_CLOSEBRACKET)) {
break;
}
$addressLiteral .= $this->lexer->current->value;
} while ($this->lexer->moveNext());
//Encapsulate
$addressLiteral = str_replace('[', '', $addressLiteral);
$isAddressLiteralIPv4 = $this->checkIPV4Tag($addressLiteral);
if (!$isAddressLiteralIPv4) {
return new ValidEmail();
}
$addressLiteral = $this->convertIPv4ToIPv6($addressLiteral);
if (!$IPv6TAG) {
$this->warnings[WarningDomainLiteral::CODE] = new WarningDomainLiteral();
return new ValidEmail();
}
$this->warnings[AddressLiteral::CODE] = new AddressLiteral();
$this->checkIPV6Tag($addressLiteral);
return new ValidEmail();
}
/**
* @param string $addressLiteral
* @param int $maxGroups
*/
public function checkIPV6Tag($addressLiteral, $maxGroups = 8): void
{
$prev = $this->lexer->getPrevious();
if ($prev->isA(EmailLexer::S_COLON)) {
$this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd();
}
$IPv6 = substr($addressLiteral, 5);
//Daniel Marschall's new IPv6 testing strategy
$matchesIP = explode(':', $IPv6);
$groupCount = count($matchesIP);
$colons = strpos($IPv6, '::');
if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) {
$this->warnings[IPV6BadChar::CODE] = new IPV6BadChar();
}
if ($colons === false) {
// We need exactly the right number of groups
if ($groupCount !== $maxGroups) {
$this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount();
}
return;
}
if ($colons !== strrpos($IPv6, '::')) {
$this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon();
return;
}
if ($colons === 0 || $colons === (strlen($IPv6) - 2)) {
// RFC 4291 allows :: at the start or end of an address
//with 7 other groups in addition
++$maxGroups;
}
if ($groupCount > $maxGroups) {
$this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups();
} elseif ($groupCount === $maxGroups) {
$this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated();
}
}
public function convertIPv4ToIPv6(string $addressLiteralIPv4): string
{
$matchesIP = [];
$IPv4Match = preg_match(self::IPV4_REGEX, $addressLiteralIPv4, $matchesIP);
// Extract IPv4 part from the end of the address-literal (if there is one)
if ($IPv4Match > 0) {
$index = (int) strrpos($addressLiteralIPv4, $matchesIP[0]);
//There's a match but it is at the start
if ($index > 0) {
// Convert IPv4 part to IPv6 format for further testing
return substr($addressLiteralIPv4, 0, $index) . '0:0';
}
}
return $addressLiteralIPv4;
}
/**
* @param string $addressLiteral
*
* @return bool
*/
protected function checkIPV4Tag($addressLiteral): bool
{
$matchesIP = [];
$IPv4Match = preg_match(self::IPV4_REGEX, $addressLiteral, $matchesIP);
// Extract IPv4 part from the end of the address-literal (if there is one)
if ($IPv4Match > 0) {
$index = strrpos($addressLiteral, $matchesIP[0]);
//There's a match but it is at the start
if ($index === 0) {
$this->warnings[AddressLiteral::CODE] = new AddressLiteral();
return false;
}
}
return true;
}
private function addObsoleteWarnings(): void
{
if (in_array($this->lexer->current->type, self::OBSOLETE_WARNINGS)) {
$this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT();
}
}
private function addTagWarnings(): void
{
if ($this->lexer->isNextToken(EmailLexer::S_COLON)) {
$this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart();
}
if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) {
$lexer = clone $this->lexer;
$lexer->moveNext();
if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) {
$this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart();
}
}
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/IDRightPart.php | src/Parser/IDRightPart.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
class IDRightPart extends DomainPart
{
protected function validateTokens(bool $hasComments): Result
{
$invalidDomainTokens = [
EmailLexer::S_DQUOTE => true,
EmailLexer::S_SQUOTE => true,
EmailLexer::S_BACKTICK => true,
EmailLexer::S_SEMICOLON => true,
EmailLexer::S_GREATERTHAN => true,
EmailLexer::S_LOWERTHAN => true,
];
if (isset($invalidDomainTokens[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->current->value), $this->lexer->current->value);
}
return new ValidEmail();
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/Comment.php | src/Parser/Comment.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Warning\QuotedPart;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Parser\CommentStrategy\CommentStrategy;
use Egulias\EmailValidator\Result\Reason\UnclosedComment;
use Egulias\EmailValidator\Result\Reason\UnOpenedComment;
use Egulias\EmailValidator\Warning\Comment as WarningComment;
class Comment extends PartParser
{
/**
* @var int
*/
private $openedParenthesis = 0;
/**
* @var CommentStrategy
*/
private $commentStrategy;
public function __construct(EmailLexer $lexer, CommentStrategy $commentStrategy)
{
$this->lexer = $lexer;
$this->commentStrategy = $commentStrategy;
}
public function parse(): Result
{
if ($this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS)) {
$this->openedParenthesis++;
if ($this->noClosingParenthesis()) {
return new InvalidEmail(new UnclosedComment(), $this->lexer->current->value);
}
}
if ($this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)) {
return new InvalidEmail(new UnOpenedComment(), $this->lexer->current->value);
}
$this->warnings[WarningComment::CODE] = new WarningComment();
$moreTokens = true;
while ($this->commentStrategy->exitCondition($this->lexer, $this->openedParenthesis) && $moreTokens) {
if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) {
$this->openedParenthesis++;
}
$this->warnEscaping();
if ($this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) {
$this->openedParenthesis--;
}
$moreTokens = $this->lexer->moveNext();
}
if ($this->openedParenthesis >= 1) {
return new InvalidEmail(new UnclosedComment(), $this->lexer->current->value);
}
if ($this->openedParenthesis < 0) {
return new InvalidEmail(new UnOpenedComment(), $this->lexer->current->value);
}
$finalValidations = $this->commentStrategy->endOfLoopValidations($this->lexer);
$this->warnings = [...$this->warnings, ...$this->commentStrategy->getWarnings()];
return $finalValidations;
}
/**
* @return void
*/
private function warnEscaping(): void
{
//Backslash found
if (!$this->lexer->current->isA(EmailLexer::S_BACKSLASH)) {
return;
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) {
return;
}
$this->warnings[QuotedPart::CODE] =
new QuotedPart($this->lexer->getPrevious()->type, $this->lexer->current->type);
}
private function noClosingParenthesis(): bool
{
try {
$this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS);
return false;
} catch (\RuntimeException $e) {
return true;
}
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/DomainPart.php | src/Parser/DomainPart.php | <?php
namespace Egulias\EmailValidator\Parser;
use Doctrine\Common\Lexer\Token;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Warning\TLD;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\DotAtEnd;
use Egulias\EmailValidator\Result\Reason\DotAtStart;
use Egulias\EmailValidator\Warning\DeprecatedComment;
use Egulias\EmailValidator\Result\Reason\CRLFAtTheEnd;
use Egulias\EmailValidator\Result\Reason\LabelTooLong;
use Egulias\EmailValidator\Result\Reason\NoDomainPart;
use Egulias\EmailValidator\Result\Reason\ConsecutiveAt;
use Egulias\EmailValidator\Result\Reason\DomainTooLong;
use Egulias\EmailValidator\Result\Reason\CharNotAllowed;
use Egulias\EmailValidator\Result\Reason\DomainHyphened;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Parser\CommentStrategy\DomainComment;
use Egulias\EmailValidator\Result\Reason\ExpectingDomainLiteralClose;
use Egulias\EmailValidator\Parser\DomainLiteral as DomainLiteralParser;
class DomainPart extends PartParser
{
public const DOMAIN_MAX_LENGTH = 253;
public const LABEL_MAX_LENGTH = 63;
/**
* @var string
*/
protected $domainPart = '';
/**
* @var string
*/
protected $label = '';
public function parse(): Result
{
$this->lexer->clearRecorded();
$this->lexer->startRecording();
$this->lexer->moveNext();
$domainChecks = $this->performDomainStartChecks();
if ($domainChecks->isInvalid()) {
return $domainChecks;
}
if ($this->lexer->current->isA(EmailLexer::S_AT)) {
return new InvalidEmail(new ConsecutiveAt(), $this->lexer->current->value);
}
$result = $this->doParseDomainPart();
if ($result->isInvalid()) {
return $result;
}
$end = $this->checkEndOfDomain();
if ($end->isInvalid()) {
return $end;
}
$this->lexer->stopRecording();
$this->domainPart = $this->lexer->getAccumulatedValues();
$length = strlen($this->domainPart);
if ($length > self::DOMAIN_MAX_LENGTH) {
return new InvalidEmail(new DomainTooLong(), $this->lexer->current->value);
}
return new ValidEmail();
}
private function checkEndOfDomain(): Result
{
$prev = $this->lexer->getPrevious();
if ($prev->isA(EmailLexer::S_DOT)) {
return new InvalidEmail(new DotAtEnd(), $this->lexer->current->value);
}
if ($prev->isA(EmailLexer::S_HYPHEN)) {
return new InvalidEmail(new DomainHyphened('Hypen found at the end of the domain'), $prev->value);
}
if ($this->lexer->current->isA(EmailLexer::S_SP)) {
return new InvalidEmail(new CRLFAtTheEnd(), $prev->value);
}
return new ValidEmail();
}
private function performDomainStartChecks(): Result
{
$invalidTokens = $this->checkInvalidTokensAfterAT();
if ($invalidTokens->isInvalid()) {
return $invalidTokens;
}
$missingDomain = $this->checkEmptyDomain();
if ($missingDomain->isInvalid()) {
return $missingDomain;
}
if ($this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS)) {
$this->warnings[DeprecatedComment::CODE] = new DeprecatedComment();
}
return new ValidEmail();
}
private function checkEmptyDomain(): Result
{
$thereIsNoDomain = $this->lexer->current->isA(EmailLexer::S_EMPTY) ||
($this->lexer->current->isA(EmailLexer::S_SP) &&
!$this->lexer->isNextToken(EmailLexer::GENERIC));
if ($thereIsNoDomain) {
return new InvalidEmail(new NoDomainPart(), $this->lexer->current->value);
}
return new ValidEmail();
}
private function checkInvalidTokensAfterAT(): Result
{
if ($this->lexer->current->isA(EmailLexer::S_DOT)) {
return new InvalidEmail(new DotAtStart(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_HYPHEN)) {
return new InvalidEmail(new DomainHyphened('After AT'), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function parseComments(): Result
{
$commentParser = new Comment($this->lexer, new DomainComment());
$result = $commentParser->parse();
$this->warnings = [...$this->warnings, ...$commentParser->getWarnings()];
return $result;
}
protected function doParseDomainPart(): Result
{
$tldMissing = true;
$hasComments = false;
$domain = '';
do {
$prev = $this->lexer->getPrevious();
$notAllowedChars = $this->checkNotAllowedChars($this->lexer->current);
if ($notAllowedChars->isInvalid()) {
return $notAllowedChars;
}
if (
$this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS) ||
$this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)
) {
$hasComments = true;
$commentsResult = $this->parseComments();
//Invalid comment parsing
if ($commentsResult->isInvalid()) {
return $commentsResult;
}
}
$dotsResult = $this->checkConsecutiveDots();
if ($dotsResult->isInvalid()) {
return $dotsResult;
}
if ($this->lexer->current->isA(EmailLexer::S_OPENBRACKET)) {
$literalResult = $this->parseDomainLiteral();
$this->addTLDWarnings($tldMissing);
return $literalResult;
}
$labelCheck = $this->checkLabelLength();
if ($labelCheck->isInvalid()) {
return $labelCheck;
}
$FwsResult = $this->parseFWS();
if ($FwsResult->isInvalid()) {
return $FwsResult;
}
$domain .= $this->lexer->current->value;
if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::GENERIC)) {
$tldMissing = false;
}
$exceptionsResult = $this->checkDomainPartExceptions($prev, $hasComments);
if ($exceptionsResult->isInvalid()) {
return $exceptionsResult;
}
$this->lexer->moveNext();
} while (!$this->lexer->current->isA(EmailLexer::S_EMPTY));
$labelCheck = $this->checkLabelLength(true);
if ($labelCheck->isInvalid()) {
return $labelCheck;
}
$this->addTLDWarnings($tldMissing);
$this->domainPart = $domain;
return new ValidEmail();
}
/**
* @param Token<int, string> $token
*
* @return Result
*/
private function checkNotAllowedChars(Token $token): Result
{
$notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH => true];
if (isset($notAllowed[$token->type])) {
return new InvalidEmail(new CharNotAllowed(), $token->value);
}
return new ValidEmail();
}
/**
* @return Result
*/
protected function parseDomainLiteral(): Result
{
try {
$this->lexer->find(EmailLexer::S_CLOSEBRACKET);
} catch (\RuntimeException $e) {
return new InvalidEmail(new ExpectingDomainLiteralClose(), $this->lexer->current->value);
}
$domainLiteralParser = new DomainLiteralParser($this->lexer);
$result = $domainLiteralParser->parse();
$this->warnings = [...$this->warnings, ...$domainLiteralParser->getWarnings()];
return $result;
}
/**
* @param Token<int, string> $prev
* @param bool $hasComments
*
* @return Result
*/
protected function checkDomainPartExceptions(Token $prev, bool $hasComments): Result
{
if ($this->lexer->current->isA(EmailLexer::S_OPENBRACKET) && $prev->type !== EmailLexer::S_AT) {
return new InvalidEmail(new ExpectingATEXT('OPENBRACKET not after AT'), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_HYPHEN) && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new DomainHyphened('Hypen found near DOT'), $this->lexer->current->value);
}
if (
$this->lexer->current->isA(EmailLexer::S_BACKSLASH)
&& $this->lexer->isNextToken(EmailLexer::GENERIC)
) {
return new InvalidEmail(new ExpectingATEXT('Escaping following "ATOM"'), $this->lexer->current->value);
}
return $this->validateTokens($hasComments);
}
protected function validateTokens(bool $hasComments): Result
{
$validDomainTokens = array(
EmailLexer::GENERIC => true,
EmailLexer::S_HYPHEN => true,
EmailLexer::S_DOT => true,
);
if ($hasComments) {
$validDomainTokens[EmailLexer::S_OPENPARENTHESIS] = true;
$validDomainTokens[EmailLexer::S_CLOSEPARENTHESIS] = true;
}
if (!isset($validDomainTokens[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->current->value), $this->lexer->current->value);
}
return new ValidEmail();
}
private function checkLabelLength(bool $isEndOfDomain = false): Result
{
if ($this->lexer->current->isA(EmailLexer::S_DOT) || $isEndOfDomain) {
if ($this->isLabelTooLong($this->label)) {
return new InvalidEmail(new LabelTooLong(), $this->lexer->current->value);
}
$this->label = '';
}
$this->label .= $this->lexer->current->value;
return new ValidEmail();
}
private function isLabelTooLong(string $label): bool
{
if (preg_match('/[^\x00-\x7F]/', $label)) {
idn_to_ascii($label, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, $idnaInfo);
/** @psalm-var array{errors: int, ...} $idnaInfo */
return (bool) ($idnaInfo['errors'] & IDNA_ERROR_LABEL_TOO_LONG);
}
return strlen($label) > self::LABEL_MAX_LENGTH;
}
private function addTLDWarnings(bool $isTLDMissing): void
{
if ($isTLDMissing) {
$this->warnings[TLD::CODE] = new TLD();
}
}
public function domainPart(): string
{
return $this->domainPart;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/IDLeftPart.php | src/Parser/IDLeftPart.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\CommentsInIDRight;
class IDLeftPart extends LocalPart
{
protected function parseComments(): Result
{
return new InvalidEmail(new CommentsInIDRight(), $this->lexer->current->value);
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/PartParser.php | src/Parser/PartParser.php | <?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ConsecutiveDot;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Warning\Warning;
abstract class PartParser
{
/**
* @var Warning[]
*/
protected $warnings = [];
/**
* @var EmailLexer
*/
protected $lexer;
public function __construct(EmailLexer $lexer)
{
$this->lexer = $lexer;
}
abstract public function parse(): Result;
/**
* @return Warning[]
*/
public function getWarnings()
{
return $this->warnings;
}
protected function parseFWS(): Result
{
$foldingWS = new FoldingWhiteSpace($this->lexer);
$resultFWS = $foldingWS->parse();
$this->warnings = [...$this->warnings, ...$foldingWS->getWarnings()];
return $resultFWS;
}
protected function checkConsecutiveDots(): Result
{
if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new ConsecutiveDot(), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function escaped(): bool
{
$previous = $this->lexer->getPrevious();
return $previous->isA(EmailLexer::S_BACKSLASH)
&& !$this->lexer->current->isA(EmailLexer::GENERIC);
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/CommentStrategy/DomainComment.php | src/Parser/CommentStrategy/DomainComment.php | <?php
namespace Egulias\EmailValidator\Parser\CommentStrategy;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
class DomainComment implements CommentStrategy
{
public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool
{
return !($openedParenthesis === 0 && $lexer->isNextToken(EmailLexer::S_DOT));
}
public function endOfLoopValidations(EmailLexer $lexer): Result
{
//test for end of string
if (!$lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new ExpectingATEXT('DOT not found near CLOSEPARENTHESIS'), $lexer->current->value);
}
//add warning
//Address is valid within the message but cannot be used unmodified for the envelope
return new ValidEmail();
}
public function getWarnings(): array
{
return [];
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/CommentStrategy/LocalComment.php | src/Parser/CommentStrategy/LocalComment.php | <?php
namespace Egulias\EmailValidator\Parser\CommentStrategy;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Warning\CFWSNearAt;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Warning\Warning;
class LocalComment implements CommentStrategy
{
/**
* @var array<int, Warning>
*/
private $warnings = [];
public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool
{
return !$lexer->isNextToken(EmailLexer::S_AT);
}
public function endOfLoopValidations(EmailLexer $lexer): Result
{
if (!$lexer->isNextToken(EmailLexer::S_AT)) {
return new InvalidEmail(new ExpectingATEXT('ATEX is not expected after closing comments'), $lexer->current->value);
}
$this->warnings[CFWSNearAt::CODE] = new CFWSNearAt();
return new ValidEmail();
}
public function getWarnings(): array
{
return $this->warnings;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Parser/CommentStrategy/CommentStrategy.php | src/Parser/CommentStrategy/CommentStrategy.php | <?php
namespace Egulias\EmailValidator\Parser\CommentStrategy;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Warning\Warning;
interface CommentStrategy
{
/**
* Return "true" to continue, "false" to exit
*/
public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool;
public function endOfLoopValidations(EmailLexer $lexer): Result;
/**
* @return Warning[]
*/
public function getWarnings(): array;
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/MultipleValidationWithAnd.php | src/Validation/MultipleValidationWithAnd.php | <?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Validation\Exception\EmptyValidationList;
use Egulias\EmailValidator\Result\MultipleErrors;
use Egulias\EmailValidator\Warning\Warning;
class MultipleValidationWithAnd implements EmailValidation
{
/**
* If one of validations fails, the remaining validations will be skipped.
* This means MultipleErrors will only contain a single error, the first found.
*/
public const STOP_ON_ERROR = 0;
/**
* All of validations will be invoked even if one of them got failure.
* So MultipleErrors will contain all causes.
*/
public const ALLOW_ALL_ERRORS = 1;
/**
* @var Warning[]
*/
private $warnings = [];
/**
* @var MultipleErrors|null
*/
private $error;
/**
* @param EmailValidation[] $validations The validations.
* @param int $mode The validation mode (one of the constants).
*/
public function __construct(private readonly array $validations, private readonly int $mode = self::ALLOW_ALL_ERRORS)
{
if (count($validations) == 0) {
throw new EmptyValidationList();
}
}
/**
* {@inheritdoc}
*/
public function isValid(string $email, EmailLexer $emailLexer): bool
{
$result = true;
foreach ($this->validations as $validation) {
$emailLexer->reset();
$validationResult = $validation->isValid($email, $emailLexer);
$result = $result && $validationResult;
$this->warnings = [...$this->warnings, ...$validation->getWarnings()];
if (!$validationResult) {
$this->processError($validation);
}
if ($this->shouldStop($result)) {
break;
}
}
return $result;
}
private function initErrorStorage(): void
{
if (null === $this->error) {
$this->error = new MultipleErrors();
}
}
private function processError(EmailValidation $validation): void
{
if (null !== $validation->getError()) {
$this->initErrorStorage();
/** @psalm-suppress PossiblyNullReference */
$this->error->addReason($validation->getError()->reason());
}
}
private function shouldStop(bool $result): bool
{
return !$result && $this->mode === self::STOP_ON_ERROR;
}
/**
* Returns the validation errors.
*/
public function getError(): ?InvalidEmail
{
return $this->error;
}
/**
* @return Warning[]
*/
public function getWarnings(): array
{
return $this->warnings;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/DNSRecords.php | src/Validation/DNSRecords.php | <?php
namespace Egulias\EmailValidator\Validation;
class DNSRecords
{
/**
* @param list<array<array-key, mixed>> $records
* @param bool $error
*/
public function __construct(private readonly array $records, private readonly bool $error = false)
{
}
/**
* @return list<array<array-key, mixed>>
*/
public function getRecords(): array
{
return $this->records;
}
public function withError(): bool
{
return $this->error;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/DNSGetRecordWrapper.php | src/Validation/DNSGetRecordWrapper.php | <?php
namespace Egulias\EmailValidator\Validation;
class DNSGetRecordWrapper
{
/**
* @param string $host
* @param int $type
*
* @return DNSRecords
*/
public function getRecords(string $host, int $type): DNSRecords
{
// A workaround to fix https://bugs.php.net/bug.php?id=73149
set_error_handler(
static function (int $errorLevel, string $errorMessage): never {
throw new \RuntimeException("Unable to get DNS record for the host: $errorMessage");
}
);
try {
// Get all MX, A and AAAA DNS records for host
return new DNSRecords(dns_get_record($host, $type));
} catch (\RuntimeException $exception) {
return new DNSRecords([], true);
} finally {
restore_error_handler();
}
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/RFCValidation.php | src/Validation/RFCValidation.php | <?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\EmailParser;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExceptionFound;
use Egulias\EmailValidator\Warning\Warning;
class RFCValidation implements EmailValidation
{
/**
* @var Warning[]
*/
private array $warnings = [];
/**
* @var ?InvalidEmail
*/
private $error;
public function isValid(string $email, EmailLexer $emailLexer): bool
{
$parser = new EmailParser($emailLexer);
try {
$result = $parser->parse($email);
$this->warnings = $parser->getWarnings();
if ($result->isInvalid()) {
/** @psalm-suppress PropertyTypeCoercion */
$this->error = $result;
return false;
}
} catch (\Exception $invalid) {
$this->error = new InvalidEmail(new ExceptionFound($invalid), '');
return false;
}
return true;
}
public function getError(): ?InvalidEmail
{
return $this->error;
}
/**
* @return Warning[]
*/
public function getWarnings(): array
{
return $this->warnings;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/NoRFCWarningsValidation.php | src/Validation/NoRFCWarningsValidation.php | <?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\RFCWarnings;
class NoRFCWarningsValidation extends RFCValidation
{
/**
* @var InvalidEmail|null
*/
private $error;
/**
* {@inheritdoc}
*/
public function isValid(string $email, EmailLexer $emailLexer) : bool
{
if (!parent::isValid($email, $emailLexer)) {
return false;
}
if (empty($this->getWarnings())) {
return true;
}
$this->error = new InvalidEmail(new RFCWarnings(), '');
return false;
}
/**
* {@inheritdoc}
*/
public function getError() : ?InvalidEmail
{
return $this->error ?: parent::getError();
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/MessageIDValidation.php | src/Validation/MessageIDValidation.php | <?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\MessageIDParser;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExceptionFound;
use Egulias\EmailValidator\Warning\Warning;
class MessageIDValidation implements EmailValidation
{
/**
* @var Warning[]
*/
private $warnings = [];
/**
* @var ?InvalidEmail
*/
private $error;
public function isValid(string $email, EmailLexer $emailLexer): bool
{
$parser = new MessageIDParser($emailLexer);
try {
$result = $parser->parse($email);
$this->warnings = $parser->getWarnings();
if ($result->isInvalid()) {
/** @psalm-suppress PropertyTypeCoercion */
$this->error = $result;
return false;
}
} catch (\Exception $invalid) {
$this->error = new InvalidEmail(new ExceptionFound($invalid), '');
return false;
}
return true;
}
/**
* @return Warning[]
*/
public function getWarnings(): array
{
return $this->warnings;
}
public function getError(): ?InvalidEmail
{
return $this->error;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/DNSCheckValidation.php | src/Validation/DNSCheckValidation.php | <?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\DomainAcceptsNoMail;
use Egulias\EmailValidator\Result\Reason\LocalOrReservedDomain;
use Egulias\EmailValidator\Result\Reason\NoDNSRecord as ReasonNoDNSRecord;
use Egulias\EmailValidator\Result\Reason\UnableToGetDNSRecord;
use Egulias\EmailValidator\Warning\NoDNSMXRecord;
use Egulias\EmailValidator\Warning\Warning;
class DNSCheckValidation implements EmailValidation
{
/**
* Reserved Top Level DNS Names (https://tools.ietf.org/html/rfc2606#section-2),
* mDNS and private DNS Namespaces (https://tools.ietf.org/html/rfc6762#appendix-G)
*
* @var string[]
*/
public const RESERVED_DNS_TOP_LEVEL_NAMES = [
// Reserved Top Level DNS Names
'test',
'example',
'invalid',
'localhost',
// mDNS
'local',
// Private DNS Namespaces
'intranet',
'internal',
'private',
'corp',
'home',
'lan',
];
/**
* @var Warning[]
*/
private $warnings = [];
/**
* @var InvalidEmail|null
*/
private $error;
/**
* @var array
*/
private $mxRecords = [];
/**
* @var DNSGetRecordWrapper
*/
private $dnsGetRecord;
public function __construct(?DNSGetRecordWrapper $dnsGetRecord = null)
{
if (!function_exists('idn_to_ascii')) {
throw new \LogicException(sprintf('The %s class requires the Intl extension.', __CLASS__));
}
if ($dnsGetRecord == null) {
$dnsGetRecord = new DNSGetRecordWrapper();
}
$this->dnsGetRecord = $dnsGetRecord;
}
public function isValid(string $email, EmailLexer $emailLexer): bool
{
// use the input to check DNS if we cannot extract something similar to a domain
$host = $email;
// Arguable pattern to extract the domain. Not aiming to validate the domain nor the email
if (false !== $lastAtPos = strrpos($email, '@')) {
$host = substr($email, $lastAtPos + 1);
}
// Get the domain parts
$hostParts = explode('.', $host);
$isLocalDomain = count($hostParts) <= 1;
$isReservedTopLevel = in_array($hostParts[(count($hostParts) - 1)], self::RESERVED_DNS_TOP_LEVEL_NAMES, true);
// Exclude reserved top level DNS names
if ($isLocalDomain || $isReservedTopLevel) {
$this->error = new InvalidEmail(new LocalOrReservedDomain(), $host);
return false;
}
return $this->checkDns($host);
}
public function getError(): ?InvalidEmail
{
return $this->error;
}
/**
* @return Warning[]
*/
public function getWarnings(): array
{
return $this->warnings;
}
/**
* @param string $host
*
* @return bool
*/
protected function checkDns($host)
{
$variant = INTL_IDNA_VARIANT_UTS46;
$host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.');
$hostParts = explode('.', $host);
$host = array_pop($hostParts);
while (count($hostParts) > 0) {
$host = array_pop($hostParts) . '.' . $host;
if ($this->validateDnsRecords($host)) {
return true;
}
}
return false;
}
/**
* Validate the DNS records for given host.
*
* @param string $host A set of DNS records in the format returned by dns_get_record.
*
* @return bool True on success.
*/
private function validateDnsRecords($host): bool
{
$dnsRecordsResult = $this->dnsGetRecord->getRecords($host, DNS_A + DNS_MX);
if ($dnsRecordsResult->withError()) {
$this->error = new InvalidEmail(new UnableToGetDNSRecord(), '');
return false;
}
$dnsRecords = $dnsRecordsResult->getRecords();
// Combined check for A+MX+AAAA can fail with SERVFAIL, even in the presence of valid A/MX records
$aaaaRecordsResult = $this->dnsGetRecord->getRecords($host, DNS_AAAA);
if (! $aaaaRecordsResult->withError()) {
$dnsRecords = array_merge($dnsRecords, $aaaaRecordsResult->getRecords());
}
// No MX, A or AAAA DNS records
if ($dnsRecords === []) {
$this->error = new InvalidEmail(new ReasonNoDNSRecord(), '');
return false;
}
// For each DNS record
foreach ($dnsRecords as $dnsRecord) {
if (!$this->validateMXRecord($dnsRecord)) {
// No MX records (fallback to A or AAAA records)
if (empty($this->mxRecords)) {
$this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
}
return false;
}
}
return true;
}
/**
* Validate an MX record
*
* @param array $dnsRecord Given DNS record.
*
* @return bool True if valid.
*/
private function validateMxRecord($dnsRecord): bool
{
if (!isset($dnsRecord['type'])) {
$this->error = new InvalidEmail(new ReasonNoDNSRecord(), '');
return false;
}
if ($dnsRecord['type'] !== 'MX') {
return true;
}
// "Null MX" record indicates the domain accepts no mail (https://tools.ietf.org/html/rfc7505)
if (empty($dnsRecord['target']) || $dnsRecord['target'] === '.') {
$this->error = new InvalidEmail(new DomainAcceptsNoMail(), "");
return false;
}
$this->mxRecords[] = $dnsRecord;
return true;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/EmailValidation.php | src/Validation/EmailValidation.php | <?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\Warning;
interface EmailValidation
{
/**
* Returns true if the given email is valid.
*
* @param string $email The email you want to validate.
* @param EmailLexer $emailLexer The email lexer.
*
* @return bool
*/
public function isValid(string $email, EmailLexer $emailLexer) : bool;
/**
* Returns the validation error.
*
* @return InvalidEmail|null
*/
public function getError() : ?InvalidEmail;
/**
* Returns the validation warnings.
*
* @return Warning[]
*/
public function getWarnings() : array;
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/Extra/SpoofCheckValidation.php | src/Validation/Extra/SpoofCheckValidation.php | <?php
namespace Egulias\EmailValidator\Validation\Extra;
use \Spoofchecker;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\SpoofEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Validation\EmailValidation;
class SpoofCheckValidation implements EmailValidation
{
/**
* @var InvalidEmail|null
*/
private $error;
public function __construct()
{
if (!extension_loaded('intl')) {
throw new \LogicException(sprintf('The %s class requires the Intl extension.', __CLASS__));
}
}
public function isValid(string $email, EmailLexer $emailLexer) : bool
{
$checker = new Spoofchecker();
$checker->setChecks(Spoofchecker::SINGLE_SCRIPT);
if ($checker->isSuspicious($email)) {
$this->error = new SpoofEmail();
}
return $this->error === null;
}
public function getError() : ?InvalidEmail
{
return $this->error;
}
public function getWarnings() : array
{
return [];
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Validation/Exception/EmptyValidationList.php | src/Validation/Exception/EmptyValidationList.php | <?php
namespace Egulias\EmailValidator\Validation\Exception;
use Exception;
class EmptyValidationList extends \InvalidArgumentException
{
/**
* @param int $code
*/
public function __construct($code = 0, ?Exception $previous = null)
{
parent::__construct("Empty validation list is not allowed", $code, $previous);
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Result.php | src/Result/Result.php | <?php
namespace Egulias\EmailValidator\Result;
interface Result
{
/**
* Is validation result valid?
*
*/
public function isValid(): bool;
/**
* Is validation result invalid?
* Usually the inverse of isValid()
*
*/
public function isInvalid(): bool;
/**
* Short description of the result, human readable.
*
*/
public function description(): string;
/**
* Code for user land to act upon.
*
*/
public function code(): int;
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/InvalidEmail.php | src/Result/InvalidEmail.php | <?php
namespace Egulias\EmailValidator\Result;
use Egulias\EmailValidator\Result\Reason\Reason;
class InvalidEmail implements Result
{
/**
* @var string
*/
private string $token;
/**
* @var Reason
*/
protected Reason $reason;
public function __construct(Reason $reason, string $token)
{
$this->token = $token;
$this->reason = $reason;
}
public function isValid(): bool
{
return false;
}
public function isInvalid(): bool
{
return true;
}
public function description(): string
{
return $this->reason->description() . " in char " . $this->token;
}
public function code(): int
{
return $this->reason->code();
}
public function reason(): Reason
{
return $this->reason;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/ValidEmail.php | src/Result/ValidEmail.php | <?php
namespace Egulias\EmailValidator\Result;
class ValidEmail implements Result
{
public function isValid(): bool
{
return true;
}
public function isInvalid(): bool
{
return false;
}
public function description(): string
{
return "Valid email";
}
public function code(): int
{
return 0;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/MultipleErrors.php | src/Result/MultipleErrors.php | <?php
namespace Egulias\EmailValidator\Result;
use Egulias\EmailValidator\Result\Reason\EmptyReason;
use Egulias\EmailValidator\Result\Reason\Reason;
/**
* @psalm-suppress PropertyNotSetInConstructor
*/
class MultipleErrors extends InvalidEmail
{
/**
* @var Reason[]
*/
private $reasons = [];
public function __construct()
{
}
public function addReason(Reason $reason) : void
{
$this->reasons[$reason->code()] = $reason;
}
/**
* @return Reason[]
*/
public function getReasons() : array
{
return $this->reasons;
}
public function reason() : Reason
{
return 0 !== count($this->reasons)
? current($this->reasons)
: new EmptyReason();
}
public function description() : string
{
$description = '';
foreach($this->reasons as $reason) {
$description .= $reason->description() . PHP_EOL;
}
return $description;
}
public function code() : int
{
return 0;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/SpoofEmail.php | src/Result/SpoofEmail.php | <?php
namespace Egulias\EmailValidator\Result;
use Egulias\EmailValidator\Result\Reason\SpoofEmail as ReasonSpoofEmail;
class SpoofEmail extends InvalidEmail
{
public function __construct()
{
$this->reason = new ReasonSpoofEmail();
parent::__construct($this->reason, '');
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/NoDNSRecord.php | src/Result/Reason/NoDNSRecord.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class NoDNSRecord implements Reason
{
public function code() : int
{
return 5;
}
public function description() : string
{
return 'No MX or A DNS record was found for this email';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/UnclosedComment.php | src/Result/Reason/UnclosedComment.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class UnclosedComment implements Reason
{
public function code() : int
{
return 146;
}
public function description(): string
{
return 'No closing comment token found';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/DomainHyphened.php | src/Result/Reason/DomainHyphened.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class DomainHyphened extends DetailedReason
{
public function code() : int
{
return 144;
}
public function description() : string
{
return 'S_HYPHEN found in domain';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/CRLFAtTheEnd.php | src/Result/Reason/CRLFAtTheEnd.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class CRLFAtTheEnd implements Reason
{
public const CODE = 149;
public const REASON = "CRLF at the end";
public function code() : int
{
return 149;
}
public function description() : string
{
return 'CRLF at the end';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/DotAtEnd.php | src/Result/Reason/DotAtEnd.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class DotAtEnd implements Reason
{
public function code() : int
{
return 142;
}
public function description() : string
{
return 'Dot at the end';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/AtextAfterCFWS.php | src/Result/Reason/AtextAfterCFWS.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class AtextAfterCFWS implements Reason
{
public function code() : int
{
return 133;
}
public function description() : string
{
return 'ATEXT found after CFWS';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/CRLFX2.php | src/Result/Reason/CRLFX2.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class CRLFX2 implements Reason
{
public function code() : int
{
return 148;
}
public function description() : string
{
return 'CR LF tokens found twice';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ExpectingDTEXT.php | src/Result/Reason/ExpectingDTEXT.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ExpectingDTEXT implements Reason
{
public function code() : int
{
return 129;
}
public function description() : string
{
return 'Expecting DTEXT';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ConsecutiveAt.php | src/Result/Reason/ConsecutiveAt.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ConsecutiveAt implements Reason
{
public function code() : int
{
return 128;
}
public function description() : string
{
return '@ found after another @';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/RFCWarnings.php | src/Result/Reason/RFCWarnings.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class RFCWarnings implements Reason
{
public function code() : int
{
return 997;
}
public function description() : string
{
return 'Warnings found after validating';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/DomainTooLong.php | src/Result/Reason/DomainTooLong.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class DomainTooLong implements Reason
{
public function code() : int
{
return 244;
}
public function description() : string
{
return 'Domain is longer than 253 characters';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/CharNotAllowed.php | src/Result/Reason/CharNotAllowed.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class CharNotAllowed implements Reason
{
public function code() : int
{
return 1;
}
public function description() : string
{
return "Character not allowed";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ExpectingATEXT.php | src/Result/Reason/ExpectingATEXT.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ExpectingATEXT extends DetailedReason
{
public function code() : int
{
return 137;
}
public function description() : string
{
return "Expecting ATEXT (Printable US-ASCII). Extended: " . $this->detailedDescription;
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/NoDomainPart.php | src/Result/Reason/NoDomainPart.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class NoDomainPart implements Reason
{
public function code() : int
{
return 131;
}
public function description() : string
{
return 'No domain part found';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/ConsecutiveDot.php | src/Result/Reason/ConsecutiveDot.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class ConsecutiveDot implements Reason
{
public function code() : int
{
return 132;
}
public function description() : string
{
return 'Concecutive DOT found';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/NoLocalPart.php | src/Result/Reason/NoLocalPart.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class NoLocalPart implements Reason
{
public function code() : int
{
return 130;
}
public function description() : string
{
return "No local part";
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
egulias/EmailValidator | https://github.com/egulias/EmailValidator/blob/d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa/src/Result/Reason/EmptyReason.php | src/Result/Reason/EmptyReason.php | <?php
namespace Egulias\EmailValidator\Result\Reason;
class EmptyReason implements Reason
{
public function code() : int
{
return 0;
}
public function description() : string
{
return 'Empty reason';
}
}
| php | MIT | d42c8731f0624ad6bdc8d3e5e9a4524f68801cfa | 2026-01-04T15:04:04.519584Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.