repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
opulencephp/Opulence | src/Opulence/Framework/Views/Bootstrappers/ViewBootstrapper.php | ViewBootstrapper.getViewCompiler | protected function getViewCompiler(IContainer $container) : ICompiler
{
$registry = new CompilerRegistry();
$viewCompiler = new Compiler($registry);
// Setup our various sub-compilers
$transpiler = new Transpiler(new Lexer(), new Parser(), $this->viewCache, new XssFilter());
$container->bindInstance(ITranspiler::class, $transpiler);
$fortuneCompiler = new FortuneCompiler($transpiler, $this->viewFactory);
$registry->registerCompiler('fortune', $fortuneCompiler);
$registry->registerCompiler('fortune.php', $fortuneCompiler);
$registry->registerCompiler('php', new PhpCompiler());
return $viewCompiler;
} | php | protected function getViewCompiler(IContainer $container) : ICompiler
{
$registry = new CompilerRegistry();
$viewCompiler = new Compiler($registry);
// Setup our various sub-compilers
$transpiler = new Transpiler(new Lexer(), new Parser(), $this->viewCache, new XssFilter());
$container->bindInstance(ITranspiler::class, $transpiler);
$fortuneCompiler = new FortuneCompiler($transpiler, $this->viewFactory);
$registry->registerCompiler('fortune', $fortuneCompiler);
$registry->registerCompiler('fortune.php', $fortuneCompiler);
$registry->registerCompiler('php', new PhpCompiler());
return $viewCompiler;
} | [
"protected",
"function",
"getViewCompiler",
"(",
"IContainer",
"$",
"container",
")",
":",
"ICompiler",
"{",
"$",
"registry",
"=",
"new",
"CompilerRegistry",
"(",
")",
";",
"$",
"viewCompiler",
"=",
"new",
"Compiler",
"(",
"$",
"registry",
")",
";",
"// Setu... | Gets the view compiler
To use a different view compiler than the one returned here, extend this class and override this method
@param IContainer $container The dependency injection container
@return ICompiler The view compiler | [
"Gets",
"the",
"view",
"compiler",
"To",
"use",
"a",
"different",
"view",
"compiler",
"than",
"the",
"one",
"returned",
"here",
"extend",
"this",
"class",
"and",
"override",
"this",
"method"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Views/Bootstrappers/ViewBootstrapper.php#L94-L108 |
opulencephp/Opulence | src/Opulence/Framework/Views/Bootstrappers/ViewBootstrapper.php | ViewBootstrapper.getViewFactory | protected function getViewFactory(IContainer $container) : IViewFactory
{
$resolver = new FileViewNameResolver();
$resolver->registerPath(Config::get('paths', 'views.raw'));
$resolver->registerExtension('fortune');
$resolver->registerExtension('fortune.php');
$resolver->registerExtension('php');
$viewReader = $this->getViewReader($container);
$container->bindInstance(IViewNameResolver::class, $resolver);
$container->bindInstance(IViewReader::class, $viewReader);
return new ViewFactory($resolver, $viewReader);
} | php | protected function getViewFactory(IContainer $container) : IViewFactory
{
$resolver = new FileViewNameResolver();
$resolver->registerPath(Config::get('paths', 'views.raw'));
$resolver->registerExtension('fortune');
$resolver->registerExtension('fortune.php');
$resolver->registerExtension('php');
$viewReader = $this->getViewReader($container);
$container->bindInstance(IViewNameResolver::class, $resolver);
$container->bindInstance(IViewReader::class, $viewReader);
return new ViewFactory($resolver, $viewReader);
} | [
"protected",
"function",
"getViewFactory",
"(",
"IContainer",
"$",
"container",
")",
":",
"IViewFactory",
"{",
"$",
"resolver",
"=",
"new",
"FileViewNameResolver",
"(",
")",
";",
"$",
"resolver",
"->",
"registerPath",
"(",
"Config",
"::",
"get",
"(",
"'paths'"... | Gets the view view factory
To use a different view factory than the one returned here, extend this class and override this method
@param IContainer $container The dependency injection container
@return IViewFactory The view factory | [
"Gets",
"the",
"view",
"view",
"factory",
"To",
"use",
"a",
"different",
"view",
"factory",
"than",
"the",
"one",
"returned",
"here",
"extend",
"this",
"class",
"and",
"override",
"this",
"method"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Views/Bootstrappers/ViewBootstrapper.php#L117-L129 |
opulencephp/Opulence | src/Opulence/Databases/ConnectionPools/ConnectionPool.php | ConnectionPool.getReadConnection | public function getReadConnection(Server $preferredServer = null) : IConnection
{
if ($preferredServer !== null) {
$this->addServer('custom', $preferredServer);
$this->setReadConnection($preferredServer);
} elseif ($this->readConnection == null) {
$this->setReadConnection();
}
return $this->readConnection;
} | php | public function getReadConnection(Server $preferredServer = null) : IConnection
{
if ($preferredServer !== null) {
$this->addServer('custom', $preferredServer);
$this->setReadConnection($preferredServer);
} elseif ($this->readConnection == null) {
$this->setReadConnection();
}
return $this->readConnection;
} | [
"public",
"function",
"getReadConnection",
"(",
"Server",
"$",
"preferredServer",
"=",
"null",
")",
":",
"IConnection",
"{",
"if",
"(",
"$",
"preferredServer",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"addServer",
"(",
"'custom'",
",",
"$",
"preferredServ... | Gets the connection used for read queries
@param Server $preferredServer The preferred server to use
@return IConnection The connection to use for reads
@throws RuntimeException Thrown if the connection pool wasn't configured correctly | [
"Gets",
"the",
"connection",
"used",
"for",
"read",
"queries"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/ConnectionPools/ConnectionPool.php#L98-L108 |
opulencephp/Opulence | src/Opulence/Databases/ConnectionPools/ConnectionPool.php | ConnectionPool.getWriteConnection | public function getWriteConnection(Server $preferredServer = null) : IConnection
{
if ($preferredServer != null) {
$this->addServer('custom', $preferredServer);
$this->setWriteConnection($preferredServer);
} elseif ($this->writeConnection == null) {
$this->setWriteConnection();
}
return $this->writeConnection;
} | php | public function getWriteConnection(Server $preferredServer = null) : IConnection
{
if ($preferredServer != null) {
$this->addServer('custom', $preferredServer);
$this->setWriteConnection($preferredServer);
} elseif ($this->writeConnection == null) {
$this->setWriteConnection();
}
return $this->writeConnection;
} | [
"public",
"function",
"getWriteConnection",
"(",
"Server",
"$",
"preferredServer",
"=",
"null",
")",
":",
"IConnection",
"{",
"if",
"(",
"$",
"preferredServer",
"!=",
"null",
")",
"{",
"$",
"this",
"->",
"addServer",
"(",
"'custom'",
",",
"$",
"preferredServ... | Gets the connection used for write queries
@param Server $preferredServer The preferred server to use
@return IConnection The connection to use for writes
@throws RuntimeException Thrown if the connection pool wasn't configured correctly | [
"Gets",
"the",
"connection",
"used",
"for",
"write",
"queries"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/ConnectionPools/ConnectionPool.php#L117-L127 |
opulencephp/Opulence | src/Opulence/Databases/ConnectionPools/ConnectionPool.php | ConnectionPool.addServer | protected function addServer(string $type, Server $server)
{
switch ($type) {
case 'master':
$this->servers['master'] = ['server' => $server, 'connection' => null];
break;
default:
$serverHashId = spl_object_hash($server);
if (!isset($this->servers[$type][$serverHashId])) {
$this->servers[$type][$serverHashId] = ['server' => $server, 'connection' => null];
}
break;
}
} | php | protected function addServer(string $type, Server $server)
{
switch ($type) {
case 'master':
$this->servers['master'] = ['server' => $server, 'connection' => null];
break;
default:
$serverHashId = spl_object_hash($server);
if (!isset($this->servers[$type][$serverHashId])) {
$this->servers[$type][$serverHashId] = ['server' => $server, 'connection' => null];
}
break;
}
} | [
"protected",
"function",
"addServer",
"(",
"string",
"$",
"type",
",",
"Server",
"$",
"server",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'master'",
":",
"$",
"this",
"->",
"servers",
"[",
"'master'",
"]",
"=",
"[",
"'server'",
"=>",
"... | Adds a server to our list of servers
@param string $type The type of server we're trying to add, eg "master", "custom"
@param Server $server The server to add | [
"Adds",
"a",
"server",
"to",
"our",
"list",
"of",
"servers"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/ConnectionPools/ConnectionPool.php#L159-L175 |
opulencephp/Opulence | src/Opulence/Databases/ConnectionPools/ConnectionPool.php | ConnectionPool.connectToServer | protected function connectToServer(Server $server) : IConnection
{
return $this->driver->connect($server, $this->connectionOptions, $this->driverOptions);
} | php | protected function connectToServer(Server $server) : IConnection
{
return $this->driver->connect($server, $this->connectionOptions, $this->driverOptions);
} | [
"protected",
"function",
"connectToServer",
"(",
"Server",
"$",
"server",
")",
":",
"IConnection",
"{",
"return",
"$",
"this",
"->",
"driver",
"->",
"connect",
"(",
"$",
"server",
",",
"$",
"this",
"->",
"connectionOptions",
",",
"$",
"this",
"->",
"driver... | Creates a database connection
@param Server $server The server to connect to
@return IConnection The database connection | [
"Creates",
"a",
"database",
"connection"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/ConnectionPools/ConnectionPool.php#L183-L186 |
opulencephp/Opulence | src/Opulence/Databases/ConnectionPools/ConnectionPool.php | ConnectionPool.getConnection | protected function getConnection(string $type, Server $server) : IConnection
{
switch ($type) {
case 'master':
if ($this->servers['master']['server'] == null) {
throw new RuntimeException('No master specified');
}
if ($this->servers['master']['connection'] == null) {
$this->servers['master']['connection'] = $this->connectToServer($server);
}
return $this->servers['master']['connection'];
default:
$serverHashId = spl_object_hash($server);
if (!isset($this->servers[$type][$serverHashId])
|| $this->servers[$type][$serverHashId]['server'] == null
) {
throw new RuntimeException("Server of type '" . $type . "' not added to connection pool");
}
if ($this->servers[$type][$serverHashId]['connection'] == null) {
$this->servers[$type][$serverHashId]['connection'] = $this->connectToServer($server);
}
return $this->servers[$type][$serverHashId]['connection'];
}
} | php | protected function getConnection(string $type, Server $server) : IConnection
{
switch ($type) {
case 'master':
if ($this->servers['master']['server'] == null) {
throw new RuntimeException('No master specified');
}
if ($this->servers['master']['connection'] == null) {
$this->servers['master']['connection'] = $this->connectToServer($server);
}
return $this->servers['master']['connection'];
default:
$serverHashId = spl_object_hash($server);
if (!isset($this->servers[$type][$serverHashId])
|| $this->servers[$type][$serverHashId]['server'] == null
) {
throw new RuntimeException("Server of type '" . $type . "' not added to connection pool");
}
if ($this->servers[$type][$serverHashId]['connection'] == null) {
$this->servers[$type][$serverHashId]['connection'] = $this->connectToServer($server);
}
return $this->servers[$type][$serverHashId]['connection'];
}
} | [
"protected",
"function",
"getConnection",
"(",
"string",
"$",
"type",
",",
"Server",
"$",
"server",
")",
":",
"IConnection",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'master'",
":",
"if",
"(",
"$",
"this",
"->",
"servers",
"[",
"'master'",
"... | Gets a connection to the input server
@param string $type The type of server we're trying to connect to, eg "master", "custom"
@param Server $server The server we want to connect to
@return IConnection The connection to the server
@throws RuntimeException Thrown if the connection pool wasn't configured correctly | [
"Gets",
"a",
"connection",
"to",
"the",
"input",
"server"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/ConnectionPools/ConnectionPool.php#L196-L224 |
opulencephp/Opulence | src/Opulence/Redis/Types/TypeMapper.php | TypeMapper.fromRedisTimestamp | public function fromRedisTimestamp($timestamp) : DateTime
{
$date = DateTime::createFromFormat('U', $timestamp);
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $date;
} | php | public function fromRedisTimestamp($timestamp) : DateTime
{
$date = DateTime::createFromFormat('U', $timestamp);
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $date;
} | [
"public",
"function",
"fromRedisTimestamp",
"(",
"$",
"timestamp",
")",
":",
"DateTime",
"{",
"$",
"date",
"=",
"DateTime",
"::",
"createFromFormat",
"(",
"'U'",
",",
"$",
"timestamp",
")",
";",
"$",
"date",
"->",
"setTimezone",
"(",
"new",
"DateTimeZone",
... | Converts a Redis Unix timestamp to a PHP timestamp
@param int $timestamp The Unix timestamp to convert from
@return DateTime The PHP timestamp | [
"Converts",
"a",
"Redis",
"Unix",
"timestamp",
"to",
"a",
"PHP",
"timestamp"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Redis/Types/TypeMapper.php#L39-L45 |
opulencephp/Opulence | src/Opulence/Cryptography/Encryption/Encrypter.php | Encrypter.createHmac | private function createHmac(
string $iv,
string $keySalt,
string $cipher,
string $value,
string $authenticationKey
) : string {
return \hash_hmac(self::$hmacAlgorithm, self::$version . $cipher . $iv . $keySalt . $value, $authenticationKey);
} | php | private function createHmac(
string $iv,
string $keySalt,
string $cipher,
string $value,
string $authenticationKey
) : string {
return \hash_hmac(self::$hmacAlgorithm, self::$version . $cipher . $iv . $keySalt . $value, $authenticationKey);
} | [
"private",
"function",
"createHmac",
"(",
"string",
"$",
"iv",
",",
"string",
"$",
"keySalt",
",",
"string",
"$",
"cipher",
",",
"string",
"$",
"value",
",",
"string",
"$",
"authenticationKey",
")",
":",
"string",
"{",
"return",
"\\",
"hash_hmac",
"(",
"... | Creates an HMAC
@param string $iv The initialization vector
@param string $keySalt The key salt
@param string $cipher The cipher used
@param string $value The value to hash
@param string $authenticationKey The authentication key
@return string The HMAC | [
"Creates",
"an",
"HMAC"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cryptography/Encryption/Encrypter.php#L165-L173 |
opulencephp/Opulence | src/Opulence/Cryptography/Encryption/Encrypter.php | Encrypter.deriveKeys | private function deriveKeys(string $cipher, string $keySalt) : DerivedKeys
{
// Extract the number of bytes from the cipher
$keyByteLength = $this->getKeyByteLengthForCipher($cipher);
if ($this->secret->getType() === SecretTypes::KEY) {
return $this->keyDeriver->deriveKeysFromKey($this->secret->getValue(), $keySalt, $keyByteLength);
} else {
return $this->keyDeriver->deriveKeysFromPassword($this->secret->getValue(), $keySalt, $keyByteLength);
}
} | php | private function deriveKeys(string $cipher, string $keySalt) : DerivedKeys
{
// Extract the number of bytes from the cipher
$keyByteLength = $this->getKeyByteLengthForCipher($cipher);
if ($this->secret->getType() === SecretTypes::KEY) {
return $this->keyDeriver->deriveKeysFromKey($this->secret->getValue(), $keySalt, $keyByteLength);
} else {
return $this->keyDeriver->deriveKeysFromPassword($this->secret->getValue(), $keySalt, $keyByteLength);
}
} | [
"private",
"function",
"deriveKeys",
"(",
"string",
"$",
"cipher",
",",
"string",
"$",
"keySalt",
")",
":",
"DerivedKeys",
"{",
"// Extract the number of bytes from the cipher",
"$",
"keyByteLength",
"=",
"$",
"this",
"->",
"getKeyByteLengthForCipher",
"(",
"$",
"ci... | Derives keys that are suitable for encryption and decryption
@param string $cipher The cipher used
@param string $keySalt The salt to use on the keys
@return DerivedKeys The derived keys | [
"Derives",
"keys",
"that",
"are",
"suitable",
"for",
"encryption",
"and",
"decryption"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cryptography/Encryption/Encrypter.php#L182-L192 |
opulencephp/Opulence | src/Opulence/Cryptography/Encryption/Encrypter.php | Encrypter.getPieces | private function getPieces(string $data) : array
{
$pieces = \json_decode(\base64_decode($data), true);
if ($pieces === false ||
!isset($pieces['version'], $pieces['hmac'], $pieces['value'], $pieces['iv'], $pieces['keySalt'], $pieces['cipher'])
) {
throw new EncryptionException('Data is not in correct format');
}
if (!in_array($pieces['cipher'], self::$approvedCiphers)) {
throw new EncryptionException("Cipher \"{$pieces['ciper']}\" is not supported");
}
if (\mb_strlen(\base64_decode($pieces['iv']), '8bit') !== \openssl_cipher_iv_length($pieces['cipher'])) {
throw new EncryptionException('IV is incorrect length');
}
if (\mb_strlen(\base64_decode($pieces['keySalt']), '8bit') !== IKeyDeriver::KEY_SALT_BYTE_LENGTH) {
throw new EncryptionException('Key salt is incorrect length');
}
if (\mb_strlen($pieces['hmac'], '8bit') !== self::$hmacByteLength) {
throw new EncryptionException('HMAC is incorrect length');
}
return $pieces;
} | php | private function getPieces(string $data) : array
{
$pieces = \json_decode(\base64_decode($data), true);
if ($pieces === false ||
!isset($pieces['version'], $pieces['hmac'], $pieces['value'], $pieces['iv'], $pieces['keySalt'], $pieces['cipher'])
) {
throw new EncryptionException('Data is not in correct format');
}
if (!in_array($pieces['cipher'], self::$approvedCiphers)) {
throw new EncryptionException("Cipher \"{$pieces['ciper']}\" is not supported");
}
if (\mb_strlen(\base64_decode($pieces['iv']), '8bit') !== \openssl_cipher_iv_length($pieces['cipher'])) {
throw new EncryptionException('IV is incorrect length');
}
if (\mb_strlen(\base64_decode($pieces['keySalt']), '8bit') !== IKeyDeriver::KEY_SALT_BYTE_LENGTH) {
throw new EncryptionException('Key salt is incorrect length');
}
if (\mb_strlen($pieces['hmac'], '8bit') !== self::$hmacByteLength) {
throw new EncryptionException('HMAC is incorrect length');
}
return $pieces;
} | [
"private",
"function",
"getPieces",
"(",
"string",
"$",
"data",
")",
":",
"array",
"{",
"$",
"pieces",
"=",
"\\",
"json_decode",
"(",
"\\",
"base64_decode",
"(",
"$",
"data",
")",
",",
"true",
")",
";",
"if",
"(",
"$",
"pieces",
"===",
"false",
"||",... | Converts the input data to an array of pieces
@param string $data The JSON data to convert
@return array The pieces
@throws EncryptionException Thrown if the pieces were not correctly set | [
"Converts",
"the",
"input",
"data",
"to",
"an",
"array",
"of",
"pieces"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cryptography/Encryption/Encrypter.php#L212-L239 |
opulencephp/Opulence | src/Opulence/Cryptography/Encryption/Encrypter.php | Encrypter.validateSecret | private function validateSecret(string $cipher)
{
if ($this->secret->getType() === SecretTypes::KEY) {
if (\mb_strlen($this->secret->getValue(), '8bit') < $this->getKeyByteLengthForCipher($cipher)) {
throw new EncryptionException("Key must be at least {$this->getKeyByteLengthForCipher($cipher)} bytes long");
}
} elseif (\mb_strlen($this->secret->getValue(), '8bit') === 0) {
throw new EncryptionException('Password cannot be empty');
}
} | php | private function validateSecret(string $cipher)
{
if ($this->secret->getType() === SecretTypes::KEY) {
if (\mb_strlen($this->secret->getValue(), '8bit') < $this->getKeyByteLengthForCipher($cipher)) {
throw new EncryptionException("Key must be at least {$this->getKeyByteLengthForCipher($cipher)} bytes long");
}
} elseif (\mb_strlen($this->secret->getValue(), '8bit') === 0) {
throw new EncryptionException('Password cannot be empty');
}
} | [
"private",
"function",
"validateSecret",
"(",
"string",
"$",
"cipher",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"secret",
"->",
"getType",
"(",
")",
"===",
"SecretTypes",
"::",
"KEY",
")",
"{",
"if",
"(",
"\\",
"mb_strlen",
"(",
"$",
"this",
"->",
"se... | Validates the secret
@param string $cipher The cipher used
@throws EncryptionException Thrown if the secret is not valid | [
"Validates",
"the",
"secret"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cryptography/Encryption/Encrypter.php#L261-L270 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.copyDirectory | public function copyDirectory(string $source, string $target, int $flags = null) : bool
{
if (!$this->exists($source)) {
return false;
}
if (!$this->isDirectory($target) && !$this->makeDirectory($target, 0777, true)) {
return false;
}
if ($flags === null) {
$flags = FilesystemIterator::SKIP_DOTS;
}
$items = new FilesystemIterator($source, $flags);
foreach ($items as $item) {
if ($item->isDir()) {
if (!$this->copyDirectory($item->getRealPath(), $target . '/' . $item->getBasename(), $flags)) {
return false;
}
} elseif ($item->isFile()) {
if (!$this->copyFile($item->getRealPath(), $target . '/' . $item->getBasename())) {
return false;
}
}
}
return true;
} | php | public function copyDirectory(string $source, string $target, int $flags = null) : bool
{
if (!$this->exists($source)) {
return false;
}
if (!$this->isDirectory($target) && !$this->makeDirectory($target, 0777, true)) {
return false;
}
if ($flags === null) {
$flags = FilesystemIterator::SKIP_DOTS;
}
$items = new FilesystemIterator($source, $flags);
foreach ($items as $item) {
if ($item->isDir()) {
if (!$this->copyDirectory($item->getRealPath(), $target . '/' . $item->getBasename(), $flags)) {
return false;
}
} elseif ($item->isFile()) {
if (!$this->copyFile($item->getRealPath(), $target . '/' . $item->getBasename())) {
return false;
}
}
}
return true;
} | [
"public",
"function",
"copyDirectory",
"(",
"string",
"$",
"source",
",",
"string",
"$",
"target",
",",
"int",
"$",
"flags",
"=",
"null",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"source",
")",
")",
"{",
"return... | Copies directories to a new path
@param string $source The path to copy from
@param string $target The path to copy to
@param null|int $flags The file permissions to use for the new directory(ies)
@return bool True if successful, otherwise false | [
"Copies",
"directories",
"to",
"a",
"new",
"path"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L45-L74 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.deleteDirectory | public function deleteDirectory(string $path, bool $keepDirectoryStructure = false) : bool
{
if (!$this->isDirectory($path)) {
return false;
}
$items = new FilesystemIterator($path);
foreach ($items as $item) {
if ($item->isDir()) {
if (!$this->deleteDirectory($item->getRealPath())) {
return false;
}
} elseif ($item->isFile()) {
if (!$this->deleteFile($item->getRealPath())) {
return false;
}
}
}
if (!$keepDirectoryStructure) {
return rmdir($path);
}
return true;
} | php | public function deleteDirectory(string $path, bool $keepDirectoryStructure = false) : bool
{
if (!$this->isDirectory($path)) {
return false;
}
$items = new FilesystemIterator($path);
foreach ($items as $item) {
if ($item->isDir()) {
if (!$this->deleteDirectory($item->getRealPath())) {
return false;
}
} elseif ($item->isFile()) {
if (!$this->deleteFile($item->getRealPath())) {
return false;
}
}
}
if (!$keepDirectoryStructure) {
return rmdir($path);
}
return true;
} | [
"public",
"function",
"deleteDirectory",
"(",
"string",
"$",
"path",
",",
"bool",
"$",
"keepDirectoryStructure",
"=",
"false",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isDirectory",
"(",
"$",
"path",
")",
")",
"{",
"return",
"false",
... | Recursively deletes a directory
@param string $path The path to the directory to delete
@param bool $keepDirectoryStructure True if we want to keep the directory structure, otherwise false
@return bool True if successful, otherwise false | [
"Recursively",
"deletes",
"a",
"directory"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L95-L120 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getBasename | public function getBasename(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("Path $path not found");
}
return pathinfo($path, PATHINFO_BASENAME);
} | php | public function getBasename(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("Path $path not found");
}
return pathinfo($path, PATHINFO_BASENAME);
} | [
"public",
"function",
"getBasename",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"Path $path not found\"",
")",
";",
"}",... | Gets the basename of a path
@param string $path The path to check
@return string The basename of the path
@throws FileSystemException Thrown if the path does not exist | [
"Gets",
"the",
"basename",
"of",
"a",
"path"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L151-L158 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getDirectories | public function getDirectories(string $path, bool $isRecursive = false) : array
{
if (!$this->isDirectory($path)) {
return [];
}
$directories = [];
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD
);
if (!$isRecursive) {
$iter->setMaxDepth(0);
}
foreach ($iter as $path => $item) {
if ($item->isDir()) {
$directories[] = $path;
}
}
return $directories;
} | php | public function getDirectories(string $path, bool $isRecursive = false) : array
{
if (!$this->isDirectory($path)) {
return [];
}
$directories = [];
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD
);
if (!$isRecursive) {
$iter->setMaxDepth(0);
}
foreach ($iter as $path => $item) {
if ($item->isDir()) {
$directories[] = $path;
}
}
return $directories;
} | [
"public",
"function",
"getDirectories",
"(",
"string",
"$",
"path",
",",
"bool",
"$",
"isRecursive",
"=",
"false",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isDirectory",
"(",
"$",
"path",
")",
")",
"{",
"return",
"[",
"]",
";",
"... | Gets all of the directories at the input path
@param string $path The path to check
@param bool $isRecursive Whether or not we should recurse through child directories
@return array All of the directories at the path | [
"Gets",
"all",
"of",
"the",
"directories",
"at",
"the",
"input",
"path"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L167-L191 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getDirectoryName | public function getDirectoryName(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
return pathinfo($path, PATHINFO_DIRNAME);
} | php | public function getDirectoryName(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
return pathinfo($path, PATHINFO_DIRNAME);
} | [
"public",
"function",
"getDirectoryName",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"File at path $path not found\"",
")",
... | Gets the directory name of a file
@param string $path The path to check
@return string The directory name of the file
@throws FileSystemException Thrown if the file does not exist | [
"Gets",
"the",
"directory",
"name",
"of",
"a",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L200-L207 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getExtension | public function getExtension(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
return pathinfo($path, PATHINFO_EXTENSION);
} | php | public function getExtension(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
return pathinfo($path, PATHINFO_EXTENSION);
} | [
"public",
"function",
"getExtension",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"File at path $path not found\"",
")",
";... | Gets the extension of a file
@param string $path The path to check
@return string The extension of the file
@throws FileSystemException Thrown if the file does not exist | [
"Gets",
"the",
"extension",
"of",
"a",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L216-L223 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getFileName | public function getFileName(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
return pathinfo($path, PATHINFO_FILENAME);
} | php | public function getFileName(string $path) : string
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
return pathinfo($path, PATHINFO_FILENAME);
} | [
"public",
"function",
"getFileName",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"File at path $path not found\"",
")",
";"... | Gets the file name of a file
@param string $path The path to check
@return string The file name
@throws FileSystemException Thrown if the file does not exist | [
"Gets",
"the",
"file",
"name",
"of",
"a",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L232-L239 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getFileSize | public function getFileSize(string $path) : int
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
$fileSize = filesize($path);
if ($fileSize === false) {
throw new FileSystemException("Failed to get file size of $path");
}
return $fileSize;
} | php | public function getFileSize(string $path) : int
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
$fileSize = filesize($path);
if ($fileSize === false) {
throw new FileSystemException("Failed to get file size of $path");
}
return $fileSize;
} | [
"public",
"function",
"getFileSize",
"(",
"string",
"$",
"path",
")",
":",
"int",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"File at path $path not found\"",
")",
";",
... | Gets the size of a file
@param string $path The path to check
@return int The number of bytes the file has
@throws FileSystemException Thrown if the file does not exist | [
"Gets",
"the",
"size",
"of",
"a",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L248-L261 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getFiles | public function getFiles(string $path, bool $isRecursive = false) : array
{
if (!$this->isDirectory($path)) {
return [];
}
$files = [];
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD
);
if (!$isRecursive) {
$iter->setMaxDepth(0);
}
foreach ($iter as $path => $item) {
if ($item->isFile()) {
$files[] = $path;
}
}
return $files;
} | php | public function getFiles(string $path, bool $isRecursive = false) : array
{
if (!$this->isDirectory($path)) {
return [];
}
$files = [];
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD
);
if (!$isRecursive) {
$iter->setMaxDepth(0);
}
foreach ($iter as $path => $item) {
if ($item->isFile()) {
$files[] = $path;
}
}
return $files;
} | [
"public",
"function",
"getFiles",
"(",
"string",
"$",
"path",
",",
"bool",
"$",
"isRecursive",
"=",
"false",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isDirectory",
"(",
"$",
"path",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
... | Gets all of the files at the input path
@param string $path The path to check
@param bool $isRecursive Whether or not we should recurse through child directories
@return array All of the files at the path | [
"Gets",
"all",
"of",
"the",
"files",
"at",
"the",
"input",
"path"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L270-L294 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.getLastModified | public function getLastModified(string $path) : DateTime
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
$modifiedTimestamp = filemtime($path);
if ($modifiedTimestamp === false) {
throw new FileSystemException("Failed to get last modified time of $path");
}
$modifiedDateTime = DateTime::createFromFormat('U', $modifiedTimestamp);
if ($modifiedDateTime === false) {
throw new FileSystemException('Failed to convert last modified time to DateTime object');
}
return $modifiedDateTime;
} | php | public function getLastModified(string $path) : DateTime
{
if (!$this->exists($path)) {
throw new FileSystemException("File at path $path not found");
}
$modifiedTimestamp = filemtime($path);
if ($modifiedTimestamp === false) {
throw new FileSystemException("Failed to get last modified time of $path");
}
$modifiedDateTime = DateTime::createFromFormat('U', $modifiedTimestamp);
if ($modifiedDateTime === false) {
throw new FileSystemException('Failed to convert last modified time to DateTime object');
}
return $modifiedDateTime;
} | [
"public",
"function",
"getLastModified",
"(",
"string",
"$",
"path",
")",
":",
"DateTime",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"File at path $path not found\"",
")",... | Gets the last modified time
@param string $path The path to check
@return DateTime The last modified time
@throws FileSystemException Thrown if the file was not found or if the modified time was not readable | [
"Gets",
"the",
"last",
"modified",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L303-L322 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.glob | public function glob(string $pattern, int $flags = 0) : array
{
$files = glob($pattern, $flags);
if ($files === false) {
throw new FileSystemException("Glob failed for pattern \"$pattern\" with flags $flags");
}
return $files;
} | php | public function glob(string $pattern, int $flags = 0) : array
{
$files = glob($pattern, $flags);
if ($files === false) {
throw new FileSystemException("Glob failed for pattern \"$pattern\" with flags $flags");
}
return $files;
} | [
"public",
"function",
"glob",
"(",
"string",
"$",
"pattern",
",",
"int",
"$",
"flags",
"=",
"0",
")",
":",
"array",
"{",
"$",
"files",
"=",
"glob",
"(",
"$",
"pattern",
",",
"$",
"flags",
")",
";",
"if",
"(",
"$",
"files",
"===",
"false",
")",
... | Finds files that match a pattern
@link http://php.net/manual/function.glob.php
@param string $pattern The pattern to match on
@param int $flags The glob flags to use
@return array The list of matched files
@throws FileSystemException Thrown if the search failed | [
"Finds",
"files",
"that",
"match",
"a",
"pattern"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L334-L343 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.makeDirectory | public function makeDirectory(string $path, int $mode = 0777, bool $isRecursive = false) : bool
{
$result = mkdir($path, $mode, $isRecursive);
// The directory might not get the correct mode due to umask, so we have to chmod it
chmod($path, $mode);
return $result;
} | php | public function makeDirectory(string $path, int $mode = 0777, bool $isRecursive = false) : bool
{
$result = mkdir($path, $mode, $isRecursive);
// The directory might not get the correct mode due to umask, so we have to chmod it
chmod($path, $mode);
return $result;
} | [
"public",
"function",
"makeDirectory",
"(",
"string",
"$",
"path",
",",
"int",
"$",
"mode",
"=",
"0777",
",",
"bool",
"$",
"isRecursive",
"=",
"false",
")",
":",
"bool",
"{",
"$",
"result",
"=",
"mkdir",
"(",
"$",
"path",
",",
"$",
"mode",
",",
"$"... | Makes a directory at the input path
@param string $path The path to the directory to make
@param int $mode The chmod permissions
@param bool $isRecursive Whether or not we create nested directories
@return bool True if successful, otherwise false | [
"Makes",
"a",
"directory",
"at",
"the",
"input",
"path"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L397-L404 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.read | public function read(string $path) : string
{
if (!$this->isFile($path)) {
throw new FileSystemException("File at path $path not found");
}
return file_get_contents($path);
} | php | public function read(string $path) : string
{
if (!$this->isFile($path)) {
throw new FileSystemException("File at path $path not found");
}
return file_get_contents($path);
} | [
"public",
"function",
"read",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isFile",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileSystemException",
"(",
"\"File at path $path not found\"",
")",
";",
"}"... | Reads the contents of a file
@param string $path The path of the file whose contents we want
@return string The contents of the file
@throws FileSystemException Thrown if the path was not a valid path
@throws InvalidArgumentException Thrown if the path was not a string | [
"Reads",
"the",
"contents",
"of",
"a",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L427-L434 |
opulencephp/Opulence | src/Opulence/IO/FileSystem.php | FileSystem.write | public function write(string $path, $data, int $flags = 0) : int
{
$bytesWritten = file_put_contents($path, $data, $flags);
if ($bytesWritten === false) {
throw new FileSystemException("Failed to write data to path $path");
}
return $bytesWritten;
} | php | public function write(string $path, $data, int $flags = 0) : int
{
$bytesWritten = file_put_contents($path, $data, $flags);
if ($bytesWritten === false) {
throw new FileSystemException("Failed to write data to path $path");
}
return $bytesWritten;
} | [
"public",
"function",
"write",
"(",
"string",
"$",
"path",
",",
"$",
"data",
",",
"int",
"$",
"flags",
"=",
"0",
")",
":",
"int",
"{",
"$",
"bytesWritten",
"=",
"file_put_contents",
"(",
"$",
"path",
",",
"$",
"data",
",",
"$",
"flags",
")",
";",
... | Writes data to a file
@param string $path The path to the file to write to
@param mixed $data The string, array, or stream source to write to the file
@param int $flags The bitwise-OR'd flags to use (identical to PHP's file_put_contents() flags)
@return int The number of bytes written
@throws FileSystemException Thrown if there was a problem writing to the file | [
"Writes",
"data",
"to",
"a",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/IO/FileSystem.php#L445-L454 |
opulencephp/Opulence | src/Opulence/Views/Filters/XssFilter.php | XssFilter.run | public function run(string $input, array $options = []) : string
{
$filteredInput = $input;
if (isset($options['forUrl']) && $options['forUrl']) {
// For URLs, "%27" is the correct way to display an apostrophe
// For HTML, "#39;" (conversion is done in functions below) is the correct way to display an apostrophe
$filteredInput = str_replace("'", '%27', $input);
}
$filteredInput = filter_var($filteredInput, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
return $filteredInput;
} | php | public function run(string $input, array $options = []) : string
{
$filteredInput = $input;
if (isset($options['forUrl']) && $options['forUrl']) {
// For URLs, "%27" is the correct way to display an apostrophe
// For HTML, "#39;" (conversion is done in functions below) is the correct way to display an apostrophe
$filteredInput = str_replace("'", '%27', $input);
}
$filteredInput = filter_var($filteredInput, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
return $filteredInput;
} | [
"public",
"function",
"run",
"(",
"string",
"$",
"input",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"string",
"{",
"$",
"filteredInput",
"=",
"$",
"input",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'forUrl'",
"]",
")",
"&&",
... | Filters the input parameter for XSS attacks
@inheritdoc
@param array $options The list of options with the following keys:
"forURL" => true if the input is being filtered for use in a URL, otherwise false | [
"Filters",
"the",
"input",
"parameter",
"for",
"XSS",
"attacks"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Filters/XssFilter.php#L25-L38 |
opulencephp/Opulence | src/Opulence/Console/Responses/Formatters/TableFormatter.php | TableFormatter.format | public function format(array $rows, array $headers = []) : string
{
if (count($rows) === 0) {
return '';
}
foreach ($rows as &$row) {
$row = (array)$row;
}
unset($row);
// If there are headers, we want them to be formatted along with the rows
$headersAndRows = count($headers) === 0 ? $rows : array_merge([$headers], $rows);
$headersAndRows = count($headers) === 0 ? $rows : array_merge([$headers], $rows);
$maxLengths = $this->padding->normalizeColumns($headersAndRows);
$eolChar = $this->padding->getEolChar();
$rowText = explode($eolChar, $this->padding->format($headersAndRows, function ($row) {
return sprintf(
'%s%s%s%s%s',
$this->verticalBorderChar,
$this->cellPaddingString,
implode($this->cellPaddingString . $this->verticalBorderChar . $this->cellPaddingString, $row),
$this->cellPaddingString,
$this->verticalBorderChar
);
}));
// Create the borders
$borders = [];
foreach ($maxLengths as $maxLength) {
$borders[] = str_repeat($this->horizontalBorderChar, $maxLength + 2 * mb_strlen($this->cellPaddingString));
}
$borderText = $this->intersectionChar . implode($this->intersectionChar, $borders) . $this->intersectionChar;
$headerText = count($headers) > 0 ? array_shift($rowText) . $eolChar . $borderText . $eolChar : '';
return $borderText . $eolChar . $headerText . implode($eolChar, $rowText) . $eolChar . $borderText;
} | php | public function format(array $rows, array $headers = []) : string
{
if (count($rows) === 0) {
return '';
}
foreach ($rows as &$row) {
$row = (array)$row;
}
unset($row);
// If there are headers, we want them to be formatted along with the rows
$headersAndRows = count($headers) === 0 ? $rows : array_merge([$headers], $rows);
$headersAndRows = count($headers) === 0 ? $rows : array_merge([$headers], $rows);
$maxLengths = $this->padding->normalizeColumns($headersAndRows);
$eolChar = $this->padding->getEolChar();
$rowText = explode($eolChar, $this->padding->format($headersAndRows, function ($row) {
return sprintf(
'%s%s%s%s%s',
$this->verticalBorderChar,
$this->cellPaddingString,
implode($this->cellPaddingString . $this->verticalBorderChar . $this->cellPaddingString, $row),
$this->cellPaddingString,
$this->verticalBorderChar
);
}));
// Create the borders
$borders = [];
foreach ($maxLengths as $maxLength) {
$borders[] = str_repeat($this->horizontalBorderChar, $maxLength + 2 * mb_strlen($this->cellPaddingString));
}
$borderText = $this->intersectionChar . implode($this->intersectionChar, $borders) . $this->intersectionChar;
$headerText = count($headers) > 0 ? array_shift($rowText) . $eolChar . $borderText . $eolChar : '';
return $borderText . $eolChar . $headerText . implode($eolChar, $rowText) . $eolChar . $borderText;
} | [
"public",
"function",
"format",
"(",
"array",
"$",
"rows",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
":",
"string",
"{",
"if",
"(",
"count",
"(",
"$",
"rows",
")",
"===",
"0",
")",
"{",
"return",
"''",
";",
"}",
"foreach",
"(",
"$",
"ro... | Formats the table into a string
@param array $rows The list of rows
@param array $headers The list of headers
@return string The formatted table | [
"Formats",
"the",
"table",
"into",
"a",
"string"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Formatters/TableFormatter.php#L44-L83 |
opulencephp/Opulence | src/Opulence/Routing/Urls/UrlGenerator.php | UrlGenerator.createFromName | public function createFromName(string $name, ...$args) : string
{
$route = $this->routeCollection->getNamedRoute($name);
if ($route === null) {
return '';
}
return $this->generateHost($route, $args) . $this->generatePath($route, $args);
} | php | public function createFromName(string $name, ...$args) : string
{
$route = $this->routeCollection->getNamedRoute($name);
if ($route === null) {
return '';
}
return $this->generateHost($route, $args) . $this->generatePath($route, $args);
} | [
"public",
"function",
"createFromName",
"(",
"string",
"$",
"name",
",",
"...",
"$",
"args",
")",
":",
"string",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"routeCollection",
"->",
"getNamedRoute",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"route",
... | Creates a URL for the named route
This function accepts variable-length arguments after the name
@param string $name The named of the route whose URL we're generating
@param array $args,... The list of arguments to pass in
@return string The generated URL if the route exists, otherwise an empty string
@throws URLException Thrown if there was an error generating the URL | [
"Creates",
"a",
"URL",
"for",
"the",
"named",
"route",
"This",
"function",
"accepts",
"variable",
"-",
"length",
"arguments",
"after",
"the",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Urls/UrlGenerator.php#L45-L54 |
opulencephp/Opulence | src/Opulence/Routing/Urls/UrlGenerator.php | UrlGenerator.createRegexFromName | public function createRegexFromName(string $name) : string
{
$route = $this->routeCollection->getNamedRoute($name);
if ($route === null) {
return '#^.*$#';
}
$strippedPathRegex = substr($route->getPathRegex(), 2, -2);
if (empty($route->getRawHost())) {
return "#^$strippedPathRegex$#";
}
$protocolRegex = preg_quote('http' . ($route->isSecure() ? 's' : '') . '://', '#');
$strippedHostRegex = substr($route->getHostRegex(), 2, -2);
return "#^$protocolRegex$strippedHostRegex$strippedPathRegex$#";
} | php | public function createRegexFromName(string $name) : string
{
$route = $this->routeCollection->getNamedRoute($name);
if ($route === null) {
return '#^.*$#';
}
$strippedPathRegex = substr($route->getPathRegex(), 2, -2);
if (empty($route->getRawHost())) {
return "#^$strippedPathRegex$#";
}
$protocolRegex = preg_quote('http' . ($route->isSecure() ? 's' : '') . '://', '#');
$strippedHostRegex = substr($route->getHostRegex(), 2, -2);
return "#^$protocolRegex$strippedHostRegex$strippedPathRegex$#";
} | [
"public",
"function",
"createRegexFromName",
"(",
"string",
"$",
"name",
")",
":",
"string",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"routeCollection",
"->",
"getNamedRoute",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"route",
"===",
"null",
")",
"... | Creates a URL regex for the named route
@param string $name The named of the route whose URL regex we're generating
@return string The generated URL regex
@throws URLException Thrown if there was an error generating the URL regex | [
"Creates",
"a",
"URL",
"regex",
"for",
"the",
"named",
"route"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Urls/UrlGenerator.php#L63-L81 |
opulencephp/Opulence | src/Opulence/Routing/Urls/UrlGenerator.php | UrlGenerator.generateHost | private function generateHost(ParsedRoute $route, &$values) : string
{
$host = '';
if (!empty($route->getRawHost())) {
$host = $this->generateUrlPart($route->getRawHost(), $route->getHostRegex(), $route->getName(), $values);
// Prefix the URL with the protocol
$host = 'http' . ($route->isSecure() ? 's' : '') . '://' . $host;
}
return $host;
} | php | private function generateHost(ParsedRoute $route, &$values) : string
{
$host = '';
if (!empty($route->getRawHost())) {
$host = $this->generateUrlPart($route->getRawHost(), $route->getHostRegex(), $route->getName(), $values);
// Prefix the URL with the protocol
$host = 'http' . ($route->isSecure() ? 's' : '') . '://' . $host;
}
return $host;
} | [
"private",
"function",
"generateHost",
"(",
"ParsedRoute",
"$",
"route",
",",
"&",
"$",
"values",
")",
":",
"string",
"{",
"$",
"host",
"=",
"''",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"route",
"->",
"getRawHost",
"(",
")",
")",
")",
"{",
"$",
... | Generates the host portion of a URL for a route
@param ParsedRoute $route The route whose URL we're generating
@param mixed|array $values The value or list of values to fill the route with
@return string The generated host value
@throws URLException Thrown if the generated host is not valid | [
"Generates",
"the",
"host",
"portion",
"of",
"a",
"URL",
"for",
"a",
"route"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Urls/UrlGenerator.php#L91-L102 |
opulencephp/Opulence | src/Opulence/Routing/Urls/UrlGenerator.php | UrlGenerator.generatePath | private function generatePath(ParsedRoute $route, &$values) : string
{
return $this->generateUrlPart($route->getRawPath(), $route->getPathRegex(), $route->getName(), $values);
} | php | private function generatePath(ParsedRoute $route, &$values) : string
{
return $this->generateUrlPart($route->getRawPath(), $route->getPathRegex(), $route->getName(), $values);
} | [
"private",
"function",
"generatePath",
"(",
"ParsedRoute",
"$",
"route",
",",
"&",
"$",
"values",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"generateUrlPart",
"(",
"$",
"route",
"->",
"getRawPath",
"(",
")",
",",
"$",
"route",
"->",
"getPathR... | Generates the path portion of a URL for a route
@param ParsedRoute $route The route whose URL we're generating
@param mixed|array $values The value or list of values to fill the route with
@return string The generated path value
@throws URLException Thrown if the generated path is not valid | [
"Generates",
"the",
"path",
"portion",
"of",
"a",
"URL",
"for",
"a",
"route"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Urls/UrlGenerator.php#L112-L115 |
opulencephp/Opulence | src/Opulence/Routing/Urls/UrlGenerator.php | UrlGenerator.generateUrlPart | private function generateUrlPart(string $rawPart, string $regex, string $routeName, &$values) : string
{
$generatedPart = $rawPart;
$count = 1000;
while ($count > 0 && count($values) > 0) {
$generatedPart = preg_replace(self::$variableMatchingRegex, $values[0], $generatedPart, 1, $count);
if ($count > 0) {
// Only remove a value if we actually replaced something
array_shift($values);
}
}
// Remove any leftover brackets or variables
$generatedPart = preg_replace(self::$leftoverBracketsAndVariablesRegex, '', $generatedPart);
// Make sure what we just generated satisfies the regex
if (!preg_match($regex, $generatedPart)) {
throw new UrlException(
"Generated URL part \"$generatedPart\" does not satisfy regex for route \"$routeName\""
);
}
return $generatedPart;
} | php | private function generateUrlPart(string $rawPart, string $regex, string $routeName, &$values) : string
{
$generatedPart = $rawPart;
$count = 1000;
while ($count > 0 && count($values) > 0) {
$generatedPart = preg_replace(self::$variableMatchingRegex, $values[0], $generatedPart, 1, $count);
if ($count > 0) {
// Only remove a value if we actually replaced something
array_shift($values);
}
}
// Remove any leftover brackets or variables
$generatedPart = preg_replace(self::$leftoverBracketsAndVariablesRegex, '', $generatedPart);
// Make sure what we just generated satisfies the regex
if (!preg_match($regex, $generatedPart)) {
throw new UrlException(
"Generated URL part \"$generatedPart\" does not satisfy regex for route \"$routeName\""
);
}
return $generatedPart;
} | [
"private",
"function",
"generateUrlPart",
"(",
"string",
"$",
"rawPart",
",",
"string",
"$",
"regex",
",",
"string",
"$",
"routeName",
",",
"&",
"$",
"values",
")",
":",
"string",
"{",
"$",
"generatedPart",
"=",
"$",
"rawPart",
";",
"$",
"count",
"=",
... | Generates a part of a URL for a route
@param string $rawPart The raw part to generate
@param string $regex The regex to match against
@param string $routeName The route name
@param mixed|array $values The value or list of values to fill the route with
@return string The generated URL part
@throws UrlException Thrown if the generated path is not valid | [
"Generates",
"a",
"part",
"of",
"a",
"URL",
"for",
"a",
"route"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Urls/UrlGenerator.php#L127-L152 |
opulencephp/Opulence | src/Opulence/Framework/Console/Bootstrappers/CommandsBootstrapper.php | CommandsBootstrapper.bindCommands | protected function bindCommands(CommandCollection $commands, IContainer $container)
{
// Resolve and add each command class
foreach (self::$commandClasses as $commandClass) {
$commands->add($container->resolve($commandClass));
}
// The command to run Opulence locally requires a path to the router file
$commands->add(new RunAppLocallyCommand(Config::get('paths', 'root') . '/localhost_router.php'));
// The flush-cache command requires some special configuration
try {
$flushCacheCommand = new FlushFrameworkCacheCommand(
new FileCache(Config::get('paths', 'tmp.framework.http') . '/cachedBootstrapperRegistry.json'),
new FileCache(Config::get('paths', 'tmp.framework.console') . '/cachedBootstrapperRegistry.json'),
$container->resolve(RouteCache::class),
$container->resolve(ViewCache::class)
);
$commands->add($flushCacheCommand);
} catch (IocException $ex) {
throw new RuntimeException('Failed to resolve ' . FlushFrameworkCacheCommand::class, 0, $ex);
}
} | php | protected function bindCommands(CommandCollection $commands, IContainer $container)
{
// Resolve and add each command class
foreach (self::$commandClasses as $commandClass) {
$commands->add($container->resolve($commandClass));
}
// The command to run Opulence locally requires a path to the router file
$commands->add(new RunAppLocallyCommand(Config::get('paths', 'root') . '/localhost_router.php'));
// The flush-cache command requires some special configuration
try {
$flushCacheCommand = new FlushFrameworkCacheCommand(
new FileCache(Config::get('paths', 'tmp.framework.http') . '/cachedBootstrapperRegistry.json'),
new FileCache(Config::get('paths', 'tmp.framework.console') . '/cachedBootstrapperRegistry.json'),
$container->resolve(RouteCache::class),
$container->resolve(ViewCache::class)
);
$commands->add($flushCacheCommand);
} catch (IocException $ex) {
throw new RuntimeException('Failed to resolve ' . FlushFrameworkCacheCommand::class, 0, $ex);
}
} | [
"protected",
"function",
"bindCommands",
"(",
"CommandCollection",
"$",
"commands",
",",
"IContainer",
"$",
"container",
")",
"{",
"// Resolve and add each command class",
"foreach",
"(",
"self",
"::",
"$",
"commandClasses",
"as",
"$",
"commandClass",
")",
"{",
"$",... | Binds commands to the collection
@param CommandCollection $commands The collection to add commands to
@param IContainer $container The dependency injection container to use | [
"Binds",
"commands",
"to",
"the",
"collection"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Console/Bootstrappers/CommandsBootstrapper.php#L97-L119 |
opulencephp/Opulence | src/Opulence/Authentication/Credentials/Authenticators/JwtAuthenticator.php | JwtAuthenticator.getSubjectFromJwt | protected function getSubjectFromJwt(SignedJwt $jwt, ICredential $credential) : ISubject
{
$roles = $jwt->getPayload()->get('roles') ?: [];
return new Subject(
[new Principal(PrincipalTypes::PRIMARY, $jwt->getPayload()->getSubject(), $roles)],
[$credential]
);
} | php | protected function getSubjectFromJwt(SignedJwt $jwt, ICredential $credential) : ISubject
{
$roles = $jwt->getPayload()->get('roles') ?: [];
return new Subject(
[new Principal(PrincipalTypes::PRIMARY, $jwt->getPayload()->getSubject(), $roles)],
[$credential]
);
} | [
"protected",
"function",
"getSubjectFromJwt",
"(",
"SignedJwt",
"$",
"jwt",
",",
"ICredential",
"$",
"credential",
")",
":",
"ISubject",
"{",
"$",
"roles",
"=",
"$",
"jwt",
"->",
"getPayload",
"(",
")",
"->",
"get",
"(",
"'roles'",
")",
"?",
":",
"[",
... | Gets a subject from a JWT
@param SignedJwt $jwt The signed JWT
@param ICredential $credential The credential
@return ISubject The subject | [
"Gets",
"a",
"subject",
"from",
"a",
"JWT"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Credentials/Authenticators/JwtAuthenticator.php#L85-L93 |
opulencephp/Opulence | src/Opulence/Routing/Controller.php | Controller.callMethod | public function callMethod(string $methodName, array $parameters) : Response
{
$this->setUpView();
/** @var Response $response */
$response = $this->$methodName(...$parameters);
if ($response === null || is_string($response)) {
$response = new Response($response === null ? '' : $response);
if ($this->viewCompiler instanceof ICompiler && $this->view !== null) {
$response->setContent($this->viewCompiler->compile($this->view));
}
}
return $response;
} | php | public function callMethod(string $methodName, array $parameters) : Response
{
$this->setUpView();
/** @var Response $response */
$response = $this->$methodName(...$parameters);
if ($response === null || is_string($response)) {
$response = new Response($response === null ? '' : $response);
if ($this->viewCompiler instanceof ICompiler && $this->view !== null) {
$response->setContent($this->viewCompiler->compile($this->view));
}
}
return $response;
} | [
"public",
"function",
"callMethod",
"(",
"string",
"$",
"methodName",
",",
"array",
"$",
"parameters",
")",
":",
"Response",
"{",
"$",
"this",
"->",
"setUpView",
"(",
")",
";",
"/** @var Response $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"$",
... | Actually calls the method in the controller
Rather than calling the method directly from the route dispatcher, call this method
@param string $methodName The name of the method in $this to call
@param array $parameters The list of parameters to pass into the action method
@return Response The HTTP response returned by the method | [
"Actually",
"calls",
"the",
"method",
"in",
"the",
"controller",
"Rather",
"than",
"calling",
"the",
"method",
"directly",
"from",
"the",
"route",
"dispatcher",
"call",
"this",
"method"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Controller.php#L41-L56 |
opulencephp/Opulence | src/Opulence/Cache/FileBridge.php | FileBridge.parseData | protected function parseData(string $key) : array
{
if (file_exists($this->getPath($key))) {
$rawData = json_decode(file_get_contents($this->getPath($key)), true);
$parsedData = ['d' => unserialize($rawData['d']), 't' => $rawData['t']];
} else {
$parsedData = ['d' => null, 't' => 0];
}
if (time() > $parsedData['t']) {
$this->delete($key);
return ['d' => null, 't' => 0];
}
return $parsedData;
} | php | protected function parseData(string $key) : array
{
if (file_exists($this->getPath($key))) {
$rawData = json_decode(file_get_contents($this->getPath($key)), true);
$parsedData = ['d' => unserialize($rawData['d']), 't' => $rawData['t']];
} else {
$parsedData = ['d' => null, 't' => 0];
}
if (time() > $parsedData['t']) {
$this->delete($key);
return ['d' => null, 't' => 0];
}
return $parsedData;
} | [
"protected",
"function",
"parseData",
"(",
"string",
"$",
"key",
")",
":",
"array",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"getPath",
"(",
"$",
"key",
")",
")",
")",
"{",
"$",
"rawData",
"=",
"json_decode",
"(",
"file_get_contents",
"("... | Runs garbage collection on a key, if necessary
@param string $key The key to run garbage collection on
@return array The array of data after running any garbage collection | [
"Runs",
"garbage",
"collection",
"on",
"a",
"key",
"if",
"necessary"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cache/FileBridge.php#L122-L138 |
opulencephp/Opulence | src/Opulence/Cache/FileBridge.php | FileBridge.serialize | protected function serialize($data, int $lifetime) : string
{
return json_encode(
['d' => serialize($data), 't' => time() + $lifetime]
);
} | php | protected function serialize($data, int $lifetime) : string
{
return json_encode(
['d' => serialize($data), 't' => time() + $lifetime]
);
} | [
"protected",
"function",
"serialize",
"(",
"$",
"data",
",",
"int",
"$",
"lifetime",
")",
":",
"string",
"{",
"return",
"json_encode",
"(",
"[",
"'d'",
"=>",
"serialize",
"(",
"$",
"data",
")",
",",
"'t'",
"=>",
"time",
"(",
")",
"+",
"$",
"lifetime"... | Serializes the data with lifetime information
@param mixed $data The data to serialize
@param int $lifetime The lifetime in seconds
@return string The serialized data | [
"Serializes",
"the",
"data",
"with",
"lifetime",
"information"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cache/FileBridge.php#L147-L152 |
opulencephp/Opulence | src/Opulence/Cache/FileBridge.php | FileBridge.unserialize | protected function unserialize(string $data)
{
$unserializedData = json_decode($data, true);
$unserializedData['d'] = unserialize($unserializedData['d']);
return $unserializedData;
} | php | protected function unserialize(string $data)
{
$unserializedData = json_decode($data, true);
$unserializedData['d'] = unserialize($unserializedData['d']);
return $unserializedData;
} | [
"protected",
"function",
"unserialize",
"(",
"string",
"$",
"data",
")",
"{",
"$",
"unserializedData",
"=",
"json_decode",
"(",
"$",
"data",
",",
"true",
")",
";",
"$",
"unserializedData",
"[",
"'d'",
"]",
"=",
"unserialize",
"(",
"$",
"unserializedData",
... | Unserializes the data from storage
@param string $data The data to unserialize
@return mixed The serialized data | [
"Unserializes",
"the",
"data",
"from",
"storage"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cache/FileBridge.php#L160-L166 |
opulencephp/Opulence | src/Opulence/QueryBuilders/Conditions/ConditionFactory.php | ConditionFactory.between | public function between(string $column, $min, $max, $dataType = PDO::PARAM_STR) : BetweenCondition
{
return new BetweenCondition($column, $min, $max, $dataType);
} | php | public function between(string $column, $min, $max, $dataType = PDO::PARAM_STR) : BetweenCondition
{
return new BetweenCondition($column, $min, $max, $dataType);
} | [
"public",
"function",
"between",
"(",
"string",
"$",
"column",
",",
"$",
"min",
",",
"$",
"max",
",",
"$",
"dataType",
"=",
"PDO",
"::",
"PARAM_STR",
")",
":",
"BetweenCondition",
"{",
"return",
"new",
"BetweenCondition",
"(",
"$",
"column",
",",
"$",
... | Creates a new BETWEEN condition
@param string $column The name of the column
@param mixed $min The min value
@param mixed $max The max value
@param int $dataType The PDO data type for the min and max
@return BetweenCondition The condition | [
"Creates",
"a",
"new",
"BETWEEN",
"condition"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/QueryBuilders/Conditions/ConditionFactory.php#L30-L33 |
opulencephp/Opulence | src/Opulence/QueryBuilders/Conditions/ConditionFactory.php | ConditionFactory.notBetween | public function notBetween(string $column, $min, $max, $dataType = PDO::PARAM_STR) : NotBetweenCondition
{
return new NotBetweenCondition($column, $min, $max, $dataType);
} | php | public function notBetween(string $column, $min, $max, $dataType = PDO::PARAM_STR) : NotBetweenCondition
{
return new NotBetweenCondition($column, $min, $max, $dataType);
} | [
"public",
"function",
"notBetween",
"(",
"string",
"$",
"column",
",",
"$",
"min",
",",
"$",
"max",
",",
"$",
"dataType",
"=",
"PDO",
"::",
"PARAM_STR",
")",
":",
"NotBetweenCondition",
"{",
"return",
"new",
"NotBetweenCondition",
"(",
"$",
"column",
",",
... | Creates a new NOT BETWEEN condition
@param string $column The name of the column
@param mixed $min The min value
@param mixed $max The max value
@param int $dataType The PDO data type for the min and max
@return NotBetweenCondition The condition | [
"Creates",
"a",
"new",
"NOT",
"BETWEEN",
"condition"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/QueryBuilders/Conditions/ConditionFactory.php#L57-L60 |
opulencephp/Opulence | src/Opulence/Authentication/Credentials/Factories/JwtCredentialFactory.php | JwtCredentialFactory.getSignedJwt | protected function getSignedJwt(ISubject $subject) : SignedJwt
{
$jwtPayload = new JwtPayload();
$jwtPayload->setIssuer($this->issuer);
$jwtPayload->setAudience($this->audience);
$jwtPayload->setSubject($subject->getPrimaryPrincipal()->getId());
$jwtPayload->setValidFrom((new DateTimeImmutable)->add($this->validFromInterval));
$jwtPayload->setValidTo((new DateTimeImmutable)->add($this->validToInterval));
$jwtPayload->setIssuedAt(new DateTimeImmutable());
$this->addCustomClaims($jwtPayload, $subject);
$unsignedJwt = new UnsignedJwt(new JwtHeader(), $jwtPayload);
return SignedJwt::createFromUnsignedJwt($unsignedJwt, $this->signer->sign($unsignedJwt->getUnsignedValue()));
} | php | protected function getSignedJwt(ISubject $subject) : SignedJwt
{
$jwtPayload = new JwtPayload();
$jwtPayload->setIssuer($this->issuer);
$jwtPayload->setAudience($this->audience);
$jwtPayload->setSubject($subject->getPrimaryPrincipal()->getId());
$jwtPayload->setValidFrom((new DateTimeImmutable)->add($this->validFromInterval));
$jwtPayload->setValidTo((new DateTimeImmutable)->add($this->validToInterval));
$jwtPayload->setIssuedAt(new DateTimeImmutable());
$this->addCustomClaims($jwtPayload, $subject);
$unsignedJwt = new UnsignedJwt(new JwtHeader(), $jwtPayload);
return SignedJwt::createFromUnsignedJwt($unsignedJwt, $this->signer->sign($unsignedJwt->getUnsignedValue()));
} | [
"protected",
"function",
"getSignedJwt",
"(",
"ISubject",
"$",
"subject",
")",
":",
"SignedJwt",
"{",
"$",
"jwtPayload",
"=",
"new",
"JwtPayload",
"(",
")",
";",
"$",
"jwtPayload",
"->",
"setIssuer",
"(",
"$",
"this",
"->",
"issuer",
")",
";",
"$",
"jwtP... | Gets the signed JWT for a subject
@param ISubject $subject The subject whose credential we're creating
@return SignedJwt The signed JWT | [
"Gets",
"the",
"signed",
"JWT",
"for",
"a",
"subject"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Credentials/Factories/JwtCredentialFactory.php#L95-L108 |
opulencephp/Opulence | src/Opulence/Databases/Migrations/FileMigrationFinder.php | FileMigrationFinder.findAll | public function findAll($paths) : array
{
if (is_string($paths)) {
$paths = [$paths];
}
if (!is_array($paths)) {
throw new InvalidArgumentException('Paths must be a string or array');
}
$allClassNames = [];
foreach ($paths as $path) {
if (!is_dir($path)) {
throw new InvalidArgumentException("Path $path is not a directory");
}
$fileIter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($fileIter as $file) {
if ($file->getExtension() !== 'php') {
continue;
}
$tokens = token_get_all(file_get_contents($file->getRealPath()));
$allClassNames = array_merge($allClassNames, $this->getClassNamesFromTokens($tokens));
}
}
// Filter out any non-concrete migration classes
$migrationClassNames = array_filter($allClassNames, function ($className) {
$reflectionClass = new ReflectionClass($className);
return $reflectionClass->implementsInterface(IMigration::class) &&
!$reflectionClass->isInterface() &&
!$reflectionClass->isAbstract();
});
// Sort the migration classes by their creation dates
usort($migrationClassNames, function (string $a, string $b) {
return $a::getCreationDate() <=> $b::getCreationDate();
});
return $migrationClassNames;
} | php | public function findAll($paths) : array
{
if (is_string($paths)) {
$paths = [$paths];
}
if (!is_array($paths)) {
throw new InvalidArgumentException('Paths must be a string or array');
}
$allClassNames = [];
foreach ($paths as $path) {
if (!is_dir($path)) {
throw new InvalidArgumentException("Path $path is not a directory");
}
$fileIter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($fileIter as $file) {
if ($file->getExtension() !== 'php') {
continue;
}
$tokens = token_get_all(file_get_contents($file->getRealPath()));
$allClassNames = array_merge($allClassNames, $this->getClassNamesFromTokens($tokens));
}
}
// Filter out any non-concrete migration classes
$migrationClassNames = array_filter($allClassNames, function ($className) {
$reflectionClass = new ReflectionClass($className);
return $reflectionClass->implementsInterface(IMigration::class) &&
!$reflectionClass->isInterface() &&
!$reflectionClass->isAbstract();
});
// Sort the migration classes by their creation dates
usort($migrationClassNames, function (string $a, string $b) {
return $a::getCreationDate() <=> $b::getCreationDate();
});
return $migrationClassNames;
} | [
"public",
"function",
"findAll",
"(",
"$",
"paths",
")",
":",
"array",
"{",
"if",
"(",
"is_string",
"(",
"$",
"paths",
")",
")",
"{",
"$",
"paths",
"=",
"[",
"$",
"paths",
"]",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"paths",
")",
")",
... | Recursively finds all migration classes in the order they're to be run
@param string|array $paths The path or list of paths to search
@return string[] The list of all migration class names
@throws InvalidArgumentException Thrown if the paths are not a string or array | [
"Recursively",
"finds",
"all",
"migration",
"classes",
"in",
"the",
"order",
"they",
"re",
"to",
"be",
"run"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Migrations/FileMigrationFinder.php#L30-L74 |
opulencephp/Opulence | src/Opulence/Databases/Migrations/FileMigrationFinder.php | FileMigrationFinder.getClassNamesFromTokens | private function getClassNamesFromTokens(array $tokens) : array
{
for ($i = 0;$i < count($tokens);$i++) {
// Skip literals
if (is_string($tokens[$i])) {
continue;
}
$className = '';
switch ($tokens[$i][0]) {
case T_NAMESPACE:
$namespace = '';
// Collect all the namespace parts and separators
while (isset($tokens[++$i][1])) {
if (in_array($tokens[$i][0], [T_NS_SEPARATOR, T_STRING])) {
$namespace .= $tokens[$i][1];
}
}
break;
case T_CLASS:
$isClassConstant = false;
// Scan previous tokens to see if they're double colons, which would mean this is a class constant
for ($j = $i - 1;$j >= 0;$j--) {
if (!isset($tokens[$j][1])) {
break;
}
if ($tokens[$j][0] === T_DOUBLE_COLON) {
$isClassConstant = true;
break 2;
} elseif ($tokens[$j][0] === T_WHITESPACE) {
// Since we found whitespace, then we know this isn't a class constant
break;
}
}
// Get the class name
while (isset($tokens[++$i][1])) {
if ($tokens[$i][0] === T_STRING) {
$className .= $tokens[$i][1];
break;
}
}
$classNames[] = ltrim($namespace . '\\' . $className, '\\');
break 2;
}
}
return $classNames;
} | php | private function getClassNamesFromTokens(array $tokens) : array
{
for ($i = 0;$i < count($tokens);$i++) {
// Skip literals
if (is_string($tokens[$i])) {
continue;
}
$className = '';
switch ($tokens[$i][0]) {
case T_NAMESPACE:
$namespace = '';
// Collect all the namespace parts and separators
while (isset($tokens[++$i][1])) {
if (in_array($tokens[$i][0], [T_NS_SEPARATOR, T_STRING])) {
$namespace .= $tokens[$i][1];
}
}
break;
case T_CLASS:
$isClassConstant = false;
// Scan previous tokens to see if they're double colons, which would mean this is a class constant
for ($j = $i - 1;$j >= 0;$j--) {
if (!isset($tokens[$j][1])) {
break;
}
if ($tokens[$j][0] === T_DOUBLE_COLON) {
$isClassConstant = true;
break 2;
} elseif ($tokens[$j][0] === T_WHITESPACE) {
// Since we found whitespace, then we know this isn't a class constant
break;
}
}
// Get the class name
while (isset($tokens[++$i][1])) {
if ($tokens[$i][0] === T_STRING) {
$className .= $tokens[$i][1];
break;
}
}
$classNames[] = ltrim($namespace . '\\' . $className, '\\');
break 2;
}
}
return $classNames;
} | [
"private",
"function",
"getClassNamesFromTokens",
"(",
"array",
"$",
"tokens",
")",
":",
"array",
"{",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"count",
"(",
"$",
"tokens",
")",
";",
"$",
"i",
"++",
")",
"{",
"// Skip literals",
"if",
"(... | Gets the class names from a list of tokens
This will work even if multiple classes are defined in each file
@param string[] $tokens The array of tokens
@return string[] The names of the classes | [
"Gets",
"the",
"class",
"names",
"from",
"a",
"list",
"of",
"tokens",
"This",
"will",
"work",
"even",
"if",
"multiple",
"classes",
"are",
"defined",
"in",
"each",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Migrations/FileMigrationFinder.php#L83-L137 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.createFromGlobals | public static function createFromGlobals(
array $query = null,
array $post = null,
array $cookies = null,
array $server = null,
array $files = null,
array $env = null,
string $rawBody = null
) : Request {
$query = $query ?? $_GET;
$post = $post ?? $_POST;
$cookies = $cookies ?? $_COOKIE;
$server = $server ?? $_SERVER;
$files = $files ?? $_FILES;
$env = $env ?? $_ENV;
// Handle the a bug that does not set CONTENT_TYPE or CONTENT_LENGTH headers
if (array_key_exists('HTTP_CONTENT_LENGTH', $server)) {
$server['CONTENT_LENGTH'] = $server['HTTP_CONTENT_LENGTH'];
}
if (array_key_exists('HTTP_CONTENT_TYPE', $server)) {
$server['CONTENT_TYPE'] = $server['HTTP_CONTENT_TYPE'];
}
return new static($query, $post, $cookies, $server, $files, $env, $rawBody);
} | php | public static function createFromGlobals(
array $query = null,
array $post = null,
array $cookies = null,
array $server = null,
array $files = null,
array $env = null,
string $rawBody = null
) : Request {
$query = $query ?? $_GET;
$post = $post ?? $_POST;
$cookies = $cookies ?? $_COOKIE;
$server = $server ?? $_SERVER;
$files = $files ?? $_FILES;
$env = $env ?? $_ENV;
// Handle the a bug that does not set CONTENT_TYPE or CONTENT_LENGTH headers
if (array_key_exists('HTTP_CONTENT_LENGTH', $server)) {
$server['CONTENT_LENGTH'] = $server['HTTP_CONTENT_LENGTH'];
}
if (array_key_exists('HTTP_CONTENT_TYPE', $server)) {
$server['CONTENT_TYPE'] = $server['HTTP_CONTENT_TYPE'];
}
return new static($query, $post, $cookies, $server, $files, $env, $rawBody);
} | [
"public",
"static",
"function",
"createFromGlobals",
"(",
"array",
"$",
"query",
"=",
"null",
",",
"array",
"$",
"post",
"=",
"null",
",",
"array",
"$",
"cookies",
"=",
"null",
",",
"array",
"$",
"server",
"=",
"null",
",",
"array",
"$",
"files",
"=",
... | Creates an instance of this class using the PHP globals
@param array|null $query The GET parameters, or null if using the globals
@param array|null $post The POST parameters, or null if using the globals
@param array|null $cookies The COOKIE parameters, or null if using the globals
@param array|null $server The SERVER parameters, or null if using the globals
@param array|null $files The FILES parameters, or null if using the globals
@param array|null $env The ENV parameters, or null if using the globals
@param string|null $rawBody The raw body
@return Request An instance of this class | [
"Creates",
"an",
"instance",
"of",
"this",
"class",
"using",
"the",
"PHP",
"globals"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L126-L152 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.createFromUrl | public static function createFromUrl(
string $url,
string $method,
array $parameters = [],
array $cookies = [],
array $server = [],
array $files = [],
array $env = [],
string $rawBody = null
) : Request {
// Define some basic server vars, but override them with with input on collision
$server = array_replace(
[
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_HOST' => 'localhost',
'REMOTE_ADDR' => '127.0.01',
'SCRIPT_FILENAME' => '',
'SCRIPT_NAME' => '',
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'SERVER_PROTOCOL' => 'HTTP/1.1'
],
$server
);
$query = [];
$post = [];
// Set the content type for unsupported HTTP methods
if ($method === RequestMethods::GET) {
$query = $parameters;
} elseif ($method === RequestMethods::POST) {
$post = $parameters;
} elseif (
in_array($method, [RequestMethods::PUT, RequestMethods::PATCH, RequestMethods::DELETE]) &&
!isset($server['CONTENT_TYPE'])
) {
$server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
}
$server['REQUEST_METHOD'] = $method;
$parsedUrl = parse_url($url);
if (isset($parsedUrl['host'])) {
$server['HTTP_HOST'] = $parsedUrl['host'];
}
if (isset($parsedUrl['path'])) {
$server['REQUEST_URI'] = $parsedUrl['path'];
}
if (isset($parsedUrl['query'])) {
parse_str(html_entity_decode($parsedUrl['query']), $queryFromUrl);
$query = array_replace($queryFromUrl, $query);
}
$queryString = http_build_query($query, '', '&');
$server['QUERY_STRING'] = $queryString;
$server['REQUEST_URI'] .= count($query) > 0 ? "?$queryString" : '';
if (isset($parsedUrl['scheme'])) {
if ($parsedUrl['scheme'] === 'https') {
$server['HTTPS'] = 'on';
$server['SERVER_PORT'] = 443;
} else {
unset($server['HTTPS']);
$server['SERVER_PORT'] = 80;
}
}
if (isset($parsedUrl['port'])) {
$server['SERVER_PORT'] = $parsedUrl['port'];
$server['HTTP_HOST'] .= ":{$parsedUrl['port']}";
}
$parsedFiles = [];
foreach ($files as $file) {
$parsedFiles[] = [
'tmp_name' => $file->getFilename(),
'name' => $file->getTempFilename(),
'size' => $file->getTempSize(),
'type' => $file->getTempMimeType(),
'error' => $file->getError()
];
}
return new static($query, $post, $cookies, $server, $parsedFiles, $env, $rawBody);
} | php | public static function createFromUrl(
string $url,
string $method,
array $parameters = [],
array $cookies = [],
array $server = [],
array $files = [],
array $env = [],
string $rawBody = null
) : Request {
// Define some basic server vars, but override them with with input on collision
$server = array_replace(
[
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_HOST' => 'localhost',
'REMOTE_ADDR' => '127.0.01',
'SCRIPT_FILENAME' => '',
'SCRIPT_NAME' => '',
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'SERVER_PROTOCOL' => 'HTTP/1.1'
],
$server
);
$query = [];
$post = [];
// Set the content type for unsupported HTTP methods
if ($method === RequestMethods::GET) {
$query = $parameters;
} elseif ($method === RequestMethods::POST) {
$post = $parameters;
} elseif (
in_array($method, [RequestMethods::PUT, RequestMethods::PATCH, RequestMethods::DELETE]) &&
!isset($server['CONTENT_TYPE'])
) {
$server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
}
$server['REQUEST_METHOD'] = $method;
$parsedUrl = parse_url($url);
if (isset($parsedUrl['host'])) {
$server['HTTP_HOST'] = $parsedUrl['host'];
}
if (isset($parsedUrl['path'])) {
$server['REQUEST_URI'] = $parsedUrl['path'];
}
if (isset($parsedUrl['query'])) {
parse_str(html_entity_decode($parsedUrl['query']), $queryFromUrl);
$query = array_replace($queryFromUrl, $query);
}
$queryString = http_build_query($query, '', '&');
$server['QUERY_STRING'] = $queryString;
$server['REQUEST_URI'] .= count($query) > 0 ? "?$queryString" : '';
if (isset($parsedUrl['scheme'])) {
if ($parsedUrl['scheme'] === 'https') {
$server['HTTPS'] = 'on';
$server['SERVER_PORT'] = 443;
} else {
unset($server['HTTPS']);
$server['SERVER_PORT'] = 80;
}
}
if (isset($parsedUrl['port'])) {
$server['SERVER_PORT'] = $parsedUrl['port'];
$server['HTTP_HOST'] .= ":{$parsedUrl['port']}";
}
$parsedFiles = [];
foreach ($files as $file) {
$parsedFiles[] = [
'tmp_name' => $file->getFilename(),
'name' => $file->getTempFilename(),
'size' => $file->getTempSize(),
'type' => $file->getTempMimeType(),
'error' => $file->getError()
];
}
return new static($query, $post, $cookies, $server, $parsedFiles, $env, $rawBody);
} | [
"public",
"static",
"function",
"createFromUrl",
"(",
"string",
"$",
"url",
",",
"string",
"$",
"method",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"array",
"$",
"cookies",
"=",
"[",
"]",
",",
"array",
"$",
"server",
"=",
"[",
"]",
",",
... | Creates an instance of this class from a URL
@param string $url The URL
@param string $method The HTTP method
@param array $parameters The parameters (will be bound to query if GET request, otherwise bound to post)
@param array $cookies The COOKIE parameters
@param array $server The SERVER parameters
@param UploadedFile[] $files The list of uploaded files
@param array $env The ENV parameters
@param string|null $rawBody The raw body
@return Request An instance of this class | [
"Creates",
"an",
"instance",
"of",
"this",
"class",
"from",
"a",
"URL"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L167-L255 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.getFullUrl | public function getFullUrl() : string
{
$isSecure = $this->isSecure();
$rawProtocol = strtolower($this->server->get('SERVER_PROTOCOL'));
$parsedProtocol = substr($rawProtocol, 0, strpos($rawProtocol, '/')) . ($isSecure ? 's' : '');
$port = $this->getPort();
$host = $this->getHost();
// Prepend a colon if the port is non-standard
if ((!$isSecure && $port != '80') || ($isSecure && $port != '443')) {
$port = ":$port";
} else {
$port = '';
}
return $parsedProtocol . '://' . $host . $port . $this->server->get('REQUEST_URI');
} | php | public function getFullUrl() : string
{
$isSecure = $this->isSecure();
$rawProtocol = strtolower($this->server->get('SERVER_PROTOCOL'));
$parsedProtocol = substr($rawProtocol, 0, strpos($rawProtocol, '/')) . ($isSecure ? 's' : '');
$port = $this->getPort();
$host = $this->getHost();
// Prepend a colon if the port is non-standard
if ((!$isSecure && $port != '80') || ($isSecure && $port != '443')) {
$port = ":$port";
} else {
$port = '';
}
return $parsedProtocol . '://' . $host . $port . $this->server->get('REQUEST_URI');
} | [
"public",
"function",
"getFullUrl",
"(",
")",
":",
"string",
"{",
"$",
"isSecure",
"=",
"$",
"this",
"->",
"isSecure",
"(",
")",
";",
"$",
"rawProtocol",
"=",
"strtolower",
"(",
"$",
"this",
"->",
"server",
"->",
"get",
"(",
"'SERVER_PROTOCOL'",
")",
"... | Gets the full URL for the current request
@return string The full URL
@link http://stackoverflow.com/questions/6768793/get-the-full-url-in-php#answer-8891890 | [
"Gets",
"the",
"full",
"URL",
"for",
"the",
"current",
"request"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L341-L357 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.getHost | public function getHost() : string
{
$host = null;
if ($this->isUsingTrustedProxy() && $this->headers->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_HOST])) {
$hosts = explode(',', $this->headers->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_HOST]));
$host = trim(end($hosts));
}
if ($host === null) {
$host = $this->headers->get('HOST');
}
if ($host === null) {
$host = $this->server->get('SERVER_NAME');
}
if ($host === null) {
// Return an empty string by default so we can do string operations on it later
$host = $this->server->get('SERVER_ADDR', '');
}
// Remove the port number
$host = strtolower(preg_replace("/:\d+$/", '', trim($host)));
// Check for forbidden characters
// Credit: Symfony HTTPFoundation
if (!empty($host) && !empty(preg_replace("/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/", '', $host))) {
throw new InvalidArgumentException("Invalid host \"$host\"");
}
return $host;
} | php | public function getHost() : string
{
$host = null;
if ($this->isUsingTrustedProxy() && $this->headers->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_HOST])) {
$hosts = explode(',', $this->headers->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_HOST]));
$host = trim(end($hosts));
}
if ($host === null) {
$host = $this->headers->get('HOST');
}
if ($host === null) {
$host = $this->server->get('SERVER_NAME');
}
if ($host === null) {
// Return an empty string by default so we can do string operations on it later
$host = $this->server->get('SERVER_ADDR', '');
}
// Remove the port number
$host = strtolower(preg_replace("/:\d+$/", '', trim($host)));
// Check for forbidden characters
// Credit: Symfony HTTPFoundation
if (!empty($host) && !empty(preg_replace("/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/", '', $host))) {
throw new InvalidArgumentException("Invalid host \"$host\"");
}
return $host;
} | [
"public",
"function",
"getHost",
"(",
")",
":",
"string",
"{",
"$",
"host",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"isUsingTrustedProxy",
"(",
")",
"&&",
"$",
"this",
"->",
"headers",
"->",
"has",
"(",
"self",
"::",
"$",
"trustedHeaderNames",
... | Gets the host name
@return string The host
@throws InvalidArgumentException Thrown if the host was invalid | [
"Gets",
"the",
"host",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L373-L405 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.getInput | public function getInput(string $name, $default = null)
{
if ($this->isJson()) {
$json = $this->getJsonBody();
if (array_key_exists($name, $json)) {
return $json[$name];
} else {
return $default;
}
} else {
$value = null;
switch ($this->method) {
case RequestMethods::GET:
return $this->query->get($name, $default);
case RequestMethods::POST:
$value = $this->post->get($name, $default);
break;
case RequestMethods::DELETE:
$value = $this->delete->get($name, $default);
break;
case RequestMethods::PUT:
$value = $this->put->get($name, $default);
break;
case RequestMethods::PATCH:
$value = $this->patch->get($name, $default);
break;
}
if ($value === null) {
// Try falling back to query
$value = $this->query->get($name, $default);
}
return $value;
}
} | php | public function getInput(string $name, $default = null)
{
if ($this->isJson()) {
$json = $this->getJsonBody();
if (array_key_exists($name, $json)) {
return $json[$name];
} else {
return $default;
}
} else {
$value = null;
switch ($this->method) {
case RequestMethods::GET:
return $this->query->get($name, $default);
case RequestMethods::POST:
$value = $this->post->get($name, $default);
break;
case RequestMethods::DELETE:
$value = $this->delete->get($name, $default);
break;
case RequestMethods::PUT:
$value = $this->put->get($name, $default);
break;
case RequestMethods::PATCH:
$value = $this->patch->get($name, $default);
break;
}
if ($value === null) {
// Try falling back to query
$value = $this->query->get($name, $default);
}
return $value;
}
} | [
"public",
"function",
"getInput",
"(",
"string",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isJson",
"(",
")",
")",
"{",
"$",
"json",
"=",
"$",
"this",
"->",
"getJsonBody",
"(",
")",
";",
"if",
"(",
... | Gets the input from either GET or POST data
@param string $name The name of the input to get
@param null|mixed $default The default value to return if the input could not be found
@return mixed The value of the input if it was found, otherwise the default value | [
"Gets",
"the",
"input",
"from",
"either",
"GET",
"or",
"POST",
"data"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L414-L451 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.getJsonBody | public function getJsonBody() : array
{
$json = json_decode($this->getRawBody(), true);
if ($json === null) {
throw new RuntimeException('Body could not be decoded as JSON');
}
return $json;
} | php | public function getJsonBody() : array
{
$json = json_decode($this->getRawBody(), true);
if ($json === null) {
throw new RuntimeException('Body could not be decoded as JSON');
}
return $json;
} | [
"public",
"function",
"getJsonBody",
"(",
")",
":",
"array",
"{",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"getRawBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"$",
"json",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeExcepti... | Gets the raw body as a JSON array
@return array The JSON-decoded body
@throws RuntimeException Thrown if the body could not be decoded | [
"Gets",
"the",
"raw",
"body",
"as",
"a",
"JSON",
"array"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L459-L468 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.getPort | public function getPort() : int
{
if ($this->isUsingTrustedProxy()) {
if ($this->server->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_PORT])) {
return (int)$this->server->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_PORT]);
} elseif ($this->server->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_PROTO]) === 'https') {
return 443;
}
}
return (int)$this->server->get('SERVER_PORT');
} | php | public function getPort() : int
{
if ($this->isUsingTrustedProxy()) {
if ($this->server->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_PORT])) {
return (int)$this->server->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_PORT]);
} elseif ($this->server->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_PROTO]) === 'https') {
return 443;
}
}
return (int)$this->server->get('SERVER_PORT');
} | [
"public",
"function",
"getPort",
"(",
")",
":",
"int",
"{",
"if",
"(",
"$",
"this",
"->",
"isUsingTrustedProxy",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"server",
"->",
"has",
"(",
"self",
"::",
"$",
"trustedHeaderNames",
"[",
"RequestHeaders... | Gets the port number
@return int The port number | [
"Gets",
"the",
"port",
"number"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L511-L522 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.getPreviousUrl | public function getPreviousUrl(bool $fallBackToReferer = true) : string
{
if (!empty($this->previousUrl)) {
return $this->previousUrl;
}
if ($fallBackToReferer) {
return $this->headers->get('REFERER', '');
}
return '';
} | php | public function getPreviousUrl(bool $fallBackToReferer = true) : string
{
if (!empty($this->previousUrl)) {
return $this->previousUrl;
}
if ($fallBackToReferer) {
return $this->headers->get('REFERER', '');
}
return '';
} | [
"public",
"function",
"getPreviousUrl",
"(",
"bool",
"$",
"fallBackToReferer",
"=",
"true",
")",
":",
"string",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"previousUrl",
")",
")",
"{",
"return",
"$",
"this",
"->",
"previousUrl",
";",
"}",
"i... | The previous URL, if one was set, otherwise the referrer header
@param bool $fallBackToReferer True if we fall back to the HTTP referer header, otherwise false
@return string The previous URL | [
"The",
"previous",
"URL",
"if",
"one",
"was",
"set",
"otherwise",
"the",
"referrer",
"header"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L538-L549 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.isPath | public function isPath(string $path, bool $isRegex = false) : bool
{
if ($isRegex) {
return preg_match('#^' . $path . '$#', $this->path) === 1;
} else {
return $this->path == $path;
}
} | php | public function isPath(string $path, bool $isRegex = false) : bool
{
if ($isRegex) {
return preg_match('#^' . $path . '$#', $this->path) === 1;
} else {
return $this->path == $path;
}
} | [
"public",
"function",
"isPath",
"(",
"string",
"$",
"path",
",",
"bool",
"$",
"isRegex",
"=",
"false",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"isRegex",
")",
"{",
"return",
"preg_match",
"(",
"'#^'",
".",
"$",
"path",
".",
"'$#'",
",",
"$",
"this",... | Gets whether or not the current path matches the input path or regular expression
@param string $path The path or regular expression to match against
If the path is a regular expression, it should not include regex delimiters
@param bool $isRegex True if the path is a regular expression, otherwise false
@return bool True if the current path matched the path, otherwise false | [
"Gets",
"whether",
"or",
"not",
"the",
"current",
"path",
"matches",
"the",
"input",
"path",
"or",
"regular",
"expression"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L627-L634 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.isSecure | public function isSecure() : bool
{
if ($this->isUsingTrustedProxy() && $this->server->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_PROTO])) {
$protoString = $this->server->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_PROTO]);
$protoArray = explode(',', $protoString);
return count($protoArray) > 0 && in_array(strtolower($protoArray[0]), ['https', 'ssl', 'on']);
}
return $this->server->has('HTTPS') && $this->server->get('HTTPS') !== 'off';
} | php | public function isSecure() : bool
{
if ($this->isUsingTrustedProxy() && $this->server->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_PROTO])) {
$protoString = $this->server->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_PROTO]);
$protoArray = explode(',', $protoString);
return count($protoArray) > 0 && in_array(strtolower($protoArray[0]), ['https', 'ssl', 'on']);
}
return $this->server->has('HTTPS') && $this->server->get('HTTPS') !== 'off';
} | [
"public",
"function",
"isSecure",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"isUsingTrustedProxy",
"(",
")",
"&&",
"$",
"this",
"->",
"server",
"->",
"has",
"(",
"self",
"::",
"$",
"trustedHeaderNames",
"[",
"RequestHeaders",
"::",
"CLIEN... | Gets whether or not the request was made through HTTPS
@return bool True if the request is secure, otherwise false | [
"Gets",
"whether",
"or",
"not",
"the",
"request",
"was",
"made",
"through",
"HTTPS"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L641-L651 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.isUrl | public function isUrl(string $url, bool $isRegex = false) : bool
{
if ($isRegex) {
return preg_match('#^' . $url . '$#', $this->getFullUrl()) === 1;
} else {
return $this->getFullUrl() == $url;
}
} | php | public function isUrl(string $url, bool $isRegex = false) : bool
{
if ($isRegex) {
return preg_match('#^' . $url . '$#', $this->getFullUrl()) === 1;
} else {
return $this->getFullUrl() == $url;
}
} | [
"public",
"function",
"isUrl",
"(",
"string",
"$",
"url",
",",
"bool",
"$",
"isRegex",
"=",
"false",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"isRegex",
")",
"{",
"return",
"preg_match",
"(",
"'#^'",
".",
"$",
"url",
".",
"'$#'",
",",
"$",
"this",
... | Gets whether or not the current URL matches the input URL or regular expression
@param string $url The URL or regular expression to match against
If the URL is a regular expression, it should not include regex delimiters
@param bool $isRegex True if the URL is a regular expression, otherwise false
@return bool True if the current URL matched the URL, otherwise false | [
"Gets",
"whether",
"or",
"not",
"the",
"current",
"URL",
"matches",
"the",
"input",
"URL",
"or",
"regular",
"expression"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L661-L668 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.setMethod | public function setMethod(string $method = null)
{
if ($method === null) {
$method = $this->server->get('REQUEST_METHOD', RequestMethods::GET);
if ($method == RequestMethods::POST) {
if (($overrideMethod = $this->server->get('X-HTTP-METHOD-OVERRIDE')) !== null) {
$method = $overrideMethod;
} elseif (($overrideMethod = $this->post->get('_method')) !== null) {
$method = $overrideMethod;
} elseif (($overrideMethod = $this->query->get('_method')) !== null) {
$method = $overrideMethod;
}
$this->originalMethodCollection = $this->post;
}
}
if (!is_string($method)) {
throw new InvalidArgumentException(
sprintf(
'HTTP method must be string, %s provided',
is_object($method) ? get_class($method) : gettype($method)
)
);
}
$method = strtoupper($method);
if (!in_array($method, self::$validMethods)) {
throw new InvalidArgumentException(
sprintf(
'Invalid HTTP method "%s"',
$method
)
);
}
$this->method = $method;
} | php | public function setMethod(string $method = null)
{
if ($method === null) {
$method = $this->server->get('REQUEST_METHOD', RequestMethods::GET);
if ($method == RequestMethods::POST) {
if (($overrideMethod = $this->server->get('X-HTTP-METHOD-OVERRIDE')) !== null) {
$method = $overrideMethod;
} elseif (($overrideMethod = $this->post->get('_method')) !== null) {
$method = $overrideMethod;
} elseif (($overrideMethod = $this->query->get('_method')) !== null) {
$method = $overrideMethod;
}
$this->originalMethodCollection = $this->post;
}
}
if (!is_string($method)) {
throw new InvalidArgumentException(
sprintf(
'HTTP method must be string, %s provided',
is_object($method) ? get_class($method) : gettype($method)
)
);
}
$method = strtoupper($method);
if (!in_array($method, self::$validMethods)) {
throw new InvalidArgumentException(
sprintf(
'Invalid HTTP method "%s"',
$method
)
);
}
$this->method = $method;
} | [
"public",
"function",
"setMethod",
"(",
"string",
"$",
"method",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"method",
"===",
"null",
")",
"{",
"$",
"method",
"=",
"$",
"this",
"->",
"server",
"->",
"get",
"(",
"'REQUEST_METHOD'",
",",
"RequestMethods",
"::... | Sets the method
If no input is specified, then it is automatically set using headers
@param string|null $method The method to set, otherwise null to automatically set the method
@throws InvalidArgumentException Thrown if the method is not an acceptable one | [
"Sets",
"the",
"method",
"If",
"no",
"input",
"is",
"specified",
"then",
"it",
"is",
"automatically",
"set",
"using",
"headers"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L677-L716 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.setPath | public function setPath(string $path = null)
{
if ($path === null) {
$uri = $this->server->get('REQUEST_URI');
if (empty($uri)) {
// Default to a slash
$this->path = '/';
} else {
$uriParts = explode('?', $uri);
$this->path = $uriParts[0];
}
} else {
$this->path = $path;
}
} | php | public function setPath(string $path = null)
{
if ($path === null) {
$uri = $this->server->get('REQUEST_URI');
if (empty($uri)) {
// Default to a slash
$this->path = '/';
} else {
$uriParts = explode('?', $uri);
$this->path = $uriParts[0];
}
} else {
$this->path = $path;
}
} | [
"public",
"function",
"setPath",
"(",
"string",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"path",
"===",
"null",
")",
"{",
"$",
"uri",
"=",
"$",
"this",
"->",
"server",
"->",
"get",
"(",
"'REQUEST_URI'",
")",
";",
"if",
"(",
"empty",
"(... | Sets the path of this request, which does not include the query string
If no input is specified, then it is automatically set using headers
@param string|null $path The path to set, otherwise null to automatically set the path | [
"Sets",
"the",
"path",
"of",
"this",
"request",
"which",
"does",
"not",
"include",
"the",
"query",
"string",
"If",
"no",
"input",
"is",
"specified",
"then",
"it",
"is",
"automatically",
"set",
"using",
"headers"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L724-L739 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.setClientIPAddresses | private function setClientIPAddresses()
{
if ($this->isUsingTrustedProxy()) {
$this->clientIPAddresses = [$this->server->get('REMOTE_ADDR')];
} else {
$ipAddresses = [];
// RFC 7239
if ($this->headers->has(self::$trustedHeaderNames[RequestHeaders::FORWARDED])) {
$header = $this->headers->get(self::$trustedHeaderNames[RequestHeaders::FORWARDED]);
preg_match_all("/for=(?:\"?\[?)([a-z0-9:\.\-\/_]*)/", $header, $matches);
$ipAddresses = $matches[1];
} elseif ($this->headers->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_IP])) {
$ipAddresses = explode(',', $this->headers->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_IP]));
$ipAddresses = array_map('trim', $ipAddresses);
}
$ipAddresses[] = $this->server->get('REMOTE_ADDR');
$fallbackIpAddresses = [$ipAddresses[0]];
foreach ($ipAddresses as $index => $ipAddress) {
// Check for valid IP address
if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
unset($ipAddresses[$index]);
}
// Don't accept trusted proxies
if (in_array($ipAddress, self::$trustedProxies)) {
unset($ipAddresses[$index]);
}
}
$this->clientIPAddresses = count($ipAddresses) === 0 ? $fallbackIpAddresses : array_reverse($ipAddresses);
}
} | php | private function setClientIPAddresses()
{
if ($this->isUsingTrustedProxy()) {
$this->clientIPAddresses = [$this->server->get('REMOTE_ADDR')];
} else {
$ipAddresses = [];
// RFC 7239
if ($this->headers->has(self::$trustedHeaderNames[RequestHeaders::FORWARDED])) {
$header = $this->headers->get(self::$trustedHeaderNames[RequestHeaders::FORWARDED]);
preg_match_all("/for=(?:\"?\[?)([a-z0-9:\.\-\/_]*)/", $header, $matches);
$ipAddresses = $matches[1];
} elseif ($this->headers->has(self::$trustedHeaderNames[RequestHeaders::CLIENT_IP])) {
$ipAddresses = explode(',', $this->headers->get(self::$trustedHeaderNames[RequestHeaders::CLIENT_IP]));
$ipAddresses = array_map('trim', $ipAddresses);
}
$ipAddresses[] = $this->server->get('REMOTE_ADDR');
$fallbackIpAddresses = [$ipAddresses[0]];
foreach ($ipAddresses as $index => $ipAddress) {
// Check for valid IP address
if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
unset($ipAddresses[$index]);
}
// Don't accept trusted proxies
if (in_array($ipAddress, self::$trustedProxies)) {
unset($ipAddresses[$index]);
}
}
$this->clientIPAddresses = count($ipAddresses) === 0 ? $fallbackIpAddresses : array_reverse($ipAddresses);
}
} | [
"private",
"function",
"setClientIPAddresses",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isUsingTrustedProxy",
"(",
")",
")",
"{",
"$",
"this",
"->",
"clientIPAddresses",
"=",
"[",
"$",
"this",
"->",
"server",
"->",
"get",
"(",
"'REMOTE_ADDR'",
")",
... | Sets the client IP addresses | [
"Sets",
"the",
"client",
"IP",
"addresses"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L764-L798 |
opulencephp/Opulence | src/Opulence/Http/Requests/Request.php | Request.setUnsupportedMethodsCollections | private function setUnsupportedMethodsCollections()
{
/**
* PHP doesn't pass in data from PUT/PATCH/DELETE requests through globals.
* In the case that we faked the method via a "_method" input, we need to use
* the original method's collection. Otherwise, we have to manually read from
* the input stream to grab their data. If the content is not from a form, we
* don't bother and just let users look the data up in the raw body.
*/
if (
(mb_strpos($this->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
|| mb_strpos($this->headers->get('CONTENT_TYPE'), 'multipart/form-data') === 0) &&
in_array($this->method, [RequestMethods::PUT, RequestMethods::PATCH, RequestMethods::DELETE])
) {
if ($this->originalMethodCollection === null) {
parse_str($this->getRawBody(), $collection);
} else {
$collection = $this->originalMethodCollection->getAll();
}
switch ($this->method) {
case RequestMethods::PUT:
$this->put->exchangeArray($collection);
break;
case RequestMethods::PATCH:
$this->patch->exchangeArray($collection);
break;
case RequestMethods::DELETE:
$this->delete->exchangeArray($collection);
break;
}
}
} | php | private function setUnsupportedMethodsCollections()
{
/**
* PHP doesn't pass in data from PUT/PATCH/DELETE requests through globals.
* In the case that we faked the method via a "_method" input, we need to use
* the original method's collection. Otherwise, we have to manually read from
* the input stream to grab their data. If the content is not from a form, we
* don't bother and just let users look the data up in the raw body.
*/
if (
(mb_strpos($this->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
|| mb_strpos($this->headers->get('CONTENT_TYPE'), 'multipart/form-data') === 0) &&
in_array($this->method, [RequestMethods::PUT, RequestMethods::PATCH, RequestMethods::DELETE])
) {
if ($this->originalMethodCollection === null) {
parse_str($this->getRawBody(), $collection);
} else {
$collection = $this->originalMethodCollection->getAll();
}
switch ($this->method) {
case RequestMethods::PUT:
$this->put->exchangeArray($collection);
break;
case RequestMethods::PATCH:
$this->patch->exchangeArray($collection);
break;
case RequestMethods::DELETE:
$this->delete->exchangeArray($collection);
break;
}
}
} | [
"private",
"function",
"setUnsupportedMethodsCollections",
"(",
")",
"{",
"/**\n * PHP doesn't pass in data from PUT/PATCH/DELETE requests through globals.\n * In the case that we faked the method via a \"_method\" input, we need to use\n * the original method's collection. Othe... | Sets PUT/PATCH/DELETE collections, if they exist | [
"Sets",
"PUT",
"/",
"PATCH",
"/",
"DELETE",
"collections",
"if",
"they",
"exist"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/Request.php#L803-L835 |
opulencephp/Opulence | src/Opulence/Routing/Routes/Route.php | Route.addMiddleware | public function addMiddleware($middleware, bool $prepend = false)
{
if (!is_array($middleware)) {
$middleware = [$middleware];
}
if ($prepend) {
$this->middleware = array_merge($middleware, $this->middleware);
} else {
$this->middleware = array_merge($this->middleware, $middleware);
}
$this->middleware = array_unique($this->middleware, SORT_REGULAR);
} | php | public function addMiddleware($middleware, bool $prepend = false)
{
if (!is_array($middleware)) {
$middleware = [$middleware];
}
if ($prepend) {
$this->middleware = array_merge($middleware, $this->middleware);
} else {
$this->middleware = array_merge($this->middleware, $middleware);
}
$this->middleware = array_unique($this->middleware, SORT_REGULAR);
} | [
"public",
"function",
"addMiddleware",
"(",
"$",
"middleware",
",",
"bool",
"$",
"prepend",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"middleware",
")",
")",
"{",
"$",
"middleware",
"=",
"[",
"$",
"middleware",
"]",
";",
"}",
"if"... | Adds middleware to this route
@param string|array $middleware The middleware or list of middleware to add
@param bool $prepend True if we want to prepend the middleware (give them higher priority), otherwise false | [
"Adds",
"middleware",
"to",
"this",
"route"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Routes/Route.php#L86-L99 |
opulencephp/Opulence | src/Opulence/Routing/Routes/Route.php | Route.setVarRegexes | public function setVarRegexes(array $regexes)
{
foreach ($regexes as $varName => $regex) {
$this->setVarRegex($varName, $regex);
}
} | php | public function setVarRegexes(array $regexes)
{
foreach ($regexes as $varName => $regex) {
$this->setVarRegex($varName, $regex);
}
} | [
"public",
"function",
"setVarRegexes",
"(",
"array",
"$",
"regexes",
")",
"{",
"foreach",
"(",
"$",
"regexes",
"as",
"$",
"varName",
"=>",
"$",
"regex",
")",
"{",
"$",
"this",
"->",
"setVarRegex",
"(",
"$",
"varName",
",",
"$",
"regex",
")",
";",
"}"... | Sets regexes variables must satisfy
@param array $regexes The mapping of variable names to their regexes | [
"Sets",
"regexes",
"variables",
"must",
"satisfy"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Routes/Route.php#L269-L274 |
opulencephp/Opulence | src/Opulence/Routing/Routes/Route.php | Route.setControllerVars | protected function setControllerVars($controller)
{
$this->controller = $controller;
if (is_callable($controller)) {
$this->setControllerCallable($controller);
} else {
$this->usesCallable = false;
$atCharPos = strpos($controller, '@');
// Make sure the "@" is somewhere in the middle of the string
if ($atCharPos === false || $atCharPos === 0 || $atCharPos === mb_strlen($controller) - 1) {
throw new InvalidArgumentException('Controller string is not formatted correctly');
}
$this->controllerName = substr($controller, 0, $atCharPos);
$this->controllerMethod = substr($controller, $atCharPos + 1);
}
} | php | protected function setControllerVars($controller)
{
$this->controller = $controller;
if (is_callable($controller)) {
$this->setControllerCallable($controller);
} else {
$this->usesCallable = false;
$atCharPos = strpos($controller, '@');
// Make sure the "@" is somewhere in the middle of the string
if ($atCharPos === false || $atCharPos === 0 || $atCharPos === mb_strlen($controller) - 1) {
throw new InvalidArgumentException('Controller string is not formatted correctly');
}
$this->controllerName = substr($controller, 0, $atCharPos);
$this->controllerMethod = substr($controller, $atCharPos + 1);
}
} | [
"protected",
"function",
"setControllerVars",
"(",
"$",
"controller",
")",
"{",
"$",
"this",
"->",
"controller",
"=",
"$",
"controller",
";",
"if",
"(",
"is_callable",
"(",
"$",
"controller",
")",
")",
"{",
"$",
"this",
"->",
"setControllerCallable",
"(",
... | Sets the controller name and method from the raw string
@param string|callable $controller The name of the controller/method or the callback
@throws InvalidArgumentException Thrown if the controller string is not formatted correctly | [
"Sets",
"the",
"controller",
"name",
"and",
"method",
"from",
"the",
"raw",
"string"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Routes/Route.php#L290-L308 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Transpiler.php | Transpiler.transpileDirectiveNode | protected function transpileDirectiveNode(Node $node) : string
{
$children = $node->getChildren();
if (count($children) === 0) {
return '';
}
$directiveName = $children[0]->getValue();
$expression = count($children) === 2 ? $children[1]->getValue() : '';
if (!isset($this->directiveTranspilers[$directiveName])) {
throw new RuntimeException(
sprintf(
'No transpiler registered for directive "%s"',
$directiveName
)
);
}
return $this->directiveTranspilers[$directiveName]($expression);
} | php | protected function transpileDirectiveNode(Node $node) : string
{
$children = $node->getChildren();
if (count($children) === 0) {
return '';
}
$directiveName = $children[0]->getValue();
$expression = count($children) === 2 ? $children[1]->getValue() : '';
if (!isset($this->directiveTranspilers[$directiveName])) {
throw new RuntimeException(
sprintf(
'No transpiler registered for directive "%s"',
$directiveName
)
);
}
return $this->directiveTranspilers[$directiveName]($expression);
} | [
"protected",
"function",
"transpileDirectiveNode",
"(",
"Node",
"$",
"node",
")",
":",
"string",
"{",
"$",
"children",
"=",
"$",
"node",
"->",
"getChildren",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"children",
")",
"===",
"0",
")",
"{",
"return",
... | Transpiles a directive node
@param Node $node The node to transpile
@return string The transpiled node
@throws RuntimeException Thrown if the directive could not be transpiled | [
"Transpiles",
"a",
"directive",
"node"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Transpiler.php#L240-L261 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Transpiler.php | Transpiler.transpileNodes | protected function transpileNodes(AbstractSyntaxTree $ast) : string
{
$transpiledView = '';
$rootNode = $ast->getRootNode();
$previousNodeWasExpression = false;
foreach ($rootNode->getChildren() as $childNode) {
switch (get_class($childNode)) {
case DirectiveNode::class:
$transpiledView .= $this->transpileDirectiveNode($childNode);
$previousNodeWasExpression = false;
break;
case SanitizedTagNode::class:
$transpiledView .= $this->transpileSanitizedTagNode($childNode);
$previousNodeWasExpression = false;
break;
case UnsanitizedTagNode::class:
$transpiledView .= $this->transpileUnsanitizedTagNode($childNode);
$previousNodeWasExpression = false;
break;
case CommentNode::class:
$transpiledView .= $this->transpileCommentNode($childNode);
$previousNodeWasExpression = false;
break;
case ExpressionNode::class:
// To keep expressions from running against each other, we pad all expressions but the first
if ($previousNodeWasExpression) {
$transpiledView .= ' ';
}
$transpiledView .= $this->transpileExpressionNode($childNode);
$previousNodeWasExpression = true;
break;
default:
throw new RuntimeException(
sprintf(
'Unknown node class %s',
get_class($childNode)
)
);
}
}
return $transpiledView;
} | php | protected function transpileNodes(AbstractSyntaxTree $ast) : string
{
$transpiledView = '';
$rootNode = $ast->getRootNode();
$previousNodeWasExpression = false;
foreach ($rootNode->getChildren() as $childNode) {
switch (get_class($childNode)) {
case DirectiveNode::class:
$transpiledView .= $this->transpileDirectiveNode($childNode);
$previousNodeWasExpression = false;
break;
case SanitizedTagNode::class:
$transpiledView .= $this->transpileSanitizedTagNode($childNode);
$previousNodeWasExpression = false;
break;
case UnsanitizedTagNode::class:
$transpiledView .= $this->transpileUnsanitizedTagNode($childNode);
$previousNodeWasExpression = false;
break;
case CommentNode::class:
$transpiledView .= $this->transpileCommentNode($childNode);
$previousNodeWasExpression = false;
break;
case ExpressionNode::class:
// To keep expressions from running against each other, we pad all expressions but the first
if ($previousNodeWasExpression) {
$transpiledView .= ' ';
}
$transpiledView .= $this->transpileExpressionNode($childNode);
$previousNodeWasExpression = true;
break;
default:
throw new RuntimeException(
sprintf(
'Unknown node class %s',
get_class($childNode)
)
);
}
}
return $transpiledView;
} | [
"protected",
"function",
"transpileNodes",
"(",
"AbstractSyntaxTree",
"$",
"ast",
")",
":",
"string",
"{",
"$",
"transpiledView",
"=",
"''",
";",
"$",
"rootNode",
"=",
"$",
"ast",
"->",
"getRootNode",
"(",
")",
";",
"$",
"previousNodeWasExpression",
"=",
"fa... | Transpiles all nodes in an abstract syntax tree
@param AbstractSyntaxTree $ast The abstract syntax tree to transpile
@return string The view with transpiled nodes
@throws RuntimeException Thrown if the nodes could not be transpiled | [
"Transpiles",
"all",
"nodes",
"in",
"an",
"abstract",
"syntax",
"tree"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Transpiler.php#L281-L330 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Transpiler.php | Transpiler.transpileSanitizedTagNode | protected function transpileSanitizedTagNode(Node $node) : string
{
$code = '';
foreach ($node->getChildren() as $childNode) {
$code .= '<?php echo $__opulenceFortuneTranspiler->sanitize(' . $childNode->getValue() . '); ?>';
}
return $code;
} | php | protected function transpileSanitizedTagNode(Node $node) : string
{
$code = '';
foreach ($node->getChildren() as $childNode) {
$code .= '<?php echo $__opulenceFortuneTranspiler->sanitize(' . $childNode->getValue() . '); ?>';
}
return $code;
} | [
"protected",
"function",
"transpileSanitizedTagNode",
"(",
"Node",
"$",
"node",
")",
":",
"string",
"{",
"$",
"code",
"=",
"''",
";",
"foreach",
"(",
"$",
"node",
"->",
"getChildren",
"(",
")",
"as",
"$",
"childNode",
")",
"{",
"$",
"code",
".=",
"'<?p... | Transpiles a sanitized tag node
@param Node $node The node to transpile
@return string The transpiled node | [
"Transpiles",
"a",
"sanitized",
"tag",
"node"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Transpiler.php#L338-L347 |
opulencephp/Opulence | src/Opulence/Sessions/Handlers/SessionHandler.php | SessionHandler.prepareForUnserialization | protected function prepareForUnserialization(string $data = null) : string
{
if ($data === null) {
return '';
}
if ($this->usesEncryption) {
if ($this->encrypter === null) {
throw new LogicException('Encrypter not set on session handler');
}
try {
return $this->encrypter->decrypt($data);
} catch (SessionEncryptionException $ex) {
return serialize([]);
}
} else {
return $data;
}
} | php | protected function prepareForUnserialization(string $data = null) : string
{
if ($data === null) {
return '';
}
if ($this->usesEncryption) {
if ($this->encrypter === null) {
throw new LogicException('Encrypter not set on session handler');
}
try {
return $this->encrypter->decrypt($data);
} catch (SessionEncryptionException $ex) {
return serialize([]);
}
} else {
return $data;
}
} | [
"protected",
"function",
"prepareForUnserialization",
"(",
"string",
"$",
"data",
"=",
"null",
")",
":",
"string",
"{",
"if",
"(",
"$",
"data",
"===",
"null",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"usesEncryption",
")",
"{",... | Prepares data that is about to be unserialized
@param string|null $data The data to be unserialized
@return string The data to be unserializd
@throws LogicException Thrown if using encryption but an encrypter has not been set | [
"Prepares",
"data",
"that",
"is",
"about",
"to",
"be",
"unserialized"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Sessions/Handlers/SessionHandler.php#L82-L101 |
opulencephp/Opulence | src/Opulence/Sessions/Handlers/SessionHandler.php | SessionHandler.prepareForWrite | protected function prepareForWrite(string $data) : string
{
if ($this->usesEncryption) {
if ($this->encrypter === null) {
throw new LogicException('Encrypter not set in session handler');
}
try {
return $this->encrypter->encrypt($data);
} catch (SessionEncryptionException $ex) {
return '';
}
} else {
return $data;
}
} | php | protected function prepareForWrite(string $data) : string
{
if ($this->usesEncryption) {
if ($this->encrypter === null) {
throw new LogicException('Encrypter not set in session handler');
}
try {
return $this->encrypter->encrypt($data);
} catch (SessionEncryptionException $ex) {
return '';
}
} else {
return $data;
}
} | [
"protected",
"function",
"prepareForWrite",
"(",
"string",
"$",
"data",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"usesEncryption",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"encrypter",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException... | Prepares data to be written to storage
@param string $data The data to prepare
@return string The prepared data
@throws LogicException Thrown if using encryption but an encrypter has not been set | [
"Prepares",
"data",
"to",
"be",
"written",
"to",
"storage"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Sessions/Handlers/SessionHandler.php#L110-L125 |
opulencephp/Opulence | src/Opulence/Routing/Routes/ParsedRoute.php | ParsedRoute.getDefaultValue | public function getDefaultValue(string $variableName)
{
if (isset($this->defaultValues[$variableName])) {
return $this->defaultValues[$variableName];
}
return null;
} | php | public function getDefaultValue(string $variableName)
{
if (isset($this->defaultValues[$variableName])) {
return $this->defaultValues[$variableName];
}
return null;
} | [
"public",
"function",
"getDefaultValue",
"(",
"string",
"$",
"variableName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"defaultValues",
"[",
"$",
"variableName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"defaultValues",
"[",
"$",
"var... | Gets the default value for a variable
@param string $variableName The name of the variable whose default value we want
@return mixed|null The default value for the variable if it exists, otherwise null | [
"Gets",
"the",
"default",
"value",
"for",
"a",
"variable"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Routes/ParsedRoute.php#L46-L53 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.checkForUpdates | protected function checkForUpdates()
{
$managedEntities = $this->entityRegistry->getEntities();
foreach ($managedEntities as $entity) {
$objectHashId = $this->entityRegistry->getObjectHashId($entity);
if ($this->entityRegistry->isRegistered($entity)
&& !isset($this->scheduledForInsertion[$objectHashId])
&& !isset($this->scheduledForUpdate[$objectHashId])
&& !isset($this->scheduledForDeletion[$objectHashId])
&& $this->changeTracker->hasChanged($entity)
) {
$this->scheduleForUpdate($entity);
}
}
} | php | protected function checkForUpdates()
{
$managedEntities = $this->entityRegistry->getEntities();
foreach ($managedEntities as $entity) {
$objectHashId = $this->entityRegistry->getObjectHashId($entity);
if ($this->entityRegistry->isRegistered($entity)
&& !isset($this->scheduledForInsertion[$objectHashId])
&& !isset($this->scheduledForUpdate[$objectHashId])
&& !isset($this->scheduledForDeletion[$objectHashId])
&& $this->changeTracker->hasChanged($entity)
) {
$this->scheduleForUpdate($entity);
}
}
} | [
"protected",
"function",
"checkForUpdates",
"(",
")",
"{",
"$",
"managedEntities",
"=",
"$",
"this",
"->",
"entityRegistry",
"->",
"getEntities",
"(",
")",
";",
"foreach",
"(",
"$",
"managedEntities",
"as",
"$",
"entity",
")",
"{",
"$",
"objectHashId",
"=",
... | Checks for any changes made to entities, and if any are found, they're scheduled for update | [
"Checks",
"for",
"any",
"changes",
"made",
"to",
"entities",
"and",
"if",
"any",
"are",
"found",
"they",
"re",
"scheduled",
"for",
"update"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L241-L257 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.delete | protected function delete($entity)
{
$dataMapper = $this->getDataMapper($this->entityRegistry->getClassName($entity));
$dataMapper->delete($entity);
// Order here matters
$this->detach($entity);
$this->entityRegistry->setState($entity, EntityStates::DEQUEUED);
} | php | protected function delete($entity)
{
$dataMapper = $this->getDataMapper($this->entityRegistry->getClassName($entity));
$dataMapper->delete($entity);
// Order here matters
$this->detach($entity);
$this->entityRegistry->setState($entity, EntityStates::DEQUEUED);
} | [
"protected",
"function",
"delete",
"(",
"$",
"entity",
")",
"{",
"$",
"dataMapper",
"=",
"$",
"this",
"->",
"getDataMapper",
"(",
"$",
"this",
"->",
"entityRegistry",
"->",
"getClassName",
"(",
"$",
"entity",
")",
")",
";",
"$",
"dataMapper",
"->",
"dele... | Attempts to update all the entities scheduled for deletion
@param object $entity The entity to delete | [
"Attempts",
"to",
"update",
"all",
"the",
"entities",
"scheduled",
"for",
"deletion"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L264-L271 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.getDataMapper | protected function getDataMapper(string $className) : IDataMapper
{
if (!isset($this->dataMappers[$className])) {
throw new RuntimeException("No data mapper for $className");
}
return $this->dataMappers[$className];
} | php | protected function getDataMapper(string $className) : IDataMapper
{
if (!isset($this->dataMappers[$className])) {
throw new RuntimeException("No data mapper for $className");
}
return $this->dataMappers[$className];
} | [
"protected",
"function",
"getDataMapper",
"(",
"string",
"$",
"className",
")",
":",
"IDataMapper",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"dataMappers",
"[",
"$",
"className",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"... | Gets the data mapper for the input class
@param string $className The name of the class whose data mapper we're searching for
@return IDataMapper The data mapper for the input class
@throws RuntimeException Thrown if there was no data mapper for the input class name | [
"Gets",
"the",
"data",
"mapper",
"for",
"the",
"input",
"class"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L280-L287 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.insert | protected function insert($entity)
{
// If this entity was a child of aggregate roots, then call its methods to set the aggregate root Id
$this->entityRegistry->runAggregateRootCallbacks($entity);
$className = $this->entityRegistry->getClassName($entity);
$dataMapper = $this->getDataMapper($className);
$idGenerator = $this->idGeneratorRegistry->getIdGenerator($className);
if ($idGenerator === null) {
$dataMapper->add($entity);
} else {
if ($idGenerator instanceof SequenceIdGenerator) {
$idGenerator->setConnection($this->connection);
}
if ($idGenerator->isPostInsert()) {
$dataMapper->add($entity);
$this->idAccessorRegistry->setEntityId(
$entity,
$idGenerator->generate($entity)
);
} else {
$this->idAccessorRegistry->setEntityId(
$entity,
$idGenerator->generate($entity)
);
$dataMapper->add($entity);
}
}
$this->entityRegistry->registerEntity($entity);
} | php | protected function insert($entity)
{
// If this entity was a child of aggregate roots, then call its methods to set the aggregate root Id
$this->entityRegistry->runAggregateRootCallbacks($entity);
$className = $this->entityRegistry->getClassName($entity);
$dataMapper = $this->getDataMapper($className);
$idGenerator = $this->idGeneratorRegistry->getIdGenerator($className);
if ($idGenerator === null) {
$dataMapper->add($entity);
} else {
if ($idGenerator instanceof SequenceIdGenerator) {
$idGenerator->setConnection($this->connection);
}
if ($idGenerator->isPostInsert()) {
$dataMapper->add($entity);
$this->idAccessorRegistry->setEntityId(
$entity,
$idGenerator->generate($entity)
);
} else {
$this->idAccessorRegistry->setEntityId(
$entity,
$idGenerator->generate($entity)
);
$dataMapper->add($entity);
}
}
$this->entityRegistry->registerEntity($entity);
} | [
"protected",
"function",
"insert",
"(",
"$",
"entity",
")",
"{",
"// If this entity was a child of aggregate roots, then call its methods to set the aggregate root Id",
"$",
"this",
"->",
"entityRegistry",
"->",
"runAggregateRootCallbacks",
"(",
"$",
"entity",
")",
";",
"$",
... | Attempts to insert all the entities scheduled for insertion
@param object $entity The entity to insert | [
"Attempts",
"to",
"insert",
"all",
"the",
"entities",
"scheduled",
"for",
"insertion"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L294-L325 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.postCommit | protected function postCommit()
{
/** @var IDataMapper $dataMapper */
foreach ($this->dataMappers as $className => $dataMapper) {
if ($dataMapper instanceof ICachedSqlDataMapper) {
// Now that the database writes have been committed, we can write to cache
/** @var ICachedSqlDataMapper $dataMapper */
$dataMapper->commit();
}
}
} | php | protected function postCommit()
{
/** @var IDataMapper $dataMapper */
foreach ($this->dataMappers as $className => $dataMapper) {
if ($dataMapper instanceof ICachedSqlDataMapper) {
// Now that the database writes have been committed, we can write to cache
/** @var ICachedSqlDataMapper $dataMapper */
$dataMapper->commit();
}
}
} | [
"protected",
"function",
"postCommit",
"(",
")",
"{",
"/** @var IDataMapper $dataMapper */",
"foreach",
"(",
"$",
"this",
"->",
"dataMappers",
"as",
"$",
"className",
"=>",
"$",
"dataMapper",
")",
"{",
"if",
"(",
"$",
"dataMapper",
"instanceof",
"ICachedSqlDataMap... | Performs any actions after the commit | [
"Performs",
"any",
"actions",
"after",
"the",
"commit"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L330-L340 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.postRollback | protected function postRollback()
{
// Unset the inserted entities' Ids
foreach ($this->scheduledForInsertion as $objectHashId => $index) {
if (($entity = $this->scheduledActions[$index][1] ?? null) === null) {
continue;
}
$idGenerator = $this->idGeneratorRegistry->getIdGenerator($this->entityRegistry->getClassName($entity));
if ($idGenerator !== null) {
$this->idAccessorRegistry->setEntityId(
$entity,
$idGenerator->getEmptyValue($entity)
);
}
}
} | php | protected function postRollback()
{
// Unset the inserted entities' Ids
foreach ($this->scheduledForInsertion as $objectHashId => $index) {
if (($entity = $this->scheduledActions[$index][1] ?? null) === null) {
continue;
}
$idGenerator = $this->idGeneratorRegistry->getIdGenerator($this->entityRegistry->getClassName($entity));
if ($idGenerator !== null) {
$this->idAccessorRegistry->setEntityId(
$entity,
$idGenerator->getEmptyValue($entity)
);
}
}
} | [
"protected",
"function",
"postRollback",
"(",
")",
"{",
"// Unset the inserted entities' Ids",
"foreach",
"(",
"$",
"this",
"->",
"scheduledForInsertion",
"as",
"$",
"objectHashId",
"=>",
"$",
"index",
")",
"{",
"if",
"(",
"(",
"$",
"entity",
"=",
"$",
"this",... | Performs any actions after a rollback | [
"Performs",
"any",
"actions",
"after",
"a",
"rollback"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L345-L362 |
opulencephp/Opulence | src/Opulence/Orm/UnitOfWork.php | UnitOfWork.update | protected function update($entity)
{
// If this entity was a child of aggregate roots, then call its methods to set the aggregate root Id
$this->entityRegistry->runAggregateRootCallbacks($entity);
$dataMapper = $this->getDataMapper($this->entityRegistry->getClassName($entity));
$dataMapper->update($entity);
$this->entityRegistry->registerEntity($entity);
} | php | protected function update($entity)
{
// If this entity was a child of aggregate roots, then call its methods to set the aggregate root Id
$this->entityRegistry->runAggregateRootCallbacks($entity);
$dataMapper = $this->getDataMapper($this->entityRegistry->getClassName($entity));
$dataMapper->update($entity);
$this->entityRegistry->registerEntity($entity);
} | [
"protected",
"function",
"update",
"(",
"$",
"entity",
")",
"{",
"// If this entity was a child of aggregate roots, then call its methods to set the aggregate root Id",
"$",
"this",
"->",
"entityRegistry",
"->",
"runAggregateRootCallbacks",
"(",
"$",
"entity",
")",
";",
"$",
... | Attempts to update all the entities scheduled for updating
@param object $entity The entity to update | [
"Attempts",
"to",
"update",
"all",
"the",
"entities",
"scheduled",
"for",
"updating"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/UnitOfWork.php#L377-L384 |
opulencephp/Opulence | src/Opulence/Framework/Validation/Bootstrappers/ValidatorBootstrapper.php | ValidatorBootstrapper.getRulesFactory | protected function getRulesFactory(IContainer $container) : RulesFactory
{
return new RulesFactory(
$this->ruleExtensionRegistry,
$this->errorTemplateRegistry,
$this->errorTemplateCompiler
);
} | php | protected function getRulesFactory(IContainer $container) : RulesFactory
{
return new RulesFactory(
$this->ruleExtensionRegistry,
$this->errorTemplateRegistry,
$this->errorTemplateCompiler
);
} | [
"protected",
"function",
"getRulesFactory",
"(",
"IContainer",
"$",
"container",
")",
":",
"RulesFactory",
"{",
"return",
"new",
"RulesFactory",
"(",
"$",
"this",
"->",
"ruleExtensionRegistry",
",",
"$",
"this",
"->",
"errorTemplateRegistry",
",",
"$",
"this",
"... | Gets the rules factory
@param IContainer $container The IoC container
@return RulesFactory The rules factory | [
"Gets",
"the",
"rules",
"factory"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Validation/Bootstrappers/ValidatorBootstrapper.php#L119-L126 |
opulencephp/Opulence | src/Opulence/Framework/Cryptography/Bootstrappers/CryptographyBootstrapper.php | CryptographyBootstrapper.getEncrypter | protected function getEncrypter() : IEncrypter
{
$encodedEncryptionKey = getenv('ENCRYPTION_KEY');
if ($encodedEncryptionKey === null) {
throw new RuntimeException('"ENCRYPTION_KEY" value not set in environment. Check that you have it set in an environment config file such as ".env.app.php". Note: ".env.example.php" is only a template for environment config files - it is not actually used.');
}
$decodedEncryptionKey = \hex2bin($encodedEncryptionKey);
if (\mb_strlen($decodedEncryptionKey, '8bit') < 32) {
throw new RuntimeException('The minimum length encryption key has been upgraded from 16 bytes to 32 bytes. Please re-run "php apex encryption:generatekey" to create a new, suitably-long encryption key.');
}
return new Encrypter(new Key($decodedEncryptionKey));
} | php | protected function getEncrypter() : IEncrypter
{
$encodedEncryptionKey = getenv('ENCRYPTION_KEY');
if ($encodedEncryptionKey === null) {
throw new RuntimeException('"ENCRYPTION_KEY" value not set in environment. Check that you have it set in an environment config file such as ".env.app.php". Note: ".env.example.php" is only a template for environment config files - it is not actually used.');
}
$decodedEncryptionKey = \hex2bin($encodedEncryptionKey);
if (\mb_strlen($decodedEncryptionKey, '8bit') < 32) {
throw new RuntimeException('The minimum length encryption key has been upgraded from 16 bytes to 32 bytes. Please re-run "php apex encryption:generatekey" to create a new, suitably-long encryption key.');
}
return new Encrypter(new Key($decodedEncryptionKey));
} | [
"protected",
"function",
"getEncrypter",
"(",
")",
":",
"IEncrypter",
"{",
"$",
"encodedEncryptionKey",
"=",
"getenv",
"(",
"'ENCRYPTION_KEY'",
")",
";",
"if",
"(",
"$",
"encodedEncryptionKey",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
... | Gets the encrypter to use
@return IEncrypter The encrypter
@throws RuntimeException Thrown if the encryption key is not set | [
"Gets",
"the",
"encrypter",
"to",
"use"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Cryptography/Bootstrappers/CryptographyBootstrapper.php#L51-L66 |
opulencephp/Opulence | src/Opulence/Views/Factories/IO/FileViewNameResolver.php | FileViewNameResolver.nameHasExtension | protected function nameHasExtension(string $name, array $sortedExtensions) : bool
{
foreach ($sortedExtensions as $extension) {
$lengthDifference = strlen($name) - strlen($extension);
if ($lengthDifference > 0 && strpos($name, $extension, $lengthDifference) !== false) {
return true;
}
}
return false;
} | php | protected function nameHasExtension(string $name, array $sortedExtensions) : bool
{
foreach ($sortedExtensions as $extension) {
$lengthDifference = strlen($name) - strlen($extension);
if ($lengthDifference > 0 && strpos($name, $extension, $lengthDifference) !== false) {
return true;
}
}
return false;
} | [
"protected",
"function",
"nameHasExtension",
"(",
"string",
"$",
"name",
",",
"array",
"$",
"sortedExtensions",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"sortedExtensions",
"as",
"$",
"extension",
")",
"{",
"$",
"lengthDifference",
"=",
"strlen",
"(",
"$"... | Gets whether or not a name has an extension
@param string $name The name to check
@param array $sortedExtensions The list of sorted extensions to check against
@return bool True if the name has an extension, otherwise false | [
"Gets",
"whether",
"or",
"not",
"a",
"name",
"has",
"an",
"extension"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Factories/IO/FileViewNameResolver.php#L79-L90 |
opulencephp/Opulence | src/Opulence/Views/Factories/IO/FileViewNameResolver.php | FileViewNameResolver.sortByPriority | protected function sortByPriority(array $list) : array
{
$nonPriorityItems = [];
$priorityItems = [];
foreach ($list as $key => $priority) {
if ($priority == -1) {
$nonPriorityItems[] = $key;
} else {
$priorityItems[$key] = $priority;
}
}
asort($priorityItems);
return array_merge(array_keys($priorityItems), $nonPriorityItems);
} | php | protected function sortByPriority(array $list) : array
{
$nonPriorityItems = [];
$priorityItems = [];
foreach ($list as $key => $priority) {
if ($priority == -1) {
$nonPriorityItems[] = $key;
} else {
$priorityItems[$key] = $priority;
}
}
asort($priorityItems);
return array_merge(array_keys($priorityItems), $nonPriorityItems);
} | [
"protected",
"function",
"sortByPriority",
"(",
"array",
"$",
"list",
")",
":",
"array",
"{",
"$",
"nonPriorityItems",
"=",
"[",
"]",
";",
"$",
"priorityItems",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"list",
"as",
"$",
"key",
"=>",
"$",
"priority",
... | Sorts a list whose values are priorities
@param array $list The list to sort
@return array The sorted list | [
"Sorts",
"a",
"list",
"whose",
"values",
"are",
"priorities"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Factories/IO/FileViewNameResolver.php#L98-L114 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/Signatures/HmacSigner.php | HmacSigner.getHashAlgorithm | private function getHashAlgorithm(string $algorithm) : string
{
switch ($algorithm) {
case Algorithms::SHA256:
return 'sha256';
case Algorithms::SHA384:
return 'sha384';
case Algorithms::SHA512:
return 'sha512';
default:
throw new InvalidArgumentException("Algorithm \"$algorithm\" is not a hash algorithm");
}
} | php | private function getHashAlgorithm(string $algorithm) : string
{
switch ($algorithm) {
case Algorithms::SHA256:
return 'sha256';
case Algorithms::SHA384:
return 'sha384';
case Algorithms::SHA512:
return 'sha512';
default:
throw new InvalidArgumentException("Algorithm \"$algorithm\" is not a hash algorithm");
}
} | [
"private",
"function",
"getHashAlgorithm",
"(",
"string",
"$",
"algorithm",
")",
":",
"string",
"{",
"switch",
"(",
"$",
"algorithm",
")",
"{",
"case",
"Algorithms",
"::",
"SHA256",
":",
"return",
"'sha256'",
";",
"case",
"Algorithms",
"::",
"SHA384",
":",
... | Gets the hash algorithm for an algorithm
@param string $algorithm The algorithm whose hash algorithm we want
@return string The algorithm to use in a hash function
@throws InvalidArgumentException Thrown if the algorithm is not an OpenSSL algorithm | [
"Gets",
"the",
"hash",
"algorithm",
"for",
"an",
"algorithm"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/Signatures/HmacSigner.php#L83-L95 |
opulencephp/Opulence | src/Opulence/QueryBuilders/AugmentingQueryBuilder.php | AugmentingQueryBuilder.addColumnValues | public function addColumnValues(array $columnNamesToValues) : self
{
$this->columnNamesToValues = array_merge($this->columnNamesToValues, $columnNamesToValues);
return $this;
} | php | public function addColumnValues(array $columnNamesToValues) : self
{
$this->columnNamesToValues = array_merge($this->columnNamesToValues, $columnNamesToValues);
return $this;
} | [
"public",
"function",
"addColumnValues",
"(",
"array",
"$",
"columnNamesToValues",
")",
":",
"self",
"{",
"$",
"this",
"->",
"columnNamesToValues",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"columnNamesToValues",
",",
"$",
"columnNamesToValues",
")",
";",
"ret... | Adds column values to the query
@param array $columnNamesToValues The mapping of column names to their respective values
@return self For method chaining | [
"Adds",
"column",
"values",
"to",
"the",
"query"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/QueryBuilders/AugmentingQueryBuilder.php#L27-L32 |
opulencephp/Opulence | src/Opulence/Console/Requests/Parsers/Parser.php | Parser.parseLongOption | protected function parseLongOption(string $token, array &$remainingTokens) : array
{
if (mb_strpos($token, '--') !== 0) {
throw new RuntimeException("Invalid long option \"$token\"");
}
// Trim the "--"
$option = mb_substr($token, 2);
if (mb_strpos($option, '=') === false) {
/**
* The option is either of the form "--foo" or "--foo bar" or "--foo -b" or "--foo --bar"
* So, we need to determine if the option has a value
*/
$nextToken = array_shift($remainingTokens);
// Check if the next token is also an option
if (mb_substr($nextToken, 0, 1) === '-' || empty($nextToken)) {
// The option must have not had a value, so put the next token back
array_unshift($remainingTokens, $nextToken);
return [$option, null];
}
// Make it "--foo=bar"
$option .= '=' . $nextToken;
}
list($name, $value) = explode('=', $option);
$value = $this->trimQuotes($value);
return [$name, $value];
} | php | protected function parseLongOption(string $token, array &$remainingTokens) : array
{
if (mb_strpos($token, '--') !== 0) {
throw new RuntimeException("Invalid long option \"$token\"");
}
// Trim the "--"
$option = mb_substr($token, 2);
if (mb_strpos($option, '=') === false) {
/**
* The option is either of the form "--foo" or "--foo bar" or "--foo -b" or "--foo --bar"
* So, we need to determine if the option has a value
*/
$nextToken = array_shift($remainingTokens);
// Check if the next token is also an option
if (mb_substr($nextToken, 0, 1) === '-' || empty($nextToken)) {
// The option must have not had a value, so put the next token back
array_unshift($remainingTokens, $nextToken);
return [$option, null];
}
// Make it "--foo=bar"
$option .= '=' . $nextToken;
}
list($name, $value) = explode('=', $option);
$value = $this->trimQuotes($value);
return [$name, $value];
} | [
"protected",
"function",
"parseLongOption",
"(",
"string",
"$",
"token",
",",
"array",
"&",
"$",
"remainingTokens",
")",
":",
"array",
"{",
"if",
"(",
"mb_strpos",
"(",
"$",
"token",
",",
"'--'",
")",
"!==",
"0",
")",
"{",
"throw",
"new",
"RuntimeExcepti... | Parses a long option token and returns an array of data
@param string $token The token to parse
@param array $remainingTokens The list of remaining tokens
@return array The name of the option mapped to its value
@throws RuntimeException Thrown if the option could not be parsed | [
"Parses",
"a",
"long",
"option",
"token",
"and",
"returns",
"an",
"array",
"of",
"data"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Requests/Parsers/Parser.php#L40-L72 |
opulencephp/Opulence | src/Opulence/Console/Requests/Parsers/Parser.php | Parser.parseShortOption | protected function parseShortOption(string $token) : array
{
if (mb_substr($token, 0, 1) !== '-') {
throw new RuntimeException("Invalid short option \"$token\"");
}
// Trim the "-"
$token = mb_substr($token, 1);
$options = [];
// Each character in a short option is an option
$tokens = preg_split('//u', $token, -1, PREG_SPLIT_NO_EMPTY);
foreach ($tokens as $singleToken) {
$options[] = [$singleToken, null];
}
return $options;
} | php | protected function parseShortOption(string $token) : array
{
if (mb_substr($token, 0, 1) !== '-') {
throw new RuntimeException("Invalid short option \"$token\"");
}
// Trim the "-"
$token = mb_substr($token, 1);
$options = [];
// Each character in a short option is an option
$tokens = preg_split('//u', $token, -1, PREG_SPLIT_NO_EMPTY);
foreach ($tokens as $singleToken) {
$options[] = [$singleToken, null];
}
return $options;
} | [
"protected",
"function",
"parseShortOption",
"(",
"string",
"$",
"token",
")",
":",
"array",
"{",
"if",
"(",
"mb_substr",
"(",
"$",
"token",
",",
"0",
",",
"1",
")",
"!==",
"'-'",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Invalid short option \... | Parses a short option token and returns an array of data
@param string $token The token to parse
@return array The name of the option mapped to its value
@throws RuntimeException Thrown if the option could not be parsed | [
"Parses",
"a",
"short",
"option",
"token",
"and",
"returns",
"an",
"array",
"of",
"data"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Requests/Parsers/Parser.php#L81-L100 |
opulencephp/Opulence | src/Opulence/Console/Requests/Parsers/Parser.php | Parser.parseTokens | protected function parseTokens(array $tokens) : Request
{
$request = new Request();
$hasParsedCommandName = false;
while ($token = array_shift($tokens)) {
if (mb_strpos($token, '--') === 0) {
$option = $this->parseLongOption($token, $tokens);
$request->addOptionValue($option[0], $option[1]);
} elseif (mb_substr($token, 0, 1) === '-') {
$options = $this->parseShortOption($token);
foreach ($options as $option) {
$request->addOptionValue($option[0], $option[1]);
}
} else {
if (!$hasParsedCommandName) {
// We consider this to be the command name
$request->setCommandName($token);
$hasParsedCommandName = true;
} else {
// We consider this to be an argument
$request->addArgumentValue($this->parseArgument($token));
}
}
}
return $request;
} | php | protected function parseTokens(array $tokens) : Request
{
$request = new Request();
$hasParsedCommandName = false;
while ($token = array_shift($tokens)) {
if (mb_strpos($token, '--') === 0) {
$option = $this->parseLongOption($token, $tokens);
$request->addOptionValue($option[0], $option[1]);
} elseif (mb_substr($token, 0, 1) === '-') {
$options = $this->parseShortOption($token);
foreach ($options as $option) {
$request->addOptionValue($option[0], $option[1]);
}
} else {
if (!$hasParsedCommandName) {
// We consider this to be the command name
$request->setCommandName($token);
$hasParsedCommandName = true;
} else {
// We consider this to be an argument
$request->addArgumentValue($this->parseArgument($token));
}
}
}
return $request;
} | [
"protected",
"function",
"parseTokens",
"(",
"array",
"$",
"tokens",
")",
":",
"Request",
"{",
"$",
"request",
"=",
"new",
"Request",
"(",
")",
";",
"$",
"hasParsedCommandName",
"=",
"false",
";",
"while",
"(",
"$",
"token",
"=",
"array_shift",
"(",
"$",... | Parses a list of tokens into a request
@param array $tokens The tokens to parse
@return Request The parsed request
@throws RuntimeException Thrown if there is an invalid token | [
"Parses",
"a",
"list",
"of",
"tokens",
"into",
"a",
"request"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Requests/Parsers/Parser.php#L109-L137 |
opulencephp/Opulence | src/Opulence/Console/Requests/Parsers/Parser.php | Parser.trimQuotes | protected function trimQuotes(string $token) : string
{
// Trim any quotes
if (($firstValueChar = mb_substr($token, 0, 1)) === mb_substr($token, -1)) {
if ($firstValueChar === "'") {
$token = trim($token, "'");
} elseif ($firstValueChar === '"') {
$token = trim($token, '"');
}
}
return $token;
} | php | protected function trimQuotes(string $token) : string
{
// Trim any quotes
if (($firstValueChar = mb_substr($token, 0, 1)) === mb_substr($token, -1)) {
if ($firstValueChar === "'") {
$token = trim($token, "'");
} elseif ($firstValueChar === '"') {
$token = trim($token, '"');
}
}
return $token;
} | [
"protected",
"function",
"trimQuotes",
"(",
"string",
"$",
"token",
")",
":",
"string",
"{",
"// Trim any quotes",
"if",
"(",
"(",
"$",
"firstValueChar",
"=",
"mb_substr",
"(",
"$",
"token",
",",
"0",
",",
"1",
")",
")",
"===",
"mb_substr",
"(",
"$",
"... | Trims the outer-most quotes from a token
@param string $token Trims quotes off of a token
@return string The trimmed token | [
"Trims",
"the",
"outer",
"-",
"most",
"quotes",
"from",
"a",
"token"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Requests/Parsers/Parser.php#L145-L157 |
opulencephp/Opulence | src/Opulence/Console/Commands/Compilers/Compiler.php | Compiler.compileArguments | protected function compileArguments(ICommand $command, IRequest $request)
{
$argumentValues = $request->getArgumentValues();
$commandArguments = $command->getArguments();
if ($this->hasTooManyArguments($argumentValues, $commandArguments)) {
throw new RuntimeException('Too many arguments');
}
$hasSetArrayArgument = false;
foreach ($commandArguments as $argument) {
if (count($argumentValues) === 0) {
if (!$argument->isOptional()) {
throw new RuntimeException("Argument \"{$argument->getName()}\" does not have default value");
}
$command->setArgumentValue($argument->getName(), $argument->getDefaultValue());
} else {
if ($hasSetArrayArgument) {
throw new RuntimeException('Array argument must appear at end of list of arguments');
}
if ($argument->isArray()) {
// Add the rest of the values in the request to this argument
$restOfArgumentValues = [];
while (count($argumentValues) > 0) {
$restOfArgumentValues[] = array_shift($argumentValues);
}
$command->setArgumentValue($argument->getName(), $restOfArgumentValues);
$hasSetArrayArgument = true;
} else {
$command->setArgumentValue($argument->getName(), array_shift($argumentValues));
}
}
}
} | php | protected function compileArguments(ICommand $command, IRequest $request)
{
$argumentValues = $request->getArgumentValues();
$commandArguments = $command->getArguments();
if ($this->hasTooManyArguments($argumentValues, $commandArguments)) {
throw new RuntimeException('Too many arguments');
}
$hasSetArrayArgument = false;
foreach ($commandArguments as $argument) {
if (count($argumentValues) === 0) {
if (!$argument->isOptional()) {
throw new RuntimeException("Argument \"{$argument->getName()}\" does not have default value");
}
$command->setArgumentValue($argument->getName(), $argument->getDefaultValue());
} else {
if ($hasSetArrayArgument) {
throw new RuntimeException('Array argument must appear at end of list of arguments');
}
if ($argument->isArray()) {
// Add the rest of the values in the request to this argument
$restOfArgumentValues = [];
while (count($argumentValues) > 0) {
$restOfArgumentValues[] = array_shift($argumentValues);
}
$command->setArgumentValue($argument->getName(), $restOfArgumentValues);
$hasSetArrayArgument = true;
} else {
$command->setArgumentValue($argument->getName(), array_shift($argumentValues));
}
}
}
} | [
"protected",
"function",
"compileArguments",
"(",
"ICommand",
"$",
"command",
",",
"IRequest",
"$",
"request",
")",
"{",
"$",
"argumentValues",
"=",
"$",
"request",
"->",
"getArgumentValues",
"(",
")",
";",
"$",
"commandArguments",
"=",
"$",
"command",
"->",
... | Compiles arguments in a command
@param ICommand $command The command to compile
@param IRequest $request The user request
@throws RuntimeException Thrown if there are too many arguments | [
"Compiles",
"arguments",
"in",
"a",
"command"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/Compilers/Compiler.php#L40-L78 |
opulencephp/Opulence | src/Opulence/Console/Commands/Compilers/Compiler.php | Compiler.compileOptions | protected function compileOptions(ICommand $command, IRequest $request)
{
foreach ($command->getOptions() as $option) {
$shortNameIsSet = $option->getShortName() === null ?
false :
$request->optionIsSet($option->getShortName());
$longNameIsSet = $request->optionIsSet($option->getName());
// All options are optional (duh)
if ($shortNameIsSet || $longNameIsSet) {
if ($longNameIsSet) {
$value = $request->getOptionValue($option->getName());
} else {
$value = $request->getOptionValue($option->getShortName());
}
if (!$option->valueIsPermitted() && $value !== null) {
throw new RuntimeException("Option \"{$option->getName()}\" does not permit a value");
}
if ($option->valueIsRequired() && $value === null) {
throw new RuntimeException("Option \"{$option->getName()}\" requires a value");
}
if ($option->valueIsOptional() && $value === null) {
$value = $option->getDefaultValue();
}
$command->setOptionValue($option->getName(), $value);
} elseif ($option->valueIsPermitted()) {
// Set the value for the option to its default value, if values are permitted
$command->setOptionValue($option->getName(), $option->getDefaultValue());
}
}
} | php | protected function compileOptions(ICommand $command, IRequest $request)
{
foreach ($command->getOptions() as $option) {
$shortNameIsSet = $option->getShortName() === null ?
false :
$request->optionIsSet($option->getShortName());
$longNameIsSet = $request->optionIsSet($option->getName());
// All options are optional (duh)
if ($shortNameIsSet || $longNameIsSet) {
if ($longNameIsSet) {
$value = $request->getOptionValue($option->getName());
} else {
$value = $request->getOptionValue($option->getShortName());
}
if (!$option->valueIsPermitted() && $value !== null) {
throw new RuntimeException("Option \"{$option->getName()}\" does not permit a value");
}
if ($option->valueIsRequired() && $value === null) {
throw new RuntimeException("Option \"{$option->getName()}\" requires a value");
}
if ($option->valueIsOptional() && $value === null) {
$value = $option->getDefaultValue();
}
$command->setOptionValue($option->getName(), $value);
} elseif ($option->valueIsPermitted()) {
// Set the value for the option to its default value, if values are permitted
$command->setOptionValue($option->getName(), $option->getDefaultValue());
}
}
} | [
"protected",
"function",
"compileOptions",
"(",
"ICommand",
"$",
"command",
",",
"IRequest",
"$",
"request",
")",
"{",
"foreach",
"(",
"$",
"command",
"->",
"getOptions",
"(",
")",
"as",
"$",
"option",
")",
"{",
"$",
"shortNameIsSet",
"=",
"$",
"option",
... | Compiles options in a command
@param ICommand $command The command to compile
@param IRequest $request The user request | [
"Compiles",
"options",
"in",
"a",
"command"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/Compilers/Compiler.php#L86-L120 |
opulencephp/Opulence | src/Opulence/Console/Commands/Compilers/Compiler.php | Compiler.hasTooManyArguments | private function hasTooManyArguments(array $argumentValues, array $commandArguments) : bool
{
if (count($argumentValues) > count($commandArguments)) {
// Only when the last argument is an array do we allow more request arguments than command arguments
if (count($commandArguments) === 0 || !end($commandArguments)->isArray()) {
return true;
}
}
return false;
} | php | private function hasTooManyArguments(array $argumentValues, array $commandArguments) : bool
{
if (count($argumentValues) > count($commandArguments)) {
// Only when the last argument is an array do we allow more request arguments than command arguments
if (count($commandArguments) === 0 || !end($commandArguments)->isArray()) {
return true;
}
}
return false;
} | [
"private",
"function",
"hasTooManyArguments",
"(",
"array",
"$",
"argumentValues",
",",
"array",
"$",
"commandArguments",
")",
":",
"bool",
"{",
"if",
"(",
"count",
"(",
"$",
"argumentValues",
")",
">",
"count",
"(",
"$",
"commandArguments",
")",
")",
"{",
... | Gets whether or not there are too many argument values
@param array $argumentValues The list of argument values
@param ICommand[] $commandArguments The list of command arguments
@return bool True if there are too many arguments, otherwise false | [
"Gets",
"whether",
"or",
"not",
"there",
"are",
"too",
"many",
"argument",
"values"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/Compilers/Compiler.php#L129-L139 |
opulencephp/Opulence | src/Opulence/Framework/Composer/Composer.php | Composer.createFromRawConfig | public static function createFromRawConfig(string $rootPath, string $psr4RootPath) : Composer
{
$composerConfigPath = "$rootPath/composer.json";
if (file_exists($composerConfigPath)) {
return new Composer(json_decode(file_get_contents($composerConfigPath), true), $rootPath, $psr4RootPath);
}
return new Composer([], $rootPath, $psr4RootPath);
} | php | public static function createFromRawConfig(string $rootPath, string $psr4RootPath) : Composer
{
$composerConfigPath = "$rootPath/composer.json";
if (file_exists($composerConfigPath)) {
return new Composer(json_decode(file_get_contents($composerConfigPath), true), $rootPath, $psr4RootPath);
}
return new Composer([], $rootPath, $psr4RootPath);
} | [
"public",
"static",
"function",
"createFromRawConfig",
"(",
"string",
"$",
"rootPath",
",",
"string",
"$",
"psr4RootPath",
")",
":",
"Composer",
"{",
"$",
"composerConfigPath",
"=",
"\"$rootPath/composer.json\"",
";",
"if",
"(",
"file_exists",
"(",
"$",
"composerC... | Creates an instance of this class from a raw Composer config file
@param string $rootPath The path to the roof of the project
@param string $psr4RootPath The path to the PSR-4 source directory
@return Composer An instance of this class | [
"Creates",
"an",
"instance",
"of",
"this",
"class",
"from",
"a",
"raw",
"Composer",
"config",
"file"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Composer/Composer.php#L44-L53 |
opulencephp/Opulence | src/Opulence/Framework/Composer/Composer.php | Composer.get | public function get(string $property)
{
$properties = explode('.', $property);
$value = $this->rawConfig;
foreach ($properties as $property) {
if (!array_key_exists($property, $value)) {
return null;
}
$value = $value[$property];
}
return $value;
} | php | public function get(string $property)
{
$properties = explode('.', $property);
$value = $this->rawConfig;
foreach ($properties as $property) {
if (!array_key_exists($property, $value)) {
return null;
}
$value = $value[$property];
}
return $value;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"property",
")",
"{",
"$",
"properties",
"=",
"explode",
"(",
"'.'",
",",
"$",
"property",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"rawConfig",
";",
"foreach",
"(",
"$",
"properties",
"as",
"$"... | Gets the value of a property
@param string $property The property to get (use periods to denote sub-properties)
@return mixed|null The value if it exists, otherwise null | [
"Gets",
"the",
"value",
"of",
"a",
"property"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Composer/Composer.php#L61-L75 |
opulencephp/Opulence | src/Opulence/Framework/Composer/Composer.php | Composer.getClassPath | public function getClassPath(string $fullyQualifiedClassName) : string
{
$parts = explode('\\', $fullyQualifiedClassName);
/**
* If the root namespace does have a directory (eg Project\MyClass lives in src/Project/MyClass.php),
* then we do include it in the path
* If the root namespace does not have a directory (eg Project\MyClass lives in src/MyClass.php),
* then we do not include it in the path (ie don't use "Project" in the path)
*
* Note: This is mainly for backwards-compatibility with the directory structure for v1.0.* of the
* skeleton project. This is hacky, but it works.
*/
if (file_exists(realpath($this->psr4RootPath . '/' . $parts[0]))) {
$path = array_slice($parts, 0, -1);
} else {
$path = array_slice($parts, 1, -1);
}
$path[] = end($parts) . '.php';
array_unshift($path, $this->psr4RootPath);
return implode(DIRECTORY_SEPARATOR, $path);
} | php | public function getClassPath(string $fullyQualifiedClassName) : string
{
$parts = explode('\\', $fullyQualifiedClassName);
/**
* If the root namespace does have a directory (eg Project\MyClass lives in src/Project/MyClass.php),
* then we do include it in the path
* If the root namespace does not have a directory (eg Project\MyClass lives in src/MyClass.php),
* then we do not include it in the path (ie don't use "Project" in the path)
*
* Note: This is mainly for backwards-compatibility with the directory structure for v1.0.* of the
* skeleton project. This is hacky, but it works.
*/
if (file_exists(realpath($this->psr4RootPath . '/' . $parts[0]))) {
$path = array_slice($parts, 0, -1);
} else {
$path = array_slice($parts, 1, -1);
}
$path[] = end($parts) . '.php';
array_unshift($path, $this->psr4RootPath);
return implode(DIRECTORY_SEPARATOR, $path);
} | [
"public",
"function",
"getClassPath",
"(",
"string",
"$",
"fullyQualifiedClassName",
")",
":",
"string",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"fullyQualifiedClassName",
")",
";",
"/**\n * If the root namespace does have a directory (eg Proje... | Gets the path from a fully-qualified class name
@param string $fullyQualifiedClassName The fully-qualified class name
@return string The path | [
"Gets",
"the",
"path",
"from",
"a",
"fully",
"-",
"qualified",
"class",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Composer/Composer.php#L83-L106 |
opulencephp/Opulence | src/Opulence/Framework/Composer/Composer.php | Composer.getFullyQualifiedClassName | public function getFullyQualifiedClassName(string $className, string $defaultNamespace) : string
{
$rootNamespace = $this->getRootNamespace();
// If the class name is already fully-qualified
if (mb_strpos($className, $rootNamespace) === 0) {
return $className;
}
return trim($defaultNamespace, '\\') . '\\' . $className;
} | php | public function getFullyQualifiedClassName(string $className, string $defaultNamespace) : string
{
$rootNamespace = $this->getRootNamespace();
// If the class name is already fully-qualified
if (mb_strpos($className, $rootNamespace) === 0) {
return $className;
}
return trim($defaultNamespace, '\\') . '\\' . $className;
} | [
"public",
"function",
"getFullyQualifiedClassName",
"(",
"string",
"$",
"className",
",",
"string",
"$",
"defaultNamespace",
")",
":",
"string",
"{",
"$",
"rootNamespace",
"=",
"$",
"this",
"->",
"getRootNamespace",
"(",
")",
";",
"// If the class name is already fu... | Gets the fully-qualified class name
@param string $className The input class name
@param string $defaultNamespace The default namespace
@return string The fully-qualified class name | [
"Gets",
"the",
"fully",
"-",
"qualified",
"class",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Composer/Composer.php#L115-L125 |
opulencephp/Opulence | src/Opulence/Framework/Composer/Composer.php | Composer.getRootNamespace | public function getRootNamespace()
{
if (($psr4 = $this->get('autoload.psr-4')) === null) {
return null;
}
foreach ($psr4 as $namespace => $namespacePaths) {
foreach ((array)$namespacePaths as $namespacePath) {
// The namespace path should be a subdirectory of the "src" directory
if (mb_strpos(realpath($this->rootPath . '/' . $namespacePath), realpath($this->psr4RootPath)) === 0) {
return rtrim($namespace, '\\');
}
}
}
return null;
} | php | public function getRootNamespace()
{
if (($psr4 = $this->get('autoload.psr-4')) === null) {
return null;
}
foreach ($psr4 as $namespace => $namespacePaths) {
foreach ((array)$namespacePaths as $namespacePath) {
// The namespace path should be a subdirectory of the "src" directory
if (mb_strpos(realpath($this->rootPath . '/' . $namespacePath), realpath($this->psr4RootPath)) === 0) {
return rtrim($namespace, '\\');
}
}
}
return null;
} | [
"public",
"function",
"getRootNamespace",
"(",
")",
"{",
"if",
"(",
"(",
"$",
"psr4",
"=",
"$",
"this",
"->",
"get",
"(",
"'autoload.psr-4'",
")",
")",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"foreach",
"(",
"$",
"psr4",
"as",
"$",
"na... | Gets the root namespace for the application
@return string|null The root namespace | [
"Gets",
"the",
"root",
"namespace",
"for",
"the",
"application"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Composer/Composer.php#L140-L156 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Elements/Style.php | Style.addTextStyle | public function addTextStyle(string $style)
{
if (!isset(self::$supportedTextStyles[$style])) {
throw new InvalidArgumentException("Invalid text style \"$style\"");
}
// Don't double-add a style
if (!in_array($style, $this->textStyles)) {
$this->textStyles[] = $style;
}
} | php | public function addTextStyle(string $style)
{
if (!isset(self::$supportedTextStyles[$style])) {
throw new InvalidArgumentException("Invalid text style \"$style\"");
}
// Don't double-add a style
if (!in_array($style, $this->textStyles)) {
$this->textStyles[] = $style;
}
} | [
"public",
"function",
"addTextStyle",
"(",
"string",
"$",
"style",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"supportedTextStyles",
"[",
"$",
"style",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid text style... | Adds the text to have a certain style
@param string $style The name of the text style
@throws InvalidArgumentException Thrown if the text style does not exist | [
"Adds",
"the",
"text",
"to",
"have",
"a",
"certain",
"style"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Elements/Style.php#L88-L98 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Elements/Style.php | Style.format | public function format(string $text) : string
{
if ($text === '') {
return $text;
}
$startCodes = [];
$endCodes = [];
if ($this->foregroundColor !== null) {
$startCodes[] = self::$supportedForegroundColors[$this->foregroundColor][0];
$endCodes[] = self::$supportedForegroundColors[$this->foregroundColor][1];
}
if ($this->backgroundColor !== null) {
$startCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][0];
$endCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][1];
}
foreach ($this->textStyles as $style) {
$startCodes[] = self::$supportedTextStyles[$style][0];
$endCodes[] = self::$supportedTextStyles[$style][1];
}
if (count($startCodes) === 0 && count($endCodes) === 0) {
// No point in trying to format the text
return $text;
}
return sprintf(
"\033[%sm%s\033[%sm",
implode(';', $startCodes),
$text,
implode(';', $endCodes)
);
} | php | public function format(string $text) : string
{
if ($text === '') {
return $text;
}
$startCodes = [];
$endCodes = [];
if ($this->foregroundColor !== null) {
$startCodes[] = self::$supportedForegroundColors[$this->foregroundColor][0];
$endCodes[] = self::$supportedForegroundColors[$this->foregroundColor][1];
}
if ($this->backgroundColor !== null) {
$startCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][0];
$endCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][1];
}
foreach ($this->textStyles as $style) {
$startCodes[] = self::$supportedTextStyles[$style][0];
$endCodes[] = self::$supportedTextStyles[$style][1];
}
if (count($startCodes) === 0 && count($endCodes) === 0) {
// No point in trying to format the text
return $text;
}
return sprintf(
"\033[%sm%s\033[%sm",
implode(';', $startCodes),
$text,
implode(';', $endCodes)
);
} | [
"public",
"function",
"format",
"(",
"string",
"$",
"text",
")",
":",
"string",
"{",
"if",
"(",
"$",
"text",
"===",
"''",
")",
"{",
"return",
"$",
"text",
";",
"}",
"$",
"startCodes",
"=",
"[",
"]",
";",
"$",
"endCodes",
"=",
"[",
"]",
";",
"if... | Formats text with the the currently-set styles
@param string $text The text to format
@return string The formatted text | [
"Formats",
"text",
"with",
"the",
"the",
"currently",
"-",
"set",
"styles"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Elements/Style.php#L119-L154 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Elements/Style.php | Style.removeTextStyle | public function removeTextStyle(string $style)
{
if (!isset(self::$supportedTextStyles[$style])) {
throw new InvalidArgumentException("Invalid text style \"$style\"");
}
if (($index = array_search($style, $this->textStyles)) !== false) {
unset($this->textStyles[$index]);
}
} | php | public function removeTextStyle(string $style)
{
if (!isset(self::$supportedTextStyles[$style])) {
throw new InvalidArgumentException("Invalid text style \"$style\"");
}
if (($index = array_search($style, $this->textStyles)) !== false) {
unset($this->textStyles[$index]);
}
} | [
"public",
"function",
"removeTextStyle",
"(",
"string",
"$",
"style",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"supportedTextStyles",
"[",
"$",
"style",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid text st... | Removes a text style
@param string $style The style to remove
@throws InvalidArgumentException Thrown if the text style is invalid | [
"Removes",
"a",
"text",
"style"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Elements/Style.php#L186-L195 |
opulencephp/Opulence | src/Opulence/Console/Commands/CommandCollection.php | CommandCollection.add | public function add(ICommand $command, bool $overwrite = false)
{
if (!$overwrite && $this->has($command->getName())) {
throw new InvalidArgumentException("A command with name \"{$command->getName()}\" already exists");
}
$command->setCommandCollection($this);
$this->commands[$command->getName()] = $command;
} | php | public function add(ICommand $command, bool $overwrite = false)
{
if (!$overwrite && $this->has($command->getName())) {
throw new InvalidArgumentException("A command with name \"{$command->getName()}\" already exists");
}
$command->setCommandCollection($this);
$this->commands[$command->getName()] = $command;
} | [
"public",
"function",
"add",
"(",
"ICommand",
"$",
"command",
",",
"bool",
"$",
"overwrite",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"overwrite",
"&&",
"$",
"this",
"->",
"has",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
")",
")",
"{",
... | Adds a command
@param ICommand $command The command to add
@param bool $overwrite True if we will overwrite a command with the same name if it already exists
@throws InvalidArgumentException Thrown if a command with the input name already exists | [
"Adds",
"a",
"command"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/CommandCollection.php#L46-L54 |
opulencephp/Opulence | src/Opulence/Console/Commands/CommandCollection.php | CommandCollection.call | public function call(string $commandName, IResponse $response, array $arguments = [], array $options = [])
{
$request = $this->requestParser->parse([
'name' => $commandName,
'arguments' => $arguments,
'options' => $options
]);
$compiledCommand = $this->commandCompiler->compile($this->get($commandName), $request);
return $compiledCommand->execute($response);
} | php | public function call(string $commandName, IResponse $response, array $arguments = [], array $options = [])
{
$request = $this->requestParser->parse([
'name' => $commandName,
'arguments' => $arguments,
'options' => $options
]);
$compiledCommand = $this->commandCompiler->compile($this->get($commandName), $request);
return $compiledCommand->execute($response);
} | [
"public",
"function",
"call",
"(",
"string",
"$",
"commandName",
",",
"IResponse",
"$",
"response",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request... | Calls a command and writes its output to the input response
@param string $commandName The name of the command to run
@param IResponse $response The response to write output to
@param array $arguments The list of arguments
@param array $options The list of options
@return int|null The status code of the command
@throws InvalidArgumentException Thrown if no command exists with the input name | [
"Calls",
"a",
"command",
"and",
"writes",
"its",
"output",
"to",
"the",
"input",
"response"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/CommandCollection.php#L66-L76 |
opulencephp/Opulence | src/Opulence/Console/Commands/CommandCollection.php | CommandCollection.get | public function get(string $name) : ICommand
{
if (!$this->has($name)) {
throw new InvalidArgumentException("No command with name \"$name\" exists");
}
return $this->commands[$name];
} | php | public function get(string $name) : ICommand
{
if (!$this->has($name)) {
throw new InvalidArgumentException("No command with name \"$name\" exists");
}
return $this->commands[$name];
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
")",
":",
"ICommand",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"No command with name \\\"$name\\\" exists\"",
"... | Gets the command with the input name
@param string $name The name of the command to get
@return ICommand The command
@throws InvalidArgumentException Thrown if no command with the input name exists | [
"Gets",
"the",
"command",
"with",
"the",
"input",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/CommandCollection.php#L85-L92 |
opulencephp/Opulence | src/Opulence/Environments/Environment.php | Environment.getVar | public static function getVar(string $name, $default = null)
{
if (array_key_exists($name, $_ENV)) {
return $_ENV[$name];
} elseif (array_key_exists($name, $_SERVER)) {
return $_SERVER[$name];
} else {
$value = getenv($name);
if ($value === false) {
return $default;
}
return $value;
}
} | php | public static function getVar(string $name, $default = null)
{
if (array_key_exists($name, $_ENV)) {
return $_ENV[$name];
} elseif (array_key_exists($name, $_SERVER)) {
return $_SERVER[$name];
} else {
$value = getenv($name);
if ($value === false) {
return $default;
}
return $value;
}
} | [
"public",
"static",
"function",
"getVar",
"(",
"string",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"_ENV",
")",
")",
"{",
"return",
"$",
"_ENV",
"[",
"$",
"name",
"]",
";",
... | Gets the value of an environment variable
@param string $name The name of the environment variable to get
@param mixed $default The default value if none existed
@return string|null The value of the environment value if one was set, otherwise null | [
"Gets",
"the",
"value",
"of",
"an",
"environment",
"variable"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Environments/Environment.php#L34-L49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.