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
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/WriterInterface.php
src/Repository/Adapter/WriterInterface.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; interface WriterInterface { /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value); /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/ArrayAdapter.php
src/Repository/Adapter/ArrayAdapter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\Option; use PhpOption\Some; final class ArrayAdapter implements AdapterInterface { /** * The variables and their values. * * @var array<string, string> */ private $variables; /** * Create a new array adapter instance. * * @return void */ private function __construct() { $this->variables = []; } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { return Option::fromArraysValue($this->variables, $name); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { $this->variables[$name] = $value; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { unset($this->variables[$name]); return true; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/MultiWriter.php
src/Repository/Adapter/MultiWriter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class MultiWriter implements WriterInterface { /** * The set of writers to use. * * @var \Dotenv\Repository\Adapter\WriterInterface[] */ private $writers; /** * Create a new multi-writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface[] $writers * * @return void */ public function __construct(array $writers) { $this->writers = $writers; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { foreach ($this->writers as $writers) { if (!$writers->write($name, $value)) { return false; } } return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { foreach ($this->writers as $writers) { if (!$writers->delete($name)) { return false; } } return true; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/AdapterInterface.php
src/Repository/Adapter/AdapterInterface.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; interface AdapterInterface extends ReaderInterface, WriterInterface { /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create(); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/ServerConstAdapter.php
src/Repository/Adapter/ServerConstAdapter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\Option; use PhpOption\Some; final class ServerConstAdapter implements AdapterInterface { /** * Create a new server const adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromArraysValue($_SERVER, $name) ->filter(static function ($value) { return \is_scalar($value); }) ->map(static function ($value) { if ($value === false) { return 'false'; } if ($value === true) { return 'true'; } return (string) $value; }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { $_SERVER[$name] = $value; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { unset($_SERVER[$name]); return true; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/EnvConstAdapter.php
src/Repository/Adapter/EnvConstAdapter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\Option; use PhpOption\Some; final class EnvConstAdapter implements AdapterInterface { /** * Create a new env const adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromArraysValue($_ENV, $name) ->filter(static function ($value) { return \is_scalar($value); }) ->map(static function ($value) { if ($value === false) { return 'false'; } if ($value === true) { return 'true'; } return (string) $value; }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { $_ENV[$name] = $value; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { unset($_ENV[$name]); return true; } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/MultiReader.php
src/Repository/Adapter/MultiReader.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\None; final class MultiReader implements ReaderInterface { /** * The set of readers to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface[] */ private $readers; /** * Create a new multi-reader instance. * * @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers * * @return void */ public function __construct(array $readers) { $this->readers = $readers; } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { foreach ($this->readers as $reader) { $result = $reader->read($name); if ($result->isDefined()) { return $result; } } return None::create(); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/ReaderInterface.php
src/Repository/Adapter/ReaderInterface.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; interface ReaderInterface { /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name); }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/GuardedWriter.php
src/Repository/Adapter/GuardedWriter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class GuardedWriter implements WriterInterface { /** * The inner writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * The variable name allow list. * * @var string[] */ private $allowList; /** * Create a new guarded writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface $writer * @param string[] $allowList * * @return void */ public function __construct(WriterInterface $writer, array $allowList) { $this->writer = $writer; $this->allowList = $allowList; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { // Don't set non-allowed variables if (!$this->isAllowed($name)) { return false; } // Set the value on the inner writer return $this->writer->write($name, $value); } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { // Don't clear non-allowed variables if (!$this->isAllowed($name)) { return false; } // Set the value on the inner writer return $this->writer->delete($name); } /** * Determine if the given variable is allowed. * * @param non-empty-string $name * * @return bool */ private function isAllowed(string $name) { return \in_array($name, $this->allowList, true); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/src/Repository/Adapter/ApacheAdapter.php
src/Repository/Adapter/ApacheAdapter.php
<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; final class ApacheAdapter implements AdapterInterface { /** * Create a new apache adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { if (self::isSupported()) { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } return None::create(); } /** * Determines if the adapter is supported. * * This happens if PHP is running as an Apache module. * * @return bool */ private static function isSupported() { return \function_exists('apache_getenv') && \function_exists('apache_setenv'); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromValue(apache_getenv($name))->filter(static function ($value) { return \is_string($value) && $value !== ''; }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { return apache_setenv($name, $value); } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { return apache_setenv($name, ''); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/DotenvTest.php
tests/Dotenv/DotenvTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests; use Dotenv\Dotenv; use Dotenv\Exception\InvalidEncodingException; use Dotenv\Exception\InvalidPathException; use Dotenv\Loader\Loader; use Dotenv\Parser\Parser; use Dotenv\Repository\RepositoryBuilder; use Dotenv\Store\StoreBuilder; use PHPUnit\Framework\TestCase; final class DotenvTest extends TestCase { /** * @var string */ private static $folder; /** * @beforeClass * * @return void */ public static function setFolder() { self::$folder = \dirname(__DIR__).'/fixtures/env'; } public function testDotenvThrowsExceptionIfUnableToLoadFile() { $dotenv = Dotenv::createMutable(__DIR__); $this->expectException(InvalidPathException::class); $this->expectExceptionMessage('Unable to read any of the environment file(s) at'); $dotenv->load(); } public function testDotenvThrowsExceptionIfUnableToLoadFiles() { $dotenv = Dotenv::createMutable([__DIR__, __DIR__.'/foo/bar']); $this->expectException(InvalidPathException::class); $this->expectExceptionMessage('Unable to read any of the environment file(s) at'); $dotenv->load(); } public function testDotenvThrowsExceptionWhenNoFiles() { $dotenv = Dotenv::createMutable([]); $this->expectException(InvalidPathException::class); $this->expectExceptionMessage('At least one environment file path must be provided.'); $dotenv->load(); } public function testDotenvTriesPathsToLoad() { $dotenv = Dotenv::createMutable([__DIR__, self::$folder]); self::assertCount(4, $dotenv->load()); } public function testDotenvTriesPathsToLoadTwice() { $dotenv = Dotenv::createMutable([__DIR__, self::$folder]); self::assertCount(4, $dotenv->load()); $dotenv = Dotenv::createImmutable([__DIR__, self::$folder]); self::assertCount(0, $dotenv->load()); } public function testDotenvTriesPathsToSafeLoad() { $dotenv = Dotenv::createMutable([__DIR__, self::$folder]); self::assertCount(4, $dotenv->safeLoad()); } public function testDotenvSkipsLoadingIfFileIsMissing() { $dotenv = Dotenv::createMutable(__DIR__); self::assertSame([], $dotenv->safeLoad()); } public function testDotenvLoadsEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder); self::assertSame( ['FOO' => 'bar', 'BAR' => 'baz', 'SPACED' => 'with spaces', 'NULL' => ''], $dotenv->load() ); self::assertSame('bar', $_SERVER['FOO']); self::assertSame('baz', $_SERVER['BAR']); self::assertSame('with spaces', $_SERVER['SPACED']); self::assertEmpty($_SERVER['NULL']); } public function testDotenvLoadsEnvironmentVarsMultipleWithShortCircuitMode() { $dotenv = Dotenv::createMutable(self::$folder, ['.env', 'example.env']); self::assertSame( ['FOO' => 'bar', 'BAR' => 'baz', 'SPACED' => 'with spaces', 'NULL' => ''], $dotenv->load() ); } public function testDotenvLoadsEnvironmentVarsMultipleWithoutShortCircuitMode() { $dotenv = Dotenv::createMutable(self::$folder, ['.env', 'example.env'], false); self::assertSame( ['FOO' => 'bar', 'BAR' => 'baz', 'SPACED' => 'with spaces', 'NULL' => '', 'EG' => 'example'], $dotenv->load() ); } public function testCommentedDotenvLoadsEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder, 'commented.env'); $dotenv->load(); self::assertSame('bar', $_SERVER['CFOO']); self::assertFalse(isset($_SERVER['CBAR'])); self::assertFalse(isset($_SERVER['CZOO'])); self::assertSame('with spaces', $_SERVER['CSPACED']); self::assertSame('a value with a # character', $_SERVER['CQUOTES']); self::assertSame('a value with a # character & a quote " character inside quotes', $_SERVER['CQUOTESWITHQUOTE']); self::assertEmpty($_SERVER['CNULL']); self::assertEmpty($_SERVER['EMPTY']); self::assertEmpty($_SERVER['EMPTY2']); self::assertSame('foo', $_SERVER['FOOO']); } public function testQuotedDotenvLoadsEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder, 'quoted.env'); $dotenv->load(); self::assertSame('bar', $_SERVER['QFOO']); self::assertSame('baz', $_SERVER['QBAR']); self::assertSame('with spaces', $_SERVER['QSPACED']); self::assertEmpty(\getenv('QNULL')); self::assertSame('pgsql:host=localhost;dbname=test', $_SERVER['QEQUALS']); self::assertSame('test some escaped characters like a quote (") or maybe a backslash (\\)', $_SERVER['QESCAPED']); self::assertSame('iiiiviiiixiiiiviiii\\n', $_SERVER['QSLASH']); self::assertSame('iiiiviiiixiiiiviiii\\\\n', $_SERVER['SQSLASH']); } public function testLargeDotenvLoadsEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder, 'large.env'); $dotenv->load(); self::assertSame(2730, \strlen($_SERVER['LARGE'])); self::assertSame(8192, \strlen($_SERVER['HUGE'])); } public function testDotenvLoadsMultibyteVars() { $dotenv = Dotenv::createMutable(self::$folder, 'multibyte.env'); $dotenv->load(); self::assertSame('Ā ā Ă ă Ą ą Ć ć Ĉ ĉ Ċ ċ Č č Ď ď Đ đ Ē ē Ĕ ĕ Ė ė Ę ę Ě ě', $_SERVER['MB1']); self::assertSame('行内支付', $_SERVER['MB2']); self::assertSame('🚀', $_SERVER['APP_ENV']); } public function testDotenvLoadsMultibyteUTF8Vars() { $dotenv = Dotenv::createMutable(self::$folder, 'multibyte.env', false, 'UTF-8'); $dotenv->load(); self::assertSame('Ā ā Ă ă Ą ą Ć ć Ĉ ĉ Ċ ċ Č č Ď ď Đ đ Ē ē Ĕ ĕ Ė ė Ę ę Ě ě', $_SERVER['MB1']); self::assertSame('行内支付', $_SERVER['MB2']); self::assertSame('🚀', $_SERVER['APP_ENV']); } public function testDotenvLoadWithInvalidEncoding() { $dotenv = Dotenv::createMutable(self::$folder, 'multibyte.env', false, 'UTF-88'); $this->expectException(InvalidEncodingException::class); $this->expectExceptionMessage('Illegal character encoding [UTF-88] specified.'); $dotenv->load(); } public function testDotenvLoadsMultibyteWindowsVars() { $dotenv = Dotenv::createMutable(self::$folder, 'windows.env', false, 'Windows-1252'); $dotenv->load(); self::assertSame('ñá', $_SERVER['MBW']); } public function testMultipleDotenvLoadsEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder, 'multiple.env'); $dotenv->load(); self::assertSame('bar', $_SERVER['MULTI1']); self::assertSame('foo', $_SERVER['MULTI2']); } public function testExportedDotenvLoadsEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder, 'exported.env'); $dotenv->load(); self::assertSame('bar', $_SERVER['EFOO']); self::assertSame('baz', $_SERVER['EBAR']); self::assertSame('with spaces', $_SERVER['ESPACED']); self::assertSame('123', $_SERVER['EDQUOTED']); self::assertSame('456', $_SERVER['ESQUOTED']); self::assertEmpty($_SERVER['ENULL']); } public function testDotenvLoadsEnvGlobals() { $dotenv = Dotenv::createMutable(self::$folder); $dotenv->load(); self::assertSame('bar', $_SERVER['FOO']); self::assertSame('baz', $_SERVER['BAR']); self::assertSame('with spaces', $_SERVER['SPACED']); self::assertEmpty($_SERVER['NULL']); } public function testDotenvLoadsServerGlobals() { $dotenv = Dotenv::createMutable(self::$folder); $dotenv->load(); self::assertSame('bar', $_ENV['FOO']); self::assertSame('baz', $_ENV['BAR']); self::assertSame('with spaces', $_ENV['SPACED']); self::assertEmpty($_ENV['NULL']); } public function testDotenvNestedEnvironmentVars() { $dotenv = Dotenv::createMutable(self::$folder, 'nested.env'); $dotenv->load(); self::assertSame('{$NVAR1} {$NVAR2}', $_ENV['NVAR3']); // not resolved self::assertSame('Hellō World!', $_ENV['NVAR4']); self::assertSame('$NVAR1 {NVAR2}', $_ENV['NVAR5']); // not resolved self::assertSame('Special Value', $_ENV['N.VAR6']); // new '.' (dot) in var name self::assertSame('Special Value', $_ENV['NVAR7']); // nested '.' (dot) variable self::assertSame('', $_ENV['NVAR8']); // nested variable is empty string self::assertSame('', $_ENV['NVAR9']); // nested variable is empty string self::assertSame('${NVAR888}', $_ENV['NVAR10']); // nested variable is not set self::assertSame('NVAR1', $_ENV['NVAR11']); self::assertSame('Hellō', $_ENV['NVAR12']); self::assertSame('${${NVAR11}}', $_ENV['NVAR13']); // single quotes self::assertSame('${NVAR1} ${NVAR2}', $_ENV['NVAR14']); // single quotes self::assertSame('${NVAR1} ${NVAR2}', $_ENV['NVAR15']); // escaped } public function testDotenvNullFileArgumentUsesDefault() { $dotenv = Dotenv::createMutable(self::$folder, null); $dotenv->load(); self::assertSame('bar', $_SERVER['FOO']); } /** * The fixture data has whitespace between the key and in the value string. * * Test that these keys are trimmed down. */ public function testDotenvTrimmedKeys() { $dotenv = Dotenv::createMutable(self::$folder, 'quoted.env'); $dotenv->load(); self::assertSame('no space', $_SERVER['QWHITESPACE']); } public function testDotenvLoadDoesNotOverwriteEnv() { \putenv('IMMUTABLE=true'); $dotenv = Dotenv::createImmutable(self::$folder, 'immutable.env'); $dotenv->load(); self::assertSame('true', \getenv('IMMUTABLE')); } public function testDotenvLoadAfterOverload() { \putenv('IMMUTABLE=true'); $dotenv = Dotenv::createUnsafeMutable(self::$folder, 'immutable.env'); $dotenv->load(); self::assertSame('false', \getenv('IMMUTABLE')); } public function testDotenvOverloadAfterLoad() { \putenv('IMMUTABLE=true'); $dotenv = Dotenv::createUnsafeImmutable(self::$folder, 'immutable.env'); $dotenv->load(); self::assertSame('true', \getenv('IMMUTABLE')); } public function testDotenvOverloadDoesOverwriteEnv() { $dotenv = Dotenv::createUnsafeMutable(self::$folder, 'mutable.env'); $dotenv->load(); self::assertSame('true', \getenv('MUTABLE')); } public function testDotenvAllowsSpecialCharacters() { $dotenv = Dotenv::createUnsafeMutable(self::$folder, 'specialchars.env'); $dotenv->load(); self::assertSame('$a6^C7k%zs+e^.jvjXk', \getenv('SPVAR1')); self::assertSame('?BUty3koaV3%GA*hMAwH}B', \getenv('SPVAR2')); self::assertSame('jdgEB4{QgEC]HL))&GcXxokB+wqoN+j>xkV7K?m$r', \getenv('SPVAR3')); self::assertSame('22222:22#2^{', \getenv('SPVAR4')); self::assertSame('test some escaped characters like a quote " or maybe a backslash \\', \getenv('SPVAR5')); self::assertSame('secret!@', \getenv('SPVAR6')); self::assertSame('secret!@#', \getenv('SPVAR7')); self::assertSame('secret!@#', \getenv('SPVAR8')); } public function testMultilineLoading() { $dotenv = Dotenv::createUnsafeMutable(self::$folder, 'multiline.env'); $dotenv->load(); self::assertSame("test\n test\"test\"\n test", \getenv('TEST')); self::assertSame("test\ntest", \getenv('TEST_ND')); self::assertSame('test\\ntest', \getenv('TEST_NS')); self::assertSame('https://vision.googleapis.com/v1/images:annotate?key=', \getenv('TEST_EQD')); self::assertSame('https://vision.googleapis.com/v1/images:annotate?key=', \getenv('TEST_EQS')); } public function testEmptyLoading() { $dotenv = Dotenv::createImmutable(self::$folder, 'empty.env'); self::assertSame(['EMPTY_VAR' => null], $dotenv->load()); } public function testUnicodeVarNames() { $dotenv = Dotenv::createImmutable(self::$folder, 'unicodevarnames.env'); $dotenv->load(); self::assertSame('Skybert', $_SERVER['AlbertÅberg']); self::assertSame('2022-04-01T00:00', $_SERVER['ДатаЗакрытияРасчетногоПериода']); } public function testDirectConstructor() { $repository = RepositoryBuilder::createWithDefaultAdapters()->make(); $store = StoreBuilder::createWithDefaultName()->addPath(self::$folder)->make(); $dotenv = new Dotenv($store, new Parser(), new Loader(), $repository); self::assertSame([ 'FOO' => 'bar', 'BAR' => 'baz', 'SPACED' => 'with spaces', 'NULL' => '', ], $dotenv->load()); } public function testDotenvParseExample1() { $output = Dotenv::parse( "BASE_DIR=\"/var/webroot/project-root\"\nCACHE_DIR=\"\${BASE_DIR}/cache\"\nTMP_DIR=\"\${BASE_DIR}/tmp\"\n" ); self::assertSame($output, [ 'BASE_DIR' => '/var/webroot/project-root', 'CACHE_DIR' => '/var/webroot/project-root/cache', 'TMP_DIR' => '/var/webroot/project-root/tmp', ]); } public function testDotenvParseExample2() { $output = Dotenv::parse("FOO=Bar\nBAZ=\"Hello \${FOO}\""); self::assertSame($output, ['FOO' => 'Bar', 'BAZ' => 'Hello Bar']); } public function testDotenvParseEmptyCase() { $output = Dotenv::parse(''); self::assertSame($output, []); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/ValidatorTest.php
tests/Dotenv/ValidatorTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests; use Dotenv\Dotenv; use Dotenv\Exception\ValidationException; use Dotenv\Repository\Adapter\ArrayAdapter; use Dotenv\Repository\RepositoryBuilder; use PHPUnit\Framework\TestCase; final class ValidatorTest extends TestCase { /** * @var string */ private static $folder; /** * @beforeClass * * @return void */ public static function setFolder() { self::$folder = \dirname(__DIR__).'/fixtures/env'; } /** * @param string $name * * @return array{\Dotenv\Repository\RepositoryInterface,\Dotenv\Dotenv} */ public static function createArrayDotenv(string $name = '.env') { $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); return [$repository, Dotenv::create($repository, self::$folder, $name)]; } /** * @doesNotPerformAssertions */ public function testDotenvRequiredStringEnvironmentVars() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $dotenv->required('FOO'); } /** * @doesNotPerformAssertions */ public function testDotenvAllowedValues() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $dotenv->required('FOO')->allowedValues(['bar', 'baz']); } /** * @doesNotPerformAssertions */ public function testDotenvAllowedValuesIfPresent() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $dotenv->ifPresent('FOO')->allowedValues(['bar', 'baz']); } /** * @doesNotPerformAssertions */ public function testDotenvAllowedValuesIfNotPresent() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $dotenv->ifPresent('FOOQWERTYOOOOOO')->allowedValues(['bar', 'baz']); } public function testDotenvProhibitedValues() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: FOO is not one of [buzz, buz].'); $dotenv->required('FOO')->allowedValues(['buzz', 'buz']); } public function testDotenvProhibitedValuesIfPresent() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: FOO is not one of [buzz, buz].'); $dotenv->ifPresent('FOO')->allowedValues(['buzz', 'buz']); } public function testDotenvRequiredThrowsRuntimeException() { [$repo, $dotenv] = self::createArrayDotenv(); $dotenv->load(); self::assertFalse($repo->has('FOOX')); self::assertFalse($repo->has('NOPE')); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: FOOX is missing, NOPE is missing.'); $dotenv->required(['FOOX', 'NOPE']); } /** * @doesNotPerformAssertions */ public function testDotenvRequiredArrayEnvironmentVars() { $dotenv = self::createArrayDotenv()[1]; $dotenv->load(); $dotenv->required(['FOO', 'BAR']); } public function testDotenvAssertions() { [$repo, $dotenv] = self::createArrayDotenv('assertions.env'); $dotenv->load(); self::assertSame('val1', $repo->get('ASSERTVAR1')); self::assertSame('', $repo->get('ASSERTVAR2')); self::assertSame('val3 ', $repo->get('ASSERTVAR3')); self::assertSame('0', $repo->get('ASSERTVAR4')); self::assertSame('#foo', $repo->get('ASSERTVAR5')); self::assertSame("val1\nval2", $repo->get('ASSERTVAR6')); self::assertSame("\nval3", $repo->get('ASSERTVAR7')); self::assertSame("val3\n", $repo->get('ASSERTVAR8')); $dotenv->required([ 'ASSERTVAR1', 'ASSERTVAR2', 'ASSERTVAR3', 'ASSERTVAR4', 'ASSERTVAR5', 'ASSERTVAR6', 'ASSERTVAR7', 'ASSERTVAR8', 'ASSERTVAR9', ]); $dotenv->required([ 'ASSERTVAR1', 'ASSERTVAR3', 'ASSERTVAR4', 'ASSERTVAR5', 'ASSERTVAR6', 'ASSERTVAR7', 'ASSERTVAR8', ])->notEmpty(); $dotenv->required([ 'ASSERTVAR1', 'ASSERTVAR4', 'ASSERTVAR5', ])->notEmpty()->allowedValues(['0', 'val1', '#foo']); } public function testDotenvEmptyThrowsRuntimeException() { $dotenv = self::createArrayDotenv('assertions.env')[1]; $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: ASSERTVAR2 is empty.'); $dotenv->required('ASSERTVAR2')->notEmpty(); } /** * @doesNotPerformAssertions */ public function testDotenvEmptyWhenNotPresent() { $dotenv = self::createArrayDotenv('assertions.env')[1]; $dotenv->load(); $dotenv->ifPresent('ASSERTVAR2_NO_SUCH_VARIABLE')->notEmpty(); } public function testDotenvStringOfSpacesConsideredEmpty() { $dotenv = self::createArrayDotenv('assertions.env')[1]; $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: ASSERTVAR9 is empty.'); $dotenv->required('ASSERTVAR9')->notEmpty(); } /** * List of valid boolean values in fixtures/env/booleans.env. * * @return string[][] */ public static function validBooleanValuesDataProvider() { return [ ['VALID_EXPLICIT_LOWERCASE_TRUE'], ['VALID_EXPLICIT_LOWERCASE_FALSE'], ['VALID_EXPLICIT_UPPERCASE_TRUE'], ['VALID_EXPLICIT_UPPERCASE_FALSE'], ['VALID_EXPLICIT_MIXEDCASE_TRUE'], ['VALID_EXPLICIT_MIXEDCASE_FALSE'], ['VALID_NUMBER_TRUE'], ['VALID_NUMBER_FALSE'], ['VALID_ONOFF_LOWERCASE_TRUE'], ['VALID_ONOFF_LOWERCASE_FALSE'], ['VALID_ONOFF_UPPERCASE_TRUE'], ['VALID_ONOFF_UPPERCASE_FALSE'], ['VALID_ONOFF_MIXEDCASE_TRUE'], ['VALID_ONOFF_MIXEDCASE_FALSE'], ['VALID_YESNO_LOWERCASE_TRUE'], ['VALID_YESNO_LOWERCASE_FALSE'], ['VALID_YESNO_UPPERCASE_TRUE'], ['VALID_YESNO_UPPERCASE_FALSE'], ['VALID_YESNO_MIXEDCASE_TRUE'], ['VALID_YESNO_MIXEDCASE_FALSE'], ]; } /** * @dataProvider validBooleanValuesDataProvider * @doesNotPerformAssertions */ public function testCanValidateBooleans(string $boolean) { $dotenv = Dotenv::createImmutable(self::$folder, 'booleans.env'); $dotenv->load(); $dotenv->required($boolean)->isBoolean(); } /** * @dataProvider validBooleanValuesDataProvider * @doesNotPerformAssertions */ public function testCanValidateBooleansIfPresent(string $boolean) { $dotenv = Dotenv::createImmutable(self::$folder, 'booleans.env'); $dotenv->load(); $dotenv->ifPresent($boolean)->isBoolean(); } /** * List of non-boolean values in fixtures/env/booleans.env. * * @return string[][] */ public static function invalidBooleanValuesDataProvider() { return [ ['INVALID_SOMETHING'], ['INVALID_EMPTY'], ['INVALID_EMPTY_STRING'], ['INVALID_NULL'], ['INVALID_NUMBER_POSITIVE'], ['INVALID_NUMBER_NEGATIVE'], ['INVALID_MINUS'], ['INVALID_TILDA'], ['INVALID_EXCLAMATION'], ]; } /** * @dataProvider invalidBooleanValuesDataProvider */ public function testCanInvalidateNonBooleans(string $boolean) { $dotenv = Dotenv::createImmutable(self::$folder, 'booleans.env'); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: INVALID_'); $dotenv->required($boolean)->isBoolean(); } /** * @dataProvider invalidBooleanValuesDataProvider */ public function testCanInvalidateNonBooleansIfPresent(string $boolean) { $dotenv = Dotenv::createImmutable(self::$folder, 'booleans.env'); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: INVALID_'); $dotenv->ifPresent($boolean)->isBoolean(); } public function testCanInvalidateBooleanNonExist() { $dotenv = Dotenv::createImmutable(self::$folder, 'booleans.env'); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: VAR_DOES_NOT_EXIST_234782462764'); $dotenv->required(['VAR_DOES_NOT_EXIST_234782462764'])->isBoolean(); } /** * @doesNotPerformAssertions */ public function testIfPresentBooleanNonExist() { $dotenv = Dotenv::createImmutable(self::$folder, 'booleans.env'); $dotenv->load(); $dotenv->ifPresent(['VAR_DOES_NOT_EXIST_234782462764'])->isBoolean(); } /** * List of valid integer values in fixtures/env/integers.env. * * @return string[][] */ public static function validIntegerValuesDataProvider() { return [ ['VALID_ZERO'], ['VALID_ONE'], ['VALID_TWO'], ['VALID_LARGE'], ['VALID_HUGE'], ]; } /** * @dataProvider validIntegerValuesDataProvider * @doesNotPerformAssertions */ public function testCanValidateIntegers(string $integer) { $dotenv = Dotenv::createImmutable(self::$folder, 'integers.env'); $dotenv->load(); $dotenv->required($integer)->isInteger(); } /** * @dataProvider validIntegerValuesDataProvider * @doesNotPerformAssertions */ public function testCanValidateIntegersIfPresent(string $integer) { $dotenv = Dotenv::createImmutable(self::$folder, 'integers.env'); $dotenv->load(); $dotenv->ifPresent($integer)->isInteger(); } /** * List of non-integer values in fixtures/env/integers.env. * * @return string[][] */ public static function invalidIntegerValuesDataProvider() { return [ ['INVALID_SOMETHING'], ['INVALID_EMPTY'], ['INVALID_EMPTY_STRING'], ['INVALID_NULL'], ['INVALID_NEGATIVE'], ['INVALID_MINUS'], ['INVALID_TILDA'], ['INVALID_EXCLAMATION'], ['INVALID_SPACES'], ['INVALID_COMMAS'], ]; } /** * @dataProvider invalidIntegerValuesDataProvider */ public function testCanInvalidateNonIntegers(string $integer) { $dotenv = Dotenv::createImmutable(self::$folder, 'integers.env'); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: INVALID_'); $dotenv->required($integer)->isInteger(); } /** * @dataProvider invalidIntegerValuesDataProvider */ public function testCanInvalidateNonIntegersIfExist(string $integer) { $dotenv = Dotenv::createImmutable(self::$folder, 'integers.env'); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: INVALID_'); $dotenv->ifPresent($integer)->isInteger(); } public function testCanInvalidateIntegerNonExist() { $dotenv = Dotenv::createImmutable(self::$folder, 'integers.env'); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: VAR_DOES_NOT_EXIST_234782462764'); $dotenv->required(['VAR_DOES_NOT_EXIST_234782462764'])->isInteger(); } /** * @doesNotPerformAssertions */ public function testIfPresentIntegerNonExist() { $dotenv = Dotenv::createImmutable(self::$folder, 'integers.env'); $dotenv->load(); $dotenv->ifPresent(['VAR_DOES_NOT_EXIST_234782462764'])->isInteger(); } /** * @doesNotPerformAssertions */ public function testDotenvRegexMatchPass() { $dotenv = Dotenv::createImmutable(self::$folder); $dotenv->load(); $dotenv->required('FOO')->allowedRegexValues('([[:lower:]]{3})'); } public function testDotenvRegexMatchFail() { $dotenv = Dotenv::createImmutable(self::$folder); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: FOO does not match "/^([[:lower:]]{1})$/".'); $dotenv->required('FOO')->allowedRegexValues('/^([[:lower:]]{1})$/'); } public function testDotenvRegexMatchError() { $dotenv = Dotenv::createImmutable(self::$folder); $dotenv->load(); $this->expectException(ValidationException::class); $this->expectExceptionMessage('One or more environment variables failed assertions: FOO does not match "/([[:lower:]{1{".'); $dotenv->required('FOO')->allowedRegexValues('/([[:lower:]{1{'); } /** * @doesNotPerformAssertions */ public function testDotenvRegexMatchNotPresent() { $dotenv = Dotenv::createImmutable(self::$folder); $dotenv->load(); $dotenv->ifPresent('FOOOOOOOOOOO')->allowedRegexValues('([[:lower:]]{3})'); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Parser/LinesTest.php
tests/Dotenv/Parser/LinesTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Parser; use Dotenv\Parser\Lines; use Dotenv\Util\Regex; use PHPUnit\Framework\TestCase; final class LinesTest extends TestCase { public function testProcessBasic() { $content = \file_get_contents(\dirname(\dirname(__DIR__)).'/fixtures/env/assertions.env'); self::assertIsString($content); $result = Regex::split("/(\r\n|\n|\r)/", $content); self::assertTrue($result->success()->isDefined()); $expected = [ 'ASSERTVAR1=val1', 'ASSERTVAR2=""', 'ASSERTVAR3="val3 "', 'ASSERTVAR4="0" # empty looking value', 'ASSERTVAR5="#foo"', "ASSERTVAR6=\"val1\nval2\"", "ASSERTVAR7=\"\nval3\" #", "ASSERTVAR8=\"val3\n\"", "ASSERTVAR9=\"\n\n\"", ]; self::assertSame($expected, Lines::process($result->success()->get())); } public function testProcessQuotes() { $content = \file_get_contents(\dirname(\dirname(__DIR__)).'/fixtures/env/multiline.env'); self::assertIsString($content); $result = Regex::split("/(\r\n|\n|\r)/", $content); self::assertTrue($result->success()->isDefined()); $expected = [ "TEST=\"test\n test\\\"test\\\"\n test\"", 'TEST_ND="test\\ntest"', 'TEST_NS=\'test\\ntest\'', 'TEST_EQD="https://vision.googleapis.com/v1/images:annotate?key="', 'TEST_EQS=\'https://vision.googleapis.com/v1/images:annotate?key=\'', "BASE64_ENCODED_MULTILINE=\"qS1zCzMVVUJWQShokv6YVYi+ruKSC/bHV7GmEiyVkLaBWJHNVHCHsgTksEBsy8wJ\nuwycAvR07ZyOJJed4XTRMKnKp1/v+6UATpWzkIjZXytK+pD+XlZimUHTx3uiDcmU\njhQX1wWSxHDqrSWxeIJiTD+BuUyId8FzmXQ3TcBydJ474tmOU2F492ubk3LAiZ18\nmhiRGoshXAOSbS/P3+RZi4bDeNE/No4=\"", ]; self::assertSame($expected, Lines::process($result->success()->get())); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Parser/EntryParserTest.php
tests/Dotenv/Parser/EntryParserTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Parser; use Dotenv\Parser\Entry; use Dotenv\Parser\EntryParser; use Dotenv\Parser\Value; use GrahamCampbell\ResultType\Result; use PHPUnit\Framework\TestCase; final class EntryParserTest extends TestCase { public function testBasicParse() { $result = EntryParser::parse('FOO=BAR'); $this->checkPositiveResult($result, 'FOO', 'BAR'); } public function testNullParse() { $result = EntryParser::parse('FOO'); $this->checkEmptyResult($result, 'FOO'); } public function testUnicodeNameParse() { $result = EntryParser::parse('FOOƱ=BAZ'); $this->checkPositiveResult($result, 'FOOƱ', 'BAZ'); } public function testQuotesParse() { $result = EntryParser::parse("FOO=\"BAR \n\""); $this->checkPositiveResult($result, 'FOO', "BAR \n"); } public function testNewlineParse() { $result = EntryParser::parse('FOO="\n"'); $this->checkPositiveResult($result, 'FOO', "\n"); } public function testTabParseDouble() { $result = EntryParser::parse('FOO="\t"'); $this->checkPositiveResult($result, 'FOO', "\t"); } public function testTabParseSingle() { $result = EntryParser::parse('FOO=\'\t\''); $this->checkPositiveResult($result, 'FOO', '\t'); } public function testNonEscapeParse1() { $result = EntryParser::parse('FOO=\n\v'); $this->checkPositiveResult($result, 'FOO', '\n\v'); } public function testNonEscapeParse2() { $result = EntryParser::parse('FOO=\q'); $this->checkPositiveResult($result, 'FOO', '\q'); } public function testBadEscapeParse() { $result = EntryParser::parse('FOO="\q"'); $this->checkErrorResult($result, 'Encountered an unexpected escape sequence at ["\q"].'); } public function testInlineVariable() { $result = EntryParser::parse('FOO=$BAR'); $this->checkPositiveResult($result, 'FOO', '$BAR', [0]); } public function testInlineVariableOffset() { $result = EntryParser::parse('FOO=AAA$BAR'); $this->checkPositiveResult($result, 'FOO', 'AAA$BAR', [3]); } public function testInlineVariables() { $result = EntryParser::parse('FOO="TEST $BAR $$BAZ"'); $this->checkPositiveResult($result, 'FOO', 'TEST $BAR $$BAZ', [11, 10, 5]); } public function testNonInlineVariable() { $result = EntryParser::parse('FOO=\'TEST $BAR $$BAZ\''); $this->checkPositiveResult($result, 'FOO', 'TEST $BAR $$BAZ'); self::assertTrue($result->success()->isDefined()); } public function testWhitespaceParse() { $result = EntryParser::parse("FOO=\"\n\""); $this->checkPositiveResult($result, 'FOO', "\n"); } public function testExportParse() { $result = EntryParser::parse('export FOO="bar baz"'); $this->checkPositiveResult($result, 'FOO', 'bar baz'); } public function testExportParseTab() { $result = EntryParser::parse("export\t\"FOO\"='bar baz'"); $this->checkPositiveResult($result, 'FOO', 'bar baz'); } public function testExportParseFail() { $result = EntryParser::parse('export "FOO="bar baz"'); $this->checkErrorResult($result, 'Encountered an invalid name at ["FOO].'); } public function testClosingSlashParse() { $result = EntryParser::parse('SPVAR5="test some escaped characters like a quote \\" or maybe a backslash \\\\" # not escaped'); $this->checkPositiveResult($result, 'SPVAR5', 'test some escaped characters like a quote " or maybe a backslash \\'); } public function testParseInvalidSpaces() { $result = EntryParser::parse('FOO=bar baz'); $this->checkErrorResult($result, 'Encountered unexpected whitespace at [bar baz].'); } public function testParseStrayEquals() { $result = EntryParser::parse('='); $this->checkErrorResult($result, 'Encountered an unexpected equals at [=].'); } public function testParseInvalidName() { $result = EntryParser::parse('FOO_ASD!=BAZ'); $this->checkErrorResult($result, 'Encountered an invalid name at [FOO_ASD!].'); } public function testParserEscapingDouble() { $result = EntryParser::parse('FOO_BAD="iiiiviiiixiiiiviiii\\a"'); $this->checkErrorResult($result, 'Encountered an unexpected escape sequence at ["iiiiviiiixiiiiviiii\a"].'); } public function testParserEscapingSingle() { $result = EntryParser::parse('FOO_BAD=\'iiiiviiiixiiiiviiii\\a\''); $this->checkPositiveResult($result, 'FOO_BAD', 'iiiiviiiixiiiiviiii\\a'); } public function testParserMissingClosingSingleQuote() { $result = EntryParser::parse('TEST=\'erert'); $this->checkErrorResult($result, 'Encountered a missing closing quote at [\'erert].'); } public function testParserMissingClosingDoubleQuote() { $result = EntryParser::parse('TEST="erert'); $this->checkErrorResult($result, 'Encountered a missing closing quote at ["erert].'); } public function testParserMissingClosingQuotes() { $result = EntryParser::parse("TEST=\"erert\nTEST='erert\n"); $this->checkErrorResult($result, 'Encountered a missing closing quote at ["erert].'); } public function testParserClosingQuoteWithEscape() { $result = EntryParser::parse('TEST="\\'); $this->checkErrorResult($result, 'Encountered a missing closing quote at ["\\].'); } /** * @param \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry,string> $result * @param string $name * @param string $chars * @param int[] $vars * * @return void */ private function checkPositiveResult(Result $result, string $name, string $chars, array $vars = []) { self::assertTrue($result->success()->isDefined()); $entry = $result->success()->get(); self::assertInstanceOf(Entry::class, $entry); self::assertSame($name, $entry->getName()); self::assertTrue($entry->getValue()->isDefined()); $value = $entry->getValue()->get(); self::assertInstanceOf(Value::class, $value); self::assertSame($chars, $value->getChars()); self::assertSame($vars, $value->getVars()); } /** * @param \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry,string> $result * @param string $name * * @return void */ private function checkEmptyResult(Result $result, string $name) { self::assertTrue($result->success()->isDefined()); $entry = $result->success()->get(); self::assertInstanceOf(Entry::class, $entry); self::assertSame('FOO', $entry->getName()); self::assertFalse($entry->getValue()->isDefined()); } /** * @param \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry,string> $result * @param string $error * * @return void */ private function checkErrorResult(Result $result, string $error) { self::assertTrue($result->error()->isDefined()); self::assertSame($error, $result->error()->get()); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Parser/LexerTest.php
tests/Dotenv/Parser/LexerTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Parser; use Dotenv\Parser\Lexer; use PHPUnit\Framework\TestCase; final class LexerTest extends TestCase { /** * @return array{string,string[]}[] */ public static function provideLexCases() { return [ ['', []], ['FOO', ['FOO']], ['FOO bar', ['FOO', ' ', 'bar']], ['FOO\\n()ab', ['FOO', '\\', 'n()ab']], ["FOO\n\n A", ['FOO', "\n\n", ' ', 'A']], ['"VA=L"', ['"', 'VA=L', '"']], ['\' \'', ['\'', ' ', '\'']], ]; } /** * @dataProvider provideLexCases * * @param string $input * @param string[] $output * * @return void */ public function testLex(string $input, array $output) { self::assertSame($output, \iterator_to_array(Lexer::lex($input))); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Parser/ParserTest.php
tests/Dotenv/Parser/ParserTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Parser; use Dotenv\Exception\InvalidFileException; use Dotenv\Parser\Entry; use Dotenv\Parser\Parser; use Dotenv\Parser\ParserInterface; use Dotenv\Parser\Value; use PHPUnit\Framework\TestCase; final class ParserTest extends TestCase { public function testParserInstanceOf() { self::assertInstanceOf(ParserInterface::class, new Parser()); } public function testFullParse() { $result = (new Parser())->parse("FOO=BAR\nFOO\nFOO=\"BAR \n\"\nFOO=\"\\n\""); self::assertIsArray($result); self::assertCount(4, $result); $this->checkPositiveEntry($result[0], 'FOO', 'BAR'); $this->checkEmptyEntry($result[1], 'FOO'); $this->checkPositiveEntry($result[2], 'FOO', "BAR \n"); $this->checkPositiveEntry($result[3], 'FOO', "\n"); } public function testBadEscapeParse() { $this->expectException(InvalidFileException::class); $this->expectExceptionMessage('Failed to parse dotenv file. Encountered an unexpected escape sequence at ["\q"].'); (new Parser())->parse('FOO="\q"'); } public function testParseInvalidSpaces() { $this->expectException(InvalidFileException::class); $this->expectExceptionMessage('Failed to parse dotenv file. Encountered unexpected whitespace at [bar baz].'); (new Parser())->parse("FOO=bar baz\n"); } public function testParseStrayEquals() { $this->expectException(InvalidFileException::class); $this->expectExceptionMessage('Failed to parse dotenv file. Encountered an unexpected equals at [=].'); (new Parser())->parse("=\n"); } public function testParseInvalidName() { $this->expectException(InvalidFileException::class); $this->expectExceptionMessage('Failed to parse dotenv file. Encountered an invalid name at [FOO_ASD!].'); (new Parser())->parse('FOO_ASD!=BAZ'); } /** * @param \Dotenv\Parser\Entry $entry * @param string $name * @param string $chars * @param int[] $vars * * @return void */ private function checkPositiveEntry(Entry $entry, string $name, string $chars, array $vars = []) { self::assertInstanceOf(Entry::class, $entry); self::assertSame($name, $entry->getName()); self::assertTrue($entry->getValue()->isDefined()); $value = $entry->getValue()->get(); self::assertInstanceOf(Value::class, $value); self::assertSame($chars, $value->getChars()); self::assertSame($vars, $value->getVars()); } /** * @param \Dotenv\Parser\Entry $entry * @param string $name * * @return void */ private function checkEmptyEntry(Entry $entry, string $name) { self::assertInstanceOf(Entry::class, $entry); self::assertSame('FOO', $entry->getName()); self::assertFalse($entry->getValue()->isDefined()); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Loader/LoaderTest.php
tests/Dotenv/Loader/LoaderTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Loader; use Dotenv\Exception\InvalidFileException; use Dotenv\Loader\Loader; use Dotenv\Loader\LoaderInterface; use Dotenv\Parser\Parser; use Dotenv\Repository\Adapter\ArrayAdapter; use Dotenv\Repository\Adapter\EnvConstAdapter; use Dotenv\Repository\Adapter\ServerConstAdapter; use Dotenv\Repository\RepositoryBuilder; use PHPUnit\Framework\TestCase; final class LoaderTest extends TestCase { public function testParserInstanceOf() { self::assertInstanceOf(LoaderInterface::class, new Loader()); } public function testLoaderWithNoReaders() { $repository = RepositoryBuilder::createWithNoAdapters()->addWriter(ArrayAdapter::class)->make(); $loader = new Loader(); $content = "NVAR1=\"Hello\"\nNVAR2=\"World!\"\nNVAR3=\"{\$NVAR1} {\$NVAR2}\"\nNVAR4=\"\${NVAR1} \${NVAR2}\""; $expected = ['NVAR1' => 'Hello', 'NVAR2' => 'World!', 'NVAR3' => '{$NVAR1} {$NVAR2}', 'NVAR4' => '${NVAR1} ${NVAR2}']; self::assertSame($expected, $loader->load($repository, (new Parser())->parse($content))); } public function testLoaderWithAllowList() { $adapter = ArrayAdapter::create()->get(); $repository = RepositoryBuilder::createWithNoAdapters()->addReader($adapter)->addWriter($adapter)->allowList(['FOO'])->make(); $loader = new Loader(); self::assertSame(['FOO' => 'Hello'], $loader->load($repository, (new Parser())->parse("FOO=\"Hello\"\nBAR=\"World!\"\n"))); self::assertTrue($adapter->read('FOO')->isDefined()); self::assertSame('Hello', $adapter->read('FOO')->get()); self::assertFalse($adapter->read('BAR')->isDefined()); } public function testLoaderWithGarbage() { $adapter = ArrayAdapter::create()->get(); $repository = RepositoryBuilder::createWithNoAdapters()->make(); $loader = new Loader(); $this->expectException(InvalidFileException::class); $this->expectExceptionMessage('Failed to parse dotenv file. Encountered unexpected whitespace at ["""].'); $loader->load($repository, (new Parser())->parse('FOO="""')); } /** * @return array<int,\Dotenv\Repository\Adapter\AdapterInterface|string>[] */ public static function providesAdapters() { return [ [ArrayAdapter::create()->get()], [EnvConstAdapter::class], [ServerConstAdapter::class], ]; } /** * @dataProvider providesAdapters * * @param \Dotenv\Repository\Adapter\AdapterInterface|string $adapter */ public function testLoaderWithSpecificAdapter($adapter) { $repository = RepositoryBuilder::createWithNoAdapters()->addReader($adapter)->addWriter($adapter)->make(); $loader = new Loader(); $content = "NVAR1=\"Hello\"\nNVAR2=\"World!\"\nNVAR3=\"{\$NVAR1} {\$NVAR2}\"\nNVAR4=\"\${NVAR1} \${NVAR2}\""; $expected = ['NVAR1' => 'Hello', 'NVAR2' => 'World!', 'NVAR3' => '{$NVAR1} {$NVAR2}', 'NVAR4' => 'Hello World!']; self::assertSame($expected, $loader->load($repository, (new Parser())->parse($content))); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Store/StoreTest.php
tests/Dotenv/Store/StoreTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Store; use Dotenv\Exception\InvalidEncodingException; use Dotenv\Store\File\Paths; use Dotenv\Store\File\Reader; use Dotenv\Store\StoreBuilder; use PHPUnit\Framework\TestCase; final class StoreTest extends TestCase { /** * @var string */ private static $folder; /** * @beforeClass * * @return void */ public static function setFolder() { self::$folder = \dirname(\dirname(__DIR__)).'/fixtures/env'; } public function testBasicReadDirect() { self::assertSame( [ self::$folder.\DIRECTORY_SEPARATOR.'.env' => "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n\nNULL=\n", ], Reader::read( Paths::filePaths([self::$folder], ['.env']) ) ); } public function testBasicRead() { $builder = StoreBuilder::createWithDefaultName() ->addPath(self::$folder); self::assertSame( "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n\nNULL=\n", $builder->make()->read() ); } public function testBasicReadWindowsEncoding() { $builder = StoreBuilder::createWithNoNames() ->addPath(self::$folder) ->addName('windows.env') ->fileEncoding('Windows-1252'); self::assertSame( "MBW=\"ñá\"\n", $builder->make()->read() ); } public function testBasicReadBadEncoding() { $builder = StoreBuilder::createWithNoNames() ->addPath(self::$folder) ->addName('windows.env') ->fileEncoding('Windowss-1252'); $this->expectException(InvalidEncodingException::class); $this->expectExceptionMessage('Illegal character encoding [Windowss-1252] specified.'); $builder->make()->read(); } public function testFileReadMultipleShortCircuitModeDirect() { self::assertSame( [ self::$folder.\DIRECTORY_SEPARATOR.'.env' => "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n\nNULL=\n", ], Reader::read( Paths::filePaths([self::$folder], ['.env', 'example.env']) ) ); } public function testFileReadMultipleShortCircuitMode() { $builder = StoreBuilder::createWithNoNames() ->addPath(self::$folder) ->addName('.env') ->addName('example.env') ->shortCircuit(); self::assertSame( "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n\nNULL=\n", $builder->make()->read() ); } public function testFileReadMultipleWithoutShortCircuitModeDirect() { self::assertSame( [ self::$folder.\DIRECTORY_SEPARATOR.'.env' => "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n\nNULL=\n", self::$folder.\DIRECTORY_SEPARATOR.'example.env' => "EG=\"example\"\n", ], Reader::read( Paths::filePaths([self::$folder], ['.env', 'example.env']), false ) ); } public function testFileReadMultipleWithoutShortCircuitMode() { $builder = StoreBuilder::createWithDefaultName() ->addPath(self::$folder) ->addName('example.env'); self::assertSame( "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n\nNULL=\n\nEG=\"example\"\n", $builder->make()->read() ); } public function testFileReadWithUtf8WithBomEncoding() { self::assertSame( [ self::$folder.\DIRECTORY_SEPARATOR.'utf8-with-bom-encoding.env' => "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n", ], Reader::read( Paths::filePaths([self::$folder], ['utf8-with-bom-encoding.env']) ) ); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Repository/RepositoryTest.php
tests/Dotenv/Repository/RepositoryTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Repository; use Dotenv\Dotenv; use Dotenv\Repository\Adapter\ArrayAdapter; use Dotenv\Repository\RepositoryBuilder; use Dotenv\Repository\RepositoryInterface; use InvalidArgumentException; use PHPUnit\Framework\TestCase; use TypeError; final class RepositoryTest extends TestCase { /** * @var array<string, string>|null */ private $keyVal; /** * @before * * @return void */ public function refreshKeyVal() { $this->keyVal(true); } /** * @return void */ private function load() { Dotenv::createMutable(\dirname(\dirname(__DIR__)).'/fixtures/env')->load(); } /** * Generates a new key/value pair or returns the previous one. * * Since most of our functionality revolves around setting/retrieving keys * and values, we have this utility function to help generate new, unique * key/value pairs. * * @param bool $reset * * @return array<string, string> */ private function keyVal(bool $reset = false) { if (!isset($this->keyVal) || $reset) { $this->keyVal = [\uniqid() => \uniqid()]; } return $this->keyVal; } /** * Returns the key from keyVal(), without reset. * * @return string */ private function key() { $keyVal = $this->keyVal(); return (string) \key($keyVal); } /** * Returns the value from keyVal(), without reset. * * @return string */ private function value() { $keyVal = $this->keyVal(); /** @var string */ return \reset($keyVal); } public function testRepositoryInstanceOf() { self::assertInstanceOf(RepositoryInterface::class, RepositoryBuilder::createWithNoAdapters()->make()); self::assertInstanceOf(RepositoryInterface::class, RepositoryBuilder::createWithDefaultAdapters()->make()); } public function testMutableLoaderClearsEnvironmentVars() { $repository = RepositoryBuilder::createWithDefaultAdapters()->make(); // Set an environment variable. $repository->set($this->key(), $this->value()); // Clear the set environment variable. $repository->clear($this->key()); self::assertNull($repository->get($this->key())); self::assertFalse(\getenv($this->key())); self::assertFalse(isset($_ENV[$this->key()])); self::assertFalse(isset($_SERVER[$this->key()])); } public function testImmutableLoaderCannotClearExistingEnvironmentVars() { $this->load(); $repository = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); // Pre-set an environment variable. RepositoryBuilder::createWithDefaultAdapters()->make()->set($this->key(), $this->value()); // Attempt to clear the environment variable, check that it fails. $repository->clear($this->key()); self::assertSame($this->value(), $repository->get($this->key())); self::assertTrue(isset($_ENV[$this->key()])); self::assertTrue(isset($_SERVER[$this->key()])); } public function testImmutableLoaderCanClearSetEnvironmentVars() { $this->load(); $repository = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); // Set an environment variable. $repository->set($this->key(), $this->value()); // Attempt to clear the environment variable, check that it works. $repository->clear($this->key()); self::assertNull($repository->get($this->key())); self::assertFalse(\getenv($this->key())); self::assertFalse(isset($_ENV[$this->key()])); self::assertFalse(isset($_SERVER[$this->key()])); } public function testCheckingWhetherVariableExists() { $this->load(); $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); self::assertTrue($repo->has('FOO')); self::assertFalse($repo->has('NON_EXISTING_VARIABLE')); } public function testHasWithBadVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(TypeError::class); $repo->has(null); } public function testGettingVariableByName() { $this->load(); $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); self::assertSame('bar', $repo->get('FOO')); } public function testGettingNullVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(TypeError::class); $repo->get(null); } public function testGettingEmptyVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected name to be a non-empty string.'); $repo->get(''); } public function testSettingVariable() { $this->load(); $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); self::assertSame('bar', $repo->get('FOO')); $repo->set('FOO', 'new'); self::assertSame('new', $repo->get('FOO')); } public function testSettingNullVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(TypeError::class); $repo->set(null, 'foo'); } public function testSettingEmptyVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected name to be a non-empty string.'); $repo->set('', 'foo'); } public function testClearingVariable() { $this->load(); $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); self::assertTrue($repo->has('FOO')); $repo->clear('FOO'); self::assertFalse($repo->has('FOO')); } public function testClearingVariableWithArrayAdapter() { $adapter = ArrayAdapter::create()->get(); $repo = RepositoryBuilder::createWithNoAdapters()->addReader($adapter)->addWriter($adapter)->make(); self::assertFalse($repo->has('FOO')); $repo->set('FOO', 'BAR'); self::assertTrue($repo->has('FOO')); $repo->clear('FOO'); self::assertFalse($repo->has('FOO')); } public function testClearingNullVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(TypeError::class); $repo->clear(null); } public function testClearingEmptyVariable() { $repo = RepositoryBuilder::createWithDefaultAdapters()->make(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected name to be a non-empty string.'); $repo->clear(''); } public function testCannotSetVariableOnImmutableInstance() { $this->load(); $repo = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); self::assertSame('bar', $repo->get('FOO')); $repo->set('FOO', 'new'); self::assertSame('bar', $repo->get('FOO')); } public function testCannotClearVariableOnImmutableInstance() { $this->load(); $repo = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); $repo->clear('FOO'); self::assertTrue($repo->has('FOO')); } public function testBuildWithBadReader() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected either an instance of '); RepositoryBuilder::createWithNoAdapters()->addReader('123'); } public function testBuildWithBadWriter() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected either an instance of '); RepositoryBuilder::createWithNoAdapters()->addWriter('123'); } public function testBuildWithBadAdapter() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected either an instance of '); RepositoryBuilder::createWithNoAdapters()->addAdapter(''); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Repository/Adapter/ServerConstAdapterTest.php
tests/Dotenv/Repository/Adapter/ServerConstAdapterTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Repository\Adapter; use Dotenv\Repository\Adapter\ServerConstAdapter; use PHPUnit\Framework\TestCase; final class ServerConstAdapterTest extends TestCase { public function testGoodRead() { $_SERVER['CONST_TEST'] = 'foo bar baz'; $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('foo bar baz', $value->get()); } public function testFalseRead() { $_SERVER['CONST_TEST'] = false; $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('false', $value->get()); } public function testTrueRead() { $_SERVER['CONST_TEST'] = true; $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('true', $value->get()); } public function testBadTypeRead() { $_SERVER['CONST_TEST'] = [123]; $value = self::createAdapter()->read('CONST_TEST'); self::assertFalse($value->isDefined()); } public function testUndefinedRead() { unset($_SERVER['CONST_TEST']); $value = self::createAdapter()->read('CONST_TEST'); self::assertFalse($value->isDefined()); } public function testGoodWrite() { self::assertTrue(self::createAdapter()->write('CONST_TEST', 'foo')); self::assertSame('foo', $_SERVER['CONST_TEST']); } public function testEmptyWrite() { self::assertTrue(self::createAdapter()->write('CONST_TEST', '')); self::assertSame('', $_SERVER['CONST_TEST']); } public function testGoodDelete() { self::assertTrue(self::createAdapter()->delete('CONST_TEST')); self::assertFalse(isset($_SERVER['CONST_TEST'])); } /** * @return \Dotenv\Repository\Adapter\AdapterInterface */ private static function createAdapter() { return ServerConstAdapter::create()->get(); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Repository/Adapter/PutenvAdapterTest.php
tests/Dotenv/Repository/Adapter/PutenvAdapterTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Repository\Adapter; use Dotenv\Repository\Adapter\PutenvAdapter; use PHPUnit\Framework\TestCase; final class PutenvAdapterTest extends TestCase { public function testGoodRead() { \putenv('CONST_TEST=foo bar baz'); $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('foo bar baz', $value->get()); } public function testUndefinedRead() { \putenv('CONST_TEST'); $value = self::createAdapter()->read('CONST_TEST'); self::assertFalse($value->isDefined()); } public function testGoodWrite() { self::assertTrue(self::createAdapter()->write('CONST_TEST', 'foo')); self::assertSame('foo', \getenv('CONST_TEST')); } public function testEmptyWrite() { self::assertTrue(self::createAdapter()->write('CONST_TEST', '')); self::assertSame('', \getenv('CONST_TEST')); } public function testGoodDelete() { self::assertTrue(self::createAdapter()->delete('CONST_TEST')); self::assertFalse(\getenv('CONST_TEST')); } /** * @return \Dotenv\Repository\Adapter\AdapterInterface */ private static function createAdapter() { return PutenvAdapter::create()->get(); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Repository/Adapter/ArrayAdapterTest.php
tests/Dotenv/Repository/Adapter/ArrayAdapterTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Repository\Adapter; use Dotenv\Repository\Adapter\ArrayAdapter; use PHPUnit\Framework\TestCase; final class ArrayAdapterTest extends TestCase { public function testGoodRead() { $adapter = self::createAdapter(); $adapter->write('CONST_TEST', 'foo bar baz'); $value = $adapter->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('foo bar baz', $value->get()); } public function testUndefinedRead() { $adapter = self::createAdapter(); unset($_ENV['CONST_TEST']); $value = $adapter->read('CONST_TEST'); self::assertFalse($value->isDefined()); } public function testGoodWrite() { $adapter = self::createAdapter(); self::assertTrue($adapter->write('CONST_TEST', 'foo')); self::assertSame('foo', $adapter->read('CONST_TEST')->get()); } public function testEmptyWrite() { $adapter = self::createAdapter(); self::assertTrue($adapter->write('CONST_TEST', '')); self::assertSame('', $adapter->read('CONST_TEST')->get()); } public function testGoodDelete() { $adapter = self::createAdapter(); self::assertTrue($adapter->delete('CONST_TEST')); self::assertFalse($adapter->read('CONST_TEST')->isDefined()); } /** * @return \Dotenv\Repository\Adapter\AdapterInterface */ private static function createAdapter() { return ArrayAdapter::create()->get(); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
vlucas/phpdotenv
https://github.com/vlucas/phpdotenv/blob/2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1/tests/Dotenv/Repository/Adapter/EnvConstAdapterTest.php
tests/Dotenv/Repository/Adapter/EnvConstAdapterTest.php
<?php declare(strict_types=1); namespace Dotenv\Tests\Repository\Adapter; use Dotenv\Repository\Adapter\EnvConstAdapter; use PHPUnit\Framework\TestCase; final class EnvConstAdapterTest extends TestCase { public function testGoodRead() { $_ENV['CONST_TEST'] = 'foo bar baz'; $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('foo bar baz', $value->get()); } public function testFalseRead() { $_ENV['CONST_TEST'] = false; $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('false', $value->get()); } public function testTrueRead() { $_ENV['CONST_TEST'] = true; $value = self::createAdapter()->read('CONST_TEST'); self::assertTrue($value->isDefined()); self::assertSame('true', $value->get()); } public function testBadTypeRead() { $_ENV['CONST_TEST'] = [123]; $value = self::createAdapter()->read('CONST_TEST'); self::assertFalse($value->isDefined()); } public function testUndefinedRead() { unset($_ENV['CONST_TEST']); $value = self::createAdapter()->read('CONST_TEST'); self::assertFalse($value->isDefined()); } public function testGoodWrite() { self::assertTrue(self::createAdapter()->write('CONST_TEST', 'foo')); self::assertSame('foo', $_ENV['CONST_TEST']); } public function testEmptyWrite() { self::assertTrue(self::createAdapter()->write('CONST_TEST', '')); self::assertSame('', $_ENV['CONST_TEST']); } public function testGoodDelete() { self::assertTrue(self::createAdapter()->delete('CONST_TEST')); self::assertFalse(isset($_ENV['CONST_TEST'])); } /** * @return \Dotenv\Repository\Adapter\AdapterInterface */ private static function createAdapter() { return EnvConstAdapter::create()->get(); } }
php
BSD-3-Clause
2af27192fc6c6bf7c05ef26e67d54afe9a0c39e1
2026-01-04T15:02:53.318618Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/server.php
server.php
<?php /** * Laravel - A PHP Framework For Web Artisans. * * @author Taylor Otwell <taylorotwell@gmail.com> */ $uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ); // This file allows us to emulate Apache's "mod_rewrite" functionality from the // built-in PHP web server. This provides a convenient way to test a Laravel // application without having installed a "real" web server software here. if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { return false; } require_once __DIR__.'/public/index.php';
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/scripts/koel-init.php
scripts/koel-init.php
#!/usr/bin/env php <?php $args = array_slice($argv, 1); passthru('composer install --ansi'); passthru('php artisan koel:init --ansi ' . implode(' ', $args));
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Helpers.php
app/Helpers.php
<?php use App\Facades\License; use App\Services\SettingService; use App\Values\Branding; use Illuminate\Support\Arr; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Webmozart\Assert\Assert; /** * Get a URL for static file requests. * If this installation of Koel has a CDN_URL configured, use it as the base. * Otherwise, just use a full URL to the asset. * * @param string|null $name The optional resource name/path */ function static_url(?string $name = null): string { $cdnUrl = trim(config('koel.cdn.url'), '/ '); return $cdnUrl ? $cdnUrl . '/' . trim(ltrim($name, '/')) : trim(asset($name)); } function base_url(): string { return app()->runningUnitTests() ? config('app.url') : asset(''); } function image_storage_path(?string $fileName, ?string $default = null): ?string { return $fileName ? public_path(config('koel.image_storage_dir') . $fileName) : $default; } function image_storage_url(?string $fileName, ?string $default = null): ?string { return $fileName ? static_url(config('koel.image_storage_dir') . $fileName) : $default; } function artifact_path(?string $subPath = null, $ensureDirectoryExists = true): string { $path = Str::finish(config('koel.artifacts_path'), DIRECTORY_SEPARATOR); if ($subPath) { $path .= ltrim($subPath, DIRECTORY_SEPARATOR); } if ($ensureDirectoryExists) { File::ensureDirectoryExists(Str::endsWith($path, DIRECTORY_SEPARATOR) ? $path : dirname($path)); } return $path; } function koel_version(): string { return trim(File::get(base_path('.version'))); } function rescue_if($condition, callable $callback, $default = null): mixed { return value($condition) ? rescue($callback, $default) : $default; } function rescue_unless($condition, callable $callback, $default = null): mixed { return rescue_if(!$condition, $callback, $default); } function gravatar(string $email, int $size = 192): string { $url = config('services.gravatar.url'); $default = config('services.gravatar.default'); return sprintf("%s/%s?s=$size&d=$default", $url, md5(Str::lower($email))); } function avatar_or_gravatar(?string $avatar, string $email): string { if (!$avatar) { return gravatar($email); } if (Str::startsWith($avatar, ['http://', 'https://'])) { return $avatar; } return image_storage_url($avatar); } /** * A quick check to determine if a mailer is configured. * This is not bulletproof but should work in most cases. */ function mailer_configured(): bool { return config('mail.default') && !in_array(config('mail.default'), ['log', 'array'], true); } /** @return array<string> */ function collect_sso_providers(): array { if (License::isCommunity()) { return []; } $providers = []; if ( config('services.google.client_id') && config('services.google.client_secret') && config('services.google.hd') ) { $providers[] = 'Google'; } return $providers; } function get_mtime(string|SplFileInfo $path): int { $path = is_string($path) ? $path : $path->getPathname(); // Workaround for #344, where getMTime() fails for certain files with Unicode names on Windows. return rescue(static fn () => File::lastModified($path)) ?? time(); } /** * Simple, non-cryptographically secure hash function for strings. * This is used for generating hashes for identifiers that do not require high security. */ function simple_hash(?string $string): string { return md5("koel-hash:$string"); } function is_image(string $path): bool { return rescue(static fn () => (bool) exif_imagetype($path)) ?? false; } /** * @param string|int ...$parts */ function cache_key(...$parts): string { return simple_hash(implode('.', $parts)); } /** * @return array<string> */ function collect_accepted_audio_extensions(): array { return array_values( collect(array_values(config('koel.streaming.supported_mime_types'))) ->flatten() ->unique() ->map(static fn (string $ext) => Str::lower($ext)) ->toArray() ); } function find_ffmpeg_path(): ?string { // for Unix-like systems, we can use the `which` command if (PHP_OS_FAMILY !== 'Windows') { $path = trim(shell_exec('which ffmpeg') ?: ''); return $path && is_executable($path) ? $path : null; } // for Windows, we can check `where` command $path = trim(shell_exec('where ffmpeg') ?: ''); if ($path && is_executable($path)) { return $path; } // finally, check the PATH environment variable $path = getenv('PATH'); if ($path) { $paths = explode(PATH_SEPARATOR, $path); foreach ($paths as $dir) { $ffmpegPath = rtrim($dir, '\\/') . DIRECTORY_SEPARATOR . 'ffmpeg.exe'; if (is_executable($ffmpegPath)) { return $ffmpegPath; } } } return null; } function koel_branding(?string $key = null): Branding|string|null { Assert::inArray($key, [null, 'name', 'logo', 'cover']); $branding = once(static function (): Branding { /** @var SettingService $service */ $service = app(SettingService::class); return $service->getBranding(); }); if (!$key) { return $branding; } return Arr::get($branding->toArray(), $key); }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/QueuedJob.php
app/Jobs/QueuedJob.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; abstract class QueuedJob implements ShouldQueue { use Dispatchable; use InteractsWithQueue; use Queueable; use SerializesModels; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/RunCommandJob.php
app/Jobs/RunCommandJob.php
<?php namespace App\Jobs; use Illuminate\Support\Facades\Artisan; class RunCommandJob extends QueuedJob { public function __construct(public readonly string $command) { } public function handle(): void { Artisan::call($this->command); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/DeleteTranscodeFilesJob.php
app/Jobs/DeleteTranscodeFilesJob.php
<?php namespace App\Jobs; use App\Services\Transcoding\TranscodeStrategyFactory; use App\Values\Transcoding\TranscodeFileInfo; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Throwable; class DeleteTranscodeFilesJob extends QueuedJob { /** * @param Collection<TranscodeFileInfo>|array<array-key, TranscodeFileInfo> $files */ public function __construct(public readonly Collection $files) { } public function handle(): void { $this->files->each(static function (TranscodeFileInfo $file): void { try { TranscodeStrategyFactory::make($file->storage)->deleteTranscodeFile($file->location, $file->storage); } catch (Throwable $e) { if (app()->runningUnitTests()) { return; } Log::error('Failed to remove transcode file', [ 'location' => $file->location, 'storage' => $file->storage, 'exception' => $e, ]); } }); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/ExtractSongFolderStructureJob.php
app/Jobs/ExtractSongFolderStructureJob.php
<?php namespace App\Jobs; use App\Models\Song; use App\Services\MediaBrowser; class ExtractSongFolderStructureJob extends QueuedJob { public function __construct(private readonly Song $song) { } public function handle(MediaBrowser $browser): void { $browser->maybeCreateFolderStructureForSong($this->song); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/DeleteSongFilesJob.php
app/Jobs/DeleteSongFilesJob.php
<?php namespace App\Jobs; use App\Services\SongStorages\SongStorage; use App\Values\Song\SongFileInfo; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Throwable; class DeleteSongFilesJob extends QueuedJob { /** * @param Collection<SongFileInfo>|array<array-key, SongFileInfo> $files */ public function __construct(public readonly Collection $files) { } public function handle(SongStorage $storage): void { $this->files->each(static function (SongFileInfo $file) use ($storage): void { try { $storage->delete($file->location, config('koel.backup_on_delete')); } catch (Throwable $e) { Log::error('Failed to remove song file', [ 'path' => $file->location, 'exception' => $e, ]); } }); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/HandleSongUploadJob.php
app/Jobs/HandleSongUploadJob.php
<?php namespace App\Jobs; use App\Models\Song; use App\Models\User; use App\Repositories\AlbumRepository; use App\Repositories\SongRepository; use App\Responses\SongUploadResponse; use App\Services\UploadService; class HandleSongUploadJob extends QueuedJob { public function __construct(public readonly string $filePath, public readonly User $uploader) { } public function handle( UploadService $uploadService, SongRepository $songRepository, AlbumRepository $albumRepository, ): Song { $song = $uploadService->handleUpload($this->filePath, $this->uploader); $populatedSong = $songRepository->getOne($song->id, $this->uploader); $album = $albumRepository->getOne($populatedSong->album_id, $this->uploader); broadcast(SongUploadResponse::make(song: $populatedSong, album: $album)); return $song; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/GenerateAlbumThumbnailJob.php
app/Jobs/GenerateAlbumThumbnailJob.php
<?php namespace App\Jobs; use App\Models\Album; use App\Services\AlbumService; class GenerateAlbumThumbnailJob extends QueuedJob { public function __construct(private readonly Album $album) { } public function handle(AlbumService $albumService): void { rescue(fn () => $albumService->generateAlbumThumbnail($this->album)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Jobs/ScrobbleJob.php
app/Jobs/ScrobbleJob.php
<?php namespace App\Jobs; use App\Models\Song; use App\Models\User; use App\Services\LastfmService; class ScrobbleJob extends QueuedJob { public function __construct(public User $user, public Song $song, public int $timestamp) { } public function handle(LastfmService $lastfmService): void { $lastfmService->scrobble($this->song, $this->user, $this->timestamp); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/ArtistNameConflictException.php
app/Exceptions/ArtistNameConflictException.php
<?php namespace App\Exceptions; use DomainException; class ArtistNameConflictException extends DomainException { public function __construct() { parent::__construct('An artist with the same name already exists.'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/CannotRemoveOwnerFromPlaylistException.php
app/Exceptions/CannotRemoveOwnerFromPlaylistException.php
<?php namespace App\Exceptions; use Exception; class CannotRemoveOwnerFromPlaylistException extends Exception { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/NonSmartPlaylistException.php
app/Exceptions/NonSmartPlaylistException.php
<?php namespace App\Exceptions; use App\Models\Playlist; use DomainException; class NonSmartPlaylistException extends DomainException { public static function create(Playlist $playlist): self { return new static($playlist->name . ' is not a smart playlist.'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/UserAlreadySubscribedToPodcastException.php
app/Exceptions/UserAlreadySubscribedToPodcastException.php
<?php namespace App\Exceptions; use App\Models\Podcast; use App\Models\User; use Exception; final class UserAlreadySubscribedToPodcastException extends Exception { public static function create(User $user, Podcast $podcast): self { return new self("User {$user->id} has already subscribed to podcast {$podcast->id}"); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/NonCloudStorageException.php
app/Exceptions/NonCloudStorageException.php
<?php namespace App\Exceptions; use App\Enums\SongStorageType; use DomainException; class NonCloudStorageException extends DomainException { public static function create(SongStorageType $type): self { return new self("Not a cloud storage type: {$type->value}."); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/AlbumNameConflictException.php
app/Exceptions/AlbumNameConflictException.php
<?php namespace App\Exceptions; use DomainException; class AlbumNameConflictException extends DomainException { public function __construct() { parent::__construct('An album with the same name already exists for this artist.'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/FailedToParsePodcastFeedException.php
app/Exceptions/FailedToParsePodcastFeedException.php
<?php namespace App\Exceptions; use RuntimeException; use Throwable; final class FailedToParsePodcastFeedException extends RuntimeException { public static function create(string $url, Throwable $previous): self { return new self("Failed to parse the podcast feed at $url.", $previous->getCode(), $previous); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/SpotifyIntegrationDisabledException.php
app/Exceptions/SpotifyIntegrationDisabledException.php
<?php namespace App\Exceptions; use DomainException; class SpotifyIntegrationDisabledException extends DomainException { public static function create(): self { return new self('Spotify integration is disabled.'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/UnsupportedSongStorageTypeException.php
app/Exceptions/UnsupportedSongStorageTypeException.php
<?php namespace App\Exceptions; use App\Enums\SongStorageType; use InvalidArgumentException; class UnsupportedSongStorageTypeException extends InvalidArgumentException { public static function create(SongStorageType $storageType): self { return new self("Unsupported song storage type: $storageType->value"); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/OperationNotApplicableForSmartPlaylistException.php
app/Exceptions/OperationNotApplicableForSmartPlaylistException.php
<?php namespace App\Exceptions; use DomainException; class OperationNotApplicableForSmartPlaylistException extends DomainException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/SongPathNotFoundException.php
app/Exceptions/SongPathNotFoundException.php
<?php namespace App\Exceptions; use RuntimeException; class SongPathNotFoundException extends RuntimeException { public static function create(string $path): self { return new static("The song at path $path cannot be found."); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/FailedToActivateLicenseException.php
app/Exceptions/FailedToActivateLicenseException.php
<?php namespace App\Exceptions; use RuntimeException; use Saloon\Exceptions\Request\RequestException; use Throwable; final class FailedToActivateLicenseException extends RuntimeException { public static function fromThrowable(Throwable $e): self { return new self($e->getMessage(), $e->getCode(), $e); } public static function fromRequestException(RequestException $e): self { try { return new self(object_get($e->getResponse()->object(), 'error'), $e->getStatus()); } catch (Throwable) { return self::fromThrowable($e); } } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/EmbeddableNotFoundException.php
app/Exceptions/EmbeddableNotFoundException.php
<?php namespace App\Exceptions; use Illuminate\Database\Eloquent\ModelNotFoundException; class EmbeddableNotFoundException extends ModelNotFoundException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/KoelPlusRequiredException.php
app/Exceptions/KoelPlusRequiredException.php
<?php namespace App\Exceptions; use DomainException; class KoelPlusRequiredException extends DomainException { public function __construct(string $message = 'This feature is only available in Koel Plus.') { parent::__construct($message); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/SongUploadFailedException.php
app/Exceptions/SongUploadFailedException.php
<?php namespace App\Exceptions; use RuntimeException; use Throwable; class SongUploadFailedException extends RuntimeException { private static function fromThrowable(Throwable $e): self { return new self($e->getMessage(), $e->getCode(), $e); } private static function fromErrorMessage(?string $error): self { return new self($error ?? 'An unknown error occurred while uploading the song.'); } public static function make(Throwable|string $error): self { if ($error instanceof Throwable) { return self::fromThrowable($error); } return self::fromErrorMessage($error); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/InvitationNotFoundException.php
app/Exceptions/InvitationNotFoundException.php
<?php namespace App\Exceptions; use RuntimeException; class InvitationNotFoundException extends RuntimeException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/UserProspectUpdateDeniedException.php
app/Exceptions/UserProspectUpdateDeniedException.php
<?php namespace App\Exceptions; use LogicException; class UserProspectUpdateDeniedException extends LogicException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/PlaylistCollaborationTokenExpiredException.php
app/Exceptions/PlaylistCollaborationTokenExpiredException.php
<?php namespace App\Exceptions; use RuntimeException; class PlaylistCollaborationTokenExpiredException extends RuntimeException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/InvalidCredentialsException.php
app/Exceptions/InvalidCredentialsException.php
<?php namespace App\Exceptions; use RuntimeException; class InvalidCredentialsException extends RuntimeException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/InstallationFailedException.php
app/Exceptions/InstallationFailedException.php
<?php namespace App\Exceptions; use RuntimeException; class InstallationFailedException extends RuntimeException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/LocalStorageRequiredException.php
app/Exceptions/LocalStorageRequiredException.php
<?php namespace App\Exceptions; use DomainException; class LocalStorageRequiredException extends DomainException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/MediaBrowserNotSupportedException.php
app/Exceptions/MediaBrowserNotSupportedException.php
<?php namespace App\Exceptions; use DomainException; class MediaBrowserNotSupportedException extends DomainException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/MethodNotImplementedException.php
app/Exceptions/MethodNotImplementedException.php
<?php namespace App\Exceptions; use BadMethodCallException; class MethodNotImplementedException extends BadMethodCallException { public static function method(string $method): self { return new self("Method $method is not implemented."); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/PlaylistBothSongsAndRulesProvidedException.php
app/Exceptions/PlaylistBothSongsAndRulesProvidedException.php
<?php namespace App\Exceptions; use InvalidArgumentException; class PlaylistBothSongsAndRulesProvidedException extends InvalidArgumentException { public function __construct() { parent::__construct('A playlist cannot have both songs and rules'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/MediaPathNotSetException.php
app/Exceptions/MediaPathNotSetException.php
<?php namespace App\Exceptions; use LogicException; class MediaPathNotSetException extends LogicException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Exceptions/NotAPlaylistCollaboratorException.php
app/Exceptions/NotAPlaylistCollaboratorException.php
<?php namespace App\Exceptions; use DomainException; class NotAPlaylistCollaboratorException extends DomainException { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Downloadable.php
app/Values/Downloadable.php
<?php namespace App\Values; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\Response; final readonly class Downloadable { private bool $redirectable; private function __construct(public string $path) { $this->redirectable = Str::startsWith($path, ['http://', 'https://']); } public static function make(string $path): self { return new self($path); } public function toResponse(): Response { return $this->redirectable ? response()->redirectTo($this->path) : response()->download($this->path); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/LastfmLoveTrackParameters.php
app/Values/LastfmLoveTrackParameters.php
<?php namespace App\Values; final readonly class LastfmLoveTrackParameters { private function __construct(public string $trackName, public string $artistName) { } public static function make(string $trackName, string $artistName): self { return new self($trackName, $artistName); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/GenreSummary.php
app/Values/GenreSummary.php
<?php namespace App\Values; final readonly class GenreSummary { private function __construct( public string $publicId, public string $name, public int $songCount, public float $length ) { } public static function make(string $publicId, string $name, int $songCount, float $length): self { return new self( publicId: $publicId, name: $name, songCount: $songCount, length: $length, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/CompositeToken.php
app/Values/CompositeToken.php
<?php namespace App\Values; use Illuminate\Contracts\Support\Arrayable; use Laravel\Sanctum\NewAccessToken; /** * A "composite token" consists of two tokens: * * - an API token, which has all abilities * - an audio token, which has only the "audio" ability i.e. to play and download audio files. This token is used for * the audio player on the frontend as part of the GET query string, and thus has limited privileges. * * This approach helps prevent the API token from being logged by servers and proxies. */ final class CompositeToken implements Arrayable { private function __construct(public string $apiToken, public string $audioToken) { } public static function fromAccessTokens(NewAccessToken $api, NewAccessToken $audio): self { return new self($api->plainTextToken, $audio->plainTextToken); } /** * @return array<string, string> */ public function toArray(): array { return [ 'token' => $this->apiToken, 'audio-token' => $this->audioToken, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/ImageWritingConfig.php
app/Values/ImageWritingConfig.php
<?php namespace App\Values; final readonly class ImageWritingConfig { private function __construct( public int $quality, public int $maxWidth, public ?int $blur, ) { } public static function make(int $quality = 80, int $maxWidth = 500, ?int $blur = 0): self { return new self($quality, $maxWidth, $blur); } public static function default(): self { return new self(quality: 80, maxWidth: 500, blur: null); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/EmbedOptions.php
app/Values/EmbedOptions.php
<?php namespace App\Values; use App\Facades\License; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Http\Request; use Illuminate\Support\Arr; use Throwable; class EmbedOptions implements Arrayable { private function __construct(public string $theme, public string $layout, public bool $preview) { // Preview mode and theme are only customizable in Koel Plus if (License::isCommunity()) { $this->theme = 'classic'; $this->preview = false; } } public static function make(string $theme = 'classic', string $layout = 'full', bool $preview = false): self { return new self($theme, $layout, $preview); } public static function fromEncrypted(string $encrypted): self { try { $array = decrypt($encrypted); return new self( theme: Arr::get($array, 'theme', 'classic'), layout: Arr::get($array, 'layout', 'full'), preview: Arr::get($array, 'preview', false), ); } catch (Throwable) { return self::make(); } } public static function fromRequest(Request $request): self { return self::fromEncrypted($request->route('options')); } public function encrypt(): string { $array = $this->toArray(); ksort($array); // Remove the default values from the array to keep the payload minimal foreach (self::make()->toArray() as $key => $value) { if ($array[$key] === $value) { unset($array[$key]); } } return encrypt($array); } /** @inheritdoc */ public function toArray(): array { return [ 'theme' => $this->theme, 'layout' => $this->layout, 'preview' => $this->preview, ]; } public function __toString(): string { return $this->encrypt(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/RequestedStreamingConfig.php
app/Values/RequestedStreamingConfig.php
<?php namespace App\Values; final readonly class RequestedStreamingConfig { private function __construct( public bool $transcode, public ?int $bitRate, public float $startTime ) { } public static function make(bool $transcode = false, ?int $bitRate = 128, float $startTime = 0.0): self { return new self($transcode, $bitRate, $startTime); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Equalizer.php
app/Values/Equalizer.php
<?php namespace App\Values; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Arr; use Throwable; final readonly class Equalizer implements Arrayable { /** @param array<int>|null $gains */ private function __construct(public ?string $name, public ?float $preamp, public ?array $gains) { } public static function tryMake(array|string $data): self { try { if (is_string($data)) { $data = ['name' => $data]; } return new self(Arr::get($data, 'name') ?? null, Arr::get($data, 'preamp'), Arr::get($data, 'gains')); } catch (Throwable) { return self::default(); } } public static function default(): self { return new self(name: 'Default', preamp: 0, gains: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'preamp' => $this->preamp, 'gains' => $this->gains, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/QueueState.php
app/Values/QueueState.php
<?php namespace App\Values; use App\Models\Song as Playable; use Illuminate\Support\Collection; final class QueueState { private function __construct( public Collection $playables, public ?Playable $currentPlayable, public ?int $playbackPosition ) { } public static function make(Collection $songs, ?Playable $currentPlayable = null, ?int $playbackPosition = 0): self { return new self($songs, $currentPlayable, $playbackPosition); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/UploadReference.php
app/Values/UploadReference.php
<?php namespace App\Values; final readonly class UploadReference { /** * @param string $location Depending on the storage type, this could be the full storage key (with prefix) * or the local path to the file. This is the value to be stored in the database. * @param string $localPath The local path to the (maybe tmp.) file, used for tag scanning or cleaning up. */ private function __construct(public string $location, public string $localPath) { } public static function make(string $location, string $localPath): self { return new self($location, $localPath); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/IpInfoLiteData.php
app/Values/IpInfoLiteData.php
<?php namespace App\Values; use Illuminate\Contracts\Support\Arrayable; use Saloon\Http\Response; final readonly class IpInfoLiteData implements Arrayable { private function __construct( public string $ip, public string $asn, public string $asName, public string $asDomain, public string $countryCode, public string $country, public string $continentCode, public string $continent, ) { } public static function fromSaloonResponse(Response $response): self { $json = $response->json(); return new self( ip: $json['ip'] ?? '', asn: $json['asn'] ?? '', asName: $json['as_name'] ?? '', asDomain: $json['as_domain'] ?? '', countryCode: $json['country_code'] ?? '', country: $json['country'] ?? '', continentCode: $json['continent_code'] ?? '', continent: $json['continent'] ?? '', ); } /** @inheritdoc */ public function toArray(): array { return [ 'ip' => $this->ip, 'asn' => $this->asn, 'as_name' => $this->asName, 'as_domain' => $this->asDomain, 'country_code' => $this->countryCode, 'country' => $this->country, 'continent_code' => $this->continentCode, 'continent' => $this->continent, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Branding.php
app/Values/Branding.php
<?php namespace App\Values; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Facades\URL; final class Branding implements Arrayable { private function __construct( public readonly string $name, public ?string $logo, public ?string $cover, ) { if ($logo && !URL::isValidUrl($logo)) { $this->logo = image_storage_url($logo); } if ($cover && !URL::isValidUrl($cover)) { $this->cover = image_storage_url($cover); } } public static function make( ?string $name = null, ?string $logo = null, ?string $cover = null, ): self { return new self( name: $name ?: config('app.name'), logo: $logo, cover: $cover, ); } public static function fromArray(array $settings): self { return new self( name: $settings['name'] ?? config('app.name'), logo: $settings['logo'] ?? null, cover: $settings['cover'] ?? null, ); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'logo' => $this->logo, 'cover' => $this->cover, ]; } public function withLogo(?string $logo): self { return new self( name: $this->name, logo: $logo, cover: $this->cover, ); } public function withoutLogo(): self { return new self( name: $this->name, logo: null, cover: $this->cover, ); } public function withName(string $name): self { return new self( name: $name, logo: $this->logo, cover: $this->cover, ); } public function withCover(string $cover): self { return new self( name: $this->name, logo: $this->logo, cover: $cover, ); } public function withoutCover(): self { return new self( name: $this->name, logo: $this->logo, cover: null, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/ExcerptSearchResult.php
app/Values/ExcerptSearchResult.php
<?php namespace App\Values; use Illuminate\Support\Collection; final class ExcerptSearchResult { private function __construct( public Collection $songs, public Collection $artists, public Collection $albums, public Collection $podcasts, public Collection $radioStations, ) { } public static function make( Collection $songs, Collection $artists, Collection $albums, Collection $podcasts, Collection $radioStations, ): self { return new self($songs, $artists, $albums, $podcasts, $radioStations); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Theme/ThemeCreateData.php
app/Values/Theme/ThemeCreateData.php
<?php namespace App\Values\Theme; final readonly class ThemeCreateData { private function __construct( public string $name, public string $fgColor, public string $bgColor, public string $bgImage, public string $highlightColor, public string $fontFamily, public float $fontSize = 13, ) { } public static function make( string $name, string $fgColor, string $bgColor, string $bgImage, string $highlightColor, string $fontFamily, float $fontSize, ): self { return new self( name: $name, fgColor: $fgColor, bgColor: $bgColor, bgImage: $bgImage, highlightColor: $highlightColor, fontFamily: $fontFamily, fontSize: $fontSize, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Theme/ThemeProperties.php
app/Values/Theme/ThemeProperties.php
<?php namespace App\Values\Theme; use Illuminate\Contracts\Support\Arrayable; final class ThemeProperties implements Arrayable { private function __construct( public readonly string $fgColor, public readonly string $bgColor, public readonly string $bgImage, public readonly string $highlightColor, public readonly string $fontFamily, public readonly float $fontSize, ) { } public static function make( string $fgColor, string $bgColor, string $bgImage, string $highlightColor, string $fontFamily, float $fontSize, ): self { return new self( fgColor: $fgColor, bgColor: $bgColor, bgImage: $bgImage, highlightColor: $highlightColor, fontFamily: $fontFamily, fontSize: $fontSize, ); } public static function empty(): self { return new self( fgColor: '', bgColor: '', bgImage: '', highlightColor: '', fontFamily: '', fontSize: 13.0, ); } public static function unserialize(object $json): self { return new self( fgColor: object_get($json, '--color-fg', ''), bgColor: object_get($json, '--color-bg', ''), bgImage: object_get($json, '--bg-image', ''), highlightColor: object_get($json, '--color-highlight', ''), fontFamily: object_get($json, '--font-family', ''), fontSize: object_get($json, '--font-size', 13.0), ); } public function serialize(): string { $arr = $this->toArray(); $arr['--bg-image'] = $this->bgImage; $arr['--font-size'] = $this->fontSize; return json_encode($arr); } /** @inheritdoc */ public function toArray(): array { return [ '--color-fg' => $this->fgColor, '--color-bg' => $this->bgColor, '--bg-image' => $this->bgImage ? 'url("' . image_storage_url($this->bgImage) . '")' : '', '--color-highlight' => $this->highlightColor, '--font-family' => $this->fontFamily, '--font-size' => $this->fontSize ? "{$this->fontSize}px" : '13.0px', ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Podcast/EpisodePlayable.php
app/Values/Podcast/EpisodePlayable.php
<?php namespace App\Values\Podcast; use App\Models\Song as Episode; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Http; final class EpisodePlayable implements Arrayable, Jsonable { private function __construct(public readonly string $path, public readonly string $checksum) { } public static function make(string $path, string $sum): self { return new self($path, $sum); } public function valid(): bool { return File::isReadable($this->path) && $this->checksum === md5_file($this->path); } public static function getForEpisode(Episode $episode): self { /** @var self|null $cached */ $cached = Cache::get("episode-playable.{$episode->id}"); return $cached?->valid() ? $cached : self::createForEpisode($episode); } private static function createForEpisode(Episode $episode): self { $file = artifact_path("episodes/{$episode->id}.mp3"); if (!File::exists($file)) { Http::sink($file)->get($episode->path)->throw(); } $playable = new self($file, File::hash($file)); Cache::forever("episode-playable.{$episode->id}", $playable); return $playable; } /** @inheritDoc */ public function toArray(): array { return [ 'path' => $this->path, 'checksum' => $this->checksum, ]; } /** @inheritDoc */ public function toJson($options = 0): string { return json_encode($this->toArray(), $options); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Podcast/PodcastState.php
app/Values/Podcast/PodcastState.php
<?php namespace App\Values\Podcast; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Support\Arr; use Illuminate\Support\Collection; final class PodcastState implements Arrayable, Jsonable { private function __construct(public readonly ?string $currentEpisode, public readonly Collection $progresses) { } public static function fromArray(array $data): self { return new self( Arr::get($data, 'current_episode'), new Collection(Arr::get($data, 'progresses', [])) ); } /** @inheritDoc */ public function toArray(): array { return [ 'current_episode' => $this->currentEpisode, 'progresses' => $this->progresses->toArray(), ]; } /** @inheritDoc */ public function toJson($options = 0): string { return json_encode($this->toArray(), $options); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Ticketmaster/TicketmasterEvent.php
app/Values/Ticketmaster/TicketmasterEvent.php
<?php namespace App\Values\Ticketmaster; use Carbon\Carbon; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Arr; readonly class TicketmasterEvent implements Arrayable { private function __construct( public string $id, public string $name, public string $url, public string $image, public ?string $start, public ?string $end, public TicketmasterVenue $venue, ) { } public static function fromArray(array $data): self { return new static( id: Arr::get($data, 'id', ''), name: Arr::get($data, 'name', ''), url: Arr::get($data, 'url', ''), image: Arr::get($data, 'images.0.url', ''), start: self::tryParseDate(Arr::get($data, 'dates.start', [])), end: self::tryParseDate(Arr::get($data, 'dates.end', [])), venue: TicketmasterVenue::fromArray(Arr::get($data, '_embedded.venues.0', [])), ); } public static function make( string $id, string $name, string $url, string $image, ?string $start, ?string $end, TicketmasterVenue $venue, ): self { return new static( id: $id, name: $name, url: $url, image: $image, start: $start, end: $end, venue: $venue, ); } private static function tryParseDate(array $dateData): ?string { if (!$dateData) { return null; } if (Arr::get($dateData, 'localTime')) { return Carbon::createFromFormat( 'Y-m-d H:i:s', Arr::get($dateData, 'localDate') . ' ' . Arr::get($dateData, 'localTime') )->format('D, j M Y, H:i'); } return Carbon::createFromFormat('Y-m-d', Arr::get($dateData, 'localDate'))->format('D, j M Y'); } /** @inheritdoc */ public function toArray(): array { return [ 'id' => $this->id, 'name' => $this->name, 'url' => $this->url, 'image' => $this->image, 'dates' => [ 'start' => $this->start, 'end' => $this->end, ], 'venue' => $this->venue->toArray(), ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Ticketmaster/TicketmasterVenue.php
app/Values/Ticketmaster/TicketmasterVenue.php
<?php namespace App\Values\Ticketmaster; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Arr; readonly class TicketmasterVenue implements Arrayable { private function __construct( public string $name, public string $url, public string $city, ) { } public static function fromArray(array $data): self { return new self( name: Arr::get($data, 'name', ''), url: Arr::get($data, 'url', ''), city: Arr::get($data, 'city.name', ''), ); } public static function make(string $name, string $url, string $city): self { return new static( name: $name, url: $url, city: $city, ); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'url' => $this->url, 'city' => $this->city, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Ticketmaster/TicketmasterAttraction.php
app/Values/Ticketmaster/TicketmasterAttraction.php
<?php namespace App\Values\Ticketmaster; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Arr; readonly class TicketmasterAttraction implements Arrayable { private function __construct( public string $id, public string $name, public string $url, public string $image, ) { } public static function fromArray(array $data): self { return new self( id: Arr::get($data, 'id'), name: Arr::get($data, 'name'), url: Arr::get($data, 'url', ''), image: Arr::get($data, 'images.0.url', ''), ); } /** @inheritdoc */ public function toArray(): array { return [ 'id' => $this->id, 'name' => $this->name, 'url' => $this->url, 'image' => $this->image, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Artist/ArtistInformation.php
app/Values/Artist/ArtistInformation.php
<?php namespace App\Values\Artist; use HTMLPurifier; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Arr; final class ArtistInformation implements Arrayable { public const JSON_STRUCTURE = [ 'url', 'image', 'bio' => [ 'summary', 'full', ], ]; private function __construct(public ?string $url, public ?string $image, public array $bio) { $purifier = new HTMLPurifier(); $this->bio['summary'] = $purifier->purify($this->bio['summary']); $this->bio['full'] = $purifier->purify($this->bio['full']); } public static function make( ?string $url = null, ?string $image = null, array $bio = ['summary' => '', 'full' => ''] ): self { return new self($url, $image, $bio); } /** * @param array<string, mixed> $summary */ public static function fromWikipediaSummary(array $summary): self { return new self( url: Arr::get($summary, 'content_urls.desktop.page'), image: Arr::get($summary, 'thumbnail.source'), bio: [ 'summary' => Arr::get($summary, 'extract', ''), 'full' => Arr::get($summary, 'extract_html', ''), ], ); } /** @inheritdoc */ public function toArray(): array { return [ 'url' => $this->url, 'image' => $this->image, 'bio' => $this->bio, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Artist/ArtistUpdateData.php
app/Values/Artist/ArtistUpdateData.php
<?php namespace App\Values\Artist; use Illuminate\Contracts\Support\Arrayable; final class ArtistUpdateData implements Arrayable { private function __construct(public string $name, public ?string $image) { } public static function make(string $name, ?string $image = null): self { return new self(name: $name, image: $image); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'cover' => $this->image, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Song/SongUpdateResult.php
app/Values/Song/SongUpdateResult.php
<?php namespace App\Values\Song; use App\Models\Album; use App\Models\Artist; use App\Models\Song; use Illuminate\Support\Collection; final readonly class SongUpdateResult { private function __construct( public Collection $updatedSongs, public Collection $removedArtistIds, public Collection $removedAlbumIds, ) { } public static function make( ?Collection $updatedSongs = null, ?Collection $removedArtistIds = null, ?Collection $removedAlbumIds = null, ): self { return new self( updatedSongs: $updatedSongs ?? collect(), removedArtistIds: $removedArtistIds ?? collect(), removedAlbumIds: $removedAlbumIds ?? collect(), ); } public function addSong(Song $song): void { $this->updatedSongs->push($song); } public function addRemovedArtist(Artist $artist): void { if ($this->removedArtistIds->doesntContain($artist->id)) { $this->removedArtistIds->push($artist->id); } } public function addRemovedAlbum(Album $album): void { if ($this->removedAlbumIds->doesntContain($album->id)) { $this->removedAlbumIds->push($album->id); } } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Song/SongFileInfo.php
app/Values/Song/SongFileInfo.php
<?php namespace App\Values\Song; use App\Enums\SongStorageType; use App\Models\Song; final readonly class SongFileInfo { private function __construct(public string $location, public SongStorageType $storage) { } public static function make(string $location, SongStorageType $storage): self { return new self($location, $storage); } public static function fromSong(Song $song): self { return self::make($song->storage_metadata->getPath(), $song->storage); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Song/SongUpdateData.php
app/Values/Song/SongUpdateData.php
<?php namespace App\Values\Song; use Illuminate\Contracts\Support\Arrayable; final class SongUpdateData implements Arrayable { private function __construct( public ?string $title, public ?string $artistName, public ?string $albumName, public ?string $albumArtistName, public ?int $track, public ?int $disc, public ?string $genre, public ?int $year, public ?string $lyrics, ) { $this->albumArtistName = $this->albumArtistName ?: $this->artistName; } public static function make( ?string $title = null, ?string $artistName = null, ?string $albumName = null, ?string $albumArtistName = null, ?int $track = null, ?int $disc = null, ?string $genre = null, ?int $year = null, ?string $lyrics = null, ): self { return new self( $title, $artistName, $albumName, $albumArtistName, $track, $disc, $genre, $year, $lyrics, ); } /** @return array<string, mixed> */ public function toArray(): array { return [ 'title' => $this->title, 'artist' => $this->artistName, 'album' => $this->albumName, 'album_artist' => $this->albumArtistName, 'track' => $this->track, 'disc' => $this->disc, 'genre' => $this->genre, 'year' => $this->year, 'lyrics' => $this->lyrics, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/WatchRecord/WatchRecord.php
app/Values/WatchRecord/WatchRecord.php
<?php namespace App\Values\WatchRecord; use App\Values\WatchRecord\Contracts\WatchRecordInterface; abstract class WatchRecord implements WatchRecordInterface { /** * Array of the occurred events. */ protected array $events; /** * Full path of the file/directory on which the event occurred. */ protected string $path; /** * The input of the watch record. * For example, an inotifywatch record should have an input similar to * "DELETE /var/www/media/song.mp3". */ protected string $input; /** * @param string $input The output from a watcher command (which is an input for our script) */ public function __construct(string $input) { $this->input = $input; } public function isFile(): bool { return !$this->isDirectory(); } /** * Check if a given event name exists in the event array. */ protected function eventExists(string $event): bool { return in_array($event, $this->events, true); } public function getPath(): string { return $this->path; } public function __toString(): string { return $this->input; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/WatchRecord/InotifyWatchRecord.php
app/Values/WatchRecord/InotifyWatchRecord.php
<?php namespace App\Values\WatchRecord; final class InotifyWatchRecord extends WatchRecord { /** * {@inheritdoc} */ public function __construct(string $input) { parent::__construct($input); $this->parse($input); } /** * Parse the inotifywait's output. The inotifywait command should be something like: * $ inotifywait -rme move,close_write,delete --format "%e %w%f" $MEDIA_PATH. */ public function parse(string $string): void { list($events, $this->path) = explode(' ', $string, 2); $this->events = explode(',', $events); } /** * Determine if the object has just been deleted or moved from our watched directory. */ public function isDeleted(): bool { return $this->eventExists('DELETE') || $this->eventExists('MOVED_FROM'); } /** * Determine if the object has just been created or modified. * For our purpose, we watch both the CREATE and the CLOSE_WRITE event, because some operating * systems only support CREATE, but not CLOSE_WRITE and MOVED_TO. * Additionally, a MOVED_TO (occurred after the object has been moved/renamed to another location * **under our watched directory**) should be considered as "modified" also. */ public function isNewOrModified(): bool { return $this->eventExists('CLOSE_WRITE') || $this->eventExists('CREATE') || $this->eventExists('MOVED_TO'); } public function isDirectory(): bool { return $this->eventExists('ISDIR'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/WatchRecord/Contracts/WatchRecordInterface.php
app/Values/WatchRecord/Contracts/WatchRecordInterface.php
<?php namespace App\Values\WatchRecord\Contracts; interface WatchRecordInterface { public function parse(string $string): void; public function getPath(): string; public function isDeleted(): bool; public function isNewOrModified(): bool; public function isDirectory(): bool; public function isFile(): bool; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Transcoding/TranscodeResult.php
app/Values/Transcoding/TranscodeResult.php
<?php namespace App\Values\Transcoding; use Illuminate\Support\Facades\File; final readonly class TranscodeResult { public function __construct(public string $path, public string $checksum) { } public function valid(): bool { return File::isReadable($this->path) && File::hash($this->path) === $this->checksum; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Transcoding/TranscodeFileInfo.php
app/Values/Transcoding/TranscodeFileInfo.php
<?php namespace App\Values\Transcoding; use App\Enums\SongStorageType; use App\Models\Transcode; class TranscodeFileInfo { public function __construct(public readonly string $location, public readonly SongStorageType $storage) { } public static function make(string $location, SongStorageType $storageType): self { return new self($location, $storageType); } public static function fromTranscode(Transcode $transcode): self { return self::make($transcode->location, $transcode->storage); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Playlist/PlaylistCollaborator.php
app/Values/Playlist/PlaylistCollaborator.php
<?php namespace App\Values\Playlist; use App\Models\User; use Illuminate\Contracts\Support\Arrayable; final class PlaylistCollaborator implements Arrayable { private function __construct(public string $publicId, public string $name, public string $avatar) { } public static function make(string $publicId, string $name, string $avatar): self { return new self($publicId, $name, $avatar); } public static function fromUser(User $user): self { return new self($user->public_id, $user->name, $user->avatar); } /** @inheritdoc */ public function toArray(): array { return [ 'type' => 'playlist_collaborators', 'id' => $this->publicId, 'name' => $this->name, 'avatar' => $this->avatar, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Playlist/PlaylistUpdateData.php
app/Values/Playlist/PlaylistUpdateData.php
<?php namespace App\Values\Playlist; use App\Values\SmartPlaylist\SmartPlaylistRuleGroupCollection; use Illuminate\Contracts\Support\Arrayable; final readonly class PlaylistUpdateData implements Arrayable { private function __construct( public string $name, public string $description, public ?string $folderId, public ?string $cover, public ?SmartPlaylistRuleGroupCollection $ruleGroups, ) { } public static function make( string $name, string $description = '', ?string $folderId = null, ?string $cover = null, ?SmartPlaylistRuleGroupCollection $ruleGroups = null, ): self { return new self( name: $name, description: $description, folderId: $folderId, cover: $cover, ruleGroups: $ruleGroups, ); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'description' => $this->description, 'folder_id' => $this->folderId, 'cover' => $this->cover, 'rule_groups' => $this->ruleGroups, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/Playlist/PlaylistCreateData.php
app/Values/Playlist/PlaylistCreateData.php
<?php namespace App\Values\Playlist; use App\Exceptions\PlaylistBothSongsAndRulesProvidedException; use App\Values\SmartPlaylist\SmartPlaylistRuleGroupCollection; use Illuminate\Contracts\Support\Arrayable; final readonly class PlaylistCreateData implements Arrayable { /** * @param array<string> $playableIds */ private function __construct( public string $name, public string $description, public ?string $folderId, public ?string $cover, public array $playableIds, public ?SmartPlaylistRuleGroupCollection $ruleGroups, ) { throw_if($this->ruleGroups && $this->playableIds, PlaylistBothSongsAndRulesProvidedException::class); } public static function make( string $name, string $description = '', ?string $folderId = null, ?string $cover = null, array $playableIds = [], ?SmartPlaylistRuleGroupCollection $ruleGroups = null, ): self { return new self( name: $name, description: $description, folderId: $folderId, cover: $cover, playableIds: $playableIds, ruleGroups: $ruleGroups, ); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'description' => $this->description, 'folder_id' => $this->folderId, 'cover' => $this->cover, 'playable_ids' => $this->playableIds, 'rule_groups' => $this->ruleGroups, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/License/LicenseInstance.php
app/Values/License/LicenseInstance.php
<?php namespace App\Values\License; use Carbon\Carbon; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; /** * A Lemon Squeezy license instance * @see https://docs.lemonsqueezy.com/api/license-key-instances#the-license-key-instance-object */ final class LicenseInstance implements Arrayable, Jsonable { private function __construct(public string $id, public string $name, public Carbon $createdAt) { } public static function make(string $id, string $name, Carbon|string $createdAt): self { return new self($id, $name, is_string($createdAt) ? Carbon::parse($createdAt) : $createdAt); } public static function fromJsonObject(object $json): self { return new self( id: object_get($json, 'id'), name: object_get($json, 'name'), createdAt: Carbon::parse(object_get($json, 'created_at')), ); } public function toJson($options = 0): string { return json_encode($this->toArray(), $options); } /** @return array<string, mixed> */ public function toArray(): array { return [ 'id' => $this->id, 'name' => $this->name, 'created_at' => $this->createdAt->format('Y-m-d H:i:s'), ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/License/LicenseMeta.php
app/Values/License/LicenseMeta.php
<?php namespace App\Values\License; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; /** * A Lemon Squeezy license meta * @see https://docs.lemonsqueezy.com/help/licensing/license-api#meta */ final class LicenseMeta implements Arrayable, Jsonable { private function __construct(public int $customerId, public string $customerName, public string $customerEmail) { } public static function make(int $customerId, string $customerName, string $customerEmail): self { return new self($customerId, $customerName, $customerEmail); } public static function fromJson(object $json): self { return new self( customerId: $json->customer_id, customerName: $json->customer_name, customerEmail: $json->customer_email, ); } public function toJson($options = 0): string { return json_encode($this->toArray(), $options); } /** @return array<string, mixed> */ public function toArray(): array { return [ 'customer_id' => $this->customerId, 'customer_name' => $this->customerName, 'customer_email' => $this->customerEmail, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/License/LicenseStatus.php
app/Values/License/LicenseStatus.php
<?php namespace App\Values\License; use App\Enums\LicenseStatus as Status; use App\Models\License; final class LicenseStatus { private function __construct(public Status $status, public ?License $license) { } public function isValid(): bool { return $this->status === Status::VALID; } public function hasNoLicense(): bool { return $this->status === Status::NO_LICENSE; } public static function noLicense(): self { return new self(Status::NO_LICENSE, null); } public static function valid(License $license): self { return new self(Status::VALID, $license); } public static function invalid(License $license): self { return new self(Status::INVALID, $license); } public static function unknown(License $license): self { return new self(Status::UNKNOWN, $license); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/User/UserPreferences.php
app/Values/User/UserPreferences.php
<?php namespace App\Values\User; use App\Values\Equalizer; use Illuminate\Contracts\Support\Arrayable; use JsonSerializable; use Webmozart\Assert\Assert; final class UserPreferences implements Arrayable, JsonSerializable { private const CASTS = [ 'albums_favorites_only' => 'boolean', 'artists_favorites_only' => 'boolean', 'confirm_before_closing' => 'boolean', 'continuous_playback' => 'boolean', 'include_public_media' => 'boolean', 'lyrics_zoom_level' => 'integer', 'make_uploads_public' => 'boolean', 'podcasts_favorites_only' => 'boolean', 'radio_stations_favorites_only' => 'boolean', 'show_album_art_overlay' => 'boolean', 'show_now_playing_notification' => 'boolean', 'support_bar_no_bugging' => 'boolean', 'transcode_on_mobile' => 'boolean', 'transcode_quality' => 'integer', 'volume' => 'float', ]; private const CUSTOMIZABLE_KEYS = [ 'active_extra_panel_tab', 'albums_favorites_only', 'albums_sort_field', 'albums_sort_order', 'albums_view_mode', 'artists_favorites_only', 'artists_sort_field', 'artists_sort_order', 'artists_view_mode', 'confirm_before_closing', 'continuous_playback', 'equalizer', 'genres_sort_field', 'genres_sort_order', 'include_public_media', 'lyrics_zoom_level', 'make_uploads_public', 'podcasts_favorites_only', 'podcasts_sort_field', 'podcasts_sort_order', 'radio_stations_favorites_only', 'radio_stations_sort_field', 'radio_stations_sort_order', 'radio_stations_view_mode', 'repeat_mode', 'show_album_art_overlay', 'show_now_playing_notification', 'support_bar_no_bugging', 'theme', 'transcode_on_mobile', 'transcode_quality', 'visualizer', 'volume', ]; private const ALL_KEYS = self::CUSTOMIZABLE_KEYS + ['lastfm_session_key']; private function __construct( public float $volume, public string $repeatMode, public Equalizer $equalizer, public string $albumsViewMode, public string $artistsViewMode, public string $radioStationsViewMode, public string $albumsSortField, public string $artistsSortField, public string $genresSortField, public string $podcastsSortField, public string $radioStationsSortField, public string $albumsSortOrder, public string $artistsSortOrder, public string $genresSortOrder, public string $podcastsSortOrder, public string $radioStationsSortOrder, public bool $albumsFavoritesOnly, public bool $artistsFavoritesOnly, public bool $podcastsFavoritesOnly, public bool $radioStationsFavoritesOnly, public string $theme, public bool $showNowPlayingNotification, public bool $confirmBeforeClosing, public bool $transcodeOnMobile, public int $transcodeQuality, public bool $showAlbumArtOverlay, public bool $makeUploadsPublic, public bool $includePublicMedia, public bool $supportBarNoBugging, public bool $continuousPlayback, public int $lyricsZoomLevel, public string $visualizer, public ?string $activeExtraPanelTab, public ?string $lastFmSessionKey ) { Assert::oneOf($this->repeatMode, ['NO_REPEAT', 'REPEAT_ALL', 'REPEAT_ONE']); Assert::oneOf($this->artistsViewMode, ['list', 'thumbnails']); Assert::oneOf($this->albumsViewMode, ['list', 'thumbnails']); Assert::oneOf($this->radioStationsViewMode, ['list', 'thumbnails']); Assert::oneOf($this->activeExtraPanelTab, [null, 'Lyrics', 'Artist', 'Album', 'YouTube']); Assert::oneOf(strtolower($this->albumsSortOrder), ['asc', 'desc']); Assert::oneOf($this->albumsSortField, ['name', 'artist_name', 'year', 'created_at']); Assert::oneOf(strtolower($this->artistsSortOrder), ['asc', 'desc']); Assert::oneOf($this->artistsSortField, ['name', 'created_at']); Assert::oneOf($this->genresSortField, ['name', 'song_count']); Assert::oneOf(strtolower($this->genresSortOrder), ['asc', 'desc']); Assert::oneOf($this->podcastsSortField, ['title', 'last_played_at', 'subscribed_at', 'author']); Assert::oneOf(strtolower($this->podcastsSortOrder), ['asc', 'desc']); Assert::oneOf($this->radioStationsSortField, ['name', 'created_at']); Assert::oneOf(strtolower($this->radioStationsSortOrder), ['asc', 'desc']); if (!in_array($this->transcodeQuality, [64, 96, 128, 192, 256, 320], true)) { $this->transcodeQuality = 128; } } public static function fromArray(array $data): self { return new self( volume: $data['volume'] ?? 7.0, repeatMode: $data['repeat_mode'] ?? 'NO_REPEAT', equalizer: isset($data['equalizer']) ? Equalizer::tryMake($data['equalizer']) : Equalizer::default(), albumsViewMode: $data['albums_view_mode'] ?? 'thumbnails', artistsViewMode: $data['artists_view_mode'] ?? 'thumbnails', radioStationsViewMode: $data['radio_stations_view_mode'] ?? 'thumbnails', albumsSortField: $data['albums_sort_field'] ?? 'name', artistsSortField: $data['artists_sort_field'] ?? 'name', genresSortField: $data['genres_sort_field'] ?? 'name', podcastsSortField: $data['podcasts_sort_field'] ?? 'title', radioStationsSortField: $data['radio_stations_sort_field'] ?? 'name', albumsSortOrder: $data['albums_sort_order'] ?? 'asc', artistsSortOrder: $data['artists_sort_order'] ?? 'asc', genresSortOrder: $data['genres_sort_order'] ?? 'asc', podcastsSortOrder: $data['podcasts_sort_order'] ?? 'asc', radioStationsSortOrder: $data['radio_stations_sort_order'] ?? 'asc', albumsFavoritesOnly: $data['albums_favorites_only'] ?? false, artistsFavoritesOnly: $data['artists_favorites_only'] ?? false, podcastsFavoritesOnly: $data['podcasts_favorites_only'] ?? false, radioStationsFavoritesOnly: $data['radio_stations_favorites_only'] ?? false, theme: $data['theme'] ?? 'classic', showNowPlayingNotification: $data['show_now_playing_notification'] ?? true, confirmBeforeClosing: $data['confirm_before_closing'] ?? false, transcodeOnMobile: $data['transcode_on_mobile'] ?? true, transcodeQuality: $data['transcode_quality'] ?? config('koel.streaming.bitrate'), showAlbumArtOverlay: $data['show_album_art_overlay'] ?? true, makeUploadsPublic: $data['make_uploads_public'] ?? false, includePublicMedia: $data['include_public_media'] ?? true, supportBarNoBugging: $data['support_bar_no_bugging'] ?? false, continuousPlayback: $data['continuous_playback'] ?? false, lyricsZoomLevel: $data['lyrics_zoom_level'] ?? 1, visualizer: $data['visualizer'] ?? 'default', activeExtraPanelTab: $data['active_extra_panel_tab'] ?? null, lastFmSessionKey: $data['lastfm_session_key'] ?? null, ); } public static function customizable(string $key): bool { return in_array($key, self::CUSTOMIZABLE_KEYS, true); } public function set(string $key, mixed $value): self { self::assertValidKey($key); $cast = self::CASTS[$key] ?? null; $value = match ($cast) { 'boolean' => filter_var($value, FILTER_VALIDATE_BOOLEAN), 'integer' => (int) $value, 'float' => (float) $value, default => $value, }; $arr = $this->toArray(); $arr[$key] = $value; return self::fromArray($arr); } public static function assertValidKey(string $key): void { Assert::inArray($key, self::ALL_KEYS); } /** @inheritdoc */ public function toArray(): array { return [ 'theme' => $this->theme, 'show_now_playing_notification' => $this->showNowPlayingNotification, 'confirm_before_closing' => $this->confirmBeforeClosing, 'show_album_art_overlay' => $this->showAlbumArtOverlay, 'transcode_on_mobile' => $this->transcodeOnMobile, 'transcode_quality' => $this->transcodeQuality, 'make_uploads_public' => $this->makeUploadsPublic, 'include_public_media' => $this->includePublicMedia, 'lastfm_session_key' => $this->lastFmSessionKey, 'support_bar_no_bugging' => $this->supportBarNoBugging, 'albums_view_mode' => $this->albumsViewMode, 'artists_view_mode' => $this->artistsViewMode, 'radio_stations_view_mode' => $this->radioStationsViewMode, 'albums_sort_field' => $this->albumsSortField, 'artists_sort_field' => $this->artistsSortField, 'genres_sort_field' => $this->genresSortField, 'podcasts_sort_field' => $this->podcastsSortField, 'radio_stations_sort_field' => $this->radioStationsSortField, 'albums_sort_order' => $this->albumsSortOrder, 'artists_sort_order' => $this->artistsSortOrder, 'genres_sort_order' => $this->genresSortOrder, 'podcasts_sort_order' => $this->podcastsSortOrder, 'radio_stations_sort_order' => $this->radioStationsSortOrder, 'albums_favorites_only' => $this->albumsFavoritesOnly, 'artists_favorites_only' => $this->artistsFavoritesOnly, 'podcasts_favorites_only' => $this->podcastsFavoritesOnly, 'radio_stations_favorites_only' => $this->radioStationsFavoritesOnly, 'repeat_mode' => $this->repeatMode, 'volume' => $this->volume, 'equalizer' => $this->equalizer->toArray(), 'lyrics_zoom_level' => $this->lyricsZoomLevel, 'visualizer' => $this->visualizer, 'active_extra_panel_tab' => $this->activeExtraPanelTab, 'continuous_playback' => $this->continuousPlayback, ]; } /** @inheritdoc */ public function jsonSerialize(): array { return $this->toArray(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/User/UserCreateData.php
app/Values/User/UserCreateData.php
<?php namespace App\Values\User; use App\Enums\Acl\Role; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Facades\Hash; final readonly class UserCreateData implements Arrayable { public string $password; public function __construct( public string $name, public string $email, ?string $plainTextPassword, public Role $role, public ?string $avatar = null, public ?string $ssoId = null, public ?string $ssoProvider = null, ) { if ($ssoProvider) { SsoUser::assertValidProvider($ssoProvider); } $this->password = $plainTextPassword ? Hash::make($plainTextPassword) : ''; } public static function fromSsoUser(SsoUser $ssoUser): self { return new self( name: $ssoUser->name, email: $ssoUser->email, plainTextPassword: '', role: Role::default(), avatar: $ssoUser->avatar, ssoId: $ssoUser->id, ssoProvider: $ssoUser->provider, ); } public static function make( string $name, string $email, ?string $plainTextPassword = null, ?Role $role = null, ?string $avatar = null, ?string $ssoId = null, ?string $ssoProvider = null, ): self { return new self( name: $name, email: $email, plainTextPassword: $plainTextPassword, role: $role ?? Role::default(), avatar: $avatar, ssoId: $ssoId, ssoProvider: $ssoProvider, ); } /** @inheritdoc */ public function toArray(): array { return [ 'name' => $this->name, 'email' => $this->email, 'password' => $this->password, 'role' => $this->role->value, 'avatar' => $this->avatar, 'sso_id' => $this->ssoId, 'sso_provider' => $this->ssoProvider, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/User/SsoUser.php
app/Values/User/SsoUser.php
<?php namespace App\Values\User; use Illuminate\Http\Request; use Laravel\Socialite\Contracts\User as SocialiteUser; use Webmozart\Assert\Assert; final class SsoUser { private function __construct( public string $provider, public string $id, public string $email, public string $name, public ?string $avatar, ) { self::assertValidProvider($provider); } public static function fromSocialite(SocialiteUser $socialiteUser, string $provider): self { return new self( provider: $provider, id: $socialiteUser->getId(), email: $socialiteUser->getEmail(), name: $socialiteUser->getName(), avatar: $socialiteUser->getAvatar(), ); } public static function fromProxyAuthRequest(Request $request): self { $identifier = $request->header(config('koel.proxy_auth.user_header')); $email = filter_var($identifier, FILTER_VALIDATE_EMAIL) ?: "$identifier@reverse.proxy"; return new self( provider: 'Reverse Proxy', id: $identifier, email: $email, name: $request->header(config('koel.proxy_auth.preferred_name_header')) ?: $identifier, avatar: null, ); } public static function assertValidProvider(string $provider): void { Assert::oneOf($provider, ['Google', 'Reverse Proxy']); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Values/User/UserUpdateData.php
app/Values/User/UserUpdateData.php
<?php namespace App\Values\User; use App\Enums\Acl\Role; use Illuminate\Support\Facades\Hash; final readonly class UserUpdateData { public ?string $password; private function __construct( public string $name, public string $email, ?string $plainTextPassword, public ?Role $role, public ?string $avatar, ) { $this->password = $plainTextPassword ? Hash::make($plainTextPassword) : null; } public static function make( string $name, string $email, ?string $plainTextPassword = null, ?Role $role = null, ?string $avatar = null ): self { return new self( name: $name, email: $email, plainTextPassword: $plainTextPassword, role: $role, avatar: $avatar, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false