repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
QoboLtd/cakephp-utils | src/Utility/Salt.php | Salt.getSalt | public static function getSalt(): string
{
$result = '';
try {
$result = static::readSaltFromFile();
} catch (InvalidArgumentException $e) {
Log::warning("Failed to read salt from file");
}
if ($result) {
return $result;
}
try {
$salt = static::generateSalt();
static::writeSaltToFile($salt);
$result = static::readSaltFromFile();
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException("Failed to regenerate and save new salt: " . $e->getMessage(), 0, $e);
}
Log::warning("New salt is generated and stored. Users might need to logout and clean their cookies.");
return $result;
} | php | public static function getSalt(): string
{
$result = '';
try {
$result = static::readSaltFromFile();
} catch (InvalidArgumentException $e) {
Log::warning("Failed to read salt from file");
}
if ($result) {
return $result;
}
try {
$salt = static::generateSalt();
static::writeSaltToFile($salt);
$result = static::readSaltFromFile();
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException("Failed to regenerate and save new salt: " . $e->getMessage(), 0, $e);
}
Log::warning("New salt is generated and stored. Users might need to logout and clean their cookies.");
return $result;
} | [
"public",
"static",
"function",
"getSalt",
"(",
")",
":",
"string",
"{",
"$",
"result",
"=",
"''",
";",
"try",
"{",
"$",
"result",
"=",
"static",
"::",
"readSaltFromFile",
"(",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{"... | Get configured salt string
If the salt was not properly configured, a new salt string
will be generated, stored, and returned.
@throws \InvalidArgumentException when cannot read or regenerate salt
@return string Salt string | [
"Get",
"configured",
"salt",
"string"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility/Salt.php#L57-L81 | train |
QoboLtd/cakephp-utils | src/Utility/Salt.php | Salt.readSaltFromFile | protected static function readSaltFromFile(): string
{
Utility::validatePath(static::$saltFile);
$result = file_get_contents(static::$saltFile);
$result = $result ?: '';
static::validateSalt($result);
return $result;
} | php | protected static function readSaltFromFile(): string
{
Utility::validatePath(static::$saltFile);
$result = file_get_contents(static::$saltFile);
$result = $result ?: '';
static::validateSalt($result);
return $result;
} | [
"protected",
"static",
"function",
"readSaltFromFile",
"(",
")",
":",
"string",
"{",
"Utility",
"::",
"validatePath",
"(",
"static",
"::",
"$",
"saltFile",
")",
";",
"$",
"result",
"=",
"file_get_contents",
"(",
"static",
"::",
"$",
"saltFile",
")",
";",
"... | Read salt string from file
@return string Valid salt string | [
"Read",
"salt",
"string",
"from",
"file"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility/Salt.php#L88-L96 | train |
QoboLtd/cakephp-utils | src/Utility/Salt.php | Salt.writeSaltToFile | protected static function writeSaltToFile(string $salt): void
{
static::validateSalt($salt);
$result = @file_put_contents(static::$saltFile, $salt);
if (($result === false) || ($result <> strlen($salt))) {
throw new InvalidArgumentException("Failed to write salt to file [" . static::$saltFile . "]");
}
} | php | protected static function writeSaltToFile(string $salt): void
{
static::validateSalt($salt);
$result = @file_put_contents(static::$saltFile, $salt);
if (($result === false) || ($result <> strlen($salt))) {
throw new InvalidArgumentException("Failed to write salt to file [" . static::$saltFile . "]");
}
} | [
"protected",
"static",
"function",
"writeSaltToFile",
"(",
"string",
"$",
"salt",
")",
":",
"void",
"{",
"static",
"::",
"validateSalt",
"(",
"$",
"salt",
")",
";",
"$",
"result",
"=",
"@",
"file_put_contents",
"(",
"static",
"::",
"$",
"saltFile",
",",
... | Write a valid salt string to file
@throws \InvalidArgumentException when storing fails
@param string $salt Valid salt string
@return void | [
"Write",
"a",
"valid",
"salt",
"string",
"to",
"file"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility/Salt.php#L105-L113 | train |
QoboLtd/cakephp-utils | src/Utility/Salt.php | Salt.validateSalt | protected static function validateSalt(string $salt): void
{
if (!ctype_print($salt)) {
throw new InvalidArgumentException("Salt is not a printable string");
}
static::validateSaltMinLength();
$saltLength = strlen($salt);
if ($saltLength < static::$saltMinLength) {
throw new InvalidArgumentException("Salt length of $saltLength characters is less than expected " . static::$saltMinLength);
}
} | php | protected static function validateSalt(string $salt): void
{
if (!ctype_print($salt)) {
throw new InvalidArgumentException("Salt is not a printable string");
}
static::validateSaltMinLength();
$saltLength = strlen($salt);
if ($saltLength < static::$saltMinLength) {
throw new InvalidArgumentException("Salt length of $saltLength characters is less than expected " . static::$saltMinLength);
}
} | [
"protected",
"static",
"function",
"validateSalt",
"(",
"string",
"$",
"salt",
")",
":",
"void",
"{",
"if",
"(",
"!",
"ctype_print",
"(",
"$",
"salt",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Salt is not a printable string\"",
")",
";... | Validate salt string
@throws \InvalidArgumentException when the salt string is not valid
@param string $salt Salt string to validate
@return void | [
"Validate",
"salt",
"string"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility/Salt.php#L122-L134 | train |
QoboLtd/cakephp-utils | src/Utility/Salt.php | Salt.generateSalt | protected static function generateSalt(): string
{
$result = '';
static::validateSaltMinLength();
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$poolSize = strlen($pool);
for ($i = 0; $i < static::$saltMinLength; $i++) {
$result .= $pool[rand(0, $poolSize - 1)];
}
return $result;
} | php | protected static function generateSalt(): string
{
$result = '';
static::validateSaltMinLength();
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$poolSize = strlen($pool);
for ($i = 0; $i < static::$saltMinLength; $i++) {
$result .= $pool[rand(0, $poolSize - 1)];
}
return $result;
} | [
"protected",
"static",
"function",
"generateSalt",
"(",
")",
":",
"string",
"{",
"$",
"result",
"=",
"''",
";",
"static",
"::",
"validateSaltMinLength",
"(",
")",
";",
"$",
"pool",
"=",
"'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'",
";",
"$",
... | Generate salt string
@return string Salt string | [
"Generate",
"salt",
"string"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility/Salt.php#L155-L168 | train |
alexandresalome/PHP-Selenium | src/Selenium/Client.php | Client.getBrowser | public function getBrowser($startPage, $type = '*firefox')
{
$url = 'http://'.$this->host.':'.$this->port.'/selenium-server/driver/';
$driver = new Driver($url, $this->timeout);
$class = $this->browserClass;
return new $class($driver, $startPage, $type);
} | php | public function getBrowser($startPage, $type = '*firefox')
{
$url = 'http://'.$this->host.':'.$this->port.'/selenium-server/driver/';
$driver = new Driver($url, $this->timeout);
$class = $this->browserClass;
return new $class($driver, $startPage, $type);
} | [
"public",
"function",
"getBrowser",
"(",
"$",
"startPage",
",",
"$",
"type",
"=",
"'*firefox'",
")",
"{",
"$",
"url",
"=",
"'http://'",
".",
"$",
"this",
"->",
"host",
".",
"':'",
".",
"$",
"this",
"->",
"port",
".",
"'/selenium-server/driver/'",
";",
... | Creates a new browser instance.
@param string $startPage The URL of the website to test
@param string $type Type of browser, for Selenium
@return Browser A browser instance | [
"Creates",
"a",
"new",
"browser",
"instance",
"."
] | f737b6e396d9d6e2ee5092794bdc42a2ff5ef2c6 | https://github.com/alexandresalome/PHP-Selenium/blob/f737b6e396d9d6e2ee5092794bdc42a2ff5ef2c6/src/Selenium/Client.php#L74-L82 | train |
atk4/schema | src/Migration/MySQL.php | MySQL.describeTable | public function describeTable($table)
{
if (!$this->connection->expr('show tables like []', [$table])->get()) {
return []; // no such table
}
$result = [];
foreach ($this->connection->expr('describe {}', [$table]) as $row) {
$row2 = [];
$row2['name'] = $row['Field'];
$row2['pk'] = $row['Key'] == 'PRI';
$row2['type'] = preg_replace('/\(.*/', '', $row['Type']);
$result[] = $row2;
}
return $result;
} | php | public function describeTable($table)
{
if (!$this->connection->expr('show tables like []', [$table])->get()) {
return []; // no such table
}
$result = [];
foreach ($this->connection->expr('describe {}', [$table]) as $row) {
$row2 = [];
$row2['name'] = $row['Field'];
$row2['pk'] = $row['Key'] == 'PRI';
$row2['type'] = preg_replace('/\(.*/', '', $row['Type']);
$result[] = $row2;
}
return $result;
} | [
"public",
"function",
"describeTable",
"(",
"$",
"table",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"connection",
"->",
"expr",
"(",
"'show tables like []'",
",",
"[",
"$",
"table",
"]",
")",
"->",
"get",
"(",
")",
")",
"{",
"return",
"[",
"]",
... | Return database table descriptions.
DB engine specific.
@param string $table
@return array | [
"Return",
"database",
"table",
"descriptions",
".",
"DB",
"engine",
"specific",
"."
] | d86750ecfa4d78a5624561ff269d4d76ecf92b40 | https://github.com/atk4/schema/blob/d86750ecfa4d78a5624561ff269d4d76ecf92b40/src/Migration/MySQL.php#L26-L44 | train |
romm/formz | Classes/Form/FormObjectHash.php | FormObjectHash.getHash | public function getHash()
{
if (null === $this->hash) {
$this->hash = $this->calculateHash();
}
return $this->hash;
} | php | public function getHash()
{
if (null === $this->hash) {
$this->hash = $this->calculateHash();
}
return $this->hash;
} | [
"public",
"function",
"getHash",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"hash",
")",
"{",
"$",
"this",
"->",
"hash",
"=",
"$",
"this",
"->",
"calculateHash",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"hash",
";",
"}"
] | Returns the hash of the form object, which should be calculated only once
for performance concerns.
@return string | [
"Returns",
"the",
"hash",
"of",
"the",
"form",
"object",
"which",
"should",
"be",
"calculated",
"only",
"once",
"for",
"performance",
"concerns",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Form/FormObjectHash.php#L44-L51 | train |
QuickenLoans/mcp-panthor | src/ErrorHandling/ErrorHandler.php | ErrorHandler.register | public function register($handledErrors = E_ALL)
{
$errHandler = [$this, 'handleError'];
$exHandler = [$this, 'handleException'];
$handledErrors = is_int($handledErrors) ? $handledErrors : E_ALL;
set_error_handler($errHandler, $handledErrors);
set_exception_handler($exHandler);
return $this;
} | php | public function register($handledErrors = E_ALL)
{
$errHandler = [$this, 'handleError'];
$exHandler = [$this, 'handleException'];
$handledErrors = is_int($handledErrors) ? $handledErrors : E_ALL;
set_error_handler($errHandler, $handledErrors);
set_exception_handler($exHandler);
return $this;
} | [
"public",
"function",
"register",
"(",
"$",
"handledErrors",
"=",
"E_ALL",
")",
"{",
"$",
"errHandler",
"=",
"[",
"$",
"this",
",",
"'handleError'",
"]",
";",
"$",
"exHandler",
"=",
"[",
"$",
"this",
",",
"'handleException'",
"]",
";",
"$",
"handledError... | Register this handler as the exception and error handler.
@param int|null $handledErrors
@return self | [
"Register",
"this",
"handler",
"as",
"the",
"exception",
"and",
"error",
"handler",
"."
] | b73e22d83d21b8ed4296bee6aebc66c8b07f292c | https://github.com/QuickenLoans/mcp-panthor/blob/b73e22d83d21b8ed4296bee6aebc66c8b07f292c/src/ErrorHandling/ErrorHandler.php#L280-L291 | train |
QuickenLoans/mcp-panthor | src/ErrorHandling/ErrorHandler.php | ErrorHandler.registerShutdown | public function registerShutdown()
{
if (self::$reservedMemory === null) {
self::$reservedMemory = str_repeat('x', 10240);
register_shutdown_function(__CLASS__ . '::handleFatalError');
}
self::$exceptionHandler = [$this, 'handleException'];
return $this;
} | php | public function registerShutdown()
{
if (self::$reservedMemory === null) {
self::$reservedMemory = str_repeat('x', 10240);
register_shutdown_function(__CLASS__ . '::handleFatalError');
}
self::$exceptionHandler = [$this, 'handleException'];
return $this;
} | [
"public",
"function",
"registerShutdown",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"reservedMemory",
"===",
"null",
")",
"{",
"self",
"::",
"$",
"reservedMemory",
"=",
"str_repeat",
"(",
"'x'",
",",
"10240",
")",
";",
"register_shutdown_function",
"(",
... | Register this handler as the shutdown handler.
@return self | [
"Register",
"this",
"handler",
"as",
"the",
"shutdown",
"handler",
"."
] | b73e22d83d21b8ed4296bee6aebc66c8b07f292c | https://github.com/QuickenLoans/mcp-panthor/blob/b73e22d83d21b8ed4296bee6aebc66c8b07f292c/src/ErrorHandling/ErrorHandler.php#L298-L308 | train |
romm/formz | Classes/Condition/Processor/ConditionProcessorFactory.php | ConditionProcessorFactory.fetchProcessorInstanceFromCache | protected function fetchProcessorInstanceFromCache($cacheIdentifier, FormObject $formObject)
{
$cacheInstance = CacheService::get()->getCacheInstance();
/** @var ConditionProcessor $instance */
if ($cacheInstance->has($cacheIdentifier)) {
$instance = $cacheInstance->get($cacheIdentifier);
$instance->attachFormObject($formObject);
} else {
$instance = $this->getNewProcessorInstance($formObject);
$instance->calculateAllTrees();
$cacheInstance->set($cacheIdentifier, $instance);
}
return $instance;
} | php | protected function fetchProcessorInstanceFromCache($cacheIdentifier, FormObject $formObject)
{
$cacheInstance = CacheService::get()->getCacheInstance();
/** @var ConditionProcessor $instance */
if ($cacheInstance->has($cacheIdentifier)) {
$instance = $cacheInstance->get($cacheIdentifier);
$instance->attachFormObject($formObject);
} else {
$instance = $this->getNewProcessorInstance($formObject);
$instance->calculateAllTrees();
$cacheInstance->set($cacheIdentifier, $instance);
}
return $instance;
} | [
"protected",
"function",
"fetchProcessorInstanceFromCache",
"(",
"$",
"cacheIdentifier",
",",
"FormObject",
"$",
"formObject",
")",
"{",
"$",
"cacheInstance",
"=",
"CacheService",
"::",
"get",
"(",
")",
"->",
"getCacheInstance",
"(",
")",
";",
"/** @var ConditionPro... | Will either fetch the processor instance from cache, using the given
identifier, or calculate it and store it in cache.
@param string $cacheIdentifier
@param FormObject $formObject
@return ConditionProcessor | [
"Will",
"either",
"fetch",
"the",
"processor",
"instance",
"from",
"cache",
"using",
"the",
"given",
"identifier",
"or",
"calculate",
"it",
"and",
"store",
"it",
"in",
"cache",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Condition/Processor/ConditionProcessorFactory.php#L56-L72 | train |
palmtreephp/form | src/Captcha/GoogleRecaptcha.php | GoogleRecaptcha.verify | public function verify($response)
{
$result = $this->getVerificationResult($response);
if ($result['success']) {
return true;
}
if (!empty($result['error-codes'])) {
$this->errors = $result['error-codes'];
}
return false;
} | php | public function verify($response)
{
$result = $this->getVerificationResult($response);
if ($result['success']) {
return true;
}
if (!empty($result['error-codes'])) {
$this->errors = $result['error-codes'];
}
return false;
} | [
"public",
"function",
"verify",
"(",
"$",
"response",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"getVerificationResult",
"(",
"$",
"response",
")",
";",
"if",
"(",
"$",
"result",
"[",
"'success'",
"]",
")",
"{",
"return",
"true",
";",
"}",
"if... | Returns whether the given response was successful.
@param string $response The form's 'g-recaptcha-response' field value.
@return bool | [
"Returns",
"whether",
"the",
"given",
"response",
"was",
"successful",
"."
] | a5addc6fe82f7e687ad04e84565b78f748e22d12 | https://github.com/palmtreephp/form/blob/a5addc6fe82f7e687ad04e84565b78f748e22d12/src/Captcha/GoogleRecaptcha.php#L58-L71 | train |
palmtreephp/form | src/Captcha/GoogleRecaptcha.php | GoogleRecaptcha.getScriptSrc | protected function getScriptSrc($onloadCallbackName)
{
$url = static::SCRIPT_URL;
$queryArgs = [];
\parse_str(\parse_url($url, PHP_URL_QUERY), $queryArgs);
$queryArgs['onload'] = $onloadCallbackName;
$queryArgs['render'] = 'explicit';
$url = \sprintf('%s?%s', \strtok($url, '?'), \http_build_query($queryArgs));
return $url;
} | php | protected function getScriptSrc($onloadCallbackName)
{
$url = static::SCRIPT_URL;
$queryArgs = [];
\parse_str(\parse_url($url, PHP_URL_QUERY), $queryArgs);
$queryArgs['onload'] = $onloadCallbackName;
$queryArgs['render'] = 'explicit';
$url = \sprintf('%s?%s', \strtok($url, '?'), \http_build_query($queryArgs));
return $url;
} | [
"protected",
"function",
"getScriptSrc",
"(",
"$",
"onloadCallbackName",
")",
"{",
"$",
"url",
"=",
"static",
"::",
"SCRIPT_URL",
";",
"$",
"queryArgs",
"=",
"[",
"]",
";",
"\\",
"parse_str",
"(",
"\\",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_QUERY",
... | Returns the recaptcha API script source with an onload callback.
@param string $onloadCallbackName
@return string | [
"Returns",
"the",
"recaptcha",
"API",
"script",
"source",
"with",
"an",
"onload",
"callback",
"."
] | a5addc6fe82f7e687ad04e84565b78f748e22d12 | https://github.com/palmtreephp/form/blob/a5addc6fe82f7e687ad04e84565b78f748e22d12/src/Captcha/GoogleRecaptcha.php#L110-L123 | train |
QuickenLoans/mcp-panthor | src/ErrorHandling/ContentHandler/NegotiatingContentHandler.php | NegotiatingContentHandler.getContentTypeHandler | private function getContentTypeHandler(ServerRequestInterface $request)
{
$acceptHeader = $request->getHeaderLine('Accept');
$acceptedTypes = explode(',', $acceptHeader);
foreach ($this->handlers as $contentType => $handler) {
if ($this->doesTypeMatch($acceptedTypes, $contentType)) {
return $handler;
}
}
return reset($this->handlers);
} | php | private function getContentTypeHandler(ServerRequestInterface $request)
{
$acceptHeader = $request->getHeaderLine('Accept');
$acceptedTypes = explode(',', $acceptHeader);
foreach ($this->handlers as $contentType => $handler) {
if ($this->doesTypeMatch($acceptedTypes, $contentType)) {
return $handler;
}
}
return reset($this->handlers);
} | [
"private",
"function",
"getContentTypeHandler",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"acceptHeader",
"=",
"$",
"request",
"->",
"getHeaderLine",
"(",
"'Accept'",
")",
";",
"$",
"acceptedTypes",
"=",
"explode",
"(",
"','",
",",
"$",
"ac... | Get a content handler based on Accept header in the request.
Falls back to default handler if no matches found.
@param ServerRequestInterface $request
@return ContentHandlerInterface | [
"Get",
"a",
"content",
"handler",
"based",
"on",
"Accept",
"header",
"in",
"the",
"request",
"."
] | b73e22d83d21b8ed4296bee6aebc66c8b07f292c | https://github.com/QuickenLoans/mcp-panthor/blob/b73e22d83d21b8ed4296bee6aebc66c8b07f292c/src/ErrorHandling/ContentHandler/NegotiatingContentHandler.php#L138-L150 | train |
QoboLtd/cakephp-utils | src/Model/Behavior/FootprintBehavior.php | FootprintBehavior.beforeSave | public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void
{
if (! is_callable($this->getConfig('callback'))) {
return;
}
$user = call_user_func($this->getConfig('callback'));
if (empty($user['id'])) {
return;
}
// Set created_by only if that field is not set during entity creation
if ($entity->isNew() && empty($entity->get($this->getConfig('created_by')))) {
$entity->set($this->getConfig('created_by'), $user['id']);
}
// Set modified_by if that field is not set during update
$userId = $entity->isDirty($this->getConfig('modified_by')) && !empty($this->getConfig('modified_by')) ? $entity->get($this->getConfig('modified_by')) : $user['id'];
$entity->set($this->getConfig('modified_by'), $userId);
} | php | public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void
{
if (! is_callable($this->getConfig('callback'))) {
return;
}
$user = call_user_func($this->getConfig('callback'));
if (empty($user['id'])) {
return;
}
// Set created_by only if that field is not set during entity creation
if ($entity->isNew() && empty($entity->get($this->getConfig('created_by')))) {
$entity->set($this->getConfig('created_by'), $user['id']);
}
// Set modified_by if that field is not set during update
$userId = $entity->isDirty($this->getConfig('modified_by')) && !empty($this->getConfig('modified_by')) ? $entity->get($this->getConfig('modified_by')) : $user['id'];
$entity->set($this->getConfig('modified_by'), $userId);
} | [
"public",
"function",
"beforeSave",
"(",
"Event",
"$",
"event",
",",
"EntityInterface",
"$",
"entity",
",",
"ArrayObject",
"$",
"options",
")",
":",
"void",
"{",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'callback'",
")",
... | BeforeSave callback method.
@param \Cake\Event\Event $event Event object
@param \Cake\Datasource\EntityInterface $entity Entity instance
@param \ArrayObject $options Query options
@return void | [
"BeforeSave",
"callback",
"method",
"."
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Model/Behavior/FootprintBehavior.php#L42-L61 | train |
vegas-cmf/forms | src/BuilderAbstract.php | BuilderAbstract.build | public function build(InputSettings $settings)
{
$this->settings = $settings;
$this->setElement();
$this->setValidator();
$this->setLabel();
$this->setDefault();
$this->setAttributes();
$this->setData();
$this->setAdditionalOptions();
return $this->getElement();
} | php | public function build(InputSettings $settings)
{
$this->settings = $settings;
$this->setElement();
$this->setValidator();
$this->setLabel();
$this->setDefault();
$this->setAttributes();
$this->setData();
$this->setAdditionalOptions();
return $this->getElement();
} | [
"public",
"function",
"build",
"(",
"InputSettings",
"$",
"settings",
")",
"{",
"$",
"this",
"->",
"settings",
"=",
"$",
"settings",
";",
"$",
"this",
"->",
"setElement",
"(",
")",
";",
"$",
"this",
"->",
"setValidator",
"(",
")",
";",
"$",
"this",
"... | Method for building form element
@param InputSettings $settings
@return mixed | [
"Method",
"for",
"building",
"form",
"element"
] | f2513b1367c3124f399955ed50ff0e3c13eb671b | https://github.com/vegas-cmf/forms/blob/f2513b1367c3124f399955ed50ff0e3c13eb671b/src/BuilderAbstract.php#L53-L66 | train |
vegas-cmf/forms | src/BuilderAbstract.php | BuilderAbstract.initElement | public function initElement()
{
if(is_null($this->settings)) {
$this->settings = new InputSettings();
}
return $this->build($this->settings);
} | php | public function initElement()
{
if(is_null($this->settings)) {
$this->settings = new InputSettings();
}
return $this->build($this->settings);
} | [
"public",
"function",
"initElement",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"settings",
")",
")",
"{",
"$",
"this",
"->",
"settings",
"=",
"new",
"InputSettings",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"build",
"(",
... | Method sets element and return object instance. Only for form builder purpose.
@return mixed | [
"Method",
"sets",
"element",
"and",
"return",
"object",
"instance",
".",
"Only",
"for",
"form",
"builder",
"purpose",
"."
] | f2513b1367c3124f399955ed50ff0e3c13eb671b | https://github.com/vegas-cmf/forms/blob/f2513b1367c3124f399955ed50ff0e3c13eb671b/src/BuilderAbstract.php#L72-L79 | train |
vegas-cmf/forms | src/BuilderAbstract.php | BuilderAbstract.setLabel | public function setLabel()
{
if($this->settings->getValue(InputSettings::LABEL_PARAM)) {
$this->element->setLabel($this->settings->getValue(InputSettings::LABEL_PARAM));
} else {
$this->element->setLabel(preg_replace('/.*\\\/', '', get_class($this)));
}
} | php | public function setLabel()
{
if($this->settings->getValue(InputSettings::LABEL_PARAM)) {
$this->element->setLabel($this->settings->getValue(InputSettings::LABEL_PARAM));
} else {
$this->element->setLabel(preg_replace('/.*\\\/', '', get_class($this)));
}
} | [
"public",
"function",
"setLabel",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"settings",
"->",
"getValue",
"(",
"InputSettings",
"::",
"LABEL_PARAM",
")",
")",
"{",
"$",
"this",
"->",
"element",
"->",
"setLabel",
"(",
"$",
"this",
"->",
"settings",
"... | Default setter for element label | [
"Default",
"setter",
"for",
"element",
"label"
] | f2513b1367c3124f399955ed50ff0e3c13eb671b | https://github.com/vegas-cmf/forms/blob/f2513b1367c3124f399955ed50ff0e3c13eb671b/src/BuilderAbstract.php#L101-L108 | train |
vegas-cmf/forms | src/BuilderAbstract.php | BuilderAbstract.setDefault | public function setDefault()
{
if($this->settings->getValue(InputSettings::DEFAULTS_PARAM)) {
$this->element->setDefault($this->settings->getValue(InputSettings::DEFAULTS_PARAM));
}
} | php | public function setDefault()
{
if($this->settings->getValue(InputSettings::DEFAULTS_PARAM)) {
$this->element->setDefault($this->settings->getValue(InputSettings::DEFAULTS_PARAM));
}
} | [
"public",
"function",
"setDefault",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"settings",
"->",
"getValue",
"(",
"InputSettings",
"::",
"DEFAULTS_PARAM",
")",
")",
"{",
"$",
"this",
"->",
"element",
"->",
"setDefault",
"(",
"$",
"this",
"->",
"setting... | Default setter for element default value | [
"Default",
"setter",
"for",
"element",
"default",
"value"
] | f2513b1367c3124f399955ed50ff0e3c13eb671b | https://github.com/vegas-cmf/forms/blob/f2513b1367c3124f399955ed50ff0e3c13eb671b/src/BuilderAbstract.php#L113-L118 | train |
vegas-cmf/forms | src/BuilderAbstract.php | BuilderAbstract.setAttributes | public function setAttributes()
{
if($this->settings->getValue(InputSettings::PLACEHOLDER_PARAM)) {
$this->element->setAttribute('placeholder', $this->settings->getValue(InputSettings::PLACEHOLDER_PARAM));
}
} | php | public function setAttributes()
{
if($this->settings->getValue(InputSettings::PLACEHOLDER_PARAM)) {
$this->element->setAttribute('placeholder', $this->settings->getValue(InputSettings::PLACEHOLDER_PARAM));
}
} | [
"public",
"function",
"setAttributes",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"settings",
"->",
"getValue",
"(",
"InputSettings",
"::",
"PLACEHOLDER_PARAM",
")",
")",
"{",
"$",
"this",
"->",
"element",
"->",
"setAttribute",
"(",
"'placeholder'",
",",
... | Default setter for placeholder attribute | [
"Default",
"setter",
"for",
"placeholder",
"attribute"
] | f2513b1367c3124f399955ed50ff0e3c13eb671b | https://github.com/vegas-cmf/forms/blob/f2513b1367c3124f399955ed50ff0e3c13eb671b/src/BuilderAbstract.php#L123-L128 | train |
portphp/doctrine | src/DoctrineWriter.php | DoctrineWriter.getNewInstance | protected function getNewInstance()
{
$className = $this->objectMetadata->getName();
if (class_exists($className) === false) {
throw new \RuntimeException('Unable to create new instance of ' . $className);
}
return new $className;
} | php | protected function getNewInstance()
{
$className = $this->objectMetadata->getName();
if (class_exists($className) === false) {
throw new \RuntimeException('Unable to create new instance of ' . $className);
}
return new $className;
} | [
"protected",
"function",
"getNewInstance",
"(",
")",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"objectMetadata",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"class_exists",
"(",
"$",
"className",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
... | Return a new instance of the object
@return object | [
"Return",
"a",
"new",
"instance",
"of",
"the",
"object"
] | fe07221f51e439f359fbcc94860ba37c0c623705 | https://github.com/portphp/doctrine/blob/fe07221f51e439f359fbcc94860ba37c0c623705/src/DoctrineWriter.php#L200-L209 | train |
portphp/doctrine | src/DoctrineWriter.php | DoctrineWriter.setValue | protected function setValue($object, $value, $setter)
{
if (method_exists($object, $setter)) {
$object->$setter($value);
}
} | php | protected function setValue($object, $value, $setter)
{
if (method_exists($object, $setter)) {
$object->$setter($value);
}
} | [
"protected",
"function",
"setValue",
"(",
"$",
"object",
",",
"$",
"value",
",",
"$",
"setter",
")",
"{",
"if",
"(",
"method_exists",
"(",
"$",
"object",
",",
"$",
"setter",
")",
")",
"{",
"$",
"object",
"->",
"$",
"setter",
"(",
"$",
"value",
")",... | Call a setter of the object
@param object $object
@param mixed $value
@param string $setter | [
"Call",
"a",
"setter",
"of",
"the",
"object"
] | fe07221f51e439f359fbcc94860ba37c0c623705 | https://github.com/portphp/doctrine/blob/fe07221f51e439f359fbcc94860ba37c0c623705/src/DoctrineWriter.php#L218-L223 | train |
romm/formz | Classes/AssetHandler/AssetHandlerFactory.php | AssetHandlerFactory.getAssetHandler | public function getAssetHandler($className)
{
if (false === array_key_exists($className, $this->instances)) {
if (false === class_exists($className)) {
throw ClassNotFoundException::wrongAssetHandlerClassName($className);
}
$instance = GeneralUtility::makeInstance($className, $this);
if (false === $instance instanceof AbstractAssetHandler) {
throw InvalidArgumentTypeException::wrongAssetHandlerType(get_class($instance));
}
$this->instances[$className] = $instance;
}
return $this->instances[$className];
} | php | public function getAssetHandler($className)
{
if (false === array_key_exists($className, $this->instances)) {
if (false === class_exists($className)) {
throw ClassNotFoundException::wrongAssetHandlerClassName($className);
}
$instance = GeneralUtility::makeInstance($className, $this);
if (false === $instance instanceof AbstractAssetHandler) {
throw InvalidArgumentTypeException::wrongAssetHandlerType(get_class($instance));
}
$this->instances[$className] = $instance;
}
return $this->instances[$className];
} | [
"public",
"function",
"getAssetHandler",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"false",
"===",
"array_key_exists",
"(",
"$",
"className",
",",
"$",
"this",
"->",
"instances",
")",
")",
"{",
"if",
"(",
"false",
"===",
"class_exists",
"(",
"$",
"clas... | Return an instance of the wanted asset handler. Local storage is handled.
@param string $className
@return AbstractAssetHandler
@throws ClassNotFoundException
@throws InvalidArgumentTypeException | [
"Return",
"an",
"instance",
"of",
"the",
"wanted",
"asset",
"handler",
".",
"Local",
"storage",
"is",
"handled",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/AssetHandlerFactory.php#L92-L109 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormInitializationJavaScriptAssetHandler.php | FormInitializationJavaScriptAssetHandler.getFormInitializationJavaScriptCode | public function getFormInitializationJavaScriptCode()
{
$formName = GeneralUtility::quoteJSvalue($this->getFormObject()->getName());
$formConfigurationJson = $this->handleFormConfiguration($this->getFormConfiguration());
$javaScriptCode = <<<JS
(function() {
Fz.Form.register($formName, $formConfigurationJson);
})();
JS;
return $javaScriptCode;
} | php | public function getFormInitializationJavaScriptCode()
{
$formName = GeneralUtility::quoteJSvalue($this->getFormObject()->getName());
$formConfigurationJson = $this->handleFormConfiguration($this->getFormConfiguration());
$javaScriptCode = <<<JS
(function() {
Fz.Form.register($formName, $formConfigurationJson);
})();
JS;
return $javaScriptCode;
} | [
"public",
"function",
"getFormInitializationJavaScriptCode",
"(",
")",
"{",
"$",
"formName",
"=",
"GeneralUtility",
"::",
"quoteJSvalue",
"(",
"$",
"this",
"->",
"getFormObject",
"(",
")",
"->",
"getName",
"(",
")",
")",
";",
"$",
"formConfigurationJson",
"=",
... | Generates and returns JavaScript code to instantiate a new form.
@return string | [
"Generates",
"and",
"returns",
"JavaScript",
"code",
"to",
"instantiate",
"a",
"new",
"form",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormInitializationJavaScriptAssetHandler.php#L32-L44 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormInitializationJavaScriptAssetHandler.php | FormInitializationJavaScriptAssetHandler.getFormConfiguration | protected function getFormConfiguration()
{
$formConfigurationArray = $this->getFormObject()->getConfiguration()->toArray();
$this->removeFieldsValidationConfiguration($formConfigurationArray)
->addClassNameProperty($formConfigurationArray);
return ArrayService::get()->arrayToJavaScriptJson($formConfigurationArray);
} | php | protected function getFormConfiguration()
{
$formConfigurationArray = $this->getFormObject()->getConfiguration()->toArray();
$this->removeFieldsValidationConfiguration($formConfigurationArray)
->addClassNameProperty($formConfigurationArray);
return ArrayService::get()->arrayToJavaScriptJson($formConfigurationArray);
} | [
"protected",
"function",
"getFormConfiguration",
"(",
")",
"{",
"$",
"formConfigurationArray",
"=",
"$",
"this",
"->",
"getFormObject",
"(",
")",
"->",
"getConfiguration",
"(",
")",
"->",
"toArray",
"(",
")",
";",
"$",
"this",
"->",
"removeFieldsValidationConfig... | Returns a JSON array containing the form configuration.
@return string | [
"Returns",
"a",
"JSON",
"array",
"containing",
"the",
"form",
"configuration",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormInitializationJavaScriptAssetHandler.php#L62-L69 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormInitializationJavaScriptAssetHandler.php | FormInitializationJavaScriptAssetHandler.removeFieldsValidationConfiguration | protected function removeFieldsValidationConfiguration(array &$formConfiguration)
{
foreach ($formConfiguration['fields'] as $fieldName => $fieldConfiguration) {
if (true === isset($fieldConfiguration['validation'])) {
unset($fieldConfiguration['validation']);
unset($fieldConfiguration['activation']);
$formConfiguration['fields'][$fieldName] = $fieldConfiguration;
}
}
return $this;
} | php | protected function removeFieldsValidationConfiguration(array &$formConfiguration)
{
foreach ($formConfiguration['fields'] as $fieldName => $fieldConfiguration) {
if (true === isset($fieldConfiguration['validation'])) {
unset($fieldConfiguration['validation']);
unset($fieldConfiguration['activation']);
$formConfiguration['fields'][$fieldName] = $fieldConfiguration;
}
}
return $this;
} | [
"protected",
"function",
"removeFieldsValidationConfiguration",
"(",
"array",
"&",
"$",
"formConfiguration",
")",
"{",
"foreach",
"(",
"$",
"formConfiguration",
"[",
"'fields'",
"]",
"as",
"$",
"fieldName",
"=>",
"$",
"fieldConfiguration",
")",
"{",
"if",
"(",
"... | To lower the length of the JavaScript code, we remove useless fields
validation configuration.
@param array $formConfiguration
@return $this | [
"To",
"lower",
"the",
"length",
"of",
"the",
"JavaScript",
"code",
"we",
"remove",
"useless",
"fields",
"validation",
"configuration",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormInitializationJavaScriptAssetHandler.php#L78-L89 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php | FormzLocalizationJavaScriptAssetHandler.getJavaScriptCode | public function getJavaScriptCode()
{
$realTranslations = [];
$translationsBinding = [];
foreach ($this->translations as $key => $value) {
$hash = HashService::get()->getHash($value);
$realTranslations[$hash] = $value;
$translationsBinding[$key] = $hash;
}
$jsonRealTranslations = $this->handleRealTranslations(ArrayService::get()->arrayToJavaScriptJson($realTranslations));
$jsonTranslationsBinding = $this->handleTranslationsBinding(ArrayService::get()->arrayToJavaScriptJson($translationsBinding));
return <<<JS
Fz.Localization.addLocalization($jsonRealTranslations, $jsonTranslationsBinding);
JS;
} | php | public function getJavaScriptCode()
{
$realTranslations = [];
$translationsBinding = [];
foreach ($this->translations as $key => $value) {
$hash = HashService::get()->getHash($value);
$realTranslations[$hash] = $value;
$translationsBinding[$key] = $hash;
}
$jsonRealTranslations = $this->handleRealTranslations(ArrayService::get()->arrayToJavaScriptJson($realTranslations));
$jsonTranslationsBinding = $this->handleTranslationsBinding(ArrayService::get()->arrayToJavaScriptJson($translationsBinding));
return <<<JS
Fz.Localization.addLocalization($jsonRealTranslations, $jsonTranslationsBinding);
JS;
} | [
"public",
"function",
"getJavaScriptCode",
"(",
")",
"{",
"$",
"realTranslations",
"=",
"[",
"]",
";",
"$",
"translationsBinding",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"translations",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$... | Will generate and return the JavaScript code which add all registered
translations to the JavaScript library.
@return string | [
"Will",
"generate",
"and",
"return",
"the",
"JavaScript",
"code",
"which",
"add",
"all",
"registered",
"translations",
"to",
"the",
"JavaScript",
"library",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php#L62-L79 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php | FormzLocalizationJavaScriptAssetHandler.getTranslationKeysForFieldValidation | public function getTranslationKeysForFieldValidation(Field $field, $validationName)
{
$result = [];
if (true === $field->hasValidation($validationName)) {
$key = $field->getName() . '-' . $validationName;
$this->storeTranslationsForFieldValidation($field);
$result = $this->translationKeysForFieldValidation[$key];
}
return $result;
} | php | public function getTranslationKeysForFieldValidation(Field $field, $validationName)
{
$result = [];
if (true === $field->hasValidation($validationName)) {
$key = $field->getName() . '-' . $validationName;
$this->storeTranslationsForFieldValidation($field);
$result = $this->translationKeysForFieldValidation[$key];
}
return $result;
} | [
"public",
"function",
"getTranslationKeysForFieldValidation",
"(",
"Field",
"$",
"field",
",",
"$",
"validationName",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"true",
"===",
"$",
"field",
"->",
"hasValidation",
"(",
"$",
"validationName",
")",... | Returns the keys which are bound to translations, for a given field
validation rule.
@param Field $field
@param string $validationName
@return array | [
"Returns",
"the",
"keys",
"which",
"are",
"bound",
"to",
"translations",
"for",
"a",
"given",
"field",
"validation",
"rule",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php#L89-L102 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php | FormzLocalizationJavaScriptAssetHandler.injectTranslationsForFormFieldsValidation | public function injectTranslationsForFormFieldsValidation()
{
$formConfiguration = $this->getFormObject()->getConfiguration();
foreach ($formConfiguration->getFields() as $field) {
$this->storeTranslationsForFieldValidation($field);
}
return $this;
} | php | public function injectTranslationsForFormFieldsValidation()
{
$formConfiguration = $this->getFormObject()->getConfiguration();
foreach ($formConfiguration->getFields() as $field) {
$this->storeTranslationsForFieldValidation($field);
}
return $this;
} | [
"public",
"function",
"injectTranslationsForFormFieldsValidation",
"(",
")",
"{",
"$",
"formConfiguration",
"=",
"$",
"this",
"->",
"getFormObject",
"(",
")",
"->",
"getConfiguration",
"(",
")",
";",
"foreach",
"(",
"$",
"formConfiguration",
"->",
"getFields",
"("... | Will loop on each field of the given form, and get every translations for
the validation rules messages.
@return $this | [
"Will",
"loop",
"on",
"each",
"field",
"of",
"the",
"given",
"form",
"and",
"get",
"every",
"translations",
"for",
"the",
"validation",
"rules",
"messages",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php#L110-L119 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php | FormzLocalizationJavaScriptAssetHandler.storeTranslationsForFieldValidation | protected function storeTranslationsForFieldValidation(Field $field)
{
if (false === $this->translationsForFieldValidationWereInjected($field)) {
$fieldName = $field->getName();
foreach ($field->getValidation() as $validationName => $validation) {
$messages = ValidatorService::get()->getValidatorMessages($validation->getClassName(), $validation->getMessages());
foreach ($messages as $key => $message) {
$message = MessageService::get()->parseMessageArray($message, ['{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}']);
$localizationKey = $this->getIdentifierForFieldValidationName($field, $validationName, $key);
$this->addTranslation($localizationKey, $message);
$messages[$key] = $localizationKey;
}
$this->translationKeysForFieldValidation[$fieldName . '-' . $validationName] = $messages;
$key = $this->getFormObject()->getClassName() . '-' . $field->getName();
$this->injectedTranslationKeysForFieldValidation[$key] = true;
}
}
return $this;
} | php | protected function storeTranslationsForFieldValidation(Field $field)
{
if (false === $this->translationsForFieldValidationWereInjected($field)) {
$fieldName = $field->getName();
foreach ($field->getValidation() as $validationName => $validation) {
$messages = ValidatorService::get()->getValidatorMessages($validation->getClassName(), $validation->getMessages());
foreach ($messages as $key => $message) {
$message = MessageService::get()->parseMessageArray($message, ['{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}']);
$localizationKey = $this->getIdentifierForFieldValidationName($field, $validationName, $key);
$this->addTranslation($localizationKey, $message);
$messages[$key] = $localizationKey;
}
$this->translationKeysForFieldValidation[$fieldName . '-' . $validationName] = $messages;
$key = $this->getFormObject()->getClassName() . '-' . $field->getName();
$this->injectedTranslationKeysForFieldValidation[$key] = true;
}
}
return $this;
} | [
"protected",
"function",
"storeTranslationsForFieldValidation",
"(",
"Field",
"$",
"field",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"translationsForFieldValidationWereInjected",
"(",
"$",
"field",
")",
")",
"{",
"$",
"fieldName",
"=",
"$",
"field... | Will loop on each validation rule of the given field, and get the
translations of the rule messages.
@param Field $field
@return $this | [
"Will",
"loop",
"on",
"each",
"validation",
"rule",
"of",
"the",
"given",
"field",
"and",
"get",
"the",
"translations",
"of",
"the",
"rule",
"messages",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php#L128-L152 | train |
romm/formz | Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php | FormzLocalizationJavaScriptAssetHandler.translationsForFieldValidationWereInjected | protected function translationsForFieldValidationWereInjected(Field $field)
{
$key = $this->getFormObject()->getClassName() . '-' . $field->getName();
return true === isset($this->injectedTranslationKeysForFieldValidation[$key]);
} | php | protected function translationsForFieldValidationWereInjected(Field $field)
{
$key = $this->getFormObject()->getClassName() . '-' . $field->getName();
return true === isset($this->injectedTranslationKeysForFieldValidation[$key]);
} | [
"protected",
"function",
"translationsForFieldValidationWereInjected",
"(",
"Field",
"$",
"field",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getFormObject",
"(",
")",
"->",
"getClassName",
"(",
")",
".",
"'-'",
".",
"$",
"field",
"->",
"getName",
"(",
... | Checks if the given field validation rules were already handled by this
asset handler.
@param Field $field
@return bool | [
"Checks",
"if",
"the",
"given",
"field",
"validation",
"rules",
"were",
"already",
"handled",
"by",
"this",
"asset",
"handler",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/JavaScript/FormzLocalizationJavaScriptAssetHandler.php#L173-L178 | train |
romm/formz | Classes/Configuration/Configuration.php | Configuration.getConfigurationObjectServices | public static function getConfigurationObjectServices()
{
return ServiceFactory::getInstance()
->attach(ServiceInterface::SERVICE_CACHE)
->with(ServiceInterface::SERVICE_CACHE)
->setOption(CacheService::OPTION_CACHE_NAME, InternalCacheService::CONFIGURATION_OBJECT_CACHE_IDENTIFIER)
->setOption(CacheService::OPTION_CACHE_BACKEND, InternalCacheService::get()->getBackendCache())
->attach(ServiceInterface::SERVICE_PARENTS)
->attach(ServiceInterface::SERVICE_DATA_PRE_PROCESSOR)
->attach(ServiceInterface::SERVICE_MIXED_TYPES);
} | php | public static function getConfigurationObjectServices()
{
return ServiceFactory::getInstance()
->attach(ServiceInterface::SERVICE_CACHE)
->with(ServiceInterface::SERVICE_CACHE)
->setOption(CacheService::OPTION_CACHE_NAME, InternalCacheService::CONFIGURATION_OBJECT_CACHE_IDENTIFIER)
->setOption(CacheService::OPTION_CACHE_BACKEND, InternalCacheService::get()->getBackendCache())
->attach(ServiceInterface::SERVICE_PARENTS)
->attach(ServiceInterface::SERVICE_DATA_PRE_PROCESSOR)
->attach(ServiceInterface::SERVICE_MIXED_TYPES);
} | [
"public",
"static",
"function",
"getConfigurationObjectServices",
"(",
")",
"{",
"return",
"ServiceFactory",
"::",
"getInstance",
"(",
")",
"->",
"attach",
"(",
"ServiceInterface",
"::",
"SERVICE_CACHE",
")",
"->",
"with",
"(",
"ServiceInterface",
"::",
"SERVICE_CAC... | Will initialize correctly the configuration object settings.
@return ServiceFactory | [
"Will",
"initialize",
"correctly",
"the",
"configuration",
"object",
"settings",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Configuration/Configuration.php#L70-L80 | train |
romm/formz | Classes/Configuration/Configuration.php | Configuration.addForm | public function addForm(FormObject $form)
{
if (true === $this->hasForm($form->getClassName(), $form->getName())) {
throw DuplicateEntryException::formWasAlreadyRegistered($form);
}
$form->getConfiguration()->setParents([$this]);
$this->forms[$form->getClassName()][$form->getName()] = $form;
} | php | public function addForm(FormObject $form)
{
if (true === $this->hasForm($form->getClassName(), $form->getName())) {
throw DuplicateEntryException::formWasAlreadyRegistered($form);
}
$form->getConfiguration()->setParents([$this]);
$this->forms[$form->getClassName()][$form->getName()] = $form;
} | [
"public",
"function",
"addForm",
"(",
"FormObject",
"$",
"form",
")",
"{",
"if",
"(",
"true",
"===",
"$",
"this",
"->",
"hasForm",
"(",
"$",
"form",
"->",
"getClassName",
"(",
")",
",",
"$",
"form",
"->",
"getName",
"(",
")",
")",
")",
"{",
"throw"... | Adds a form to the forms list of this FormZ configuration. Note that this
function will also handle the parent service from the
`configuration_object` extension.
@param FormObject $form
@throws DuplicateEntryException | [
"Adds",
"a",
"form",
"to",
"the",
"forms",
"list",
"of",
"this",
"FormZ",
"configuration",
".",
"Note",
"that",
"this",
"function",
"will",
"also",
"handle",
"the",
"parent",
"service",
"from",
"the",
"configuration_object",
"extension",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Configuration/Configuration.php#L98-L107 | train |
romm/formz | Classes/Configuration/Configuration.php | Configuration.calculateHash | public function calculateHash()
{
$fullArray = $this->toArray();
$configurationArray = [
'view' => $fullArray['view'],
'settings' => $fullArray['settings']
];
$this->hash = HashService::get()->getHash(serialize($configurationArray));
} | php | public function calculateHash()
{
$fullArray = $this->toArray();
$configurationArray = [
'view' => $fullArray['view'],
'settings' => $fullArray['settings']
];
$this->hash = HashService::get()->getHash(serialize($configurationArray));
} | [
"public",
"function",
"calculateHash",
"(",
")",
"{",
"$",
"fullArray",
"=",
"$",
"this",
"->",
"toArray",
"(",
")",
";",
"$",
"configurationArray",
"=",
"[",
"'view'",
"=>",
"$",
"fullArray",
"[",
"'view'",
"]",
",",
"'settings'",
"=>",
"$",
"fullArray"... | Calculates a hash for this configuration, which can be used as a unique
identifier. It should be called once, before the configuration is put in
cache, so it is not needed to call it again after being fetched from
cache. | [
"Calculates",
"a",
"hash",
"for",
"this",
"configuration",
"which",
"can",
"be",
"used",
"as",
"a",
"unique",
"identifier",
".",
"It",
"should",
"be",
"called",
"once",
"before",
"the",
"configuration",
"is",
"put",
"in",
"cache",
"so",
"it",
"is",
"not",
... | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Configuration/Configuration.php#L145-L154 | train |
alexandresalome/PHP-Selenium | src/Selenium/Specification/Dumper/MethodBuilder.php | MethodBuilder.buildCode | public function buildCode()
{
$code = '';
if ($this->documentation) {
$code .= ' /**'."\n";
$code .= ' * '.str_replace("\n", "\n * ", wordwrap($this->documentation, 73))."\n";
$code .= ' */'."\n";
}
$code .= ' public function '.$this->name.'('.implode(', ', $this->parameters).')'."\n";
$code .= ' {'."\n";
$code .= ' '.str_replace("\n", "\n ", $this->body)."\n";
$code .= ' }';
// Trim trailing whitespaces
$code = preg_replace('/[ ]+$/m', '', $code);
return $code;
} | php | public function buildCode()
{
$code = '';
if ($this->documentation) {
$code .= ' /**'."\n";
$code .= ' * '.str_replace("\n", "\n * ", wordwrap($this->documentation, 73))."\n";
$code .= ' */'."\n";
}
$code .= ' public function '.$this->name.'('.implode(', ', $this->parameters).')'."\n";
$code .= ' {'."\n";
$code .= ' '.str_replace("\n", "\n ", $this->body)."\n";
$code .= ' }';
// Trim trailing whitespaces
$code = preg_replace('/[ ]+$/m', '', $code);
return $code;
} | [
"public",
"function",
"buildCode",
"(",
")",
"{",
"$",
"code",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"documentation",
")",
"{",
"$",
"code",
".=",
"' /**'",
".",
"\"\\n\"",
";",
"$",
"code",
".=",
"' * '",
".",
"str_replace",
"(",
"\"\... | Builds the PHP code for the method.
@return string The method code | [
"Builds",
"the",
"PHP",
"code",
"for",
"the",
"method",
"."
] | f737b6e396d9d6e2ee5092794bdc42a2ff5ef2c6 | https://github.com/alexandresalome/PHP-Selenium/blob/f737b6e396d9d6e2ee5092794bdc42a2ff5ef2c6/src/Selenium/Specification/Dumper/MethodBuilder.php#L108-L127 | train |
DevFactoryCH/taxonomy | src/Taxonomy.php | Taxonomy.createVocabulary | public function createVocabulary($name) {
if ($this->vocabulary->where('name', $name)->count()) {
throw new Exceptions\VocabularyExistsException();
}
return $this->vocabulary->create(['name' => $name]);
} | php | public function createVocabulary($name) {
if ($this->vocabulary->where('name', $name)->count()) {
throw new Exceptions\VocabularyExistsException();
}
return $this->vocabulary->create(['name' => $name]);
} | [
"public",
"function",
"createVocabulary",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"vocabulary",
"->",
"where",
"(",
"'name'",
",",
"$",
"name",
")",
"->",
"count",
"(",
")",
")",
"{",
"throw",
"new",
"Exceptions",
"\\",
"VocabularyExi... | Create a new Vocabulary with the given name
@param string $name
The name of the Vocabulary
@return mixed
The Vocabulary object if created, FALSE if error creating,
Exception if the vocabulary name already exists. | [
"Create",
"a",
"new",
"Vocabulary",
"with",
"the",
"given",
"name"
] | ff49a2e450d749b82243e5514e8e847ae21371e8 | https://github.com/DevFactoryCH/taxonomy/blob/ff49a2e450d749b82243e5514e8e847ae21371e8/src/Taxonomy.php#L28-L34 | train |
DevFactoryCH/taxonomy | src/Taxonomy.php | Taxonomy.getVocabularyByNameAsArray | public function getVocabularyByNameAsArray($name) {
$vocabulary = $this->vocabulary->where('name', $name)->first();
if (!is_null($vocabulary)) {
return $vocabulary->terms->pluck('name', 'id')->toArray();
}
return [];
} | php | public function getVocabularyByNameAsArray($name) {
$vocabulary = $this->vocabulary->where('name', $name)->first();
if (!is_null($vocabulary)) {
return $vocabulary->terms->pluck('name', 'id')->toArray();
}
return [];
} | [
"public",
"function",
"getVocabularyByNameAsArray",
"(",
"$",
"name",
")",
"{",
"$",
"vocabulary",
"=",
"$",
"this",
"->",
"vocabulary",
"->",
"where",
"(",
"'name'",
",",
"$",
"name",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
... | Get a Vocabulary by name
@param string $name
The name of the Vocabulary to fetch
@return
The Vocabulary Model object, otherwise NULL | [
"Get",
"a",
"Vocabulary",
"by",
"name"
] | ff49a2e450d749b82243e5514e8e847ae21371e8 | https://github.com/DevFactoryCH/taxonomy/blob/ff49a2e450d749b82243e5514e8e847ae21371e8/src/Taxonomy.php#L71-L79 | train |
DevFactoryCH/taxonomy | src/Taxonomy.php | Taxonomy.getVocabularyByNameOptionsArray | public function getVocabularyByNameOptionsArray($name) {
$vocabulary = $this->vocabulary->where('name', $name)->first();
if (is_null($vocabulary)) {
return [];
}
$parents = $this->term->whereParent(0)
->whereVocabularyId($vocabulary->id)
->orderBy('weight', 'ASC')
->get();
$options = [];
foreach ($parents as $parent) {
$options[$parent->id] = $parent->name;
$this->recurse_children($parent, $options);
}
return $options;
} | php | public function getVocabularyByNameOptionsArray($name) {
$vocabulary = $this->vocabulary->where('name', $name)->first();
if (is_null($vocabulary)) {
return [];
}
$parents = $this->term->whereParent(0)
->whereVocabularyId($vocabulary->id)
->orderBy('weight', 'ASC')
->get();
$options = [];
foreach ($parents as $parent) {
$options[$parent->id] = $parent->name;
$this->recurse_children($parent, $options);
}
return $options;
} | [
"public",
"function",
"getVocabularyByNameOptionsArray",
"(",
"$",
"name",
")",
"{",
"$",
"vocabulary",
"=",
"$",
"this",
"->",
"vocabulary",
"->",
"where",
"(",
"'name'",
",",
"$",
"name",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"is_null",
"(",
... | Get a Vocabulary by name as an options array for dropdowns
@param string $name
The name of the Vocabulary to fetch
@return
The Vocabulary Model object, otherwise NULL | [
"Get",
"a",
"Vocabulary",
"by",
"name",
"as",
"an",
"options",
"array",
"for",
"dropdowns"
] | ff49a2e450d749b82243e5514e8e847ae21371e8 | https://github.com/DevFactoryCH/taxonomy/blob/ff49a2e450d749b82243e5514e8e847ae21371e8/src/Taxonomy.php#L90-L109 | train |
DevFactoryCH/taxonomy | src/Taxonomy.php | Taxonomy.recurse_children | private function recurse_children($parent, &$options, $depth = 1) {
$parent->childrens->map(function($child) use (&$options, $depth) {
$options[$child->id] = str_repeat('-', $depth) .' '. $child->name;
if ($child->childrens) {
$this->recurse_children($child, $options, $depth+1);
}
});
} | php | private function recurse_children($parent, &$options, $depth = 1) {
$parent->childrens->map(function($child) use (&$options, $depth) {
$options[$child->id] = str_repeat('-', $depth) .' '. $child->name;
if ($child->childrens) {
$this->recurse_children($child, $options, $depth+1);
}
});
} | [
"private",
"function",
"recurse_children",
"(",
"$",
"parent",
",",
"&",
"$",
"options",
",",
"$",
"depth",
"=",
"1",
")",
"{",
"$",
"parent",
"->",
"childrens",
"->",
"map",
"(",
"function",
"(",
"$",
"child",
")",
"use",
"(",
"&",
"$",
"options",
... | Recursively visit the children of a term and generate the '- ' option array for dropdowns
@param Object $parent
@param array $options
@param int $depth
@return array | [
"Recursively",
"visit",
"the",
"children",
"of",
"a",
"term",
"and",
"generate",
"the",
"-",
"option",
"array",
"for",
"dropdowns"
] | ff49a2e450d749b82243e5514e8e847ae21371e8 | https://github.com/DevFactoryCH/taxonomy/blob/ff49a2e450d749b82243e5514e8e847ae21371e8/src/Taxonomy.php#L120-L128 | train |
DevFactoryCH/taxonomy | src/Taxonomy.php | Taxonomy.deleteVocabularyByName | public function deleteVocabularyByName($name) {
$vocabulary = $this->vocabulary->where('name', $name)->first();
if (!is_null($vocabulary)) {
return $vocabulary->delete();
}
return FALSE;
} | php | public function deleteVocabularyByName($name) {
$vocabulary = $this->vocabulary->where('name', $name)->first();
if (!is_null($vocabulary)) {
return $vocabulary->delete();
}
return FALSE;
} | [
"public",
"function",
"deleteVocabularyByName",
"(",
"$",
"name",
")",
"{",
"$",
"vocabulary",
"=",
"$",
"this",
"->",
"vocabulary",
"->",
"where",
"(",
"'name'",
",",
"$",
"name",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$... | Delete a Vocabulary by name
@param string $name
The name of the Vocabulary to delete
@return bool
TRUE if Vocabulary is deletes, otherwise FALSE | [
"Delete",
"a",
"Vocabulary",
"by",
"name"
] | ff49a2e450d749b82243e5514e8e847ae21371e8 | https://github.com/DevFactoryCH/taxonomy/blob/ff49a2e450d749b82243e5514e8e847ae21371e8/src/Taxonomy.php#L156-L164 | train |
DevFactoryCH/taxonomy | src/Taxonomy.php | Taxonomy.createTerm | public function createTerm($vid, $name, $parent = 0, $weight = 0) {
$vocabulary = $this->vocabulary->findOrFail($vid);
$term = [
'name' => $name,
'vocabulary_id' => $vid,
'parent' => $parent,
'weight' => $weight,
];
return $this->term->create($term);
} | php | public function createTerm($vid, $name, $parent = 0, $weight = 0) {
$vocabulary = $this->vocabulary->findOrFail($vid);
$term = [
'name' => $name,
'vocabulary_id' => $vid,
'parent' => $parent,
'weight' => $weight,
];
return $this->term->create($term);
} | [
"public",
"function",
"createTerm",
"(",
"$",
"vid",
",",
"$",
"name",
",",
"$",
"parent",
"=",
"0",
",",
"$",
"weight",
"=",
"0",
")",
"{",
"$",
"vocabulary",
"=",
"$",
"this",
"->",
"vocabulary",
"->",
"findOrFail",
"(",
"$",
"vid",
")",
";",
"... | Create a new term in a specific vocabulary
@param int $vid
The Vocabulary ID in which to add the term
@param string $name
The name of the term
@param int $parent
The ID of the parent term if it is a child
@param int $weight
The weight of the term in order to sort them inside the Vocabulary
@return int
The ID of the created term
@thrown Illuminate\Database\Eloquent\ModelNotFoundException | [
"Create",
"a",
"new",
"term",
"in",
"a",
"specific",
"vocabulary"
] | ff49a2e450d749b82243e5514e8e847ae21371e8 | https://github.com/DevFactoryCH/taxonomy/blob/ff49a2e450d749b82243e5514e8e847ae21371e8/src/Taxonomy.php#L186-L197 | train |
romm/formz | Classes/Validation/Validator/Internal/ConditionIsValidValidator.php | ConditionIsValidValidator.isValid | public function isValid($condition)
{
$conditionTree = ConditionParser::get()
->parse($condition);
if (true === $conditionTree->getValidationResult()->hasErrors()) {
$errorMessage = $this->translateErrorMessage(
'validator.form.condition_is_valid.error',
'formz',
[
$condition->getExpression(),
$conditionTree->getValidationResult()->getFirstError()->getMessage()
]
);
$this->addError($errorMessage, self::ERROR_CODE);
}
} | php | public function isValid($condition)
{
$conditionTree = ConditionParser::get()
->parse($condition);
if (true === $conditionTree->getValidationResult()->hasErrors()) {
$errorMessage = $this->translateErrorMessage(
'validator.form.condition_is_valid.error',
'formz',
[
$condition->getExpression(),
$conditionTree->getValidationResult()->getFirstError()->getMessage()
]
);
$this->addError($errorMessage, self::ERROR_CODE);
}
} | [
"public",
"function",
"isValid",
"(",
"$",
"condition",
")",
"{",
"$",
"conditionTree",
"=",
"ConditionParser",
"::",
"get",
"(",
")",
"->",
"parse",
"(",
"$",
"condition",
")",
";",
"if",
"(",
"true",
"===",
"$",
"conditionTree",
"->",
"getValidationResul... | Checks if the value is a valid condition string.
@param ActivationInterface $condition The condition instance that should be validated. | [
"Checks",
"if",
"the",
"value",
"is",
"a",
"valid",
"condition",
"string",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Validation/Validator/Internal/ConditionIsValidValidator.php#L29-L46 | train |
bigcommerce-labs/injector | src/InjectorServiceProvider.php | InjectorServiceProvider.alias | protected function alias($aliasKey, $serviceKey)
{
// Bound as a factory to ALWAYS pass through to underlying definition.
$this->bindFactory(
$aliasKey,
function (Container $app) use ($serviceKey) {
return $app[$serviceKey];
}
);
} | php | protected function alias($aliasKey, $serviceKey)
{
// Bound as a factory to ALWAYS pass through to underlying definition.
$this->bindFactory(
$aliasKey,
function (Container $app) use ($serviceKey) {
return $app[$serviceKey];
}
);
} | [
"protected",
"function",
"alias",
"(",
"$",
"aliasKey",
",",
"$",
"serviceKey",
")",
"{",
"// Bound as a factory to ALWAYS pass through to underlying definition.",
"$",
"this",
"->",
"bindFactory",
"(",
"$",
"aliasKey",
",",
"function",
"(",
"Container",
"$",
"app",
... | Alias a service name to another one within the service container, allowing for example
concrete types to be aliased to an interface, or legacy string service keys against concrete class names.
@param string $aliasKey
@param string $serviceKey
@throws \InvalidArgumentException
@return void | [
"Alias",
"a",
"service",
"name",
"to",
"another",
"one",
"within",
"the",
"service",
"container",
"allowing",
"for",
"example",
"concrete",
"types",
"to",
"be",
"aliased",
"to",
"an",
"interface",
"or",
"legacy",
"string",
"service",
"keys",
"against",
"concre... | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/InjectorServiceProvider.php#L116-L125 | train |
bigcommerce-labs/injector | src/InjectorServiceProvider.php | InjectorServiceProvider.autoBind | protected function autoBind($className, callable $parameterFactory = null)
{
$this->bind(
$className,
$this->closureFactory->createAutoWireClosure($className, $parameterFactory)
);
} | php | protected function autoBind($className, callable $parameterFactory = null)
{
$this->bind(
$className,
$this->closureFactory->createAutoWireClosure($className, $parameterFactory)
);
} | [
"protected",
"function",
"autoBind",
"(",
"$",
"className",
",",
"callable",
"$",
"parameterFactory",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"bind",
"(",
"$",
"className",
",",
"$",
"this",
"->",
"closureFactory",
"->",
"createAutoWireClosure",
"(",
"$",
... | Automatically bind and wire a service using the Injector. Accepts an optional callable to build parameter
overrides
@param string $className FQCN of a class to auto-wire bind.
@param callable|null $parameterFactory Callable to generate parameters to inject to the service. Will receive
the IoC container as its first parameter.
@throws \Exception
@return void | [
"Automatically",
"bind",
"and",
"wire",
"a",
"service",
"using",
"the",
"Injector",
".",
"Accepts",
"an",
"optional",
"callable",
"to",
"build",
"parameter",
"overrides"
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/InjectorServiceProvider.php#L179-L185 | train |
bigcommerce-labs/injector | src/InjectorServiceProvider.php | InjectorServiceProvider.autoBindFactory | protected function autoBindFactory($className, callable $parameterFactory = null)
{
$this->bindFactory(
$className,
$this->closureFactory->createAutoWireClosure($className, $parameterFactory)
);
} | php | protected function autoBindFactory($className, callable $parameterFactory = null)
{
$this->bindFactory(
$className,
$this->closureFactory->createAutoWireClosure($className, $parameterFactory)
);
} | [
"protected",
"function",
"autoBindFactory",
"(",
"$",
"className",
",",
"callable",
"$",
"parameterFactory",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"bindFactory",
"(",
"$",
"className",
",",
"$",
"this",
"->",
"closureFactory",
"->",
"createAutoWireClosure",
... | Automatically bind and wire a factory using the Injector. Accepts an optional callable to build parameter
overrides.
@param string $className FQCN of a class to auto-wire bind.
@param callable|null $parameterFactory Callable to generate parameters to inject to the service. Will receive
the IoC container as its first parameter.
@throws \Exception
@return void | [
"Automatically",
"bind",
"and",
"wire",
"a",
"factory",
"using",
"the",
"Injector",
".",
"Accepts",
"an",
"optional",
"callable",
"to",
"build",
"parameter",
"overrides",
"."
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/InjectorServiceProvider.php#L197-L203 | train |
bigcommerce-labs/injector | src/Injector.php | Injector.create | public function create($className, $parameters = [])
{
$reflectionClass = new \ReflectionClass($className);
if (!$reflectionClass->hasMethod("__construct")) {
//This class doesn't have a constructor
return $reflectionClass->newInstanceWithoutConstructor();
}
if (!$reflectionClass->getMethod('__construct')->isPublic()) {
throw new InjectorInvocationException(
"Injector failed to create $className - constructor isn't public." .
" Do you need to use a static factory method instead?"
);
}
try {
$parameters = $this->buildParameterArray(
$this->inspector->getSignatureByReflectionClass($reflectionClass, "__construct"),
$parameters
);
return $reflectionClass->newInstanceArgs($parameters);
} catch (MissingRequiredParameterException $e) {
throw new InjectorInvocationException(
"Can't create $className " .
" - __construct() missing parameter '" . $e->getParameterString() . "'" .
" could not be found. Either register it as a service or pass it to create via parameters."
);
} catch (InjectorInvocationException $e) {
//Wrap the exception stack for recursive calls to aid debugging
throw new InjectorInvocationException(
$e->getMessage() .
PHP_EOL . " => (Called when creating $className)"
);
}
} | php | public function create($className, $parameters = [])
{
$reflectionClass = new \ReflectionClass($className);
if (!$reflectionClass->hasMethod("__construct")) {
//This class doesn't have a constructor
return $reflectionClass->newInstanceWithoutConstructor();
}
if (!$reflectionClass->getMethod('__construct')->isPublic()) {
throw new InjectorInvocationException(
"Injector failed to create $className - constructor isn't public." .
" Do you need to use a static factory method instead?"
);
}
try {
$parameters = $this->buildParameterArray(
$this->inspector->getSignatureByReflectionClass($reflectionClass, "__construct"),
$parameters
);
return $reflectionClass->newInstanceArgs($parameters);
} catch (MissingRequiredParameterException $e) {
throw new InjectorInvocationException(
"Can't create $className " .
" - __construct() missing parameter '" . $e->getParameterString() . "'" .
" could not be found. Either register it as a service or pass it to create via parameters."
);
} catch (InjectorInvocationException $e) {
//Wrap the exception stack for recursive calls to aid debugging
throw new InjectorInvocationException(
$e->getMessage() .
PHP_EOL . " => (Called when creating $className)"
);
}
} | [
"public",
"function",
"create",
"(",
"$",
"className",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"reflectionClass",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"className",
")",
";",
"if",
"(",
"!",
"$",
"reflectionClass",
"->",
"hasMethod... | Instantiate an object and attempt to inject the dependencies for the class by mapping constructor parameter \
names to objects registered within the IoC container.
The optional $parameters passed to this method accept and will inject values based on:
- Type: [Cache::class => new RedisCache()] will inject RedisCache to each parameter typed Cache::class
- Name: ["cache" => new RedisCache()] will inject RedisCache to the parameter named $cache
- Index: [ 3 => new RedisCache()] will inject RedisCache to the 4th parameter (zero index)
@param string $className The fully qualified class name for the object we're creating
@param array $parameters An optional array of additional parameters to pass to the created objects constructor.
@return object
@throws InjectorInvocationException
@throws \InvalidArgumentException
@throws \ReflectionException | [
"Instantiate",
"an",
"object",
"and",
"attempt",
"to",
"inject",
"the",
"dependencies",
"for",
"the",
"class",
"by",
"mapping",
"constructor",
"parameter",
"\\",
"names",
"to",
"objects",
"registered",
"within",
"the",
"IoC",
"container",
"."
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/Injector.php#L74-L107 | train |
bigcommerce-labs/injector | src/Injector.php | Injector.canAutoCreate | public function canAutoCreate($className)
{
foreach ($this->autoCreateWhiteList as $regex) {
if (preg_match($regex, $className)) {
return true;
}
}
return false;
} | php | public function canAutoCreate($className)
{
foreach ($this->autoCreateWhiteList as $regex) {
if (preg_match($regex, $className)) {
return true;
}
}
return false;
} | [
"public",
"function",
"canAutoCreate",
"(",
"$",
"className",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"autoCreateWhiteList",
"as",
"$",
"regex",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"className",
")",
")",
"{",
"return",
... | Check whether the Injector has been configured to allow automatic construction of the given FQCN as a dependency
@param string $className
@return bool | [
"Check",
"whether",
"the",
"Injector",
"has",
"been",
"configured",
"to",
"allow",
"automatic",
"construction",
"of",
"the",
"given",
"FQCN",
"as",
"a",
"dependency"
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/Injector.php#L181-L190 | train |
bigcommerce-labs/injector | src/Injector.php | Injector.buildParameterArray | private function buildParameterArray($methodSignature, $providedParameters)
{
$parameters = [];
foreach ($methodSignature as $position => $parameterData) {
if (!isset($parameterData['variadic'])) {
$parameters[$position] = $this->resolveParameter($position, $parameterData, $providedParameters);
} else {
// variadic parameter must be the last one, so
// the rest of the provided paramters should be piped
// into it to mimic native php behaviour
foreach ($providedParameters as $variadicParameter) {
$parameters[] = $variadicParameter;
}
}
}
return $parameters;
} | php | private function buildParameterArray($methodSignature, $providedParameters)
{
$parameters = [];
foreach ($methodSignature as $position => $parameterData) {
if (!isset($parameterData['variadic'])) {
$parameters[$position] = $this->resolveParameter($position, $parameterData, $providedParameters);
} else {
// variadic parameter must be the last one, so
// the rest of the provided paramters should be piped
// into it to mimic native php behaviour
foreach ($providedParameters as $variadicParameter) {
$parameters[] = $variadicParameter;
}
}
}
return $parameters;
} | [
"private",
"function",
"buildParameterArray",
"(",
"$",
"methodSignature",
",",
"$",
"providedParameters",
")",
"{",
"$",
"parameters",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"methodSignature",
"as",
"$",
"position",
"=>",
"$",
"parameterData",
")",
"{",
"... | Construct the parameter array to be passed to a method call based on its parameter signature
@param array $methodSignature
@param array $providedParameters
@return array
@throws InjectorInvocationException
@throws MissingRequiredParameterException
@throws \InvalidArgumentException
@throws \ReflectionException | [
"Construct",
"the",
"parameter",
"array",
"to",
"be",
"passed",
"to",
"a",
"method",
"call",
"based",
"on",
"its",
"parameter",
"signature"
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/Injector.php#L203-L219 | train |
bigcommerce-labs/injector | src/Reflection/ParameterInspector.php | ParameterInspector.getSignatureByReflectionClass | public function getSignatureByReflectionClass(\ReflectionClass $reflectionClass, $methodName)
{
$className = $reflectionClass->getName();
return $this->getMethodSignature($className, $methodName, $reflectionClass);
} | php | public function getSignatureByReflectionClass(\ReflectionClass $reflectionClass, $methodName)
{
$className = $reflectionClass->getName();
return $this->getMethodSignature($className, $methodName, $reflectionClass);
} | [
"public",
"function",
"getSignatureByReflectionClass",
"(",
"\\",
"ReflectionClass",
"$",
"reflectionClass",
",",
"$",
"methodName",
")",
"{",
"$",
"className",
"=",
"$",
"reflectionClass",
"->",
"getName",
"(",
")",
";",
"return",
"$",
"this",
"->",
"getMethodS... | Fetch the method signature of a method when we have already created a \ReflectionClass
@param \ReflectionClass $reflectionClass
@param string $methodName
@return array
@throws \ReflectionException | [
"Fetch",
"the",
"method",
"signature",
"of",
"a",
"method",
"when",
"we",
"have",
"already",
"created",
"a",
"\\",
"ReflectionClass"
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/Reflection/ParameterInspector.php#L38-L42 | train |
bigcommerce-labs/injector | src/ServiceProvider/BindingClosureFactory.php | BindingClosureFactory.createAutoWireClosure | public function createAutoWireClosure($className, callable $parameterFactory = null)
{
return function (Container $app) use ($className, $parameterFactory) {
$parameters = $parameterFactory ? $parameterFactory($app) : [];
return $this->injector->create($className, $parameters);
};
} | php | public function createAutoWireClosure($className, callable $parameterFactory = null)
{
return function (Container $app) use ($className, $parameterFactory) {
$parameters = $parameterFactory ? $parameterFactory($app) : [];
return $this->injector->create($className, $parameters);
};
} | [
"public",
"function",
"createAutoWireClosure",
"(",
"$",
"className",
",",
"callable",
"$",
"parameterFactory",
"=",
"null",
")",
"{",
"return",
"function",
"(",
"Container",
"$",
"app",
")",
"use",
"(",
"$",
"className",
",",
"$",
"parameterFactory",
")",
"... | Generate a closure that will use the Injector to auto-wire a service definition.
@param string $className FQCN of a class to auto-wire bind.
@param callable|null $parameterFactory Callable to generate parameters to inject to the service. Will receive
the IoC container as its first parameter.
@return \Closure | [
"Generate",
"a",
"closure",
"that",
"will",
"use",
"the",
"Injector",
"to",
"auto",
"-",
"wire",
"a",
"service",
"definition",
"."
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/ServiceProvider/BindingClosureFactory.php#L43-L49 | train |
bigcommerce-labs/injector | src/ServiceProvider/BindingClosureFactory.php | BindingClosureFactory.createProxy | private function createProxy($className, callable $serviceFactory, Container $app)
{
return $this->proxyFactory->createProxy(
$className,
function (&$wrappedObject, $proxy, $method, $parameters, &$initializer) use (
$className,
$serviceFactory,
$app
) {
$wrappedObject = $serviceFactory($app);
$initializer = null;
return true;
}
);
} | php | private function createProxy($className, callable $serviceFactory, Container $app)
{
return $this->proxyFactory->createProxy(
$className,
function (&$wrappedObject, $proxy, $method, $parameters, &$initializer) use (
$className,
$serviceFactory,
$app
) {
$wrappedObject = $serviceFactory($app);
$initializer = null;
return true;
}
);
} | [
"private",
"function",
"createProxy",
"(",
"$",
"className",
",",
"callable",
"$",
"serviceFactory",
",",
"Container",
"$",
"app",
")",
"{",
"return",
"$",
"this",
"->",
"proxyFactory",
"->",
"createProxy",
"(",
"$",
"className",
",",
"function",
"(",
"&",
... | Create a project object for the specified ClassName bound to the given ServiceFactory method.
@param string $className
@param callable $serviceFactory
@param Container $app
@return \ProxyManager\Proxy\VirtualProxyInterface | [
"Create",
"a",
"project",
"object",
"for",
"the",
"specified",
"ClassName",
"bound",
"to",
"the",
"given",
"ServiceFactory",
"method",
"."
] | 8c6673265860478031c24faedb5ba0a5df5b2ee5 | https://github.com/bigcommerce-labs/injector/blob/8c6673265860478031c24faedb5ba0a5df5b2ee5/src/ServiceProvider/BindingClosureFactory.php#L79-L93 | train |
inphinit/framework | src/Inphinit/Packages.php | Packages.classmap | public function classmap()
{
$path = $this->composerPath . $this->classmapName;
$i = 0;
if (is_file($path)) {
$data = include $path;
foreach ($data as $key => $value) {
if (false === empty($value)) {
$this->libs[addcslashes($key, '\\')] = $value;
$i++;
}
}
$this->log[] = 'Imported ' . $i . ' classes from classmap';
return $i;
}
$this->log[] = 'Warn: classmap not found';
return false;
} | php | public function classmap()
{
$path = $this->composerPath . $this->classmapName;
$i = 0;
if (is_file($path)) {
$data = include $path;
foreach ($data as $key => $value) {
if (false === empty($value)) {
$this->libs[addcslashes($key, '\\')] = $value;
$i++;
}
}
$this->log[] = 'Imported ' . $i . ' classes from classmap';
return $i;
}
$this->log[] = 'Warn: classmap not found';
return false;
} | [
"public",
"function",
"classmap",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"composerPath",
".",
"$",
"this",
"->",
"classmapName",
";",
"$",
"i",
"=",
"0",
";",
"if",
"(",
"is_file",
"(",
"$",
"path",
")",
")",
"{",
"$",
"data",
"=",
... | Load `autoload_classmap.php` classes
@return int|bool Return total packages loaded, if `autoload_classmap.php`
is not accessible return `false` | [
"Load",
"autoload_classmap",
".",
"php",
"classes"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Packages.php#L87-L108 | train |
inphinit/framework | src/Inphinit/Packages.php | Packages.psr0 | public function psr0()
{
$i = $this->load($this->composerPath . $this->psrZeroName);
if ($i !== false) {
$this->log[] = 'Imported ' . $i . ' classes from psr0';
return $i;
}
$this->log[] = 'Warn: psr0 not found';
return false;
} | php | public function psr0()
{
$i = $this->load($this->composerPath . $this->psrZeroName);
if ($i !== false) {
$this->log[] = 'Imported ' . $i . ' classes from psr0';
return $i;
}
$this->log[] = 'Warn: psr0 not found';
return false;
} | [
"public",
"function",
"psr0",
"(",
")",
"{",
"$",
"i",
"=",
"$",
"this",
"->",
"load",
"(",
"$",
"this",
"->",
"composerPath",
".",
"$",
"this",
"->",
"psrZeroName",
")",
";",
"if",
"(",
"$",
"i",
"!==",
"false",
")",
"{",
"$",
"this",
"->",
"l... | Load `autoload_namespaces.php` classes, used by PSR-0 packages
@return int|bool Return total packages loaded, if `autoload_namespaces.php`
is not accessible return `false` | [
"Load",
"autoload_namespaces",
".",
"php",
"classes",
"used",
"by",
"PSR",
"-",
"0",
"packages"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Packages.php#L116-L127 | train |
inphinit/framework | src/Inphinit/Packages.php | Packages.psr4 | public function psr4()
{
$i = $this->load($this->composerPath . $this->psrFourName);
if ($i !== false) {
$this->log[] = 'Imported ' . $i . ' classes from psr4';
return $i;
}
$this->log[] = 'Warn: psr4 not found';
return false;
} | php | public function psr4()
{
$i = $this->load($this->composerPath . $this->psrFourName);
if ($i !== false) {
$this->log[] = 'Imported ' . $i . ' classes from psr4';
return $i;
}
$this->log[] = 'Warn: psr4 not found';
return false;
} | [
"public",
"function",
"psr4",
"(",
")",
"{",
"$",
"i",
"=",
"$",
"this",
"->",
"load",
"(",
"$",
"this",
"->",
"composerPath",
".",
"$",
"this",
"->",
"psrFourName",
")",
";",
"if",
"(",
"$",
"i",
"!==",
"false",
")",
"{",
"$",
"this",
"->",
"l... | Load `autoload_psr4.php` classes, used by PSR-4 packages
@return int|bool Return total packages loaded, if `autoload_psr4.php`
is not accessible return `false` | [
"Load",
"autoload_psr4",
".",
"php",
"classes",
"used",
"by",
"PSR",
"-",
"4",
"packages"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Packages.php#L135-L146 | train |
inphinit/framework | src/Inphinit/Packages.php | Packages.save | public function save($path)
{
if (count($this->libs) === 0) {
return false;
}
$handle = fopen($path, 'w');
if ($handle === false) {
throw new \InvalidArgumentException('This path is not writabled: ' . $path);
}
$first = true;
$eol = chr(10);
fwrite($handle, '<?php' . $eol . 'return array(');
foreach ($this->libs as $key => $value) {
$value = self::relativePath($value);
fwrite($handle, ($first ? '' : ',') . $eol . " '" . $key . "' => '" . $value . "'");
$first = false;
}
fwrite($handle, $eol . ');' . $eol);
fclose($handle);
return true;
} | php | public function save($path)
{
if (count($this->libs) === 0) {
return false;
}
$handle = fopen($path, 'w');
if ($handle === false) {
throw new \InvalidArgumentException('This path is not writabled: ' . $path);
}
$first = true;
$eol = chr(10);
fwrite($handle, '<?php' . $eol . 'return array(');
foreach ($this->libs as $key => $value) {
$value = self::relativePath($value);
fwrite($handle, ($first ? '' : ',') . $eol . " '" . $key . "' => '" . $value . "'");
$first = false;
}
fwrite($handle, $eol . ');' . $eol);
fclose($handle);
return true;
} | [
"public",
"function",
"save",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"libs",
")",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"$",
"handle",
"=",
"fopen",
"(",
"$",
"path",
",",
"'w'",
")",
";",
"if",
"... | Save imported packages path to file in PHP format
@param string $path File to save packages paths, eg. `/foo/namespaces.php`
@return bool | [
"Save",
"imported",
"packages",
"path",
"to",
"file",
"in",
"PHP",
"format"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Packages.php#L154-L183 | train |
inphinit/framework | src/Inphinit/Packages.php | Packages.version | public static function version($name)
{
$file = INPHINIT_ROOT . 'composer.lock';
$data = is_file($file) ? json_decode(file_get_contents($file)) : false;
if (empty($data->packages)) {
return false;
}
$version = false;
foreach ($data->packages as $package) {
if ($package->name === $name) {
$version = $package->version;
break;
}
}
$data = null;
return $version;
} | php | public static function version($name)
{
$file = INPHINIT_ROOT . 'composer.lock';
$data = is_file($file) ? json_decode(file_get_contents($file)) : false;
if (empty($data->packages)) {
return false;
}
$version = false;
foreach ($data->packages as $package) {
if ($package->name === $name) {
$version = $package->version;
break;
}
}
$data = null;
return $version;
} | [
"public",
"static",
"function",
"version",
"(",
"$",
"name",
")",
"{",
"$",
"file",
"=",
"INPHINIT_ROOT",
".",
"'composer.lock'",
";",
"$",
"data",
"=",
"is_file",
"(",
"$",
"file",
")",
"?",
"json_decode",
"(",
"file_get_contents",
"(",
"$",
"file",
")"... | Get package version from composer.lock file
@param string $name set package for detect version
@return bool|string | [
"Get",
"package",
"version",
"from",
"composer",
".",
"lock",
"file"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Packages.php#L225-L246 | train |
brick/std | src/ObjectArrayStorage.php | ObjectArrayStorage.get | public function get($object) : array
{
$values = $this->storage->get($object);
return ($values === null) ? [] : $values;
} | php | public function get($object) : array
{
$values = $this->storage->get($object);
return ($values === null) ? [] : $values;
} | [
"public",
"function",
"get",
"(",
"$",
"object",
")",
":",
"array",
"{",
"$",
"values",
"=",
"$",
"this",
"->",
"storage",
"->",
"get",
"(",
"$",
"object",
")",
";",
"return",
"(",
"$",
"values",
"===",
"null",
")",
"?",
"[",
"]",
":",
"$",
"va... | Returns the values associated to the given object.
If the object is not present in the storage, an empty array is returned.
@param object $object The object.
@return array The values associated with the object. | [
"Returns",
"the",
"values",
"associated",
"to",
"the",
"given",
"object",
"."
] | d19162fcefcce457eeaa27904c797f76f9f49007 | https://github.com/brick/std/blob/d19162fcefcce457eeaa27904c797f76f9f49007/src/ObjectArrayStorage.php#L48-L53 | train |
brick/std | src/ObjectArrayStorage.php | ObjectArrayStorage.add | public function add($object, $value) : void
{
$values = $this->get($object);
$values[] = $value;
$this->storage->set($object, $values);
} | php | public function add($object, $value) : void
{
$values = $this->get($object);
$values[] = $value;
$this->storage->set($object, $values);
} | [
"public",
"function",
"add",
"(",
"$",
"object",
",",
"$",
"value",
")",
":",
"void",
"{",
"$",
"values",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"object",
")",
";",
"$",
"values",
"[",
"]",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"storage"... | Adds data associated with the given object.
@param object $object The object.
@param mixed $value The value to add.
@return void | [
"Adds",
"data",
"associated",
"with",
"the",
"given",
"object",
"."
] | d19162fcefcce457eeaa27904c797f76f9f49007 | https://github.com/brick/std/blob/d19162fcefcce457eeaa27904c797f76f9f49007/src/ObjectArrayStorage.php#L63-L68 | train |
alchemy-fr/embed-bundle | src/Component/Media/Media.php | Media.getDimensions | private function getDimensions(\media_subdef $subdef)
{
$outWidth = $subdef->get_width();
$outHeight = $subdef->get_height() | $outWidth;
$thumbnail_height = $subdef->get_height() > 0 ? $subdef->get_height() : 120;
$thumbnail_width = $subdef->get_width() > 0 ? $subdef->get_width() : 120;
$subdefRatio = 0;
$thumbnailRatio = $thumbnail_width / $thumbnail_height;
if ($outWidth > 0 && $outHeight > 0) {
$subdefRatio = $outWidth / $outHeight;
}
if ($thumbnailRatio > $subdefRatio) {
if ($outWidth > $thumbnail_width) {
$outWidth = $thumbnail_width;
}
$outHeight = $outWidth / $thumbnail_width * $thumbnail_height;
$top = ($outHeight - $outHeight) / 2;
} else {
if ($outHeight > $thumbnail_height) {
$outHeight = $thumbnail_height;
}
$outWidth = $outHeight * $thumbnail_width / $thumbnail_height;
$top = (($outHeight - $outHeight) / 2);
}
return [
'width' => round($outWidth),
'height' => round($outHeight),
'top' => $top
];
} | php | private function getDimensions(\media_subdef $subdef)
{
$outWidth = $subdef->get_width();
$outHeight = $subdef->get_height() | $outWidth;
$thumbnail_height = $subdef->get_height() > 0 ? $subdef->get_height() : 120;
$thumbnail_width = $subdef->get_width() > 0 ? $subdef->get_width() : 120;
$subdefRatio = 0;
$thumbnailRatio = $thumbnail_width / $thumbnail_height;
if ($outWidth > 0 && $outHeight > 0) {
$subdefRatio = $outWidth / $outHeight;
}
if ($thumbnailRatio > $subdefRatio) {
if ($outWidth > $thumbnail_width) {
$outWidth = $thumbnail_width;
}
$outHeight = $outWidth / $thumbnail_width * $thumbnail_height;
$top = ($outHeight - $outHeight) / 2;
} else {
if ($outHeight > $thumbnail_height) {
$outHeight = $thumbnail_height;
}
$outWidth = $outHeight * $thumbnail_width / $thumbnail_height;
$top = (($outHeight - $outHeight) / 2);
}
return [
'width' => round($outWidth),
'height' => round($outHeight),
'top' => $top
];
} | [
"private",
"function",
"getDimensions",
"(",
"\\",
"media_subdef",
"$",
"subdef",
")",
"{",
"$",
"outWidth",
"=",
"$",
"subdef",
"->",
"get_width",
"(",
")",
";",
"$",
"outHeight",
"=",
"$",
"subdef",
"->",
"get_height",
"(",
")",
"|",
"$",
"outWidth",
... | Php raw implementation of thumbnails.html.twig macro
@param \media_subdef $subdef
@return array | [
"Php",
"raw",
"implementation",
"of",
"thumbnails",
".",
"html",
".",
"twig",
"macro"
] | fc3df52f0258afadf885120166442165c6845a97 | https://github.com/alchemy-fr/embed-bundle/blob/fc3df52f0258afadf885120166442165c6845a97/src/Component/Media/Media.php#L157-L190 | train |
alchemy-fr/embed-bundle | src/Component/Media/Media.php | Media.getVideoTextTrackContent | public function getVideoTextTrackContent(MediaInformation $media, $id)
{
$id = (int)$id;
$record = $media->getResource()->get_record();
$videoTextTrack = false;
if ($record->getType() === 'video') {
$databox = $record->getDatabox();
$vttIds = [];
// list available vtt ids
foreach ($databox->get_meta_structure() as $meta) {
if (preg_match('/^VideoTextTrack(.*)$/iu', $meta->get_name(), $foundParts)) {
$vttIds[] = $meta->get_id();
}
}
// extract vtt content from ids
foreach ($record->get_caption()->get_fields(null, true) as $field) {
// if a category is matching, ensure it's vtt related
if (!in_array($id, $vttIds) || $id !== $field->get_meta_struct_id()) {
continue;
}
foreach ($field->get_values() as $value) {
// get vtt raw content
$videoTextTrack = $value->getValue();
}
}
}
return $videoTextTrack;
} | php | public function getVideoTextTrackContent(MediaInformation $media, $id)
{
$id = (int)$id;
$record = $media->getResource()->get_record();
$videoTextTrack = false;
if ($record->getType() === 'video') {
$databox = $record->getDatabox();
$vttIds = [];
// list available vtt ids
foreach ($databox->get_meta_structure() as $meta) {
if (preg_match('/^VideoTextTrack(.*)$/iu', $meta->get_name(), $foundParts)) {
$vttIds[] = $meta->get_id();
}
}
// extract vtt content from ids
foreach ($record->get_caption()->get_fields(null, true) as $field) {
// if a category is matching, ensure it's vtt related
if (!in_array($id, $vttIds) || $id !== $field->get_meta_struct_id()) {
continue;
}
foreach ($field->get_values() as $value) {
// get vtt raw content
$videoTextTrack = $value->getValue();
}
}
}
return $videoTextTrack;
} | [
"public",
"function",
"getVideoTextTrackContent",
"(",
"MediaInformation",
"$",
"media",
",",
"$",
"id",
")",
"{",
"$",
"id",
"=",
"(",
"int",
")",
"$",
"id",
";",
"$",
"record",
"=",
"$",
"media",
"->",
"getResource",
"(",
")",
"->",
"get_record",
"("... | Fetch vtt files content if exists
@param MediaInformation $media
@return bool|string Video Text Track content | [
"Fetch",
"vtt",
"files",
"content",
"if",
"exists"
] | fc3df52f0258afadf885120166442165c6845a97 | https://github.com/alchemy-fr/embed-bundle/blob/fc3df52f0258afadf885120166442165c6845a97/src/Component/Media/Media.php#L204-L236 | train |
inphinit/framework | src/Experimental/Maintenance.php | Maintenance.ignoreif | public static function ignoreif($callback)
{
if (is_callable($callback) === false) {
throw new Exception('Invalid callback');
}
App::on('init', function () use ($callback) {
if ($callback()) {
App::env('maintenance', false);
}
});
} | php | public static function ignoreif($callback)
{
if (is_callable($callback) === false) {
throw new Exception('Invalid callback');
}
App::on('init', function () use ($callback) {
if ($callback()) {
App::env('maintenance', false);
}
});
} | [
"public",
"static",
"function",
"ignoreif",
"(",
"$",
"callback",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"callback",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Invalid callback'",
")",
";",
"}",
"App",
"::",
"on",
"(",
"'... | Up the site only in certain conditions, eg. the site administrator of the IP.
@param callable $callback
@return void | [
"Up",
"the",
"site",
"only",
"in",
"certain",
"conditions",
"eg",
".",
"the",
"site",
"administrator",
"of",
"the",
"IP",
"."
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Maintenance.php#L70-L81 | train |
p3ym4n/jdate | src/JDate.php | JDate.createFromFormat | public static function createFromFormat($format, $date, $tz = null) {
if ($tz !== null) {
$tz = static::safeCreateDateTimeZone($tz);
}
$instance = new static($tz);
$instance->parseFormat($format, $date);
return $instance;
} | php | public static function createFromFormat($format, $date, $tz = null) {
if ($tz !== null) {
$tz = static::safeCreateDateTimeZone($tz);
}
$instance = new static($tz);
$instance->parseFormat($format, $date);
return $instance;
} | [
"public",
"static",
"function",
"createFromFormat",
"(",
"$",
"format",
",",
"$",
"date",
",",
"$",
"tz",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"tz",
"!==",
"null",
")",
"{",
"$",
"tz",
"=",
"static",
"::",
"safeCreateDateTimeZone",
"(",
"$",
"tz",
... | Create a JDate instance from a specific format
@param string $format
@param string $date
@param DateTimeZone|string|null $tz
@return static | [
"Create",
"a",
"JDate",
"instance",
"from",
"a",
"specific",
"format"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L359-L370 | train |
p3ym4n/jdate | src/JDate.php | JDate.calculateYearInQuadCycle | private static function calculateYearInQuadCycle($year) {
$yearInGrandCycle = static::calculateYearInGrandCycle($year);
// static::FIRST_QUAD_CYCLE;
$yearInQuadCycle = $yearInGrandCycle % static::FIRST_QUAD_CYCLE;
if ((static::GRAND_CYCLE_LENGTH - static::SECOND_QUAD_CYCLE) < $yearInGrandCycle) {
// static::SECOND_QUAD_CYCLE;
$yearInQuadCycle = $yearInGrandCycle - (21 * static::FIRST_QUAD_CYCLE);
}
return $yearInQuadCycle;
} | php | private static function calculateYearInQuadCycle($year) {
$yearInGrandCycle = static::calculateYearInGrandCycle($year);
// static::FIRST_QUAD_CYCLE;
$yearInQuadCycle = $yearInGrandCycle % static::FIRST_QUAD_CYCLE;
if ((static::GRAND_CYCLE_LENGTH - static::SECOND_QUAD_CYCLE) < $yearInGrandCycle) {
// static::SECOND_QUAD_CYCLE;
$yearInQuadCycle = $yearInGrandCycle - (21 * static::FIRST_QUAD_CYCLE);
}
return $yearInQuadCycle;
} | [
"private",
"static",
"function",
"calculateYearInQuadCycle",
"(",
"$",
"year",
")",
"{",
"$",
"yearInGrandCycle",
"=",
"static",
"::",
"calculateYearInGrandCycle",
"(",
"$",
"year",
")",
";",
"// static::FIRST_QUAD_CYCLE;",
"$",
"yearInQuadCycle",
"=",
"$",
"yearInG... | check the quad cycle type & count
@param int $year the year in jalali calendar
@return int|number year in quad cycle | [
"check",
"the",
"quad",
"cycle",
"type",
"&",
"count"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L492-L507 | train |
p3ym4n/jdate | src/JDate.php | JDate.calculateYearInGrandCycle | private static function calculateYearInGrandCycle($year) {
$grandCycle = static::calculateGrandCycle($year);
if ($grandCycle < 0) {
$year = (static::GRAND_CYCLE_BEGINNING + ($grandCycle * static::GRAND_CYCLE_LENGTH)) - $year;
} elseif ($grandCycle > 0) {
$year = $year - (static::GRAND_CYCLE_BEGINNING + ($grandCycle * static::GRAND_CYCLE_LENGTH));
} else {
$year -= static::GRAND_CYCLE_BEGINNING;
}
$yearInGrandCycle = abs($year) + 1;
return $yearInGrandCycle;
} | php | private static function calculateYearInGrandCycle($year) {
$grandCycle = static::calculateGrandCycle($year);
if ($grandCycle < 0) {
$year = (static::GRAND_CYCLE_BEGINNING + ($grandCycle * static::GRAND_CYCLE_LENGTH)) - $year;
} elseif ($grandCycle > 0) {
$year = $year - (static::GRAND_CYCLE_BEGINNING + ($grandCycle * static::GRAND_CYCLE_LENGTH));
} else {
$year -= static::GRAND_CYCLE_BEGINNING;
}
$yearInGrandCycle = abs($year) + 1;
return $yearInGrandCycle;
} | [
"private",
"static",
"function",
"calculateYearInGrandCycle",
"(",
"$",
"year",
")",
"{",
"$",
"grandCycle",
"=",
"static",
"::",
"calculateGrandCycle",
"(",
"$",
"year",
")",
";",
"if",
"(",
"$",
"grandCycle",
"<",
"0",
")",
"{",
"$",
"year",
"=",
"(",
... | returns the number of year in current grand cycle
@param int $year the year in jalali calendar
@return number | [
"returns",
"the",
"number",
"of",
"year",
"in",
"current",
"grand",
"cycle"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L516-L536 | train |
p3ym4n/jdate | src/JDate.php | JDate.calculateGrandCycle | private static function calculateGrandCycle($year) {
$endOfFirstGrandCycle = static::GRAND_CYCLE_BEGINNING + static::GRAND_CYCLE_LENGTH;
// by default we are in the first grand cycle
$grandCycle = 0;
if ($year < static::GRAND_CYCLE_BEGINNING) {
$beginningYear = static::GRAND_CYCLE_BEGINNING;
while ($year < $beginningYear) {
$beginningYear -= static::GRAND_CYCLE_LENGTH;
$grandCycle--;
}
} elseif ($year >= $endOfFirstGrandCycle) {
$beginningYear = $endOfFirstGrandCycle;
while ($year >= $beginningYear) {
$beginningYear += static::GRAND_CYCLE_LENGTH;
$grandCycle++;
}
}
return $grandCycle;
} | php | private static function calculateGrandCycle($year) {
$endOfFirstGrandCycle = static::GRAND_CYCLE_BEGINNING + static::GRAND_CYCLE_LENGTH;
// by default we are in the first grand cycle
$grandCycle = 0;
if ($year < static::GRAND_CYCLE_BEGINNING) {
$beginningYear = static::GRAND_CYCLE_BEGINNING;
while ($year < $beginningYear) {
$beginningYear -= static::GRAND_CYCLE_LENGTH;
$grandCycle--;
}
} elseif ($year >= $endOfFirstGrandCycle) {
$beginningYear = $endOfFirstGrandCycle;
while ($year >= $beginningYear) {
$beginningYear += static::GRAND_CYCLE_LENGTH;
$grandCycle++;
}
}
return $grandCycle;
} | [
"private",
"static",
"function",
"calculateGrandCycle",
"(",
"$",
"year",
")",
"{",
"$",
"endOfFirstGrandCycle",
"=",
"static",
"::",
"GRAND_CYCLE_BEGINNING",
"+",
"static",
"::",
"GRAND_CYCLE_LENGTH",
";",
"// by default we are in the first grand cycle",
"$",
"grandCycle... | calculate that which grand cycle we are in
@param int $year the year in jalali calendar
@return int | [
"calculate",
"that",
"which",
"grand",
"cycle",
"we",
"are",
"in"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L545-L569 | train |
p3ym4n/jdate | src/JDate.php | JDate.setYear | private function setYear($year) {
//preventing duplication process
if ($year == $this->year) {
return;
}
$this->year = (int) $year;
$maximumDayAvailable = static::getMonthLength($this->year, $this->month);
if ($this->day > $maximumDayAvailable) {
$this->day = $maximumDayAvailable;
}
} | php | private function setYear($year) {
//preventing duplication process
if ($year == $this->year) {
return;
}
$this->year = (int) $year;
$maximumDayAvailable = static::getMonthLength($this->year, $this->month);
if ($this->day > $maximumDayAvailable) {
$this->day = $maximumDayAvailable;
}
} | [
"private",
"function",
"setYear",
"(",
"$",
"year",
")",
"{",
"//preventing duplication process",
"if",
"(",
"$",
"year",
"==",
"$",
"this",
"->",
"year",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"year",
"=",
"(",
"int",
")",
"$",
"year",
";"... | Update year in jalali date
@param int $year | [
"Update",
"year",
"in",
"jalali",
"date"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L1086-L1097 | train |
p3ym4n/jdate | src/JDate.php | JDate.setMonth | private function setMonth($month) {
//preventing duplication process
if ($month == $this->month) {
return;
}
$yearToSet = $this->year;
$monthToSet = $month;
if ($monthToSet < 1) {
$monthToSet = abs($monthToSet);
$yearToSet--;
$yearToSet -= floor($monthToSet / 12);
$monthToSet = 12 - ($monthToSet % 12);
} elseif ($monthToSet > 12) {
$yearToSet += floor($monthToSet / 12);
$monthToSet = ($month % 12);
if ($monthToSet == 0) {
$monthToSet = 12;
$yearToSet--;
}
}
$this->month = (int) $monthToSet;
$this->setYear($yearToSet);
} | php | private function setMonth($month) {
//preventing duplication process
if ($month == $this->month) {
return;
}
$yearToSet = $this->year;
$monthToSet = $month;
if ($monthToSet < 1) {
$monthToSet = abs($monthToSet);
$yearToSet--;
$yearToSet -= floor($monthToSet / 12);
$monthToSet = 12 - ($monthToSet % 12);
} elseif ($monthToSet > 12) {
$yearToSet += floor($monthToSet / 12);
$monthToSet = ($month % 12);
if ($monthToSet == 0) {
$monthToSet = 12;
$yearToSet--;
}
}
$this->month = (int) $monthToSet;
$this->setYear($yearToSet);
} | [
"private",
"function",
"setMonth",
"(",
"$",
"month",
")",
"{",
"//preventing duplication process",
"if",
"(",
"$",
"month",
"==",
"$",
"this",
"->",
"month",
")",
"{",
"return",
";",
"}",
"$",
"yearToSet",
"=",
"$",
"this",
"->",
"year",
";",
"$",
"mo... | Update month in jalali date
@param int $month | [
"Update",
"month",
"in",
"jalali",
"date"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L1104-L1131 | train |
p3ym4n/jdate | src/JDate.php | JDate.setDay | private function setDay($day) {
//preventing duplication process
if ($day == $this->day) {
return;
}
$maximumDayOfMonth = static::getMonthLength($this->month, $this->year);
$dayToSet = $day;
if ($dayToSet < 1) {
$dayToSet = abs($dayToSet);
while ($dayToSet > $maximumDayOfMonth) {
$dayToSet -= $maximumDayOfMonth;
$month = $this->month - 1;
$this->setMonth($month);
$maximumDayOfMonth = static::getMonthLength($this->month, $this->year);
}
$dayToSet = $maximumDayOfMonth - $dayToSet;
$month = $this->month - 1;
$this->setMonth($month);
} elseif ($dayToSet > $maximumDayOfMonth) {
while ($dayToSet > $maximumDayOfMonth) {
$dayToSet -= $maximumDayOfMonth;
$month = $this->month + 1;
$this->setMonth($month);
$maximumDayOfMonth = static::getMonthLength($this->month, $this->year);
}
}
$this->day = (int) $dayToSet;
} | php | private function setDay($day) {
//preventing duplication process
if ($day == $this->day) {
return;
}
$maximumDayOfMonth = static::getMonthLength($this->month, $this->year);
$dayToSet = $day;
if ($dayToSet < 1) {
$dayToSet = abs($dayToSet);
while ($dayToSet > $maximumDayOfMonth) {
$dayToSet -= $maximumDayOfMonth;
$month = $this->month - 1;
$this->setMonth($month);
$maximumDayOfMonth = static::getMonthLength($this->month, $this->year);
}
$dayToSet = $maximumDayOfMonth - $dayToSet;
$month = $this->month - 1;
$this->setMonth($month);
} elseif ($dayToSet > $maximumDayOfMonth) {
while ($dayToSet > $maximumDayOfMonth) {
$dayToSet -= $maximumDayOfMonth;
$month = $this->month + 1;
$this->setMonth($month);
$maximumDayOfMonth = static::getMonthLength($this->month, $this->year);
}
}
$this->day = (int) $dayToSet;
} | [
"private",
"function",
"setDay",
"(",
"$",
"day",
")",
"{",
"//preventing duplication process",
"if",
"(",
"$",
"day",
"==",
"$",
"this",
"->",
"day",
")",
"{",
"return",
";",
"}",
"$",
"maximumDayOfMonth",
"=",
"static",
"::",
"getMonthLength",
"(",
"$",
... | Update day in jalali date
@param int $day | [
"Update",
"day",
"in",
"jalali",
"date"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L1138-L1171 | train |
p3ym4n/jdate | src/JDate.php | JDate.year | public function year($value) {
$this->setDate($value, $this->month, $this->day);
return $this;
} | php | public function year($value) {
$this->setDate($value, $this->month, $this->day);
return $this;
} | [
"public",
"function",
"year",
"(",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"setDate",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"month",
",",
"$",
"this",
"->",
"day",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Set the instance's year
@param int $value
@return static | [
"Set",
"the",
"instance",
"s",
"year"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L1180-L1185 | train |
p3ym4n/jdate | src/JDate.php | JDate.setDate | public function setDate($year, $month, $day) {
$this->setYear((int) $year);
$this->setMonth((int) $month);
$this->setDay((int) $day);
$this->updateGeorgianFromJalali();
return $this;
} | php | public function setDate($year, $month, $day) {
$this->setYear((int) $year);
$this->setMonth((int) $month);
$this->setDay((int) $day);
$this->updateGeorgianFromJalali();
return $this;
} | [
"public",
"function",
"setDate",
"(",
"$",
"year",
",",
"$",
"month",
",",
"$",
"day",
")",
"{",
"$",
"this",
"->",
"setYear",
"(",
"(",
"int",
")",
"$",
"year",
")",
";",
"$",
"this",
"->",
"setMonth",
"(",
"(",
"int",
")",
"$",
"month",
")",
... | Sets the current date of the DateTime object to a different date.
@param int $year
@param int $month
@param int $day
@return $this | [
"Sets",
"the",
"current",
"date",
"of",
"the",
"DateTime",
"object",
"to",
"a",
"different",
"date",
"."
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L1266-L1275 | train |
p3ym4n/jdate | src/JDate.php | JDate.setTime | public function setTime($hour, $minute, $second = 0) {
$this->carbon->setTime($hour, $minute, $second);
return $this;
} | php | public function setTime($hour, $minute, $second = 0) {
$this->carbon->setTime($hour, $minute, $second);
return $this;
} | [
"public",
"function",
"setTime",
"(",
"$",
"hour",
",",
"$",
"minute",
",",
"$",
"second",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"carbon",
"->",
"setTime",
"(",
"$",
"hour",
",",
"$",
"minute",
",",
"$",
"second",
")",
";",
"return",
"$",
"this"... | Sets the current time of the DateTime object to a different time.
@param int $hour
@param int $minute
@param int $second
@return $this | [
"Sets",
"the",
"current",
"time",
"of",
"the",
"DateTime",
"object",
"to",
"a",
"different",
"time",
"."
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L1286-L1291 | train |
p3ym4n/jdate | src/JDate.php | JDate.updateJalaliFromGeorgian | private function updateJalaliFromGeorgian($force = false) {
if ($this->converted && ! $force) {
return;
}
list($year, $month, $day) = self::julian2jalali(self::georgian2julian($this->carbon->year, $this->carbon->month, $this->carbon->day));
$this->year = $year;
$this->month = $month;
$this->day = $day;
// it tells that the jalali core is updated
$this->converted = true;
} | php | private function updateJalaliFromGeorgian($force = false) {
if ($this->converted && ! $force) {
return;
}
list($year, $month, $day) = self::julian2jalali(self::georgian2julian($this->carbon->year, $this->carbon->month, $this->carbon->day));
$this->year = $year;
$this->month = $month;
$this->day = $day;
// it tells that the jalali core is updated
$this->converted = true;
} | [
"private",
"function",
"updateJalaliFromGeorgian",
"(",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"converted",
"&&",
"!",
"$",
"force",
")",
"{",
"return",
";",
"}",
"list",
"(",
"$",
"year",
",",
"$",
"month",
",",
"$",
"... | Update the Jalali Core from the Carbon As Georgian Core
@param bool $force
@return int | [
"Update",
"the",
"Jalali",
"Core",
"from",
"the",
"Carbon",
"As",
"Georgian",
"Core"
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L2109-L2124 | train |
p3ym4n/jdate | src/JDate.php | JDate.jalali2julian | protected static function jalali2julian($year, $month, $day) {
$parsed = self::parseJalali($year);
return self::georgian2julian($parsed['gYear'], 3, $parsed['march']) + ($month - 1) * 31 - self::division($month, 7) * ($month - 7) + $day - 1;
} | php | protected static function jalali2julian($year, $month, $day) {
$parsed = self::parseJalali($year);
return self::georgian2julian($parsed['gYear'], 3, $parsed['march']) + ($month - 1) * 31 - self::division($month, 7) * ($month - 7) + $day - 1;
} | [
"protected",
"static",
"function",
"jalali2julian",
"(",
"$",
"year",
",",
"$",
"month",
",",
"$",
"day",
")",
"{",
"$",
"parsed",
"=",
"self",
"::",
"parseJalali",
"(",
"$",
"year",
")",
";",
"return",
"self",
"::",
"georgian2julian",
"(",
"$",
"parse... | Converts a date of the Jalali calendar to the Julian Day number.
@param int $year Jalali year (1 to 3100)
@param int $month Jalali month (1 to 12)
@param int $day Jalali day (1 to 29/31)
@return int Julian Day number | [
"Converts",
"a",
"date",
"of",
"the",
"Jalali",
"calendar",
"to",
"the",
"Julian",
"Day",
"number",
"."
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L2298-L2303 | train |
p3ym4n/jdate | src/JDate.php | JDate.julian2jalali | protected static function julian2jalali($julianDayNumber) {
$gYear = self::julian2georgian($julianDayNumber)[0];
$year = $gYear - static::HEGIRA_STARTING_YEAR;
$parsed = self::parseJalali($year);
$jdn1f = self::georgian2julian($gYear, 3, $parsed['march']);
// Find number of days that passed since 1 Farvardin.
$passed = $julianDayNumber - $jdn1f;
if ($passed >= 0) {
if ($passed <= 185) {
$month = 1 + self::division($passed, 31);
$day = ($passed % 31) + 1;
return [$year, $month, $day];
} else {
$passed -= 186;
}
} else {
$year -= 1;
$passed += 179;
if ($parsed['leap'] === 1) {
$passed += 1;
}
}
$month = 7 + self::division($passed, 30);
$day = ($passed % 30) + 1;
return [$year, $month, $day];
} | php | protected static function julian2jalali($julianDayNumber) {
$gYear = self::julian2georgian($julianDayNumber)[0];
$year = $gYear - static::HEGIRA_STARTING_YEAR;
$parsed = self::parseJalali($year);
$jdn1f = self::georgian2julian($gYear, 3, $parsed['march']);
// Find number of days that passed since 1 Farvardin.
$passed = $julianDayNumber - $jdn1f;
if ($passed >= 0) {
if ($passed <= 185) {
$month = 1 + self::division($passed, 31);
$day = ($passed % 31) + 1;
return [$year, $month, $day];
} else {
$passed -= 186;
}
} else {
$year -= 1;
$passed += 179;
if ($parsed['leap'] === 1) {
$passed += 1;
}
}
$month = 7 + self::division($passed, 30);
$day = ($passed % 30) + 1;
return [$year, $month, $day];
} | [
"protected",
"static",
"function",
"julian2jalali",
"(",
"$",
"julianDayNumber",
")",
"{",
"$",
"gYear",
"=",
"self",
"::",
"julian2georgian",
"(",
"$",
"julianDayNumber",
")",
"[",
"0",
"]",
";",
"$",
"year",
"=",
"$",
"gYear",
"-",
"static",
"::",
"HEG... | Converts the Julian Day number to a date in the Jalali calendar.
@param int $julianDayNumber Julian Day number
@return array
0: Jalali year (1 to 3100)
1: Jalali month (1 to 12)
2: Jalali day (1 to 29/31) | [
"Converts",
"the",
"Julian",
"Day",
"number",
"to",
"a",
"date",
"in",
"the",
"Jalali",
"calendar",
"."
] | e5f1e03bba1fe7818601af9f90ef2bff8dc08830 | https://github.com/p3ym4n/jdate/blob/e5f1e03bba1fe7818601af9f90ef2bff8dc08830/src/JDate.php#L2315-L2347 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.fromArray | public function fromArray(array $data)
{
if (empty($data)) {
throw new DomException('Array is empty', 2);
} elseif (count($data) > 1) {
throw new DomException('Root array accepts only a key', 2);
} elseif (Helper::seq($data)) {
throw new DomException('Document accpet only a node', 2);
}
if ($this->documentElement) {
$this->removeChild($this->documentElement);
}
$this->enableRestoreInternal(true);
$this->generate($this, $data);
$this->raise($this->exceptionlevel);
$this->enableRestoreInternal(false);
} | php | public function fromArray(array $data)
{
if (empty($data)) {
throw new DomException('Array is empty', 2);
} elseif (count($data) > 1) {
throw new DomException('Root array accepts only a key', 2);
} elseif (Helper::seq($data)) {
throw new DomException('Document accpet only a node', 2);
}
if ($this->documentElement) {
$this->removeChild($this->documentElement);
}
$this->enableRestoreInternal(true);
$this->generate($this, $data);
$this->raise($this->exceptionlevel);
$this->enableRestoreInternal(false);
} | [
"public",
"function",
"fromArray",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"DomException",
"(",
"'Array is empty'",
",",
"2",
")",
";",
"}",
"elseif",
"(",
"count",
"(",
"$",
"data",
... | Convert a array in node elements
@param array|\Traversable $data
@throws \Inphinit\Experimental\Exception
@return void | [
"Convert",
"a",
"array",
"in",
"node",
"elements"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L89-L110 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.toJson | public function toJson($format = Document::MININAL, $options = 0)
{
$this->exceptionlevel = 4;
$json = json_encode($this->toArray($format), $options);
$this->exceptionlevel = 3;
return $json;
} | php | public function toJson($format = Document::MININAL, $options = 0)
{
$this->exceptionlevel = 4;
$json = json_encode($this->toArray($format), $options);
$this->exceptionlevel = 3;
return $json;
} | [
"public",
"function",
"toJson",
"(",
"$",
"format",
"=",
"Document",
"::",
"MININAL",
",",
"$",
"options",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"exceptionlevel",
"=",
"4",
";",
"$",
"json",
"=",
"json_encode",
"(",
"$",
"this",
"->",
"toArray",
"("... | Convert DOM to JSON string
@param bool $format
@param int $options `JSON_HEX_QUOT`, `JSON_HEX_TAG`, `JSON_HEX_AMP`, `JSON_HEX_APOS`, `JSON_NUMERIC_CHECK`, `JSON_PRETTY_PRINT`, `JSON_UNESCAPED_SLASHES`, `JSON_FORCE_OBJECT`, `JSON_PRESERVE_ZERO_FRACTION`, `JSON_UNESCAPED_UNICODE`, `JSON_PARTIAL_OUTPUT_ON_ERROR`. The behaviour of these constants is described in http://php.net/manual/en/json.constants.php
@return string | [
"Convert",
"DOM",
"to",
"JSON",
"string"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L120-L129 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.toArray | public function toArray($type = Document::SIMPLE)
{
switch ($type) {
case Document::MININAL:
$this->simple = false;
$this->complete = false;
break;
case Document::SIMPLE:
$this->simple = true;
break;
case Document::COMPLETE:
$this->complete = true;
break;
default:
throw new DomException('Invalid type', 2);
}
return $this->getNodes($this->childNodes, true);
} | php | public function toArray($type = Document::SIMPLE)
{
switch ($type) {
case Document::MININAL:
$this->simple = false;
$this->complete = false;
break;
case Document::SIMPLE:
$this->simple = true;
break;
case Document::COMPLETE:
$this->complete = true;
break;
default:
throw new DomException('Invalid type', 2);
}
return $this->getNodes($this->childNodes, true);
} | [
"public",
"function",
"toArray",
"(",
"$",
"type",
"=",
"Document",
"::",
"SIMPLE",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"Document",
"::",
"MININAL",
":",
"$",
"this",
"->",
"simple",
"=",
"false",
";",
"$",
"this",
"->",
"complete... | Convert DOM to Array
@param int $type
@throws \Inphinit\Experimental\Exception
@return array | [
"Convert",
"DOM",
"to",
"Array"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L138-L159 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.save | public function save($path, $format = Document::XML)
{
switch ($format) {
case Document::XML:
$format = 'saveXML';
break;
case Document::HTML:
$format = 'saveHTML';
break;
case Document::JSON:
$format = 'toJson';
break;
default:
throw new DomException('Invalid format', 2);
}
$tmp = Storage::temp($this->$format(), 'tmp', '~xml-');
if ($tmp === false) {
throw new DomException('Can\'t create tmp file', 2);
} elseif (copy($tmp, $path) === false) {
throw new DomException('Can\'t copy tmp file to ' . $path, 2);
} else {
unlink($tmp);
}
} | php | public function save($path, $format = Document::XML)
{
switch ($format) {
case Document::XML:
$format = 'saveXML';
break;
case Document::HTML:
$format = 'saveHTML';
break;
case Document::JSON:
$format = 'toJson';
break;
default:
throw new DomException('Invalid format', 2);
}
$tmp = Storage::temp($this->$format(), 'tmp', '~xml-');
if ($tmp === false) {
throw new DomException('Can\'t create tmp file', 2);
} elseif (copy($tmp, $path) === false) {
throw new DomException('Can\'t copy tmp file to ' . $path, 2);
} else {
unlink($tmp);
}
} | [
"public",
"function",
"save",
"(",
"$",
"path",
",",
"$",
"format",
"=",
"Document",
"::",
"XML",
")",
"{",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"Document",
"::",
"XML",
":",
"$",
"format",
"=",
"'saveXML'",
";",
"break",
";",
"case",
"D... | Save file to location
@param string $path
@param int $format Support XML, HTML, and JSON
@throws \Inphinit\Experimental\Exception
@return void | [
"Save",
"file",
"to",
"location"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L192-L217 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.getNamespaces | public function getNamespaces(\DOMElement $element = null)
{
if ($this->xpath === null) {
$this->xpath = new \DOMXPath($this);
}
if ($element === null) {
$nodes = $this->xpath->query('namespace::*');
} else {
$nodes = $this->xpath->query('namespace::*', $element);
}
$ns = array();
if ($nodes) {
foreach ($nodes as $node) {
$arr = $element->getAttribute($node->nodeName);
if ($arr) {
$ns[$node->nodeName] = $arr;
}
}
$nodes = null;
}
return $ns;
} | php | public function getNamespaces(\DOMElement $element = null)
{
if ($this->xpath === null) {
$this->xpath = new \DOMXPath($this);
}
if ($element === null) {
$nodes = $this->xpath->query('namespace::*');
} else {
$nodes = $this->xpath->query('namespace::*', $element);
}
$ns = array();
if ($nodes) {
foreach ($nodes as $node) {
$arr = $element->getAttribute($node->nodeName);
if ($arr) {
$ns[$node->nodeName] = $arr;
}
}
$nodes = null;
}
return $ns;
} | [
"public",
"function",
"getNamespaces",
"(",
"\\",
"DOMElement",
"$",
"element",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"xpath",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"xpath",
"=",
"new",
"\\",
"DOMXPath",
"(",
"$",
"this",
")",
... | Get namespace attributes from root element or specific element
@param \DOMElement $element
@throws \Inphinit\Experimental\Exception
@return void | [
"Get",
"namespace",
"attributes",
"from",
"root",
"element",
"or",
"specific",
"element"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L226-L253 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.query | public function query($selector, \DOMNode $context = null)
{
$this->enableRestoreInternal(true);
if ($this->selector === null) {
$this->selector = new Selector($this);
}
$nodes = $this->selector->get($selector, $context);
$this->raise($this->exceptionlevel);
$this->enableRestoreInternal(false);
return $nodes;
} | php | public function query($selector, \DOMNode $context = null)
{
$this->enableRestoreInternal(true);
if ($this->selector === null) {
$this->selector = new Selector($this);
}
$nodes = $this->selector->get($selector, $context);
$this->raise($this->exceptionlevel);
$this->enableRestoreInternal(false);
return $nodes;
} | [
"public",
"function",
"query",
"(",
"$",
"selector",
",",
"\\",
"DOMNode",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"enableRestoreInternal",
"(",
"true",
")",
";",
"if",
"(",
"$",
"this",
"->",
"selector",
"===",
"null",
")",
"{",
"$... | Use query-selector like CSS, jQuery, querySelectorAll
@param string $selector
@param \DOMNode $context
@return \DOMNodeList | [
"Use",
"query",
"-",
"selector",
"like",
"CSS",
"jQuery",
"querySelectorAll"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L314-L329 | train |
inphinit/framework | src/Experimental/Dom/Document.php | Document.first | public function first($selector, \DOMNode $context = null)
{
$this->exceptionlevel = 4;
$nodes = $this->query($selector, $context);
$this->exceptionlevel = 3;
$node = $nodes->length ? $nodes->item(0) : null;
$nodes = null;
return $node;
} | php | public function first($selector, \DOMNode $context = null)
{
$this->exceptionlevel = 4;
$nodes = $this->query($selector, $context);
$this->exceptionlevel = 3;
$node = $nodes->length ? $nodes->item(0) : null;
$nodes = null;
return $node;
} | [
"public",
"function",
"first",
"(",
"$",
"selector",
",",
"\\",
"DOMNode",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"exceptionlevel",
"=",
"4",
";",
"$",
"nodes",
"=",
"$",
"this",
"->",
"query",
"(",
"$",
"selector",
",",
"$",
"co... | Use query-selector like CSS, jQuery, querySelector
@param string $selector
@param \DOMNode $context
@return \DOMNode | [
"Use",
"query",
"-",
"selector",
"like",
"CSS",
"jQuery",
"querySelector"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Dom/Document.php#L338-L351 | train |
archfizz/slotmachine | src/Slot.php | Slot.getCard | public function getCard($index = 0, $failOnNoCardFound = false)
{
if (!array_key_exists($index, $this->reel['cards'])) {
if ($failOnNoCardFound) {
throw new Exception\NoCardFoundException(sprintf(
"Cannot resolve a card value for the '%s' slot. (Perhaps you need to set a '_default' alias for the slot or the card of index 0 is missing from the slot's assigned reel?)",
$this->name
));
}
switch ($this->undefinedCardResolution) {
case UndefinedCardResolution::NO_CARD_FOUND_EXCEPTION:
default:
throw new Exception\NoCardFoundException(sprintf(
"Card of index %d was not found in the slot `%s`.", $index, $this->name
));
case UndefinedCardResolution::DEFAULT_CARD:
return $this->getDefaultCard();
case UndefinedCardResolution::FALLBACK_CARD:
return $this->getFallbackCard();
case UndefinedCardResolution::BLANK_CARD:
return '';
// End Switch
}
}
return $this->reel['cards'][$index];
} | php | public function getCard($index = 0, $failOnNoCardFound = false)
{
if (!array_key_exists($index, $this->reel['cards'])) {
if ($failOnNoCardFound) {
throw new Exception\NoCardFoundException(sprintf(
"Cannot resolve a card value for the '%s' slot. (Perhaps you need to set a '_default' alias for the slot or the card of index 0 is missing from the slot's assigned reel?)",
$this->name
));
}
switch ($this->undefinedCardResolution) {
case UndefinedCardResolution::NO_CARD_FOUND_EXCEPTION:
default:
throw new Exception\NoCardFoundException(sprintf(
"Card of index %d was not found in the slot `%s`.", $index, $this->name
));
case UndefinedCardResolution::DEFAULT_CARD:
return $this->getDefaultCard();
case UndefinedCardResolution::FALLBACK_CARD:
return $this->getFallbackCard();
case UndefinedCardResolution::BLANK_CARD:
return '';
// End Switch
}
}
return $this->reel['cards'][$index];
} | [
"public",
"function",
"getCard",
"(",
"$",
"index",
"=",
"0",
",",
"$",
"failOnNoCardFound",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"index",
",",
"$",
"this",
"->",
"reel",
"[",
"'cards'",
"]",
")",
")",
"{",
"if",
"(... | Get a value of a card by its index.
If the card does not exist, resolve based on the slot's resolve_undefined setting.
@param integer $index
@return mixed
@throws SlotMachine\Exception\NoCardFoundException if the key does not exist and
the undefinedCardResolution property is set to NO_CARD_FOUND_EXCEPTION. | [
"Get",
"a",
"value",
"of",
"a",
"card",
"by",
"its",
"index",
".",
"If",
"the",
"card",
"does",
"not",
"exist",
"resolve",
"based",
"on",
"the",
"slot",
"s",
"resolve_undefined",
"setting",
"."
] | 9707b9e60d16f4ac214964f5b1db973df623e9c5 | https://github.com/archfizz/slotmachine/blob/9707b9e60d16f4ac214964f5b1db973df623e9c5/src/Slot.php#L80-L109 | train |
archfizz/slotmachine | src/Slot.php | Slot.getCardByAlias | public function getCardByAlias($alias)
{
if (!array_key_exists($alias, $this->aliases)) {
throw new Exception\NoSuchAliasException(sprintf('Alias "%s" has not been assigned to any cards.', $alias));
}
return $this->getCard($this->aliases[$alias]);
} | php | public function getCardByAlias($alias)
{
if (!array_key_exists($alias, $this->aliases)) {
throw new Exception\NoSuchAliasException(sprintf('Alias "%s" has not been assigned to any cards.', $alias));
}
return $this->getCard($this->aliases[$alias]);
} | [
"public",
"function",
"getCardByAlias",
"(",
"$",
"alias",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"alias",
",",
"$",
"this",
"->",
"aliases",
")",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"NoSuchAliasException",
"(",
"sprintf",
"(",
... | Get a card from the reel by an alias.
@param string $alias
@return mixed | [
"Get",
"a",
"card",
"from",
"the",
"reel",
"by",
"an",
"alias",
"."
] | 9707b9e60d16f4ac214964f5b1db973df623e9c5 | https://github.com/archfizz/slotmachine/blob/9707b9e60d16f4ac214964f5b1db973df623e9c5/src/Slot.php#L117-L124 | train |
Modularr/YAML-FrontMatter | src/frontmatter.php | FrontMatter.FrontMatter | function FrontMatter($input)
{
if (!$this->startsWith($input, $this->yaml_separator)) {
# No front matter
# Store Content in Final array
$final['content'] = $input;
# Return Final array
return $final;
}
# Explode Seperators. At most, make three pieces out of the input file
$document = explode($this->yaml_separator,$input, 3);
switch( sizeof($document) ) {
case 0:
case 1:
// Empty document
$front_matter = "";
$content = "";
break;
case 2:
# Only front matter given
$front_matter = $document[1];
$content = "";
break;
default:
# Normal document
$front_matter = $document[1];
$content = $document[2];
}
# Parse YAML
try {
$final = Yaml::parse($front_matter);
} catch (ParseException $e) {
printf("Unable to parse the YAML string: %s", $e->getMessage());
}
# Store Content in Final array
$final['content'] = $content;
# Return Final array
return $final;
} | php | function FrontMatter($input)
{
if (!$this->startsWith($input, $this->yaml_separator)) {
# No front matter
# Store Content in Final array
$final['content'] = $input;
# Return Final array
return $final;
}
# Explode Seperators. At most, make three pieces out of the input file
$document = explode($this->yaml_separator,$input, 3);
switch( sizeof($document) ) {
case 0:
case 1:
// Empty document
$front_matter = "";
$content = "";
break;
case 2:
# Only front matter given
$front_matter = $document[1];
$content = "";
break;
default:
# Normal document
$front_matter = $document[1];
$content = $document[2];
}
# Parse YAML
try {
$final = Yaml::parse($front_matter);
} catch (ParseException $e) {
printf("Unable to parse the YAML string: %s", $e->getMessage());
}
# Store Content in Final array
$final['content'] = $content;
# Return Final array
return $final;
} | [
"function",
"FrontMatter",
"(",
"$",
"input",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"startsWith",
"(",
"$",
"input",
",",
"$",
"this",
"->",
"yaml_separator",
")",
")",
"{",
"# No front matter",
"# Store Content in Final array",
"$",
"final",
"[",
"... | FrontMatter method, rturns all the variables from a YAML Frontmatter input
@param string $input The input string
@return array $final returns all variables in an array | [
"FrontMatter",
"method",
"rturns",
"all",
"the",
"variables",
"from",
"a",
"YAML",
"Frontmatter",
"input"
] | e6e0400db5c9ef42989cddecec717c5b915bf30c | https://github.com/Modularr/YAML-FrontMatter/blob/e6e0400db5c9ef42989cddecec717c5b915bf30c/src/frontmatter.php#L71-L114 | train |
Modularr/YAML-FrontMatter | src/frontmatter.php | FrontMatter.Read | protected function Read($file)
{
# Open File
$fh = fopen($file, 'r');
$fileSize = filesize($file);
if(!empty($fileSize)) {
# Read Data
$data = fread($fh, $fileSize);
# Fix Data Stream to be the exact same format as PHP's strings
$data = str_replace(array("\r\n", "\r", "\n"), "\n", $data);
} else {
$data = '';
}
# Close File
fclose($fh);
# Return Data
return $data;
} | php | protected function Read($file)
{
# Open File
$fh = fopen($file, 'r');
$fileSize = filesize($file);
if(!empty($fileSize)) {
# Read Data
$data = fread($fh, $fileSize);
# Fix Data Stream to be the exact same format as PHP's strings
$data = str_replace(array("\r\n", "\r", "\n"), "\n", $data);
} else {
$data = '';
}
# Close File
fclose($fh);
# Return Data
return $data;
} | [
"protected",
"function",
"Read",
"(",
"$",
"file",
")",
"{",
"# Open File",
"$",
"fh",
"=",
"fopen",
"(",
"$",
"file",
",",
"'r'",
")",
";",
"$",
"fileSize",
"=",
"filesize",
"(",
"$",
"file",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"fileSiz... | Read Method, Read file and returns it's contents
@return string $data returned data | [
"Read",
"Method",
"Read",
"file",
"and",
"returns",
"it",
"s",
"contents"
] | e6e0400db5c9ef42989cddecec717c5b915bf30c | https://github.com/Modularr/YAML-FrontMatter/blob/e6e0400db5c9ef42989cddecec717c5b915bf30c/src/frontmatter.php#L132-L153 | train |
inphinit/framework | src/Inphinit/Helper.php | Helper.parseVersion | public static function parseVersion($version)
{
if (preg_match('#^(\d+)\.(\d+)\.(\d+)(\-([\w.\-]+)|)$#', $version, $match)) {
return (object) array(
'major' => $match[1],
'minor' => $match[2],
'patch' => $match[3],
'extra' => empty($match[5]) ? null : $match[5]
);
}
return false;
} | php | public static function parseVersion($version)
{
if (preg_match('#^(\d+)\.(\d+)\.(\d+)(\-([\w.\-]+)|)$#', $version, $match)) {
return (object) array(
'major' => $match[1],
'minor' => $match[2],
'patch' => $match[3],
'extra' => empty($match[5]) ? null : $match[5]
);
}
return false;
} | [
"public",
"static",
"function",
"parseVersion",
"(",
"$",
"version",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'#^(\\d+)\\.(\\d+)\\.(\\d+)(\\-([\\w.\\-]+)|)$#'",
",",
"$",
"version",
",",
"$",
"match",
")",
")",
"{",
"return",
"(",
"object",
")",
"array",
"(",
... | Parse version format
@param string $version
@return array|bool | [
"Parse",
"version",
"format"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Helper.php#L20-L32 | train |
inphinit/framework | src/Inphinit/Helper.php | Helper.toAscii | public static function toAscii($text)
{
$encode = mb_detect_encoding($text, mb_detect_order(), true);
return 'ASCII' === $encode ? $text : iconv($encode, 'ASCII//TRANSLIT//IGNORE', $text);
} | php | public static function toAscii($text)
{
$encode = mb_detect_encoding($text, mb_detect_order(), true);
return 'ASCII' === $encode ? $text : iconv($encode, 'ASCII//TRANSLIT//IGNORE', $text);
} | [
"public",
"static",
"function",
"toAscii",
"(",
"$",
"text",
")",
"{",
"$",
"encode",
"=",
"mb_detect_encoding",
"(",
"$",
"text",
",",
"mb_detect_order",
"(",
")",
",",
"true",
")",
";",
"return",
"'ASCII'",
"===",
"$",
"encode",
"?",
"$",
"text",
":"... | Convert string to ASCII
@param string $text
@return string | [
"Convert",
"string",
"to",
"ASCII"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Helper.php#L40-L44 | train |
inphinit/framework | src/Inphinit/Helper.php | Helper.capitalize | public static function capitalize($text, $delimiter = '-', $glue = '')
{
return implode($glue, array_map('ucfirst', explode($delimiter, strtolower($text))));
} | php | public static function capitalize($text, $delimiter = '-', $glue = '')
{
return implode($glue, array_map('ucfirst', explode($delimiter, strtolower($text))));
} | [
"public",
"static",
"function",
"capitalize",
"(",
"$",
"text",
",",
"$",
"delimiter",
"=",
"'-'",
",",
"$",
"glue",
"=",
"''",
")",
"{",
"return",
"implode",
"(",
"$",
"glue",
",",
"array_map",
"(",
"'ucfirst'",
",",
"explode",
"(",
"$",
"delimiter",
... | Capitalize words using hyphen or a custom delimiter.
@param string $text
@param string $delimiter
@param string $glue
@return string | [
"Capitalize",
"words",
"using",
"hyphen",
"or",
"a",
"custom",
"delimiter",
"."
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Helper.php#L54-L57 | train |
inphinit/framework | src/Inphinit/Helper.php | Helper.extract | public static function extract($path, $items)
{
$paths = explode('.', $path);
foreach ($paths as $value) {
if (self::iterable($items) && array_key_exists($value, $items)) {
$items = $items[$value];
} else {
return false;
}
}
return $items;
} | php | public static function extract($path, $items)
{
$paths = explode('.', $path);
foreach ($paths as $value) {
if (self::iterable($items) && array_key_exists($value, $items)) {
$items = $items[$value];
} else {
return false;
}
}
return $items;
} | [
"public",
"static",
"function",
"extract",
"(",
"$",
"path",
",",
"$",
"items",
")",
"{",
"$",
"paths",
"=",
"explode",
"(",
"'.'",
",",
"$",
"path",
")",
";",
"foreach",
"(",
"$",
"paths",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
... | Read array by path using dot
@param string $path
@param array|\Traversable $items
@return mixed | [
"Read",
"array",
"by",
"path",
"using",
"dot"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Helper.php#L66-L79 | train |
inphinit/framework | src/Inphinit/Storage.php | Storage.resolve | public static function resolve($path)
{
if (empty($path)) {
return false;
}
$path = Uri::canonpath($path);
if ($path . '/' === self::path() || strpos($path, self::path()) === 0) {
return $path;
}
return self::path() . $path;
} | php | public static function resolve($path)
{
if (empty($path)) {
return false;
}
$path = Uri::canonpath($path);
if ($path . '/' === self::path() || strpos($path, self::path()) === 0) {
return $path;
}
return self::path() . $path;
} | [
"public",
"static",
"function",
"resolve",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"path",
"=",
"Uri",
"::",
"canonpath",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"pa... | Convert path to storage path
@param string $path
@return bool|string | [
"Convert",
"path",
"to",
"storage",
"path"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Storage.php#L30-L43 | train |
inphinit/framework | src/Inphinit/Storage.php | Storage.autoclean | public static function autoclean($path, $time = -1)
{
$path = self::resolve($path);
if ($path !== false && is_dir($path) && ($dh = opendir($path))) {
if ($time < 0) {
$time = App::env('appdata_expires');
}
$expires = REQUEST_TIME - $time;
$path .= '/';
while (false !== ($file = readdir($dh))) {
$current = $path . $file;
if (is_file($current) && filemtime($current) < $expires) {
unlink($current);
}
}
closedir($dh);
$dh = null;
}
} | php | public static function autoclean($path, $time = -1)
{
$path = self::resolve($path);
if ($path !== false && is_dir($path) && ($dh = opendir($path))) {
if ($time < 0) {
$time = App::env('appdata_expires');
}
$expires = REQUEST_TIME - $time;
$path .= '/';
while (false !== ($file = readdir($dh))) {
$current = $path . $file;
if (is_file($current) && filemtime($current) < $expires) {
unlink($current);
}
}
closedir($dh);
$dh = null;
}
} | [
"public",
"static",
"function",
"autoclean",
"(",
"$",
"path",
",",
"$",
"time",
"=",
"-",
"1",
")",
"{",
"$",
"path",
"=",
"self",
"::",
"resolve",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"path",
"!==",
"false",
"&&",
"is_dir",
"(",
"$",
"... | Clear old files in a folder from storage path
@param string $path
@param int $time
@return void | [
"Clear",
"old",
"files",
"in",
"a",
"folder",
"from",
"storage",
"path"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Storage.php#L52-L76 | train |
inphinit/framework | src/Inphinit/Storage.php | Storage.put | public static function put($path, $data = null, $flags = null)
{
$path = self::resolve($path);
if ($path === false) {
return false;
}
$data = is_numeric($data) === false && !$data ? '' : $data;
if (is_file($path) && !$data) {
return true;
}
$flags = $flags ? $flags : FILE_APPEND|LOCK_EX;
return self::createFolder(dirname($path)) && file_put_contents($path, $data, $flags) !== false;
} | php | public static function put($path, $data = null, $flags = null)
{
$path = self::resolve($path);
if ($path === false) {
return false;
}
$data = is_numeric($data) === false && !$data ? '' : $data;
if (is_file($path) && !$data) {
return true;
}
$flags = $flags ? $flags : FILE_APPEND|LOCK_EX;
return self::createFolder(dirname($path)) && file_put_contents($path, $data, $flags) !== false;
} | [
"public",
"static",
"function",
"put",
"(",
"$",
"path",
",",
"$",
"data",
"=",
"null",
",",
"$",
"flags",
"=",
"null",
")",
"{",
"$",
"path",
"=",
"self",
"::",
"resolve",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"path",
"===",
"false",
")"... | Create a file in a folder in storage or append data to existing file
@param string $path
@param string $data
@param int $flags
@return bool | [
"Create",
"a",
"file",
"in",
"a",
"folder",
"in",
"storage",
"or",
"append",
"data",
"to",
"existing",
"file"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Storage.php#L125-L142 | train |
inphinit/framework | src/Inphinit/Storage.php | Storage.remove | public static function remove($path)
{
$path = self::resolve($path);
return $path && is_file($path) && unlink($path);
} | php | public static function remove($path)
{
$path = self::resolve($path);
return $path && is_file($path) && unlink($path);
} | [
"public",
"static",
"function",
"remove",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"self",
"::",
"resolve",
"(",
"$",
"path",
")",
";",
"return",
"$",
"path",
"&&",
"is_file",
"(",
"$",
"path",
")",
"&&",
"unlink",
"(",
"$",
"path",
")",
";"... | Delete a file in storage
@param string $path
@return bool | [
"Delete",
"a",
"file",
"in",
"storage"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Storage.php#L150-L155 | train |
inphinit/framework | src/Inphinit/Storage.php | Storage.removeFolder | public static function removeFolder($path)
{
$path = self::resolve($path);
return $path && is_dir($path) && self::rrmdir($path);
} | php | public static function removeFolder($path)
{
$path = self::resolve($path);
return $path && is_dir($path) && self::rrmdir($path);
} | [
"public",
"static",
"function",
"removeFolder",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"self",
"::",
"resolve",
"(",
"$",
"path",
")",
";",
"return",
"$",
"path",
"&&",
"is_dir",
"(",
"$",
"path",
")",
"&&",
"self",
"::",
"rrmdir",
"(",
"$",... | Remove recursive folders in storage folder
@param string $path
@return bool | [
"Remove",
"recursive",
"folders",
"in",
"storage",
"folder"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Storage.php#L176-L181 | train |
inphinit/framework | src/Inphinit/Storage.php | Storage.rrmdir | private static function rrmdir($path)
{
$path .= '/';
foreach (array_diff(scandir($path), array('..', '.')) as $file) {
$current = $path . $file;
if (is_dir($current)) {
if (self::rrmdir($current) === false) {
return false;
}
} elseif (unlink($current) === false) {
return false;
}
}
return rmdir($path);
} | php | private static function rrmdir($path)
{
$path .= '/';
foreach (array_diff(scandir($path), array('..', '.')) as $file) {
$current = $path . $file;
if (is_dir($current)) {
if (self::rrmdir($current) === false) {
return false;
}
} elseif (unlink($current) === false) {
return false;
}
}
return rmdir($path);
} | [
"private",
"static",
"function",
"rrmdir",
"(",
"$",
"path",
")",
"{",
"$",
"path",
".=",
"'/'",
";",
"foreach",
"(",
"array_diff",
"(",
"scandir",
"(",
"$",
"path",
")",
",",
"array",
"(",
"'..'",
",",
"'.'",
")",
")",
"as",
"$",
"file",
")",
"{... | Remove recursive folders
@param string $path
@return bool | [
"Remove",
"recursive",
"folders"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Inphinit/Storage.php#L189-L206 | train |
inphinit/framework | src/Experimental/Session.php | Session.commit | public function commit($unlock = true)
{
if (empty($this->insertions) && empty($this->deletions)) {
return null;
}
$this->lock();
$data = '';
rewind($this->handle);
$data = trim(stream_get_contents($this->handle));
if ($data !== '') {
$data = unserialize($data);
$this->data = $this->insertions + $data;
$data = null;
foreach ($this->deletions as $key => $value) {
unset($this->data[$key]);
}
} else {
$this->data = $this->insertions;
}
$this->insertions = array();
$this->deletions = array();
$this->write();
if ($unlock) {
flock($this->handle, LOCK_UN);
}
$this->iterator = new \ArrayIterator($this->data);
} | php | public function commit($unlock = true)
{
if (empty($this->insertions) && empty($this->deletions)) {
return null;
}
$this->lock();
$data = '';
rewind($this->handle);
$data = trim(stream_get_contents($this->handle));
if ($data !== '') {
$data = unserialize($data);
$this->data = $this->insertions + $data;
$data = null;
foreach ($this->deletions as $key => $value) {
unset($this->data[$key]);
}
} else {
$this->data = $this->insertions;
}
$this->insertions = array();
$this->deletions = array();
$this->write();
if ($unlock) {
flock($this->handle, LOCK_UN);
}
$this->iterator = new \ArrayIterator($this->data);
} | [
"public",
"function",
"commit",
"(",
"$",
"unlock",
"=",
"true",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"insertions",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"deletions",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
... | Lock session file and save variables
@param bool $unlock
@return void | [
"Lock",
"session",
"file",
"and",
"save",
"variables"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Session.php#L93-L131 | train |
inphinit/framework | src/Experimental/Session.php | Session.read | private function read()
{
$this->lock();
$data = '';
rewind($this->handle);
$data = trim(stream_get_contents($this->handle));
if ($data !== '') {
$this->data = unserialize($data);
$data = null;
}
flock($this->handle, LOCK_UN);
$this->iterator = new \ArrayIterator($this->data);
} | php | private function read()
{
$this->lock();
$data = '';
rewind($this->handle);
$data = trim(stream_get_contents($this->handle));
if ($data !== '') {
$this->data = unserialize($data);
$data = null;
}
flock($this->handle, LOCK_UN);
$this->iterator = new \ArrayIterator($this->data);
} | [
"private",
"function",
"read",
"(",
")",
"{",
"$",
"this",
"->",
"lock",
"(",
")",
";",
"$",
"data",
"=",
"''",
";",
"rewind",
"(",
"$",
"this",
"->",
"handle",
")",
";",
"$",
"data",
"=",
"trim",
"(",
"stream_get_contents",
"(",
"$",
"this",
"->... | Read session file
@return void | [
"Read",
"session",
"file"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Session.php#L200-L218 | train |
inphinit/framework | src/Experimental/Session.php | Session.write | private function write()
{
ftruncate($this->handle, 0);
rewind($this->handle);
fwrite($this->handle, serialize($this->data));
} | php | private function write()
{
ftruncate($this->handle, 0);
rewind($this->handle);
fwrite($this->handle, serialize($this->data));
} | [
"private",
"function",
"write",
"(",
")",
"{",
"ftruncate",
"(",
"$",
"this",
"->",
"handle",
",",
"0",
")",
";",
"rewind",
"(",
"$",
"this",
"->",
"handle",
")",
";",
"fwrite",
"(",
"$",
"this",
"->",
"handle",
",",
"serialize",
"(",
"$",
"this",
... | Write variables in session file
@return void | [
"Write",
"variables",
"in",
"session",
"file"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Session.php#L238-L244 | train |
inphinit/framework | src/Experimental/Form.php | Form.setup | public static function setup($byType, array $attributes)
{
if (0 !== preg_match('#^(' . self::$alloweds . '|select|form)$#', $type)) {
self::$preAttrs[$byType] = $attributes;
}
} | php | public static function setup($byType, array $attributes)
{
if (0 !== preg_match('#^(' . self::$alloweds . '|select|form)$#', $type)) {
self::$preAttrs[$byType] = $attributes;
}
} | [
"public",
"static",
"function",
"setup",
"(",
"$",
"byType",
",",
"array",
"$",
"attributes",
")",
"{",
"if",
"(",
"0",
"!==",
"preg_match",
"(",
"'#^('",
".",
"self",
"::",
"$",
"alloweds",
".",
"'|select|form)$#'",
",",
"$",
"type",
")",
")",
"{",
... | Define default attributes for all elements
@param string $byType
@param array $attributes
@return void | [
"Define",
"default",
"attributes",
"for",
"all",
"elements"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Form.php#L37-L42 | train |
inphinit/framework | src/Experimental/Form.php | Form.comboRange | public static function comboRange($name, $low, $high, $step = null, $value = null, array $attributes = array())
{
$range = $step !== null ? range($low, $high, $step) : range($low, $high);
$range = array_combine($range, $range);
return self::combo($name, $range, $value, $attributes);
} | php | public static function comboRange($name, $low, $high, $step = null, $value = null, array $attributes = array())
{
$range = $step !== null ? range($low, $high, $step) : range($low, $high);
$range = array_combine($range, $range);
return self::combo($name, $range, $value, $attributes);
} | [
"public",
"static",
"function",
"comboRange",
"(",
"$",
"name",
",",
"$",
"low",
",",
"$",
"high",
",",
"$",
"step",
"=",
"null",
",",
"$",
"value",
"=",
"null",
",",
"array",
"$",
"attributes",
"=",
"array",
"(",
")",
")",
"{",
"$",
"range",
"="... | Generate combo by range
@param string $name
@param string|int $low
@param string|int $high
@param int $step
@param string|null $value
@param string $attributes
@return string|null | [
"Generate",
"combo",
"by",
"range"
] | 81eddb711e0225116a1ced91ed65e71437b7288c | https://github.com/inphinit/framework/blob/81eddb711e0225116a1ced91ed65e71437b7288c/src/Experimental/Form.php#L55-L61 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.