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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
agentsib/diadoc-php | src/Api/Proto/Events/CustomDataPatch.php | CustomDataPatch.setOperation | public function setOperation(\AgentSIB\Diadoc\Api\Proto\Events\CustomDataPatchOperation $value)
{
$this->Operation = $value;
} | php | public function setOperation(\AgentSIB\Diadoc\Api\Proto\Events\CustomDataPatchOperation $value)
{
$this->Operation = $value;
} | [
"public",
"function",
"setOperation",
"(",
"\\",
"AgentSIB",
"\\",
"Diadoc",
"\\",
"Api",
"\\",
"Proto",
"\\",
"Events",
"\\",
"CustomDataPatchOperation",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"Operation",
"=",
"$",
"value",
";",
"}"
] | Set 'Operation' value
@param \AgentSIB\Diadoc\Api\Proto\Events\CustomDataPatchOperation $value | [
"Set",
"Operation",
"value"
] | 0dbfe63397a1f3083c4815ad7033bcb986904979 | https://github.com/agentsib/diadoc-php/blob/0dbfe63397a1f3083c4815ad7033bcb986904979/src/Api/Proto/Events/CustomDataPatch.php#L110-L113 | train |
agentsib/diadoc-php | src/Api/Proto/Certificate.php | Certificate.setRawCertificateData | public function setRawCertificateData($value)
{
if ($value !== null && ! $value instanceof \Protobuf\Stream) {
$value = \Protobuf\Stream::wrap($value);
}
$this->RawCertificateData = $value;
} | php | public function setRawCertificateData($value)
{
if ($value !== null && ! $value instanceof \Protobuf\Stream) {
$value = \Protobuf\Stream::wrap($value);
}
$this->RawCertificateData = $value;
} | [
"public",
"function",
"setRawCertificateData",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"!==",
"null",
"&&",
"!",
"$",
"value",
"instanceof",
"\\",
"Protobuf",
"\\",
"Stream",
")",
"{",
"$",
"value",
"=",
"\\",
"Protobuf",
"\\",
"Stream",
... | Set 'RawCertificateData' value
@param \Protobuf\Stream $value | [
"Set",
"RawCertificateData",
"value"
] | 0dbfe63397a1f3083c4815ad7033bcb986904979 | https://github.com/agentsib/diadoc-php/blob/0dbfe63397a1f3083c4815ad7033bcb986904979/src/Api/Proto/Certificate.php#L59-L66 | train |
agentsib/diadoc-php | src/Api/Proto/CertificateChainElement.php | CertificateChainElement.setDerCertificate | public function setDerCertificate($value)
{
if ($value !== null && ! $value instanceof \Protobuf\Stream) {
$value = \Protobuf\Stream::wrap($value);
}
$this->DerCertificate = $value;
} | php | public function setDerCertificate($value)
{
if ($value !== null && ! $value instanceof \Protobuf\Stream) {
$value = \Protobuf\Stream::wrap($value);
}
$this->DerCertificate = $value;
} | [
"public",
"function",
"setDerCertificate",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"!==",
"null",
"&&",
"!",
"$",
"value",
"instanceof",
"\\",
"Protobuf",
"\\",
"Stream",
")",
"{",
"$",
"value",
"=",
"\\",
"Protobuf",
"\\",
"Stream",
"::"... | Set 'DerCertificate' value
@param \Protobuf\Stream $value | [
"Set",
"DerCertificate",
"value"
] | 0dbfe63397a1f3083c4815ad7033bcb986904979 | https://github.com/agentsib/diadoc-php/blob/0dbfe63397a1f3083c4815ad7033bcb986904979/src/Api/Proto/CertificateChainElement.php#L96-L103 | train |
agentsib/diadoc-php | src/Api/Proto/Documents/InvoiceDocument/InvoiceRevisionMetadata.php | InvoiceRevisionMetadata.setInvoiceRevisionStatus | public function setInvoiceRevisionStatus(\AgentSIB\Diadoc\Api\Proto\Documents\InvoiceDocument\InvoiceStatus $value = null)
{
$this->InvoiceRevisionStatus = $value;
} | php | public function setInvoiceRevisionStatus(\AgentSIB\Diadoc\Api\Proto\Documents\InvoiceDocument\InvoiceStatus $value = null)
{
$this->InvoiceRevisionStatus = $value;
} | [
"public",
"function",
"setInvoiceRevisionStatus",
"(",
"\\",
"AgentSIB",
"\\",
"Diadoc",
"\\",
"Api",
"\\",
"Proto",
"\\",
"Documents",
"\\",
"InvoiceDocument",
"\\",
"InvoiceStatus",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"InvoiceRevisionStatus... | Set 'InvoiceRevisionStatus' value
@param \AgentSIB\Diadoc\Api\Proto\Documents\InvoiceDocument\InvoiceStatus $value | [
"Set",
"InvoiceRevisionStatus",
"value"
] | 0dbfe63397a1f3083c4815ad7033bcb986904979 | https://github.com/agentsib/diadoc-php/blob/0dbfe63397a1f3083c4815ad7033bcb986904979/src/Api/Proto/Documents/InvoiceDocument/InvoiceRevisionMetadata.php#L119-L122 | train |
ohdearapp/ohdear-php-sdk | src/Resources/Site.php | Site.uptime | public function uptime(string $startedAt, string $endedAt, string $split)
{
return $this->ohDear->uptime($this->id, $startedAt, $endedAt, $split);
} | php | public function uptime(string $startedAt, string $endedAt, string $split)
{
return $this->ohDear->uptime($this->id, $startedAt, $endedAt, $split);
} | [
"public",
"function",
"uptime",
"(",
"string",
"$",
"startedAt",
",",
"string",
"$",
"endedAt",
",",
"string",
"$",
"split",
")",
"{",
"return",
"$",
"this",
"->",
"ohDear",
"->",
"uptime",
"(",
"$",
"this",
"->",
"id",
",",
"$",
"startedAt",
",",
"$... | Get the uptime percentages for a site.
@param string $startedAt Must be in format Ymdhis
@param string $endedAt Must be in format Ymdhis
@param string $split Use hour, day or month
@return array | [
"Get",
"the",
"uptime",
"percentages",
"for",
"a",
"site",
"."
] | 7851e55d28ea62ae29f516ab2b5bb4be576a6427 | https://github.com/ohdearapp/ohdear-php-sdk/blob/7851e55d28ea62ae29f516ab2b5bb4be576a6427/src/Resources/Site.php#L83-L86 | train |
ohdearapp/ohdear-php-sdk | src/Resources/Site.php | Site.downtime | public function downtime(string $startedAt, string $endedAt)
{
return $this->ohDear->downtime($this->id, $startedAt, $endedAt);
} | php | public function downtime(string $startedAt, string $endedAt)
{
return $this->ohDear->downtime($this->id, $startedAt, $endedAt);
} | [
"public",
"function",
"downtime",
"(",
"string",
"$",
"startedAt",
",",
"string",
"$",
"endedAt",
")",
"{",
"return",
"$",
"this",
"->",
"ohDear",
"->",
"downtime",
"(",
"$",
"this",
"->",
"id",
",",
"$",
"startedAt",
",",
"$",
"endedAt",
")",
";",
"... | Get the downtime periods for a site.
@param string $startedAt Must be in format Ymdhis
@param string $endedAt Must be in format Ymdhis
@return array | [
"Get",
"the",
"downtime",
"periods",
"for",
"a",
"site",
"."
] | 7851e55d28ea62ae29f516ab2b5bb4be576a6427 | https://github.com/ohdearapp/ohdear-php-sdk/blob/7851e55d28ea62ae29f516ab2b5bb4be576a6427/src/Resources/Site.php#L96-L99 | train |
8p/guzzle-wsse-middleware | src/EightPoints/Guzzle/WsseAuthMiddleware.php | WsseAuthMiddleware.attach | public function attach()
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
$createdAt = $this->getCreatedAt()->format('c');
$nonce = $this->generateNonce();
$digest = $this->generateDigest($nonce, $createdAt, $this->password);
$xwsse = array(
sprintf('Username="%s"', $this->username),
sprintf('PasswordDigest="%s"', $digest),
sprintf('Nonce="%s"', $nonce),
sprintf('Created="%s"', $createdAt)
);
$request = $request->withHeader('Authorization', 'WSSE profile="UsernameToken"');
$request = $request->withHeader('X-WSSE', sprintf('UsernameToken %s', implode(', ', $xwsse)));
return $handler($request, $options);
};
};
} | php | public function attach()
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
$createdAt = $this->getCreatedAt()->format('c');
$nonce = $this->generateNonce();
$digest = $this->generateDigest($nonce, $createdAt, $this->password);
$xwsse = array(
sprintf('Username="%s"', $this->username),
sprintf('PasswordDigest="%s"', $digest),
sprintf('Nonce="%s"', $nonce),
sprintf('Created="%s"', $createdAt)
);
$request = $request->withHeader('Authorization', 'WSSE profile="UsernameToken"');
$request = $request->withHeader('X-WSSE', sprintf('UsernameToken %s', implode(', ', $xwsse)));
return $handler($request, $options);
};
};
} | [
"public",
"function",
"attach",
"(",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"$",
... | Add WSSE auth headers to Request
@version 3.0
@since 2015-06
@return callable
@throws \InvalidArgumentException | [
"Add",
"WSSE",
"auth",
"headers",
"to",
"Request"
] | 3998dae6fed29f2d3384024764046b63a764ddda | https://github.com/8p/guzzle-wsse-middleware/blob/3998dae6fed29f2d3384024764046b63a764ddda/src/EightPoints/Guzzle/WsseAuthMiddleware.php#L165-L188 | train |
ohdearapp/ohdear-php-sdk | src/Resources/Check.php | Check.enable | public function enable()
{
$updatedCheck = $this->ohDear->enableCheck($this->id);
$this->enabled = $updatedCheck->enabled;
} | php | public function enable()
{
$updatedCheck = $this->ohDear->enableCheck($this->id);
$this->enabled = $updatedCheck->enabled;
} | [
"public",
"function",
"enable",
"(",
")",
"{",
"$",
"updatedCheck",
"=",
"$",
"this",
"->",
"ohDear",
"->",
"enableCheck",
"(",
"$",
"this",
"->",
"id",
")",
";",
"$",
"this",
"->",
"enabled",
"=",
"$",
"updatedCheck",
"->",
"enabled",
";",
"}"
] | Enable the check. | [
"Enable",
"the",
"check",
"."
] | 7851e55d28ea62ae29f516ab2b5bb4be576a6427 | https://github.com/ohdearapp/ohdear-php-sdk/blob/7851e55d28ea62ae29f516ab2b5bb4be576a6427/src/Resources/Check.php#L38-L43 | train |
ohdearapp/ohdear-php-sdk | src/Resources/Check.php | Check.disable | public function disable()
{
$updatedCheck = $this->ohDear->disableCheck($this->id);
$this->enabled = $updatedCheck->enabled;
} | php | public function disable()
{
$updatedCheck = $this->ohDear->disableCheck($this->id);
$this->enabled = $updatedCheck->enabled;
} | [
"public",
"function",
"disable",
"(",
")",
"{",
"$",
"updatedCheck",
"=",
"$",
"this",
"->",
"ohDear",
"->",
"disableCheck",
"(",
"$",
"this",
"->",
"id",
")",
";",
"$",
"this",
"->",
"enabled",
"=",
"$",
"updatedCheck",
"->",
"enabled",
";",
"}"
] | Disable the check. | [
"Disable",
"the",
"check",
"."
] | 7851e55d28ea62ae29f516ab2b5bb4be576a6427 | https://github.com/ohdearapp/ohdear-php-sdk/blob/7851e55d28ea62ae29f516ab2b5bb4be576a6427/src/Resources/Check.php#L48-L53 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.configureOptions | private function configureOptions()
{
$this->addOption(
self::OPTIONS_KEY_IMAGES,
'i',
InputOption::VALUE_OPTIONAL,
'The list of docker images to use (comma or space delimited).'
);
$this->addOption(
self::OPTIONS_KEY_CONFIGFILE,
'c',
InputOption::VALUE_OPTIONAL,
'The path to the configuration file.'
);
$this->addOption(
self::OPTIONS_KEY_SYNTAX,
's',
InputOption::VALUE_OPTIONAL,
'A flag indicating whether to run syntax checks.'
);
$this->addOption(
self::OPTIONS_KEY_SYNTAXCOMMAND,
'S',
InputOption::VALUE_OPTIONAL,
'The command to run syntax checks.'
);
$this->addOption(
self::OPTIONS_KEY_UNITTESTS,
'u',
InputOption::VALUE_OPTIONAL,
'A flag indicating whether to run the unit test suite.'
);
$this->addOption(
self::OPTIONS_KEY_UNITTESTSCOMMAND,
'U',
InputOption::VALUE_OPTIONAL,
'The command to run the unit tests.'
);
$this->addOption(
self::OPTIONS_KEY_PULL,
'p',
InputOption::VALUE_NONE,
'A flag indicating to pull new images instead of running the linter or unit tests.'
);
} | php | private function configureOptions()
{
$this->addOption(
self::OPTIONS_KEY_IMAGES,
'i',
InputOption::VALUE_OPTIONAL,
'The list of docker images to use (comma or space delimited).'
);
$this->addOption(
self::OPTIONS_KEY_CONFIGFILE,
'c',
InputOption::VALUE_OPTIONAL,
'The path to the configuration file.'
);
$this->addOption(
self::OPTIONS_KEY_SYNTAX,
's',
InputOption::VALUE_OPTIONAL,
'A flag indicating whether to run syntax checks.'
);
$this->addOption(
self::OPTIONS_KEY_SYNTAXCOMMAND,
'S',
InputOption::VALUE_OPTIONAL,
'The command to run syntax checks.'
);
$this->addOption(
self::OPTIONS_KEY_UNITTESTS,
'u',
InputOption::VALUE_OPTIONAL,
'A flag indicating whether to run the unit test suite.'
);
$this->addOption(
self::OPTIONS_KEY_UNITTESTSCOMMAND,
'U',
InputOption::VALUE_OPTIONAL,
'The command to run the unit tests.'
);
$this->addOption(
self::OPTIONS_KEY_PULL,
'p',
InputOption::VALUE_NONE,
'A flag indicating to pull new images instead of running the linter or unit tests.'
);
} | [
"private",
"function",
"configureOptions",
"(",
")",
"{",
"$",
"this",
"->",
"addOption",
"(",
"self",
"::",
"OPTIONS_KEY_IMAGES",
",",
"'i'",
",",
"InputOption",
"::",
"VALUE_OPTIONAL",
",",
"'The list of docker images to use (comma or space delimited).'",
")",
";",
... | Configures the list of command options. | [
"Configures",
"the",
"list",
"of",
"command",
"options",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L100-L144 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
// retrieve the current settings
$options = $this->getCurrentOptions($input, $output);
// check if docker is installed
if (false === $this->commandExists('docker')) {
$output->writeln('Docker is required to run DUnit.');
return self::ERROR_CODE;
}
// loop over each of the docker images specified
foreach ($options[self::OPTIONS_KEY_IMAGES] as $image) {
if ($options[self::OPTIONS_KEY_PULL]) {
passthru(sprintf(
self::DOCKER_COMMAND_PULL,
escapeshellarg($image)
));
continue;
}
$output->writeln('Running against image '.$image);
if ($options[self::OPTIONS_KEY_SYNTAX]) {
$output->writeln('Checking syntax');
// run the syntax checks
$this->executeCommandForImage(
$image,
$options[self::OPTIONS_KEY_SYNTAXCOMMAND]
);
}
if ($options[self::OPTIONS_KEY_UNITTESTS]) {
$output->writeln('Running unit test suite');
// run the unit tests
$this->executeCommandForImage(
$image,
$options[self::OPTIONS_KEY_UNITTESTSCOMMAND]
);
}
}
return self::NO_ERROR;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
// retrieve the current settings
$options = $this->getCurrentOptions($input, $output);
// check if docker is installed
if (false === $this->commandExists('docker')) {
$output->writeln('Docker is required to run DUnit.');
return self::ERROR_CODE;
}
// loop over each of the docker images specified
foreach ($options[self::OPTIONS_KEY_IMAGES] as $image) {
if ($options[self::OPTIONS_KEY_PULL]) {
passthru(sprintf(
self::DOCKER_COMMAND_PULL,
escapeshellarg($image)
));
continue;
}
$output->writeln('Running against image '.$image);
if ($options[self::OPTIONS_KEY_SYNTAX]) {
$output->writeln('Checking syntax');
// run the syntax checks
$this->executeCommandForImage(
$image,
$options[self::OPTIONS_KEY_SYNTAXCOMMAND]
);
}
if ($options[self::OPTIONS_KEY_UNITTESTS]) {
$output->writeln('Running unit test suite');
// run the unit tests
$this->executeCommandForImage(
$image,
$options[self::OPTIONS_KEY_UNITTESTSCOMMAND]
);
}
}
return self::NO_ERROR;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"// retrieve the current settings",
"$",
"options",
"=",
"$",
"this",
"->",
"getCurrentOptions",
"(",
"$",
"input",
",",
"$",
"output",
")",... | The entry point for the command.
@param InputInterface $input The input for options and arguments.
@param OutputInterface $output The output writer.
@return null|int null or 0 if everything went fine, or an error code | [
"The",
"entry",
"point",
"for",
"the",
"command",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L152-L191 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.getCurrentOptions | private function getCurrentOptions(InputInterface $input, OutputInterface $output)
{
$options = $this->getDefaultOptions();
try {
$options = $this->mergeConfigFileIntoOptions(
$options,
$input->getOption(self::OPTIONS_KEY_CONFIGFILE)
);
} catch (Exception $e) {
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) {
$output->writeln('WARNING: Config file could not be read. Falling back to built-in defaults.');
}
}
$options = $this->mergeEnvironmentVariablesIntoOptions($options);
// handle the individual options
// handle the list of images
$options[self::OPTIONS_KEY_IMAGES] = $this->getArrayOption(
$input, self::OPTIONS_KEY_IMAGES, $options[self::OPTIONS_KEY_IMAGES]
);
// if the user specified a syntax command we assume they want to run
// the syntax checks
$syntaxCommand = $input->getOption(self::OPTIONS_KEY_SYNTAXCOMMAND);
if (!empty($syntaxCommand)) {
$options[self::OPTIONS_KEY_SYNTAX] = true;
} else {
// check for the syntax flag
$options[self::OPTIONS_KEY_SYNTAX] = $this->getBooleanOption(
$input, self::OPTIONS_KEY_SYNTAX, $options[self::OPTIONS_KEY_SYNTAX]
);
}
// if they are running syntax, check for the actual command option
if ($options[self::OPTIONS_KEY_SYNTAX]) {
$options[self::OPTIONS_KEY_SYNTAXCOMMAND] = $this->getStringOption(
$input, self::OPTIONS_KEY_SYNTAXCOMMAND, $options[self::OPTIONS_KEY_SYNTAXCOMMAND]
);
}
// if the user specified a unit tests command we assume they want to
// run the unit tests
if ($input->hasOption(self::OPTIONS_KEY_UNITTESTSCOMMAND)) {
$options[self::OPTIONS_KEY_UNITTESTS] = true;
} else {
// check for the unit tests flag
$options[self::OPTIONS_KEY_UNITTESTS] = $this->getBooleanOption(
$input, self::OPTIONS_KEY_UNITTESTS, $options[self::OPTIONS_KEY_UNITTESTS]
);
}
// if they are running the unit tests, check for the actual command
if ($options[self::OPTIONS_KEY_UNITTESTS]) {
$options[self::OPTIONS_KEY_UNITTESTSCOMMAND] = $this->getStringOption(
$input,
self::OPTIONS_KEY_UNITTESTSCOMMAND,
$options[self::OPTIONS_KEY_UNITTESTSCOMMAND]
);
}
$options[self::OPTIONS_KEY_PULL] = $input->getOption(self::OPTIONS_KEY_PULL);
return $options;
} | php | private function getCurrentOptions(InputInterface $input, OutputInterface $output)
{
$options = $this->getDefaultOptions();
try {
$options = $this->mergeConfigFileIntoOptions(
$options,
$input->getOption(self::OPTIONS_KEY_CONFIGFILE)
);
} catch (Exception $e) {
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) {
$output->writeln('WARNING: Config file could not be read. Falling back to built-in defaults.');
}
}
$options = $this->mergeEnvironmentVariablesIntoOptions($options);
// handle the individual options
// handle the list of images
$options[self::OPTIONS_KEY_IMAGES] = $this->getArrayOption(
$input, self::OPTIONS_KEY_IMAGES, $options[self::OPTIONS_KEY_IMAGES]
);
// if the user specified a syntax command we assume they want to run
// the syntax checks
$syntaxCommand = $input->getOption(self::OPTIONS_KEY_SYNTAXCOMMAND);
if (!empty($syntaxCommand)) {
$options[self::OPTIONS_KEY_SYNTAX] = true;
} else {
// check for the syntax flag
$options[self::OPTIONS_KEY_SYNTAX] = $this->getBooleanOption(
$input, self::OPTIONS_KEY_SYNTAX, $options[self::OPTIONS_KEY_SYNTAX]
);
}
// if they are running syntax, check for the actual command option
if ($options[self::OPTIONS_KEY_SYNTAX]) {
$options[self::OPTIONS_KEY_SYNTAXCOMMAND] = $this->getStringOption(
$input, self::OPTIONS_KEY_SYNTAXCOMMAND, $options[self::OPTIONS_KEY_SYNTAXCOMMAND]
);
}
// if the user specified a unit tests command we assume they want to
// run the unit tests
if ($input->hasOption(self::OPTIONS_KEY_UNITTESTSCOMMAND)) {
$options[self::OPTIONS_KEY_UNITTESTS] = true;
} else {
// check for the unit tests flag
$options[self::OPTIONS_KEY_UNITTESTS] = $this->getBooleanOption(
$input, self::OPTIONS_KEY_UNITTESTS, $options[self::OPTIONS_KEY_UNITTESTS]
);
}
// if they are running the unit tests, check for the actual command
if ($options[self::OPTIONS_KEY_UNITTESTS]) {
$options[self::OPTIONS_KEY_UNITTESTSCOMMAND] = $this->getStringOption(
$input,
self::OPTIONS_KEY_UNITTESTSCOMMAND,
$options[self::OPTIONS_KEY_UNITTESTSCOMMAND]
);
}
$options[self::OPTIONS_KEY_PULL] = $input->getOption(self::OPTIONS_KEY_PULL);
return $options;
} | [
"private",
"function",
"getCurrentOptions",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"getDefaultOptions",
"(",
")",
";",
"try",
"{",
"$",
"options",
"=",
"$",
"this",
"->"... | Returns an array of the currently active options given all possible
options, environment variables, config file settings, etc.
@param InputInterface $input The input of options and arguments.
@param OutputInterface $output The output writer.
@return array Returns an array of settings. | [
"Returns",
"an",
"array",
"of",
"the",
"currently",
"active",
"options",
"given",
"all",
"possible",
"options",
"environment",
"variables",
"config",
"file",
"settings",
"etc",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L200-L261 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.getDefaultOptions | private function getDefaultOptions()
{
// the list of default options if no config is found or specified
return array(
self::OPTIONS_KEY_IMAGES => array(
'vectorface/php5.4',
'vectorface/php5.5',
'vectorface/php5.6',
'vectorface/hhvm'
),
self::OPTIONS_KEY_SYNTAX => true,
self::OPTIONS_KEY_SYNTAXCOMMAND => 'find /opt/source -type f -name "*.php" ! -path "*/vendor/*" -print0 | xargs -0 -n 1 -P 8 php -l | grep -v "No syntax errors"',
self::OPTIONS_KEY_UNITTESTS => true,
self::OPTIONS_KEY_UNITTESTSCOMMAND => '/opt/source/vendor/bin/phpunit',
self::OPTIONS_KEY_PULL => false,
);
} | php | private function getDefaultOptions()
{
// the list of default options if no config is found or specified
return array(
self::OPTIONS_KEY_IMAGES => array(
'vectorface/php5.4',
'vectorface/php5.5',
'vectorface/php5.6',
'vectorface/hhvm'
),
self::OPTIONS_KEY_SYNTAX => true,
self::OPTIONS_KEY_SYNTAXCOMMAND => 'find /opt/source -type f -name "*.php" ! -path "*/vendor/*" -print0 | xargs -0 -n 1 -P 8 php -l | grep -v "No syntax errors"',
self::OPTIONS_KEY_UNITTESTS => true,
self::OPTIONS_KEY_UNITTESTSCOMMAND => '/opt/source/vendor/bin/phpunit',
self::OPTIONS_KEY_PULL => false,
);
} | [
"private",
"function",
"getDefaultOptions",
"(",
")",
"{",
"// the list of default options if no config is found or specified",
"return",
"array",
"(",
"self",
"::",
"OPTIONS_KEY_IMAGES",
"=>",
"array",
"(",
"'vectorface/php5.4'",
",",
"'vectorface/php5.5'",
",",
"'vectorface... | Returns an array of built-in options if none are found or specified.
@return array The array of deafult options. | [
"Returns",
"an",
"array",
"of",
"built",
"-",
"in",
"options",
"if",
"none",
"are",
"found",
"or",
"specified",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L267-L283 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.mergeConfigFileIntoOptions | private function mergeConfigFileIntoOptions($options, $configFile)
{
$configFile = ($configFile) ?: realpath(getcwd()).'/.dunitconfig';
if (file_exists($configFile) && is_readable($configFile)) {
if (false !== ($settings = parse_ini_file($configFile))) {
return array_merge($options, $settings);
}
}
throw new Exception(
'WARNING: Config file could not be read. Falling back to built-in defaults.'
);
} | php | private function mergeConfigFileIntoOptions($options, $configFile)
{
$configFile = ($configFile) ?: realpath(getcwd()).'/.dunitconfig';
if (file_exists($configFile) && is_readable($configFile)) {
if (false !== ($settings = parse_ini_file($configFile))) {
return array_merge($options, $settings);
}
}
throw new Exception(
'WARNING: Config file could not be read. Falling back to built-in defaults.'
);
} | [
"private",
"function",
"mergeConfigFileIntoOptions",
"(",
"$",
"options",
",",
"$",
"configFile",
")",
"{",
"$",
"configFile",
"=",
"(",
"$",
"configFile",
")",
"?",
":",
"realpath",
"(",
"getcwd",
"(",
")",
")",
".",
"'/.dunitconfig'",
";",
"if",
"(",
"... | Merges the default options with values from the config file specified.
@param array $options The current options.
@param string $configFile The path to the config file. If the config
file specified is not valid the method will fall back to the
default config file location (./.dunitconfig)
@return array Returns the array of merged settings.
@throws Exception Throws an exception if no config file can be found. | [
"Merges",
"the",
"default",
"options",
"with",
"values",
"from",
"the",
"config",
"file",
"specified",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L294-L305 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.mergeEnvironmentVariablesIntoOptions | private function mergeEnvironmentVariablesIntoOptions($options)
{
// map environment variables to script options
foreach (self::$optionsMap as $env => $option) {
if (false !== ($value = getenv($env))) {
$options[$option] = (string)$value;
}
}
return $options;
} | php | private function mergeEnvironmentVariablesIntoOptions($options)
{
// map environment variables to script options
foreach (self::$optionsMap as $env => $option) {
if (false !== ($value = getenv($env))) {
$options[$option] = (string)$value;
}
}
return $options;
} | [
"private",
"function",
"mergeEnvironmentVariablesIntoOptions",
"(",
"$",
"options",
")",
"{",
"// map environment variables to script options",
"foreach",
"(",
"self",
"::",
"$",
"optionsMap",
"as",
"$",
"env",
"=>",
"$",
"option",
")",
"{",
"if",
"(",
"false",
"!... | Merges in the value of the environment variables into the settings.
@param array $options The current settings.
@return array The merged settings with the environment variables. | [
"Merges",
"in",
"the",
"value",
"of",
"the",
"environment",
"variables",
"into",
"the",
"settings",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L312-L321 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.getArrayOption | private function getArrayOption(InputInterface $input, $key, $default)
{
$value = trim((string)$input->getOption($key));
if (strlen($value)) {
$current = $this->parseStringToArray($input->getOption($key));
if (!empty($current)) {
return $current;
}
}
return is_string($default) ? $this->parseStringToArray($default) : $default;
} | php | private function getArrayOption(InputInterface $input, $key, $default)
{
$value = trim((string)$input->getOption($key));
if (strlen($value)) {
$current = $this->parseStringToArray($input->getOption($key));
if (!empty($current)) {
return $current;
}
}
return is_string($default) ? $this->parseStringToArray($default) : $default;
} | [
"private",
"function",
"getArrayOption",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"key",
",",
"$",
"default",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"(",
"string",
")",
"$",
"input",
"->",
"getOption",
"(",
"$",
"key",
")",
")",
";",
"if",
... | Retrieves the given key from the input options as an array and uses
the default value if not found or empty.
@param InputInterface $input The input for options.
@param string $key The input key for the option.
@param mixed $default current value for the images.
@return array Returns the list of images as an array. | [
"Retrieves",
"the",
"given",
"key",
"from",
"the",
"input",
"options",
"as",
"an",
"array",
"and",
"uses",
"the",
"default",
"value",
"if",
"not",
"found",
"or",
"empty",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L331-L341 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.parseStringToArray | private function parseStringToArray($string)
{
// convert commas to spaces
$string = str_replace(',', ' ', $string);
// convert new lines to spaces
$string = str_replace(PHP_EOL, ' ', $string);
// split on the spaces and filter out empty elements
return array_values(
array_filter(
array_map(
'trim',
explode(' ', $string)
),
'strlen'
)
);
} | php | private function parseStringToArray($string)
{
// convert commas to spaces
$string = str_replace(',', ' ', $string);
// convert new lines to spaces
$string = str_replace(PHP_EOL, ' ', $string);
// split on the spaces and filter out empty elements
return array_values(
array_filter(
array_map(
'trim',
explode(' ', $string)
),
'strlen'
)
);
} | [
"private",
"function",
"parseStringToArray",
"(",
"$",
"string",
")",
"{",
"// convert commas to spaces",
"$",
"string",
"=",
"str_replace",
"(",
"','",
",",
"' '",
",",
"$",
"string",
")",
";",
"// convert new lines to spaces",
"$",
"string",
"=",
"str_replace",
... | Parses a string into an array by splitting on spaces, commas or
new line characters and stripping out any empty elements.
@param string $string The input string.
@return array Returns the list of elements as an array. | [
"Parses",
"a",
"string",
"into",
"an",
"array",
"by",
"splitting",
"on",
"spaces",
"commas",
"or",
"new",
"line",
"characters",
"and",
"stripping",
"out",
"any",
"empty",
"elements",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L349-L365 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.getBooleanOption | private function getBooleanOption(InputInterface $input, $key, $default)
{
$value = trim((string)$input->getOption($key));
if (strlen($value)) {
return filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
return filter_var($default, FILTER_VALIDATE_BOOLEAN);
} | php | private function getBooleanOption(InputInterface $input, $key, $default)
{
$value = trim((string)$input->getOption($key));
if (strlen($value)) {
return filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
return filter_var($default, FILTER_VALIDATE_BOOLEAN);
} | [
"private",
"function",
"getBooleanOption",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"key",
",",
"$",
"default",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"(",
"string",
")",
"$",
"input",
"->",
"getOption",
"(",
"$",
"key",
")",
")",
";",
"if",... | Retrieves the given key from the input options as a boolean.
@param InputInterface $input The input interface.
@param string $key The option key.
@param mixed $default The default value.
@return boolean Returns the boolean value of the option or the default
if the option is not found. | [
"Retrieves",
"the",
"given",
"key",
"from",
"the",
"input",
"options",
"as",
"a",
"boolean",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L375-L382 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.getStringOption | private function getStringOption(InputInterface $input, $key, $default)
{
$value = trim((string)$input->getOption($key));
if (strlen($value)) {
return $value;
}
return (string)$default;
} | php | private function getStringOption(InputInterface $input, $key, $default)
{
$value = trim((string)$input->getOption($key));
if (strlen($value)) {
return $value;
}
return (string)$default;
} | [
"private",
"function",
"getStringOption",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"key",
",",
"$",
"default",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"(",
"string",
")",
"$",
"input",
"->",
"getOption",
"(",
"$",
"key",
")",
")",
";",
"if",
... | Retrieves the given key from the input options as a string.
@param InputInterface $input The input interface.
@param string $key The option key.
@param mixed $default The default value.
@return string Returns the string value of the option or the default if
if the option is not found. | [
"Retrieves",
"the",
"given",
"key",
"from",
"the",
"input",
"options",
"as",
"a",
"string",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L393-L400 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.commandExists | private function commandExists($command)
{
$response = trim(shell_exec(sprintf(
'which %s',
escapeshellarg($command)
)));
return !empty($response);
} | php | private function commandExists($command)
{
$response = trim(shell_exec(sprintf(
'which %s',
escapeshellarg($command)
)));
return !empty($response);
} | [
"private",
"function",
"commandExists",
"(",
"$",
"command",
")",
"{",
"$",
"response",
"=",
"trim",
"(",
"shell_exec",
"(",
"sprintf",
"(",
"'which %s'",
",",
"escapeshellarg",
"(",
"$",
"command",
")",
")",
")",
")",
";",
"return",
"!",
"empty",
"(",
... | Determines if a command exists on the current environment.
N.B. This function is not cross platform. The "which" command used is
not portable to Microsoft Windows OS. Feel free to provide a pull
request if you wish to use dunit on windows.
@param string $command The command to check
@return boolean Returns true if the command has been found and false,
otherwise. | [
"Determines",
"if",
"a",
"command",
"exists",
"on",
"the",
"current",
"environment",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L425-L432 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.executeCommandForImage | private function executeCommandForImage($image, $command)
{
passthru(sprintf(
self::DOCKER_COMMAND_FORMAT,
escapeshellarg($image),
intval($this->getColumns()),
$command
));
} | php | private function executeCommandForImage($image, $command)
{
passthru(sprintf(
self::DOCKER_COMMAND_FORMAT,
escapeshellarg($image),
intval($this->getColumns()),
$command
));
} | [
"private",
"function",
"executeCommandForImage",
"(",
"$",
"image",
",",
"$",
"command",
")",
"{",
"passthru",
"(",
"sprintf",
"(",
"self",
"::",
"DOCKER_COMMAND_FORMAT",
",",
"escapeshellarg",
"(",
"$",
"image",
")",
",",
"intval",
"(",
"$",
"this",
"->",
... | Executes an arbitrary command against the image.
@param string $image The docker image to use.
@param string $command The command to run inside the docker image. | [
"Executes",
"an",
"arbitrary",
"command",
"against",
"the",
"image",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L439-L447 | train |
Vectorface/dunit | src/DunitCommand.php | DunitCommand.getColumns | private function getColumns()
{
$dimensions = $this->getApplication()->getTerminalDimensions();
if (is_array($dimensions) && count($dimensions) > self::DIMENSION_WIDTH) {
return $dimensions[self::DIMENSION_WIDTH];
} else {
return self::DEFAULT_WIDTH;
}
} | php | private function getColumns()
{
$dimensions = $this->getApplication()->getTerminalDimensions();
if (is_array($dimensions) && count($dimensions) > self::DIMENSION_WIDTH) {
return $dimensions[self::DIMENSION_WIDTH];
} else {
return self::DEFAULT_WIDTH;
}
} | [
"private",
"function",
"getColumns",
"(",
")",
"{",
"$",
"dimensions",
"=",
"$",
"this",
"->",
"getApplication",
"(",
")",
"->",
"getTerminalDimensions",
"(",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"dimensions",
")",
"&&",
"count",
"(",
"$",
"dimensi... | Returns the number of character columns in the terminal.
@return int The width of the terminal (in number of characters). | [
"Returns",
"the",
"number",
"of",
"character",
"columns",
"in",
"the",
"terminal",
"."
] | 3f04c7a8bef5ff100666e92db96e93f80a6640bf | https://github.com/Vectorface/dunit/blob/3f04c7a8bef5ff100666e92db96e93f80a6640bf/src/DunitCommand.php#L453-L461 | train |
apisearch-io/apisearch-bundle | Command/ExportIndexCommand.php | ExportIndexCommand.exportToFile | public static function exportToFile(
string $file,
OutputInterface $output,
callable $queryItems
) {
$resource = fopen($file, 'w');
$i = 1;
$count = 0;
while (true) {
$items = $queryItems(Query::create('', $i, 500))->getItems();
if (empty($items)) {
break;
}
self::writeItemsToResource(
$resource,
$items
);
self::printPartialCountSaved($output, count($items));
$count += count($items);
++$i;
}
fclose($resource);
return $count;
} | php | public static function exportToFile(
string $file,
OutputInterface $output,
callable $queryItems
) {
$resource = fopen($file, 'w');
$i = 1;
$count = 0;
while (true) {
$items = $queryItems(Query::create('', $i, 500))->getItems();
if (empty($items)) {
break;
}
self::writeItemsToResource(
$resource,
$items
);
self::printPartialCountSaved($output, count($items));
$count += count($items);
++$i;
}
fclose($resource);
return $count;
} | [
"public",
"static",
"function",
"exportToFile",
"(",
"string",
"$",
"file",
",",
"OutputInterface",
"$",
"output",
",",
"callable",
"$",
"queryItems",
")",
"{",
"$",
"resource",
"=",
"fopen",
"(",
"$",
"file",
",",
"'w'",
")",
";",
"$",
"i",
"=",
"1",
... | Save items and return total imported.
@param string $file
@param OutputInterface $output
@param callable $queryItems
@return int | [
"Save",
"items",
"and",
"return",
"total",
"imported",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ExportIndexCommand.php#L86-L115 | train |
apisearch-io/apisearch-bundle | Command/ExportIndexCommand.php | ExportIndexCommand.writeItemsToResource | private static function writeItemsToResource(
$resource,
array $items
) {
foreach ($items as $item) {
fputcsv($resource, [
$item->getId(),
$item->getType(),
json_encode($item->getMetadata()),
json_encode($item->getIndexedMetadata()),
json_encode($item->getSearchableMetadata()),
json_encode($item->getExactMatchingMetadata()),
json_encode($item->getSuggest()),
json_encode(
($item->getCoordinate() instanceof Coordinate)
? $item->getCoordinate()->toArray()
: null
),
]);
}
} | php | private static function writeItemsToResource(
$resource,
array $items
) {
foreach ($items as $item) {
fputcsv($resource, [
$item->getId(),
$item->getType(),
json_encode($item->getMetadata()),
json_encode($item->getIndexedMetadata()),
json_encode($item->getSearchableMetadata()),
json_encode($item->getExactMatchingMetadata()),
json_encode($item->getSuggest()),
json_encode(
($item->getCoordinate() instanceof Coordinate)
? $item->getCoordinate()->toArray()
: null
),
]);
}
} | [
"private",
"static",
"function",
"writeItemsToResource",
"(",
"$",
"resource",
",",
"array",
"$",
"items",
")",
"{",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"fputcsv",
"(",
"$",
"resource",
",",
"[",
"$",
"item",
"->",
"getId",
"(",
... | Echo items as CSV.
@param resource $resource
@param Item[] $items | [
"Echo",
"items",
"as",
"CSV",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ExportIndexCommand.php#L123-L143 | train |
apisearch-io/apisearch-bundle | Command/WithAppRepositoryBucketCommand.php | WithAppRepositoryBucketCommand.getRepositoryAndIndices | protected function getRepositoryAndIndices(
InputInterface $input,
OutputInterface $output
): array {
$appName = $input->getArgument('app-name');
$configuration = $this->repositoryBucket->getConfiguration();
if (!isset($configuration[$appName])) {
throw new Exception(sprintf('App %s not found under apisearch configuration', $appName));
}
$appId = $configuration[$appName]['app_id'];
self::printInfoMessage(
$output,
$this->getHeader(),
"App: <strong>{$appName} / {$appId}</strong>"
);
if (!$input->hasOption('index-name')) {
return [$configuration[$appName]['app_id'], []];
}
$indexNamesAsArray = $configuration[$appName]['indices'] ?? [];
$indices = array_map(function (string $indexName) use ($indexNamesAsArray, $appName, $output) {
if (!isset($indexNamesAsArray[$indexName])) {
throw new Exception(sprintf(
'Index %s not found under %s repository. Indices availables: %s',
$indexName,
$appName,
implode(', ', array_keys($indexNamesAsArray))
));
}
$indexId = $indexNamesAsArray[$indexName];
self::printInfoMessage(
$output,
$this->getHeader(),
"Index: <strong>{$indexName} / {$indexId}</strong>"
);
return IndexUUID::createById($indexId);
}, $input->getOption('index-name'));
return [
AppUUID::createById($appId),
$indices,
];
} | php | protected function getRepositoryAndIndices(
InputInterface $input,
OutputInterface $output
): array {
$appName = $input->getArgument('app-name');
$configuration = $this->repositoryBucket->getConfiguration();
if (!isset($configuration[$appName])) {
throw new Exception(sprintf('App %s not found under apisearch configuration', $appName));
}
$appId = $configuration[$appName]['app_id'];
self::printInfoMessage(
$output,
$this->getHeader(),
"App: <strong>{$appName} / {$appId}</strong>"
);
if (!$input->hasOption('index-name')) {
return [$configuration[$appName]['app_id'], []];
}
$indexNamesAsArray = $configuration[$appName]['indices'] ?? [];
$indices = array_map(function (string $indexName) use ($indexNamesAsArray, $appName, $output) {
if (!isset($indexNamesAsArray[$indexName])) {
throw new Exception(sprintf(
'Index %s not found under %s repository. Indices availables: %s',
$indexName,
$appName,
implode(', ', array_keys($indexNamesAsArray))
));
}
$indexId = $indexNamesAsArray[$indexName];
self::printInfoMessage(
$output,
$this->getHeader(),
"Index: <strong>{$indexName} / {$indexId}</strong>"
);
return IndexUUID::createById($indexId);
}, $input->getOption('index-name'));
return [
AppUUID::createById($appId),
$indices,
];
} | [
"protected",
"function",
"getRepositoryAndIndices",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"array",
"{",
"$",
"appName",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'app-name'",
")",
";",
"$",
"configuration",
"... | Check repository and indices existence.
@param InputInterface $input
@param OutputInterface $output
@return array
@throws Exception | [
"Check",
"repository",
"and",
"indices",
"existence",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/WithAppRepositoryBucketCommand.php#L59-L107 | train |
apisearch-io/apisearch-bundle | Command/QueryCommand.php | QueryCommand.makeQueryAndPrintResults | public static function makeQueryAndPrintResults(
InputInterface $input,
OutputInterface $output,
callable $makeQuery
) {
$query = $input->getArgument('query');
self::printInfoMessage(
$output,
'Query / Page / Size',
sprintf('<strong>%s</strong> / %d / %d',
'' === $query
? '*'
: $query,
$input->getOption('page'),
$input->getOption('size')
)
);
try {
$result = $makeQuery(Query::create(
$input->getArgument('query'),
(int) $input->getOption('page'),
(int) $input->getOption('size')
));
self::printResult($output, $result);
} catch (ResourceNotAvailableException $exception) {
self::printInfoMessage(
$output,
self::getHeader(),
$output->writeln('Index not found. Skipping.')
);
}
} | php | public static function makeQueryAndPrintResults(
InputInterface $input,
OutputInterface $output,
callable $makeQuery
) {
$query = $input->getArgument('query');
self::printInfoMessage(
$output,
'Query / Page / Size',
sprintf('<strong>%s</strong> / %d / %d',
'' === $query
? '*'
: $query,
$input->getOption('page'),
$input->getOption('size')
)
);
try {
$result = $makeQuery(Query::create(
$input->getArgument('query'),
(int) $input->getOption('page'),
(int) $input->getOption('size')
));
self::printResult($output, $result);
} catch (ResourceNotAvailableException $exception) {
self::printInfoMessage(
$output,
self::getHeader(),
$output->writeln('Index not found. Skipping.')
);
}
} | [
"public",
"static",
"function",
"makeQueryAndPrintResults",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"callable",
"$",
"makeQuery",
")",
"{",
"$",
"query",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'query'",
")",
";",... | Make query and print results.
@param InputInterface $input
@param OutputInterface $output
@param callable $makeQuery | [
"Make",
"query",
"and",
"print",
"results",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/QueryCommand.php#L106-L140 | train |
apisearch-io/apisearch-bundle | Command/QueryCommand.php | QueryCommand.printResult | public static function printResult(
OutputInterface $output,
Result $result
) {
self::printInfoMessage(
$output,
'Number of resources in index',
$result->getTotalItems()
);
self::printInfoMessage(
$output,
'Number of hits',
$result->getTotalHits()
);
$output->writeln('');
foreach ($result->getItems() as $item) {
$firstStringPosition = array_reduce($item->getAllMetadata(), function ($carry, $element) {
return is_string($carry)
? $carry
: (
is_string($element)
? $element
: null
);
}, null);
self::printInfoMessage(
$output,
'x',
sprintf('%s - %s',
$item->getUUID()->composeUUID(),
substr((string) $firstStringPosition, 0, 50)
)
);
}
} | php | public static function printResult(
OutputInterface $output,
Result $result
) {
self::printInfoMessage(
$output,
'Number of resources in index',
$result->getTotalItems()
);
self::printInfoMessage(
$output,
'Number of hits',
$result->getTotalHits()
);
$output->writeln('');
foreach ($result->getItems() as $item) {
$firstStringPosition = array_reduce($item->getAllMetadata(), function ($carry, $element) {
return is_string($carry)
? $carry
: (
is_string($element)
? $element
: null
);
}, null);
self::printInfoMessage(
$output,
'x',
sprintf('%s - %s',
$item->getUUID()->composeUUID(),
substr((string) $firstStringPosition, 0, 50)
)
);
}
} | [
"public",
"static",
"function",
"printResult",
"(",
"OutputInterface",
"$",
"output",
",",
"Result",
"$",
"result",
")",
"{",
"self",
"::",
"printInfoMessage",
"(",
"$",
"output",
",",
"'Number of resources in index'",
",",
"$",
"result",
"->",
"getTotalItems",
... | Print results.
@param OutputInterface $output
@param Result $result | [
"Print",
"results",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/QueryCommand.php#L148-L186 | train |
apisearch-io/apisearch-bundle | Command/ImportIndexCommand.php | ImportIndexCommand.importFromFile | public static function importFromFile(
string $file,
OutputInterface $output,
callable $saveItems
): int {
$itemsBuffer = [];
$itemsNb = 0;
if (false !== ($handle = fopen($file, 'r'))) {
while (false !== ($data = fgetcsv($handle, 0, ','))) {
$itemAsArray = [
'uuid' => [
'id' => $data[0],
'type' => $data[1],
],
'metadata' => json_decode($data[2], true),
'indexed_metadata' => json_decode($data[3], true),
'searchable_metadata' => json_decode($data[4], true),
'exact_matching_metadata' => json_decode($data[5], true),
'suggest' => json_decode($data[6], true),
];
if (is_array($data[7])) {
$itemAsArray['coordinate'] = $data[7];
}
$item = Item::createFromArray($itemAsArray);
$itemsBuffer[] = $item;
++$itemsNb;
if (count($itemsBuffer) >= 500) {
$saveItems($itemsBuffer, false);
self::printPartialCountSaved($output, count($itemsBuffer));
$itemsBuffer = [];
}
}
$saveItems($itemsBuffer, true);
self::printPartialCountSaved($output, count($itemsBuffer));
}
fclose($handle);
return $itemsNb;
} | php | public static function importFromFile(
string $file,
OutputInterface $output,
callable $saveItems
): int {
$itemsBuffer = [];
$itemsNb = 0;
if (false !== ($handle = fopen($file, 'r'))) {
while (false !== ($data = fgetcsv($handle, 0, ','))) {
$itemAsArray = [
'uuid' => [
'id' => $data[0],
'type' => $data[1],
],
'metadata' => json_decode($data[2], true),
'indexed_metadata' => json_decode($data[3], true),
'searchable_metadata' => json_decode($data[4], true),
'exact_matching_metadata' => json_decode($data[5], true),
'suggest' => json_decode($data[6], true),
];
if (is_array($data[7])) {
$itemAsArray['coordinate'] = $data[7];
}
$item = Item::createFromArray($itemAsArray);
$itemsBuffer[] = $item;
++$itemsNb;
if (count($itemsBuffer) >= 500) {
$saveItems($itemsBuffer, false);
self::printPartialCountSaved($output, count($itemsBuffer));
$itemsBuffer = [];
}
}
$saveItems($itemsBuffer, true);
self::printPartialCountSaved($output, count($itemsBuffer));
}
fclose($handle);
return $itemsNb;
} | [
"public",
"static",
"function",
"importFromFile",
"(",
"string",
"$",
"file",
",",
"OutputInterface",
"$",
"output",
",",
"callable",
"$",
"saveItems",
")",
":",
"int",
"{",
"$",
"itemsBuffer",
"=",
"[",
"]",
";",
"$",
"itemsNb",
"=",
"0",
";",
"if",
"... | Import from file and return total number of elements.
@param string $file
@param OutputInterface $output
@param callable $saveItems
@return int | [
"Import",
"from",
"file",
"and",
"return",
"total",
"number",
"of",
"elements",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ImportIndexCommand.php#L88-L133 | train |
apisearch-io/apisearch-bundle | Command/ImportIndexCommand.php | ImportIndexCommand.printPartialCountSaved | private static function printPartialCountSaved(
OutputInterface $output,
int $count
) {
self::printInfoMessage(
$output,
self::getHeader(),
sprintf('Partial import of %d items', $count)
);
} | php | private static function printPartialCountSaved(
OutputInterface $output,
int $count
) {
self::printInfoMessage(
$output,
self::getHeader(),
sprintf('Partial import of %d items', $count)
);
} | [
"private",
"static",
"function",
"printPartialCountSaved",
"(",
"OutputInterface",
"$",
"output",
",",
"int",
"$",
"count",
")",
"{",
"self",
"::",
"printInfoMessage",
"(",
"$",
"output",
",",
"self",
"::",
"getHeader",
"(",
")",
",",
"sprintf",
"(",
"'Parti... | Print partial save.
@param OutputInterface $output
@param int $count | [
"Print",
"partial",
"save",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ImportIndexCommand.php#L141-L150 | train |
ezdeliveryco/snorlax | src/RestResource.php | RestResource.getPath | private function getPath(array $action, array $args)
{
$pattern = '/{(\d+)}/';
$callback = function ($matches) use ($args) {
return $args[$matches[1]];
};
return preg_replace_callback($pattern, $callback, $action['path']);
} | php | private function getPath(array $action, array $args)
{
$pattern = '/{(\d+)}/';
$callback = function ($matches) use ($args) {
return $args[$matches[1]];
};
return preg_replace_callback($pattern, $callback, $action['path']);
} | [
"private",
"function",
"getPath",
"(",
"array",
"$",
"action",
",",
"array",
"$",
"args",
")",
"{",
"$",
"pattern",
"=",
"'/{(\\d+)}/'",
";",
"$",
"callback",
"=",
"function",
"(",
"$",
"matches",
")",
"use",
"(",
"$",
"args",
")",
"{",
"return",
"$"... | Returns the URI path for the request
@param array $action
@param array $args
@return mixed | [
"Returns",
"the",
"URI",
"path",
"for",
"the",
"request"
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestResource.php#L69-L77 | train |
ezdeliveryco/snorlax | src/RestResource.php | RestResource.getParams | private function getParams(array $args)
{
if (count($args) == 0) {
return [];
}
$params = array_slice($args, -1)[0];
return is_array($params) ? $params : [];
} | php | private function getParams(array $args)
{
if (count($args) == 0) {
return [];
}
$params = array_slice($args, -1)[0];
return is_array($params) ? $params : [];
} | [
"private",
"function",
"getParams",
"(",
"array",
"$",
"args",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"args",
")",
"==",
"0",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"params",
"=",
"array_slice",
"(",
"$",
"args",
",",
"-",
"1",
")",
"[",... | Extracts the params from the arguments passed
@param $args array
@return array | [
"Extracts",
"the",
"params",
"from",
"the",
"arguments",
"passed"
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestResource.php#L86-L95 | train |
apisearch-io/apisearch-bundle | Command/ApisearchCommand.php | ApisearchCommand.configureFormatter | protected static function configureFormatter(OutputInterface $output)
{
$formatter = $output->getFormatter();
$formatter->setStyle('system', new OutputFormatterStyle('green'));
$formatter->setStyle('line', new OutputFormatterStyle('yellow'));
$formatter->setStyle('fail', new OutputFormatterStyle('red'));
$formatter->setStyle('info', new OutputFormatterStyle('blue'));
$formatter->setStyle('body', new OutputFormatterStyle('white'));
$formatter->setStyle('strong', new OutputFormatterStyle(null, null, ['bold']));
} | php | protected static function configureFormatter(OutputInterface $output)
{
$formatter = $output->getFormatter();
$formatter->setStyle('system', new OutputFormatterStyle('green'));
$formatter->setStyle('line', new OutputFormatterStyle('yellow'));
$formatter->setStyle('fail', new OutputFormatterStyle('red'));
$formatter->setStyle('info', new OutputFormatterStyle('blue'));
$formatter->setStyle('body', new OutputFormatterStyle('white'));
$formatter->setStyle('strong', new OutputFormatterStyle(null, null, ['bold']));
} | [
"protected",
"static",
"function",
"configureFormatter",
"(",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"formatter",
"=",
"$",
"output",
"->",
"getFormatter",
"(",
")",
";",
"$",
"formatter",
"->",
"setStyle",
"(",
"'system'",
",",
"new",
"OutputFormatt... | Configure formatter with Apisearch specific style.
@param OutputInterface $output | [
"Configure",
"formatter",
"with",
"Apisearch",
"specific",
"style",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ApisearchCommand.php#L70-L79 | train |
apisearch-io/apisearch-bundle | Command/ApisearchCommand.php | ApisearchCommand.printSystemMessage | protected static function printSystemMessage(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'system'
);
} | php | protected static function printSystemMessage(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'system'
);
} | [
"protected",
"static",
"function",
"printSystemMessage",
"(",
"OutputInterface",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
")",
"{",
"self",
"::",
"printStructureMessage",
"(",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
",",
"'system'",
... | Print system message.
@param OutputInterface $output
@param string $header
@param string $body | [
"Print",
"system",
"message",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ApisearchCommand.php#L88-L99 | train |
apisearch-io/apisearch-bundle | Command/ApisearchCommand.php | ApisearchCommand.printMessage | protected static function printMessage(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'line'
);
} | php | protected static function printMessage(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'line'
);
} | [
"protected",
"static",
"function",
"printMessage",
"(",
"OutputInterface",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
")",
"{",
"self",
"::",
"printStructureMessage",
"(",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
",",
"'line'",
")",
... | Print line message.
@param OutputInterface $output
@param string $header
@param string $body | [
"Print",
"line",
"message",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ApisearchCommand.php#L108-L119 | train |
apisearch-io/apisearch-bundle | Command/ApisearchCommand.php | ApisearchCommand.printInfoMessage | protected static function printInfoMessage(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'info'
);
} | php | protected static function printInfoMessage(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'info'
);
} | [
"protected",
"static",
"function",
"printInfoMessage",
"(",
"OutputInterface",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
")",
"{",
"self",
"::",
"printStructureMessage",
"(",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
",",
"'info'",
")... | Print info message.
@param OutputInterface $output
@param string $header
@param string $body | [
"Print",
"info",
"message",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ApisearchCommand.php#L128-L139 | train |
apisearch-io/apisearch-bundle | Command/ApisearchCommand.php | ApisearchCommand.printMessageFail | protected static function printMessageFail(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'fail'
);
} | php | protected static function printMessageFail(
OutputInterface $output,
$header,
$body
) {
self::printStructureMessage(
$output,
$header,
$body,
'fail'
);
} | [
"protected",
"static",
"function",
"printMessageFail",
"(",
"OutputInterface",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
")",
"{",
"self",
"::",
"printStructureMessage",
"(",
"$",
"output",
",",
"$",
"header",
",",
"$",
"body",
",",
"'fail'",
")... | Print fail message.
@param OutputInterface $output
@param string $header
@param string $body | [
"Print",
"fail",
"message",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ApisearchCommand.php#L148-L159 | train |
apisearch-io/apisearch-bundle | Command/ApisearchCommand.php | ApisearchCommand.getEndpoints | protected function getEndpoints(InputInterface $input): array
{
$endpointsName = $input->getOption('endpoint');
$endpoints = Endpoints::filter($endpointsName);
if (count($endpointsName) > count($endpoints)) {
throw new Exception(sprintf(
'Endpoint not found. Endpoints available: %s',
implode(', ', array_keys(Endpoints::all()))
));
}
return $endpoints;
} | php | protected function getEndpoints(InputInterface $input): array
{
$endpointsName = $input->getOption('endpoint');
$endpoints = Endpoints::filter($endpointsName);
if (count($endpointsName) > count($endpoints)) {
throw new Exception(sprintf(
'Endpoint not found. Endpoints available: %s',
implode(', ', array_keys(Endpoints::all()))
));
}
return $endpoints;
} | [
"protected",
"function",
"getEndpoints",
"(",
"InputInterface",
"$",
"input",
")",
":",
"array",
"{",
"$",
"endpointsName",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'endpoint'",
")",
";",
"$",
"endpoints",
"=",
"Endpoints",
"::",
"filter",
"(",
"$",
"en... | Get endpoint compositions given their names.
@param InputInterface $input
@return array
@throws Exception | [
"Get",
"endpoint",
"compositions",
"given",
"their",
"names",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/ApisearchCommand.php#L219-L232 | train |
apisearch-io/apisearch-bundle | Command/PrintTokensCommand.php | PrintTokensCommand.printTokens | public static function printTokens(
InputInterface $input,
OutputInterface $output,
array $tokens
) {
$withMetadata = $input->getOption('with-metadata');
$table = new Table($output);
$headers = ['UUID', 'Indices', 'endpoints', 'plugins', 'ttl'];
if ($withMetadata) {
$headers[] = 'Metadata';
}
$table->setHeaders($headers);
foreach ($tokens as $token) {
$row = [
$token->getTokenUUID()->composeUUID(),
implode(', ', array_map(function (IndexUUID $index) {
return $index->composeUUID();
}, $token->getIndices())),
implode(', ', $token->getEndpoints()),
implode(', ', $token->getPlugins()),
$token->getTtl(),
];
if ($withMetadata) {
$metadataRow = [];
foreach ($token->getMetadata() as $metadataField => $metadataValue) {
$metadataRow[] = sprintf("$metadataField = %s",
is_bool($metadataValue)
? $metadataValue ? 'true' : 'false'
: (
is_array($metadataValue)
? implode(', ', $metadataValue)
: (string) $metadataValue
)
);
}
$row[] = implode(PHP_EOL, $metadataRow);
}
$table->addRow($row);
}
$table->render();
} | php | public static function printTokens(
InputInterface $input,
OutputInterface $output,
array $tokens
) {
$withMetadata = $input->getOption('with-metadata');
$table = new Table($output);
$headers = ['UUID', 'Indices', 'endpoints', 'plugins', 'ttl'];
if ($withMetadata) {
$headers[] = 'Metadata';
}
$table->setHeaders($headers);
foreach ($tokens as $token) {
$row = [
$token->getTokenUUID()->composeUUID(),
implode(', ', array_map(function (IndexUUID $index) {
return $index->composeUUID();
}, $token->getIndices())),
implode(', ', $token->getEndpoints()),
implode(', ', $token->getPlugins()),
$token->getTtl(),
];
if ($withMetadata) {
$metadataRow = [];
foreach ($token->getMetadata() as $metadataField => $metadataValue) {
$metadataRow[] = sprintf("$metadataField = %s",
is_bool($metadataValue)
? $metadataValue ? 'true' : 'false'
: (
is_array($metadataValue)
? implode(', ', $metadataValue)
: (string) $metadataValue
)
);
}
$row[] = implode(PHP_EOL, $metadataRow);
}
$table->addRow($row);
}
$table->render();
} | [
"public",
"static",
"function",
"printTokens",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"array",
"$",
"tokens",
")",
"{",
"$",
"withMetadata",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'with-metadata'",
")",
";",
"$"... | Print tokens.
@param InputInterface $input
@param OutputInterface $output
@param Token[] $tokens | [
"Print",
"tokens",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/PrintTokensCommand.php#L103-L147 | train |
ezdeliveryco/snorlax | src/RestPool.php | RestPool.addResource | public function addResource($name, RestClient $client, $route, $params = [])
{
$this->resources[$name] = $this->buildRequest($client, $route, $params);
} | php | public function addResource($name, RestClient $client, $route, $params = [])
{
$this->resources[$name] = $this->buildRequest($client, $route, $params);
} | [
"public",
"function",
"addResource",
"(",
"$",
"name",
",",
"RestClient",
"$",
"client",
",",
"$",
"route",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"resources",
"[",
"$",
"name",
"]",
"=",
"$",
"this",
"->",
"buildRequest",
... | Add new resource to request pool
@param string $name
@param RestClient $client
@param string $route
@param array $params | [
"Add",
"new",
"resource",
"to",
"request",
"pool"
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestPool.php#L29-L32 | train |
ezdeliveryco/snorlax | src/RestPool.php | RestPool.buildRequest | private function buildRequest($client, $route, $params)
{
list($resource, $method) = $this->explodeRoute($route);
if (array_key_exists('parameters', $params)) {
$parameters = $params['parameters'];
unset($params['parameters']);
return call_user_func_array(
[ $client->setAsync()->{$resource}, $method ],
array_merge($parameters, [$params])
);
}
return $client->setAsync()->{$resource}->{$method}($params);
} | php | private function buildRequest($client, $route, $params)
{
list($resource, $method) = $this->explodeRoute($route);
if (array_key_exists('parameters', $params)) {
$parameters = $params['parameters'];
unset($params['parameters']);
return call_user_func_array(
[ $client->setAsync()->{$resource}, $method ],
array_merge($parameters, [$params])
);
}
return $client->setAsync()->{$resource}->{$method}($params);
} | [
"private",
"function",
"buildRequest",
"(",
"$",
"client",
",",
"$",
"route",
",",
"$",
"params",
")",
"{",
"list",
"(",
"$",
"resource",
",",
"$",
"method",
")",
"=",
"$",
"this",
"->",
"explodeRoute",
"(",
"$",
"route",
")",
";",
"if",
"(",
"arra... | Build a async request using the injected client
@param RestClient $client
@param string $route
@param array $params
@return RestClient | [
"Build",
"a",
"async",
"request",
"using",
"the",
"injected",
"client"
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestPool.php#L43-L58 | train |
ezdeliveryco/snorlax | src/RestPool.php | RestPool.send | public function send()
{
$responses = new \StdClass();
foreach ($this->resources as $key => $promise) {
$response = $promise->wait();
$responses->{$key} = $this->parse($response->getBody());
}
return $responses;
} | php | public function send()
{
$responses = new \StdClass();
foreach ($this->resources as $key => $promise) {
$response = $promise->wait();
$responses->{$key} = $this->parse($response->getBody());
}
return $responses;
} | [
"public",
"function",
"send",
"(",
")",
"{",
"$",
"responses",
"=",
"new",
"\\",
"StdClass",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"resources",
"as",
"$",
"key",
"=>",
"$",
"promise",
")",
"{",
"$",
"response",
"=",
"$",
"promise",
"->"... | Send and parse the request pool
@return \StdClass | [
"Send",
"and",
"parse",
"the",
"request",
"pool"
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestPool.php#L85-L95 | train |
ezdeliveryco/snorlax | src/RestClient.php | RestClient.createDefaultClient | private function createDefaultClient(array $params)
{
$stack = HandlerStack::create();
if (isset($params['cache']) && $params['cache'] === true) {
$cache = new CacheMiddleware($this->getCacheStrategy());
$stack->push($cache, 'snorlax-cache');
}
if (isset($params['log']) && $params['log'] === true) {
$logger = new Logger($this->getLogger());
$logger->setLogLevel(LogLevel::DEBUG);
$logger->setRequestLoggingEnabled();
$logger->setFormatter(new MessageFormatter(
'REQ "{method} {target} HTTP/{version}"',
'RES "{method} {target} HTTP/{version}" {code}'
));
$stack->push($logger, 'snorlax-logger');
}
$params = array_merge($params, ['handler' => $stack]);
return new Client($params);
} | php | private function createDefaultClient(array $params)
{
$stack = HandlerStack::create();
if (isset($params['cache']) && $params['cache'] === true) {
$cache = new CacheMiddleware($this->getCacheStrategy());
$stack->push($cache, 'snorlax-cache');
}
if (isset($params['log']) && $params['log'] === true) {
$logger = new Logger($this->getLogger());
$logger->setLogLevel(LogLevel::DEBUG);
$logger->setRequestLoggingEnabled();
$logger->setFormatter(new MessageFormatter(
'REQ "{method} {target} HTTP/{version}"',
'RES "{method} {target} HTTP/{version}" {code}'
));
$stack->push($logger, 'snorlax-logger');
}
$params = array_merge($params, ['handler' => $stack]);
return new Client($params);
} | [
"private",
"function",
"createDefaultClient",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"stack",
"=",
"HandlerStack",
"::",
"create",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"params",
"[",
"'cache'",
"]",
")",
"&&",
"$",
"params",
"[",
"'cache'"... | Creates a new default client based on the given parameters
@param array $params
@return \GuzzleHttp\Client | [
"Creates",
"a",
"new",
"default",
"client",
"based",
"on",
"the",
"given",
"parameters"
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestClient.php#L203-L228 | train |
ezdeliveryco/snorlax | src/RestClient.php | RestClient.getResource | public function getResource($resource)
{
if (array_key_exists($resource, $this->cache)) {
return $this->cache[$resource];
}
if (!array_key_exists($resource, $this->resources)) {
throw new ResourceNotImplemented($resource);
}
$params = $this->resources[$resource];
$instance = $params['instance'];
if (is_null($instance)) {
$class = $params['class'];
$instance = new $class($this);
}
return $this->cache[$resource] = $instance;
} | php | public function getResource($resource)
{
if (array_key_exists($resource, $this->cache)) {
return $this->cache[$resource];
}
if (!array_key_exists($resource, $this->resources)) {
throw new ResourceNotImplemented($resource);
}
$params = $this->resources[$resource];
$instance = $params['instance'];
if (is_null($instance)) {
$class = $params['class'];
$instance = new $class($this);
}
return $this->cache[$resource] = $instance;
} | [
"public",
"function",
"getResource",
"(",
"$",
"resource",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"resource",
",",
"$",
"this",
"->",
"cache",
")",
")",
"{",
"return",
"$",
"this",
"->",
"cache",
"[",
"$",
"resource",
"]",
";",
"}",
"if",... | Instantiates and returns the asked resource.
@param string $resource The resource name
@throws \Snorlax\Exception\ResourceNotImplemented If the resource is not available
@return \Snorlax\Resource The instantiated resource | [
"Instantiates",
"and",
"returns",
"the",
"asked",
"resource",
"."
] | b7f40413f5954c6c71f7f9a7c7accfd1ec87d606 | https://github.com/ezdeliveryco/snorlax/blob/b7f40413f5954c6c71f7f9a7c7accfd1ec87d606/src/RestClient.php#L238-L258 | train |
apisearch-io/apisearch-bundle | DependencyInjection/CompilerPass/RepositoryCompilerPass.php | RepositoryCompilerPass.createClientRetryMap | private function createClientRetryMap(
ContainerBuilder $container,
string $name,
array $repositoryConfiguration
) {
if (!$this->repositoryIsHttp($repositoryConfiguration)) {
return;
}
$clientRetryMapName = rtrim("apisearch.retry_map_$name", '.');
$container
->register($clientRetryMapName, RetryMap::class)
->setFactory([
RetryMap::class,
'createFromArray',
])
->setArgument(0, $repositoryConfiguration['http']['retry_map']);
} | php | private function createClientRetryMap(
ContainerBuilder $container,
string $name,
array $repositoryConfiguration
) {
if (!$this->repositoryIsHttp($repositoryConfiguration)) {
return;
}
$clientRetryMapName = rtrim("apisearch.retry_map_$name", '.');
$container
->register($clientRetryMapName, RetryMap::class)
->setFactory([
RetryMap::class,
'createFromArray',
])
->setArgument(0, $repositoryConfiguration['http']['retry_map']);
} | [
"private",
"function",
"createClientRetryMap",
"(",
"ContainerBuilder",
"$",
"container",
",",
"string",
"$",
"name",
",",
"array",
"$",
"repositoryConfiguration",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"repositoryIsHttp",
"(",
"$",
"repositoryConfiguration"... | Create client retry map.
@param ContainerBuilder $container
@param string $name
@param string $name
@param array $repositoryConfiguration | [
"Create",
"client",
"retry",
"map",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/DependencyInjection/CompilerPass/RepositoryCompilerPass.php#L168-L185 | train |
apisearch-io/apisearch-bundle | DependencyInjection/CompilerPass/RepositoryCompilerPass.php | RepositoryCompilerPass.createSearchRepository | private function createSearchRepository(
ContainerBuilder $container,
string $name,
array $repositoryConfiguration,
string $indexName
) {
$repositoryName = "apisearch.repository_$name.$indexName";
$repositoryTransformableName = "apisearch.repository_transformable_$name.$indexName";
$clientName = "apisearch.client_$name";
switch ($repositoryConfiguration['adapter']) {
case 'in_memory':
$repositoryDefinition = $container
->register($repositoryName, InMemoryRepository::class)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'disk':
$repositoryDefinition = $container
->register($repositoryName, DiskRepository::class)
->addArgument($repositoryConfiguration['disk_file'].'.'.$name)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'http':
case 'http_test':
$repositoryDefinition = $container
->register($repositoryName, HttpRepository::class)
->addArgument(new Reference($clientName))
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'service':
$container->setAlias($repositoryName, $repositoryConfiguration['search']['repository_service']);
$aliasDefinition = $container->getAlias($repositoryName);
$aliasDefinition->setPublic($this->repositoryIsTest($repositoryConfiguration));
$repositoryDefinition = $container->getDefinition($repositoryConfiguration['search']['repository_service']);
break;
}
$this->injectRepositoryCredentials(
$repositoryDefinition,
$name,
$repositoryConfiguration,
$indexName
);
$definition = $container
->register($repositoryTransformableName, TransformableRepository::class)
->setDecoratedService($repositoryName)
->addArgument(new Reference($repositoryTransformableName.'.inner'))
->addArgument(new Reference('apisearch.transformer'))
->setPublic($this->repositoryIsTest($repositoryConfiguration));
$this->injectRepositoryCredentials(
$definition,
$name,
$repositoryConfiguration,
$indexName
);
$container
->getDefinition('apisearch.repository_bucket')
->addMethodCall(
'addRepository',
[$name, $indexName, new Reference($repositoryName)]
)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
} | php | private function createSearchRepository(
ContainerBuilder $container,
string $name,
array $repositoryConfiguration,
string $indexName
) {
$repositoryName = "apisearch.repository_$name.$indexName";
$repositoryTransformableName = "apisearch.repository_transformable_$name.$indexName";
$clientName = "apisearch.client_$name";
switch ($repositoryConfiguration['adapter']) {
case 'in_memory':
$repositoryDefinition = $container
->register($repositoryName, InMemoryRepository::class)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'disk':
$repositoryDefinition = $container
->register($repositoryName, DiskRepository::class)
->addArgument($repositoryConfiguration['disk_file'].'.'.$name)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'http':
case 'http_test':
$repositoryDefinition = $container
->register($repositoryName, HttpRepository::class)
->addArgument(new Reference($clientName))
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'service':
$container->setAlias($repositoryName, $repositoryConfiguration['search']['repository_service']);
$aliasDefinition = $container->getAlias($repositoryName);
$aliasDefinition->setPublic($this->repositoryIsTest($repositoryConfiguration));
$repositoryDefinition = $container->getDefinition($repositoryConfiguration['search']['repository_service']);
break;
}
$this->injectRepositoryCredentials(
$repositoryDefinition,
$name,
$repositoryConfiguration,
$indexName
);
$definition = $container
->register($repositoryTransformableName, TransformableRepository::class)
->setDecoratedService($repositoryName)
->addArgument(new Reference($repositoryTransformableName.'.inner'))
->addArgument(new Reference('apisearch.transformer'))
->setPublic($this->repositoryIsTest($repositoryConfiguration));
$this->injectRepositoryCredentials(
$definition,
$name,
$repositoryConfiguration,
$indexName
);
$container
->getDefinition('apisearch.repository_bucket')
->addMethodCall(
'addRepository',
[$name, $indexName, new Reference($repositoryName)]
)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
} | [
"private",
"function",
"createSearchRepository",
"(",
"ContainerBuilder",
"$",
"container",
",",
"string",
"$",
"name",
",",
"array",
"$",
"repositoryConfiguration",
",",
"string",
"$",
"indexName",
")",
"{",
"$",
"repositoryName",
"=",
"\"apisearch.repository_$name.$... | Create a repository by connection configuration.
@param ContainerBuilder $container
@param string $name
@param array $repositoryConfiguration
@param string $indexName | [
"Create",
"a",
"repository",
"by",
"connection",
"configuration",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/DependencyInjection/CompilerPass/RepositoryCompilerPass.php#L233-L301 | train |
apisearch-io/apisearch-bundle | DependencyInjection/CompilerPass/RepositoryCompilerPass.php | RepositoryCompilerPass.createStandardRepository | private function createStandardRepository(
ContainerBuilder $container,
string $appName,
array $repositoryConfiguration,
string $indexName,
string $prefix,
string $inMemoryRepositoryNamespace,
string $diskRepositoryNamespace,
string $httpRepositoryNamespace
) {
$repositoryName = rtrim("apisearch.{$prefix}_repository_$appName.$indexName", '.');
$tokenUUIDName = rtrim("apisearch.token_uuid.$appName");
$clientName = rtrim("apisearch.client_$appName", '.');
$tokenUUIDReference = $container->register($tokenUUIDName, TokenUUID::class);
$tokenUUIDReference
->setFactory([
TokenUUID::class,
'createById',
])
->addArgument((string) $repositoryConfiguration['token'])
->setPrivate(true);
$repositoryReferenceName = rtrim("apisearch.repository_reference.$appName.$indexName", '.');
$repositoryReferenceReference = new Reference($repositoryReferenceName);
switch ($repositoryConfiguration['adapter']) {
case 'in_memory':
$container
->register($repositoryName, $inMemoryRepositoryNamespace)
->addMethodCall('setRepositoryReference', [
$repositoryReferenceReference,
])
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'disk':
$container
->register($repositoryName, $diskRepositoryNamespace)
->addMethodCall('setRepositoryReference', [
$repositoryReferenceReference,
])
->addArgument($repositoryConfiguration['disk_file'].'.'.$prefix.'.'.$appName)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'http':
case 'http_test':
$container
->register($repositoryName, $httpRepositoryNamespace)
->addArgument(new Reference($clientName))
->addMethodCall('setCredentials', [
$repositoryReferenceReference,
new Reference($tokenUUIDName),
])
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'service':
$repoDefinition = $container->getDefinition($repositoryConfiguration[$prefix]['repository_service']);
$this->injectRepositoryCredentials(
$repoDefinition,
$appName,
$repositoryConfiguration,
$indexName
);
$container->setAlias($repositoryName, $repositoryConfiguration[$prefix]['repository_service']);
$aliasDefinition = $container->getAlias($repositoryName);
$aliasDefinition->setPublic($this->repositoryIsTest($repositoryConfiguration));
}
$container
->getDefinition("apisearch.{$prefix}_repository_bucket")
->addMethodCall(
'addRepository',
[$appName, new Reference($repositoryName)]
)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
} | php | private function createStandardRepository(
ContainerBuilder $container,
string $appName,
array $repositoryConfiguration,
string $indexName,
string $prefix,
string $inMemoryRepositoryNamespace,
string $diskRepositoryNamespace,
string $httpRepositoryNamespace
) {
$repositoryName = rtrim("apisearch.{$prefix}_repository_$appName.$indexName", '.');
$tokenUUIDName = rtrim("apisearch.token_uuid.$appName");
$clientName = rtrim("apisearch.client_$appName", '.');
$tokenUUIDReference = $container->register($tokenUUIDName, TokenUUID::class);
$tokenUUIDReference
->setFactory([
TokenUUID::class,
'createById',
])
->addArgument((string) $repositoryConfiguration['token'])
->setPrivate(true);
$repositoryReferenceName = rtrim("apisearch.repository_reference.$appName.$indexName", '.');
$repositoryReferenceReference = new Reference($repositoryReferenceName);
switch ($repositoryConfiguration['adapter']) {
case 'in_memory':
$container
->register($repositoryName, $inMemoryRepositoryNamespace)
->addMethodCall('setRepositoryReference', [
$repositoryReferenceReference,
])
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'disk':
$container
->register($repositoryName, $diskRepositoryNamespace)
->addMethodCall('setRepositoryReference', [
$repositoryReferenceReference,
])
->addArgument($repositoryConfiguration['disk_file'].'.'.$prefix.'.'.$appName)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'http':
case 'http_test':
$container
->register($repositoryName, $httpRepositoryNamespace)
->addArgument(new Reference($clientName))
->addMethodCall('setCredentials', [
$repositoryReferenceReference,
new Reference($tokenUUIDName),
])
->setPublic($this->repositoryIsTest($repositoryConfiguration));
break;
case 'service':
$repoDefinition = $container->getDefinition($repositoryConfiguration[$prefix]['repository_service']);
$this->injectRepositoryCredentials(
$repoDefinition,
$appName,
$repositoryConfiguration,
$indexName
);
$container->setAlias($repositoryName, $repositoryConfiguration[$prefix]['repository_service']);
$aliasDefinition = $container->getAlias($repositoryName);
$aliasDefinition->setPublic($this->repositoryIsTest($repositoryConfiguration));
}
$container
->getDefinition("apisearch.{$prefix}_repository_bucket")
->addMethodCall(
'addRepository',
[$appName, new Reference($repositoryName)]
)
->setPublic($this->repositoryIsTest($repositoryConfiguration));
} | [
"private",
"function",
"createStandardRepository",
"(",
"ContainerBuilder",
"$",
"container",
",",
"string",
"$",
"appName",
",",
"array",
"$",
"repositoryConfiguration",
",",
"string",
"$",
"indexName",
",",
"string",
"$",
"prefix",
",",
"string",
"$",
"inMemoryR... | Create standard repository.
@param ContainerBuilder $container
@param string $appName
@param array $repositoryConfiguration
@param string $indexName
@param string $prefix
@param string $inMemoryRepositoryNamespace
@param string $diskRepositoryNamespace
@param string $httpRepositoryNamespace | [
"Create",
"standard",
"repository",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/DependencyInjection/CompilerPass/RepositoryCompilerPass.php#L315-L394 | train |
apisearch-io/apisearch-bundle | DependencyInjection/CompilerPass/RepositoryCompilerPass.php | RepositoryCompilerPass.injectRepositoryCredentials | private function injectRepositoryCredentials(
Definition $definition,
string $appName,
array $repositoryConfiguration,
string $indexName
) {
if ($repositoryConfiguration['app_id']) {
$repositoryReferenceName = rtrim("apisearch.repository_reference.$appName.$indexName", '.');
$tokenUUIDName = rtrim("apisearch.token_uuid.$appName");
$repositoryReferenceReference = new Reference($repositoryReferenceName);
$repositoryConfiguration['token']
? $definition->addMethodCall('setCredentials', [
$repositoryReferenceReference,
new Reference($tokenUUIDName),
])
: $definition->addMethodCall('setRepositoryReference', [
$repositoryReferenceReference,
]);
}
} | php | private function injectRepositoryCredentials(
Definition $definition,
string $appName,
array $repositoryConfiguration,
string $indexName
) {
if ($repositoryConfiguration['app_id']) {
$repositoryReferenceName = rtrim("apisearch.repository_reference.$appName.$indexName", '.');
$tokenUUIDName = rtrim("apisearch.token_uuid.$appName");
$repositoryReferenceReference = new Reference($repositoryReferenceName);
$repositoryConfiguration['token']
? $definition->addMethodCall('setCredentials', [
$repositoryReferenceReference,
new Reference($tokenUUIDName),
])
: $definition->addMethodCall('setRepositoryReference', [
$repositoryReferenceReference,
]);
}
} | [
"private",
"function",
"injectRepositoryCredentials",
"(",
"Definition",
"$",
"definition",
",",
"string",
"$",
"appName",
",",
"array",
"$",
"repositoryConfiguration",
",",
"string",
"$",
"indexName",
")",
"{",
"if",
"(",
"$",
"repositoryConfiguration",
"[",
"'ap... | Inject credentials in repository.
@param Definition $definition
@param string $appName
@param array $repositoryConfiguration
@param string $indexName | [
"Inject",
"credentials",
"in",
"repository",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/DependencyInjection/CompilerPass/RepositoryCompilerPass.php#L404-L424 | train |
apisearch-io/apisearch-bundle | DependencyInjection/CompilerPass/RepositoryCompilerPass.php | RepositoryCompilerPass.createRepositoryReferenceServiceReference | private function createRepositoryReferenceServiceReference(
ContainerBuilder $container,
string $appName,
array $repositoryConfiguration,
string $indexId,
string $indexName
): Definition {
$repositoryReferenceName = rtrim("apisearch.repository_reference.$appName.$indexName", '.');
$appUUIDReference = $container->register("apisearch.app_uuid.$appName", AppUUID::class);
$appUUIDReference
->setFactory([
AppUUID::class,
'createById',
])
->addArgument((string) $repositoryConfiguration['app_id'])
->setPrivate(true);
$indexUUIDReference = $container->register("apisearch.index_uuid.$appName.$indexName", IndexUUID::class);
$indexUUIDReference
->setFactory([
IndexUUID::class,
'createById',
])
->addArgument((string) $indexId)
->setPrivate(true);
$reference = $container->register($repositoryReferenceName, RepositoryReference::class);
$reference
->setFactory([
RepositoryReference::class,
'create',
])
->addArgument(new Reference("apisearch.app_uuid.$appName"))
->addArgument(new Reference("apisearch.index_uuid.$appName.$indexName"))
->setPublic($this->repositoryIsTest($repositoryConfiguration));
return $reference;
} | php | private function createRepositoryReferenceServiceReference(
ContainerBuilder $container,
string $appName,
array $repositoryConfiguration,
string $indexId,
string $indexName
): Definition {
$repositoryReferenceName = rtrim("apisearch.repository_reference.$appName.$indexName", '.');
$appUUIDReference = $container->register("apisearch.app_uuid.$appName", AppUUID::class);
$appUUIDReference
->setFactory([
AppUUID::class,
'createById',
])
->addArgument((string) $repositoryConfiguration['app_id'])
->setPrivate(true);
$indexUUIDReference = $container->register("apisearch.index_uuid.$appName.$indexName", IndexUUID::class);
$indexUUIDReference
->setFactory([
IndexUUID::class,
'createById',
])
->addArgument((string) $indexId)
->setPrivate(true);
$reference = $container->register($repositoryReferenceName, RepositoryReference::class);
$reference
->setFactory([
RepositoryReference::class,
'create',
])
->addArgument(new Reference("apisearch.app_uuid.$appName"))
->addArgument(new Reference("apisearch.index_uuid.$appName.$indexName"))
->setPublic($this->repositoryIsTest($repositoryConfiguration));
return $reference;
} | [
"private",
"function",
"createRepositoryReferenceServiceReference",
"(",
"ContainerBuilder",
"$",
"container",
",",
"string",
"$",
"appName",
",",
"array",
"$",
"repositoryConfiguration",
",",
"string",
"$",
"indexId",
",",
"string",
"$",
"indexName",
")",
":",
"Def... | Crate Repository Reference service reference.
@param ContainerBuilder $container
@param string $appName
@param array $repositoryConfiguration
@param string $indexId
@param string $indexName
@return Definition | [
"Crate",
"Repository",
"Reference",
"service",
"reference",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/DependencyInjection/CompilerPass/RepositoryCompilerPass.php#L437-L474 | train |
apisearch-io/apisearch-bundle | Command/PrintIndicesCommand.php | PrintIndicesCommand.printIndices | public static function printIndices(
InputInterface $input,
OutputInterface $output,
array $indices
) {
$hasIndices = !empty($indices);
$table = new Table($output);
$headers = ['UUID', 'App ID', 'Doc Count', 'Size', 'Ok?', 'shards', 'replicas'];
$withMetadata = $input->getOption('with-metadata');
$withFields = $input->getOption('with-fields');
if ($hasIndices && $withFields) {
$headers[] = 'Fields';
}
if ($hasIndices && $withMetadata) {
foreach ($indices[0]->getMetadata() as $field => $_) {
$headers[] = ucfirst($field);
}
}
$table->setHeaders($headers);
/*
* @var Index
*/
foreach ($indices as $index) {
$row = [
$index->getUUID()->composeUUID(),
$index->getAppUUID()->composeUUID(),
$index->getDocCount(),
$index->getSize(),
$index->isOK()
? 'Yes'
: 'No',
$index->getShards(),
$index->getReplicas(),
];
if ($withFields) {
$fields = $index->getFields();
array_walk($fields, function (string &$type, string $field) {
$type = "$field: $type";
});
$row[] = implode("\n", $fields);
}
if ($withMetadata) {
foreach ($index->getMetadata() as $_ => $value) {
$row[] = $value;
}
}
$table->addRow($row);
}
$table->render();
} | php | public static function printIndices(
InputInterface $input,
OutputInterface $output,
array $indices
) {
$hasIndices = !empty($indices);
$table = new Table($output);
$headers = ['UUID', 'App ID', 'Doc Count', 'Size', 'Ok?', 'shards', 'replicas'];
$withMetadata = $input->getOption('with-metadata');
$withFields = $input->getOption('with-fields');
if ($hasIndices && $withFields) {
$headers[] = 'Fields';
}
if ($hasIndices && $withMetadata) {
foreach ($indices[0]->getMetadata() as $field => $_) {
$headers[] = ucfirst($field);
}
}
$table->setHeaders($headers);
/*
* @var Index
*/
foreach ($indices as $index) {
$row = [
$index->getUUID()->composeUUID(),
$index->getAppUUID()->composeUUID(),
$index->getDocCount(),
$index->getSize(),
$index->isOK()
? 'Yes'
: 'No',
$index->getShards(),
$index->getReplicas(),
];
if ($withFields) {
$fields = $index->getFields();
array_walk($fields, function (string &$type, string $field) {
$type = "$field: $type";
});
$row[] = implode("\n", $fields);
}
if ($withMetadata) {
foreach ($index->getMetadata() as $_ => $value) {
$row[] = $value;
}
}
$table->addRow($row);
}
$table->render();
} | [
"public",
"static",
"function",
"printIndices",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"array",
"$",
"indices",
")",
"{",
"$",
"hasIndices",
"=",
"!",
"empty",
"(",
"$",
"indices",
")",
";",
"$",
"table",
"=",
"n... | Print indices.
@param InputInterface $input
@param OutputInterface $output
@param Index[] $indices | [
"Print",
"indices",
"."
] | 70d34ee385d85aa12d291436892ffd2f432583ad | https://github.com/apisearch-io/apisearch-bundle/blob/70d34ee385d85aa12d291436892ffd2f432583ad/Command/PrintIndicesCommand.php#L86-L141 | train |
traderinteractive/dws-coding-standard | DWS/Helpers/WhiteSpace.php | DWS_Helpers_Whitespace.indentOfLine | public static function indentOfLine(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$beginningElement = $stackPtr;
$previousElement = $phpcsFile->findPrevious(T_WHITESPACE, $beginningElement - 1, null, true);
while ($previousElement !== false && $tokens[$previousElement]['line'] === $tokens[$stackPtr]['line']) {
$beginningElement = $previousElement;
$previousElement = $phpcsFile->findPrevious(T_WHITESPACE, $beginningElement - 1, null, true);
}
return $tokens[$beginningElement]['column'];
} | php | public static function indentOfLine(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$beginningElement = $stackPtr;
$previousElement = $phpcsFile->findPrevious(T_WHITESPACE, $beginningElement - 1, null, true);
while ($previousElement !== false && $tokens[$previousElement]['line'] === $tokens[$stackPtr]['line']) {
$beginningElement = $previousElement;
$previousElement = $phpcsFile->findPrevious(T_WHITESPACE, $beginningElement - 1, null, true);
}
return $tokens[$beginningElement]['column'];
} | [
"public",
"static",
"function",
"indentOfLine",
"(",
"PHP_CodeSniffer_File",
"$",
"phpcsFile",
",",
"$",
"stackPtr",
")",
"{",
"$",
"tokens",
"=",
"$",
"phpcsFile",
"->",
"getTokens",
"(",
")",
";",
"$",
"beginningElement",
"=",
"$",
"stackPtr",
";",
"$",
... | Returns the indentation level of the requested line.
@param PHP_CodeSniffer_File $phpcsFile The file in question.
@param int $stackPtr The stack pointer to the element on the line in question.
@return int The normalized column number for the initial non-whitespace token on the line. | [
"Returns",
"the",
"indentation",
"level",
"of",
"the",
"requested",
"line",
"."
] | c1e8da9f16a7fcf36d5f2a664a3514fb98261ad5 | https://github.com/traderinteractive/dws-coding-standard/blob/c1e8da9f16a7fcf36d5f2a664a3514fb98261ad5/DWS/Helpers/WhiteSpace.php#L25-L36 | train |
yiisoft/yii2-jui | src/Widget.php | Widget.registerClientOptions | protected function registerClientOptions($name, $id)
{
if ($this->clientOptions !== false) {
$options = empty($this->clientOptions) ? '' : Json::htmlEncode($this->clientOptions);
$js = "jQuery('#$id').$name($options);";
$this->getView()->registerJs($js);
}
} | php | protected function registerClientOptions($name, $id)
{
if ($this->clientOptions !== false) {
$options = empty($this->clientOptions) ? '' : Json::htmlEncode($this->clientOptions);
$js = "jQuery('#$id').$name($options);";
$this->getView()->registerJs($js);
}
} | [
"protected",
"function",
"registerClientOptions",
"(",
"$",
"name",
",",
"$",
"id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"clientOptions",
"!==",
"false",
")",
"{",
"$",
"options",
"=",
"empty",
"(",
"$",
"this",
"->",
"clientOptions",
")",
"?",
"''"... | Registers a specific jQuery UI widget options
@param string $name the name of the jQuery UI widget
@param string $id the ID of the widget | [
"Registers",
"a",
"specific",
"jQuery",
"UI",
"widget",
"options"
] | 49d2f37852f5b9ce6cf43b2467c77bdb6710c340 | https://github.com/yiisoft/yii2-jui/blob/49d2f37852f5b9ce6cf43b2467c77bdb6710c340/src/Widget.php#L74-L81 | train |
yiisoft/yii2-jui | src/Widget.php | Widget.registerClientEvents | protected function registerClientEvents($name, $id)
{
if (!empty($this->clientEvents)) {
$js = [];
foreach ($this->clientEvents as $event => $handler) {
if (isset($this->clientEventMap[$event])) {
$eventName = $this->clientEventMap[$event];
} else {
$eventName = strtolower($name . $event);
}
$js[] = "jQuery('#$id').on('$eventName', $handler);";
}
$this->getView()->registerJs(implode("\n", $js));
}
} | php | protected function registerClientEvents($name, $id)
{
if (!empty($this->clientEvents)) {
$js = [];
foreach ($this->clientEvents as $event => $handler) {
if (isset($this->clientEventMap[$event])) {
$eventName = $this->clientEventMap[$event];
} else {
$eventName = strtolower($name . $event);
}
$js[] = "jQuery('#$id').on('$eventName', $handler);";
}
$this->getView()->registerJs(implode("\n", $js));
}
} | [
"protected",
"function",
"registerClientEvents",
"(",
"$",
"name",
",",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"clientEvents",
")",
")",
"{",
"$",
"js",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"clientEv... | Registers a specific jQuery UI widget events
@param string $name the name of the jQuery UI widget
@param string $id the ID of the widget | [
"Registers",
"a",
"specific",
"jQuery",
"UI",
"widget",
"events"
] | 49d2f37852f5b9ce6cf43b2467c77bdb6710c340 | https://github.com/yiisoft/yii2-jui/blob/49d2f37852f5b9ce6cf43b2467c77bdb6710c340/src/Widget.php#L88-L102 | train |
yiisoft/yii2-jui | src/Widget.php | Widget.registerWidget | protected function registerWidget($name, $id = null)
{
if ($id === null) {
$id = $this->options['id'];
}
JuiAsset::register($this->getView());
$this->registerClientEvents($name, $id);
$this->registerClientOptions($name, $id);
} | php | protected function registerWidget($name, $id = null)
{
if ($id === null) {
$id = $this->options['id'];
}
JuiAsset::register($this->getView());
$this->registerClientEvents($name, $id);
$this->registerClientOptions($name, $id);
} | [
"protected",
"function",
"registerWidget",
"(",
"$",
"name",
",",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"id",
"===",
"null",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"options",
"[",
"'id'",
"]",
";",
"}",
"JuiAsset",
"::",
"regist... | Registers a specific jQuery UI widget asset bundle, initializes it with client options and registers related events
@param string $name the name of the jQuery UI widget
@param string $id the ID of the widget. If null, it will use the `id` value of [[options]]. | [
"Registers",
"a",
"specific",
"jQuery",
"UI",
"widget",
"asset",
"bundle",
"initializes",
"it",
"with",
"client",
"options",
"and",
"registers",
"related",
"events"
] | 49d2f37852f5b9ce6cf43b2467c77bdb6710c340 | https://github.com/yiisoft/yii2-jui/blob/49d2f37852f5b9ce6cf43b2467c77bdb6710c340/src/Widget.php#L109-L117 | train |
TCB13/thunder-tus-php | src/Server.php | Server.handle | public function handle(): Server
{
// Check the upload directory
if (!is_dir($this->uploadDir))
throw new ThunderTUSException("Invalid upload directory. Path wasn't set, it doesn't exist or it isn't a directory.");
// Call handlers
$method = "handle" . $this->request->getMethod();
if (!method_exists($this, $method))
throw new ThunderTUSException("Invalid HTTP request method. Not TUS or ThunderTUS compliant.");
// Check if this server supports the client protocol version
if ($this->request->getHeaderLine("Tus-Resumable") != self::PROTOCOL_VERSION) {
$this->response = $this->response->withStatus(412);
return $this;
}
// Gather the filename from the last part of the URL and set the resource location
$this->apiPath = rtrim($this->apiPath, "/") . "/";
$this->uploadDir = rtrim(realpath($this->uploadDir), \DIRECTORY_SEPARATOR) . \DIRECTORY_SEPARATOR;
$url = $this->request->getUri();
$this->file = str_replace(["\\", "/"], "", substr($url, strrpos($url, $this->apiPath) + strlen($this->apiPath)));
$this->location = $this->apiPath . $this->file;
$this->file = $this->uploadDir . $this->file;
// Replicate the input stream so we can control its pointer
$this->stream = fopen('php://temp', 'w+');
stream_copy_to_stream(fopen($this->streamURI, 'r'), $this->stream);
rewind($this->stream);
$this->response = $this->$method();
return $this;
} | php | public function handle(): Server
{
// Check the upload directory
if (!is_dir($this->uploadDir))
throw new ThunderTUSException("Invalid upload directory. Path wasn't set, it doesn't exist or it isn't a directory.");
// Call handlers
$method = "handle" . $this->request->getMethod();
if (!method_exists($this, $method))
throw new ThunderTUSException("Invalid HTTP request method. Not TUS or ThunderTUS compliant.");
// Check if this server supports the client protocol version
if ($this->request->getHeaderLine("Tus-Resumable") != self::PROTOCOL_VERSION) {
$this->response = $this->response->withStatus(412);
return $this;
}
// Gather the filename from the last part of the URL and set the resource location
$this->apiPath = rtrim($this->apiPath, "/") . "/";
$this->uploadDir = rtrim(realpath($this->uploadDir), \DIRECTORY_SEPARATOR) . \DIRECTORY_SEPARATOR;
$url = $this->request->getUri();
$this->file = str_replace(["\\", "/"], "", substr($url, strrpos($url, $this->apiPath) + strlen($this->apiPath)));
$this->location = $this->apiPath . $this->file;
$this->file = $this->uploadDir . $this->file;
// Replicate the input stream so we can control its pointer
$this->stream = fopen('php://temp', 'w+');
stream_copy_to_stream(fopen($this->streamURI, 'r'), $this->stream);
rewind($this->stream);
$this->response = $this->$method();
return $this;
} | [
"public",
"function",
"handle",
"(",
")",
":",
"Server",
"{",
"// Check the upload directory",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"this",
"->",
"uploadDir",
")",
")",
"throw",
"new",
"ThunderTUSException",
"(",
"\"Invalid upload directory. Path wasn't set, it doesn't... | Handles the incoming request.
@throws \ThunderTUS\ThunderTUSException | [
"Handles",
"the",
"incoming",
"request",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L67-L101 | train |
TCB13/thunder-tus-php | src/Server.php | Server.handlePOST | protected function handlePOST(): ResponseInterface
{
// If the already exists we can't create it
if (is_file($this->file))
return $this->response->withStatus(409);
// Get the total upload expected length
$length = $this->request->getHeaderLine("Upload-Length");
if ($length === "") // Note: Some PSR7 implementations discard headers set to 0.
return $this->response->withStatus(400);
// Check for the size of the entire upload
if ($this->uploadMaxFileSize > 0 && $this->uploadMaxFileSize < $length)
return $this->response->withStatus(413);
// Create empty cache container
$cache = new \stdClass();
$cache->length = $length;
// Extension Thunder TUS CrossCheck: get complete upload checksum
if ($this->extCrossCheck) {
$cache->checksum = self::parseChecksum($this->request->getHeaderLine("Upload-CrossChecksum"));
if ($cache->checksum === false)
return $this->response->withStatus(400);
}
// Create an empty file to store the upload and save the cache container
touch($this->file);
file_put_contents($this->file . ".cachecontainer", \json_encode($cache));
return $this->response->withStatus(201)
->withHeader("Location", $this->location);
} | php | protected function handlePOST(): ResponseInterface
{
// If the already exists we can't create it
if (is_file($this->file))
return $this->response->withStatus(409);
// Get the total upload expected length
$length = $this->request->getHeaderLine("Upload-Length");
if ($length === "") // Note: Some PSR7 implementations discard headers set to 0.
return $this->response->withStatus(400);
// Check for the size of the entire upload
if ($this->uploadMaxFileSize > 0 && $this->uploadMaxFileSize < $length)
return $this->response->withStatus(413);
// Create empty cache container
$cache = new \stdClass();
$cache->length = $length;
// Extension Thunder TUS CrossCheck: get complete upload checksum
if ($this->extCrossCheck) {
$cache->checksum = self::parseChecksum($this->request->getHeaderLine("Upload-CrossChecksum"));
if ($cache->checksum === false)
return $this->response->withStatus(400);
}
// Create an empty file to store the upload and save the cache container
touch($this->file);
file_put_contents($this->file . ".cachecontainer", \json_encode($cache));
return $this->response->withStatus(201)
->withHeader("Location", $this->location);
} | [
"protected",
"function",
"handlePOST",
"(",
")",
":",
"ResponseInterface",
"{",
"// If the already exists we can't create it",
"if",
"(",
"is_file",
"(",
"$",
"this",
"->",
"file",
")",
")",
"return",
"$",
"this",
"->",
"response",
"->",
"withStatus",
"(",
"409"... | Handle POST requests.
Creates new files on the server and caches its expected size.
If the client uses the ThunderTUS CrossCheck extension this method will also cache the final file
checksum - the checksum of the entire file.
@return \Psr\Http\Message\ResponseInterface | [
"Handle",
"POST",
"requests",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L113-L146 | train |
TCB13/thunder-tus-php | src/Server.php | Server.handleHEAD | protected function handleHEAD(): ResponseInterface
{
// Extension Thunder TUS Express: create the file on HEAD request
if ($this->extExpress) {
$this->response = $this->handlePOST();
$code = $this->response->getStatusCode();
if ($code !== 201 && $code !== 409)
return $this->response;
$this->response = $this->response->withHeader("Location", $this->location);
}
else { // For Standard TUS
if (!is_file($this->file))
return $this->response->withStatus(404);
}
// Standard TUS HEAD response
$localSize = filesize($this->file);
return $this->response->withStatus(200)
->withHeader("Upload-Offset", $localSize);
} | php | protected function handleHEAD(): ResponseInterface
{
// Extension Thunder TUS Express: create the file on HEAD request
if ($this->extExpress) {
$this->response = $this->handlePOST();
$code = $this->response->getStatusCode();
if ($code !== 201 && $code !== 409)
return $this->response;
$this->response = $this->response->withHeader("Location", $this->location);
}
else { // For Standard TUS
if (!is_file($this->file))
return $this->response->withStatus(404);
}
// Standard TUS HEAD response
$localSize = filesize($this->file);
return $this->response->withStatus(200)
->withHeader("Upload-Offset", $localSize);
} | [
"protected",
"function",
"handleHEAD",
"(",
")",
":",
"ResponseInterface",
"{",
"// Extension Thunder TUS Express: create the file on HEAD request",
"if",
"(",
"$",
"this",
"->",
"extExpress",
")",
"{",
"$",
"this",
"->",
"response",
"=",
"$",
"this",
"->",
"handleP... | Handle HEAD requests.
Informs the client about the status of a file. If the file exists, the number of bytes (offset) already
stored in the server is also provided.
If the client uses the ThunderTUS Express extension this method will also create new files bypassing
the need to call POST.
@return \Psr\Http\Message\ResponseInterface | [
"Handle",
"HEAD",
"requests",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L159-L181 | train |
TCB13/thunder-tus-php | src/Server.php | Server.handlePATCH | protected function handlePATCH(): ResponseInterface
{
$offset = $this->request->getHeaderLine("Upload-Offset");
if ($offset === "") // Note: Some PSR7 implementations discard headers set to 0.
return $this->response->withStatus(400);
// Check if the server supports the proposed checksum algorithm
$checksum = self::parseChecksum($this->request->getHeaderLine("Upload-Checksum"));
if ($checksum === false)
return $this->response->withStatus(400);
// Extension Thunder TUS Express: create the file on PATCH request
if ($this->extExpress && $offset == 0) {
$this->response = $this->handlePOST();
$code = $this->response->getStatusCode();
if ($code !== 201 && $code !== 409)
return $this->response;
if ($code === 409 && !file_exists($this->file . ".cachecontainer")) // Avoid overwriting completed uploads
return $this->response;
}
else { // For Standard TUS
if (!is_file($this->file))
return $this->response->withStatus(404);
}
// Check if the current stored file offset is different from the proposed upload offset
// This ensures we're getting the file block by block in the right order and nothing is missing
if (filesize($this->file) != $offset) {
return $this->response->withStatus(409)
->withHeader("Upload-Offset", filesize($this->file));
}
// Compare proposed checksum with the received data checksum
$hashContext = hash_init($checksum->algorithm);
hash_update_stream($hashContext, $this->stream);
$localChecksum = base64_encode(hash_final($hashContext, true));
if ($localChecksum !== $checksum->value)
return $this->response->withStatus(460, "Checksum Mismatch")
->withHeader("Upload-Offset", filesize($this->file));
rewind($this->stream);
// Write the uploaded chunk to the file
$file = fopen($this->file, "ab");
stream_copy_to_stream($this->stream, $file);
fclose($file);
clearstatcache(true, $this->file);
$localSize = filesize($this->file);
// Detect when the upload is complete
$cache = \json_decode(file_get_contents($this->file . ".cachecontainer"));
if ($cache->length <= $localSize) {
// Remove the cache container, we don't need it anymore
unlink($this->file . ".cachecontainer");
// Extension Thunder TUS CrossCheck: verify if the uploaded file is as expected or delete it
if ($this->extCrossCheck) {
$localChecksum = base64_encode(hash_file($cache->checksum->algorithm, $this->file, true));
if ($localChecksum !== $cache->checksum->value) {
unlink($this->file);
return $this->response->withStatus(410);
}
}
}
if ($this->extCrossCheck)
$this->response = $this->response->withHeader("Location", $this->location);
// File uploaded successfully!
return $this->response->withStatus(204)
->withHeader("Upload-Offset", $localSize);
} | php | protected function handlePATCH(): ResponseInterface
{
$offset = $this->request->getHeaderLine("Upload-Offset");
if ($offset === "") // Note: Some PSR7 implementations discard headers set to 0.
return $this->response->withStatus(400);
// Check if the server supports the proposed checksum algorithm
$checksum = self::parseChecksum($this->request->getHeaderLine("Upload-Checksum"));
if ($checksum === false)
return $this->response->withStatus(400);
// Extension Thunder TUS Express: create the file on PATCH request
if ($this->extExpress && $offset == 0) {
$this->response = $this->handlePOST();
$code = $this->response->getStatusCode();
if ($code !== 201 && $code !== 409)
return $this->response;
if ($code === 409 && !file_exists($this->file . ".cachecontainer")) // Avoid overwriting completed uploads
return $this->response;
}
else { // For Standard TUS
if (!is_file($this->file))
return $this->response->withStatus(404);
}
// Check if the current stored file offset is different from the proposed upload offset
// This ensures we're getting the file block by block in the right order and nothing is missing
if (filesize($this->file) != $offset) {
return $this->response->withStatus(409)
->withHeader("Upload-Offset", filesize($this->file));
}
// Compare proposed checksum with the received data checksum
$hashContext = hash_init($checksum->algorithm);
hash_update_stream($hashContext, $this->stream);
$localChecksum = base64_encode(hash_final($hashContext, true));
if ($localChecksum !== $checksum->value)
return $this->response->withStatus(460, "Checksum Mismatch")
->withHeader("Upload-Offset", filesize($this->file));
rewind($this->stream);
// Write the uploaded chunk to the file
$file = fopen($this->file, "ab");
stream_copy_to_stream($this->stream, $file);
fclose($file);
clearstatcache(true, $this->file);
$localSize = filesize($this->file);
// Detect when the upload is complete
$cache = \json_decode(file_get_contents($this->file . ".cachecontainer"));
if ($cache->length <= $localSize) {
// Remove the cache container, we don't need it anymore
unlink($this->file . ".cachecontainer");
// Extension Thunder TUS CrossCheck: verify if the uploaded file is as expected or delete it
if ($this->extCrossCheck) {
$localChecksum = base64_encode(hash_file($cache->checksum->algorithm, $this->file, true));
if ($localChecksum !== $cache->checksum->value) {
unlink($this->file);
return $this->response->withStatus(410);
}
}
}
if ($this->extCrossCheck)
$this->response = $this->response->withHeader("Location", $this->location);
// File uploaded successfully!
return $this->response->withStatus(204)
->withHeader("Upload-Offset", $localSize);
} | [
"protected",
"function",
"handlePATCH",
"(",
")",
":",
"ResponseInterface",
"{",
"$",
"offset",
"=",
"$",
"this",
"->",
"request",
"->",
"getHeaderLine",
"(",
"\"Upload-Offset\"",
")",
";",
"if",
"(",
"$",
"offset",
"===",
"\"\"",
")",
"// Note: Some PSR7 impl... | Handle PATCH requests.
Receives a chuck of a file and stores it on the server. Implements the checksum extension to validate
the integrity of the chunk.
If the client uses the ThunderTUS Express extension this method will also create new files bypassing
the need to call POST/HEAD.
If the client uses the ThunderTUS CrossCheck extension this method will also verify the final file
checksum (after all chunks are received) against checksum previously stored in the cache.
@return \Psr\Http\Message\ResponseInterface | [
"Handle",
"PATCH",
"requests",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L197-L274 | train |
TCB13/thunder-tus-php | src/Server.php | Server.handleDELETE | protected function handleDELETE(): ResponseInterface
{
if (!is_file($this->file))
return $this->response->withStatus(404);
unlink($this->file);
$cacheStore = $this->file . ".cachecontainer";
if (is_file($cacheStore))
unlink($cacheStore);
return $this->response->withStatus(204);
} | php | protected function handleDELETE(): ResponseInterface
{
if (!is_file($this->file))
return $this->response->withStatus(404);
unlink($this->file);
$cacheStore = $this->file . ".cachecontainer";
if (is_file($cacheStore))
unlink($cacheStore);
return $this->response->withStatus(204);
} | [
"protected",
"function",
"handleDELETE",
"(",
")",
":",
"ResponseInterface",
"{",
"if",
"(",
"!",
"is_file",
"(",
"$",
"this",
"->",
"file",
")",
")",
"return",
"$",
"this",
"->",
"response",
"->",
"withStatus",
"(",
"404",
")",
";",
"unlink",
"(",
"$"... | Handle DELETE requests.
Remove an existing file from the server and its associated resources. Useful when the client
decides to abort an upload.
@return \Psr\Http\Message\ResponseInterface | [
"Handle",
"DELETE",
"requests",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L284-L296 | train |
TCB13/thunder-tus-php | src/Server.php | Server.handleOPTIONS | protected function handleOPTIONS(): ResponseInterface
{
return $this->response->withStatus(204)
->withHeader("Tus-Version", self::PROTOCOL_VERSION)
->withHeader("Tus-Max-Size", $this->uploadMaxFileSize)
->withHeader("Tus-Extension", "creation,checksum,termination,crosscheck,express");
} | php | protected function handleOPTIONS(): ResponseInterface
{
return $this->response->withStatus(204)
->withHeader("Tus-Version", self::PROTOCOL_VERSION)
->withHeader("Tus-Max-Size", $this->uploadMaxFileSize)
->withHeader("Tus-Extension", "creation,checksum,termination,crosscheck,express");
} | [
"protected",
"function",
"handleOPTIONS",
"(",
")",
":",
"ResponseInterface",
"{",
"return",
"$",
"this",
"->",
"response",
"->",
"withStatus",
"(",
"204",
")",
"->",
"withHeader",
"(",
"\"Tus-Version\"",
",",
"self",
"::",
"PROTOCOL_VERSION",
")",
"->",
"with... | Handle OPTIONS requests.
Return information about the server's current configuration. Useful to get the protocol
version, the maximum upload file size and supported extensions.
@return \Psr\Http\Message\ResponseInterface | [
"Handle",
"OPTIONS",
"requests",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L306-L312 | train |
TCB13/thunder-tus-php | src/Server.php | Server.getStream | public function getStream(bool $rewind = true)
{
if ($rewind)
rewind($this->stream);
return $this->stream;
} | php | public function getStream(bool $rewind = true)
{
if ($rewind)
rewind($this->stream);
return $this->stream;
} | [
"public",
"function",
"getStream",
"(",
"bool",
"$",
"rewind",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"rewind",
")",
"rewind",
"(",
"$",
"this",
"->",
"stream",
")",
";",
"return",
"$",
"this",
"->",
"stream",
";",
"}"
] | Returns the underlying stream resource where the data sent to the server was stored.
@param bool $rewind If the stream should be rewinded before returned.
@return bool|resource | [
"Returns",
"the",
"underlying",
"stream",
"resource",
"where",
"the",
"data",
"sent",
"to",
"the",
"server",
"was",
"stored",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L349-L355 | train |
TCB13/thunder-tus-php | src/Server.php | Server.setUploadDir | public function setUploadDir(string $uploadDir): Server
{
$uploadDir = \realpath($uploadDir);
if (!is_dir($uploadDir))
throw new ThunderTUSException("Invalid upload directory. Path doesn't exist or it isn't a directory.");
$this->uploadDir = $uploadDir;
return $this;
} | php | public function setUploadDir(string $uploadDir): Server
{
$uploadDir = \realpath($uploadDir);
if (!is_dir($uploadDir))
throw new ThunderTUSException("Invalid upload directory. Path doesn't exist or it isn't a directory.");
$this->uploadDir = $uploadDir;
return $this;
} | [
"public",
"function",
"setUploadDir",
"(",
"string",
"$",
"uploadDir",
")",
":",
"Server",
"{",
"$",
"uploadDir",
"=",
"\\",
"realpath",
"(",
"$",
"uploadDir",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"uploadDir",
")",
")",
"throw",
"new",
"Thunde... | Set the directory where Thunder-TUS should save uploads.
@param string $uploadDir
@return \ThunderTUS\Server
@throws \ThunderTUS\ThunderTUSException | [
"Set",
"the",
"directory",
"where",
"Thunder",
"-",
"TUS",
"should",
"save",
"uploads",
"."
] | a6a8782407d4e03475e4e8fce24902509b8f4f9d | https://github.com/TCB13/thunder-tus-php/blob/a6a8782407d4e03475e4e8fce24902509b8f4f9d/src/Server.php#L394-L404 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.getConfiguration | public static function getConfiguration()
{
if (is_null(self::$_configuration)) {
self::$_configuration = new stdClass();
self::$_configuration->trigger = 'never';
self::$_configuration->filters = new stdClass();
$file = BP . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'aoe_profiler.xml';
if (is_file($file)) {
$conf = simplexml_load_file($file);
if ($conf !== false) {
self::$_configuration->trigger = (string)$conf->aoe_profiler->trigger;
self::$_configuration->captureModelInfo = (bool)(string)$conf->aoe_profiler->captureModelInfo;
self::$_configuration->captureBacktraces = (bool)(string)$conf->aoe_profiler->captureBacktraces;
self::$_configuration->enableFilters = (bool)(string)$conf->aoe_profiler->enableFilters;
if (self::$_configuration->enableFilters) {
self::$_configuration->filters->sampling = (float)$conf->aoe_profiler->filters->sampling;
self::$_configuration->filters->timeThreshold = (int)$conf->aoe_profiler->filters->timeThreshold;
self::$_configuration->filters->memoryThreshold = (int)$conf->aoe_profiler->filters->memoryThreshold;
self::$_configuration->filters->requestUriWhiteList = (string)$conf->aoe_profiler->filters->requestUriWhiteList;
self::$_configuration->filters->requestUriBlackList = (string)$conf->aoe_profiler->filters->requestUriBlackList;
}
}
}
}
return self::$_configuration;
} | php | public static function getConfiguration()
{
if (is_null(self::$_configuration)) {
self::$_configuration = new stdClass();
self::$_configuration->trigger = 'never';
self::$_configuration->filters = new stdClass();
$file = BP . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'aoe_profiler.xml';
if (is_file($file)) {
$conf = simplexml_load_file($file);
if ($conf !== false) {
self::$_configuration->trigger = (string)$conf->aoe_profiler->trigger;
self::$_configuration->captureModelInfo = (bool)(string)$conf->aoe_profiler->captureModelInfo;
self::$_configuration->captureBacktraces = (bool)(string)$conf->aoe_profiler->captureBacktraces;
self::$_configuration->enableFilters = (bool)(string)$conf->aoe_profiler->enableFilters;
if (self::$_configuration->enableFilters) {
self::$_configuration->filters->sampling = (float)$conf->aoe_profiler->filters->sampling;
self::$_configuration->filters->timeThreshold = (int)$conf->aoe_profiler->filters->timeThreshold;
self::$_configuration->filters->memoryThreshold = (int)$conf->aoe_profiler->filters->memoryThreshold;
self::$_configuration->filters->requestUriWhiteList = (string)$conf->aoe_profiler->filters->requestUriWhiteList;
self::$_configuration->filters->requestUriBlackList = (string)$conf->aoe_profiler->filters->requestUriBlackList;
}
}
}
}
return self::$_configuration;
} | [
"public",
"static",
"function",
"getConfiguration",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"self",
"::",
"$",
"_configuration",
")",
")",
"{",
"self",
"::",
"$",
"_configuration",
"=",
"new",
"stdClass",
"(",
")",
";",
"self",
"::",
"$",
"_configurati... | Get configuration object
@return stdClass | [
"Get",
"configuration",
"object"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L46-L72 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.isEnabled | public static function isEnabled()
{
if (!self::$_checkedEnabled) {
self::$_checkedEnabled = true;
$conf = self::getConfiguration();
$enabled = false;
if (strtolower($conf->trigger) == 'always') {
$enabled = true;
} elseif (strtolower($conf->trigger) == 'parameter') {
if ((isset($_GET['profile']) && $_GET['profile'] == true) || (isset($_COOKIE['profile']) && $_COOKIE['profile'] == true)) {
$enabled = true;
}
}
// Process filters
if ($enabled && $conf->enableFilters) {
// sampling filter
if ($enabled && rand(0,100000) > $conf->filters->sampling * 1000) {
$enabled = false;
}
// request uri whitelist/blacklist
$requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; // TODO: use script name instead for cli?
if ($enabled && $conf->filters->requestUriWhiteList && !preg_match($conf->filters->requestUriWhiteList, $requestUri)) {
$enabled = false;
}
if ($enabled && $conf->filters->requestUriBlackList && preg_match($conf->filters->requestUriBlackList, $requestUri)) {
$enabled = false;
}
// note: timeThreshold and memoryThreshold will be checked before persisting records. In these cases data will still be recorded during the request
}
if ($enabled) {
self::enable();
}
}
return self::$_enabled;
} | php | public static function isEnabled()
{
if (!self::$_checkedEnabled) {
self::$_checkedEnabled = true;
$conf = self::getConfiguration();
$enabled = false;
if (strtolower($conf->trigger) == 'always') {
$enabled = true;
} elseif (strtolower($conf->trigger) == 'parameter') {
if ((isset($_GET['profile']) && $_GET['profile'] == true) || (isset($_COOKIE['profile']) && $_COOKIE['profile'] == true)) {
$enabled = true;
}
}
// Process filters
if ($enabled && $conf->enableFilters) {
// sampling filter
if ($enabled && rand(0,100000) > $conf->filters->sampling * 1000) {
$enabled = false;
}
// request uri whitelist/blacklist
$requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; // TODO: use script name instead for cli?
if ($enabled && $conf->filters->requestUriWhiteList && !preg_match($conf->filters->requestUriWhiteList, $requestUri)) {
$enabled = false;
}
if ($enabled && $conf->filters->requestUriBlackList && preg_match($conf->filters->requestUriBlackList, $requestUri)) {
$enabled = false;
}
// note: timeThreshold and memoryThreshold will be checked before persisting records. In these cases data will still be recorded during the request
}
if ($enabled) {
self::enable();
}
}
return self::$_enabled;
} | [
"public",
"static",
"function",
"isEnabled",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"_checkedEnabled",
")",
"{",
"self",
"::",
"$",
"_checkedEnabled",
"=",
"true",
";",
"$",
"conf",
"=",
"self",
"::",
"getConfiguration",
"(",
")",
";",
"$",
... | Check if profiler is enabled.
@static
@return bool | [
"Check",
"if",
"profiler",
"is",
"enabled",
"."
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L106-L147 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.start | public static function start($name, $type = '')
{
if (!self::isEnabled()) {
return;
}
$currentPointer = 'timetracker_' . self::$uniqueCounter++;
array_push(self::$currentPointerStack, $currentPointer);
array_push(self::$stack, $name);
self::$stackLevel++;
self::$stackLevelMax[] = self::$stackLevel;
self::$stackLog[$currentPointer] = array(
'level' => self::$stackLevel,
'stack' => self::$stack,
'time_start' => microtime(true),
'realmem_start' => memory_get_usage(true),
// 'emalloc_start' => memory_get_usage(false),
'type' => $type,
);
if ($name == '__EAV_LOAD_MODEL__' && !empty(self::getConfiguration()->captureModelInfo)) {
$trace = debug_backtrace();
$className = get_class($trace[1]['args'][0]);
$entityId = isset($trace[1]['args'][1]) ? $trace[1]['args'][1] : 'not set';
$attributes = isset($trace[1]['args'][2]) ? $trace[1]['args'][2] : null;
self::$stackLog[$currentPointer]['detail'] = "$className, id: $entityId, attributes: " . var_export($attributes, true);
}
if (!empty(self::getConfiguration()->captureBacktraces)) {
$trace = isset($trace) ? $trace : debug_backtrace();
$fileAndLine = self::getFileAndLine($trace, $type, $name);
self::$stackLog[$currentPointer]['file'] = $fileAndLine['file'];
self::$stackLog[$currentPointer]['line'] = $fileAndLine['line'];
}
} | php | public static function start($name, $type = '')
{
if (!self::isEnabled()) {
return;
}
$currentPointer = 'timetracker_' . self::$uniqueCounter++;
array_push(self::$currentPointerStack, $currentPointer);
array_push(self::$stack, $name);
self::$stackLevel++;
self::$stackLevelMax[] = self::$stackLevel;
self::$stackLog[$currentPointer] = array(
'level' => self::$stackLevel,
'stack' => self::$stack,
'time_start' => microtime(true),
'realmem_start' => memory_get_usage(true),
// 'emalloc_start' => memory_get_usage(false),
'type' => $type,
);
if ($name == '__EAV_LOAD_MODEL__' && !empty(self::getConfiguration()->captureModelInfo)) {
$trace = debug_backtrace();
$className = get_class($trace[1]['args'][0]);
$entityId = isset($trace[1]['args'][1]) ? $trace[1]['args'][1] : 'not set';
$attributes = isset($trace[1]['args'][2]) ? $trace[1]['args'][2] : null;
self::$stackLog[$currentPointer]['detail'] = "$className, id: $entityId, attributes: " . var_export($attributes, true);
}
if (!empty(self::getConfiguration()->captureBacktraces)) {
$trace = isset($trace) ? $trace : debug_backtrace();
$fileAndLine = self::getFileAndLine($trace, $type, $name);
self::$stackLog[$currentPointer]['file'] = $fileAndLine['file'];
self::$stackLog[$currentPointer]['line'] = $fileAndLine['line'];
}
} | [
"public",
"static",
"function",
"start",
"(",
"$",
"name",
",",
"$",
"type",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"isEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"currentPointer",
"=",
"'timetracker_'",
".",
"self",
"::",
"$... | Pushes to the stack
@param string $name
@param string $type
@return void | [
"Pushes",
"to",
"the",
"stack"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L156-L193 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.getLineNumber | public static function getLineNumber($file, $regex)
{
$i = 0;
$lineFound = false;
$handle = @fopen($file, 'r');
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$i++;
if (preg_match($regex, $buffer)) {
$lineFound = true;
break;
}
}
fclose($handle);
}
return $lineFound ? $i : false;
} | php | public static function getLineNumber($file, $regex)
{
$i = 0;
$lineFound = false;
$handle = @fopen($file, 'r');
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$i++;
if (preg_match($regex, $buffer)) {
$lineFound = true;
break;
}
}
fclose($handle);
}
return $lineFound ? $i : false;
} | [
"public",
"static",
"function",
"getLineNumber",
"(",
"$",
"file",
",",
"$",
"regex",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"lineFound",
"=",
"false",
";",
"$",
"handle",
"=",
"@",
"fopen",
"(",
"$",
"file",
",",
"'r'",
")",
";",
"if",
"(",
"... | Get the line number of the first line in a file matching a given regex
Not the nicest solution, but probably the fastest
@param $file
@param $regex
@return bool|int | [
"Get",
"the",
"line",
"number",
"of",
"the",
"first",
"line",
"in",
"a",
"file",
"matching",
"a",
"given",
"regex",
"Not",
"the",
"nicest",
"solution",
"but",
"probably",
"the",
"fastest"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L324-L340 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.stop | public static function stop($name)
{
if (!self::isEnabled()) {
return;
}
$currentName = end(self::$stack);
if ($currentName != $name) {
if (Mage::getStoreConfigFlag('dev/debug/logInvalidNesting')) {
Mage::log('[INVALID NESTING!] Found: ' . $name . " | Expecting: $currentName");
}
if (in_array($name, self::$stack)) {
// trying to stop something that has been started before,
// but there are other unstopped stack items
// -> auto-stop them
while (($latestStackItem = end(self::$stack)) != $name) {
if (Mage::getStoreConfigFlag('dev/debug/logInvalidNesting')) {
Mage::log('Auto-stopping timer "' . $latestStackItem . '" because of incorrect nesting');
}
self::stop($latestStackItem);
}
} else {
// trying to stop something that hasn't been started before -> just ignore
return;
}
// We shouldn't add another name to the stack if we've already crawled up to the current one...
// $name = '[INVALID NESTING!] ' . $name;
// self::start($name);
// return;
// throw new Exception(sprintf("Invalid nesting! Expected: '%s', was: '%s'", $currentName, $name));
}
$currentPointer = end(self::$currentPointerStack);
self::$stackLog[$currentPointer]['time_end'] = microtime(true);
self::$stackLog[$currentPointer]['realmem_end'] = memory_get_usage(true);
// self::$stackLog[$currentPointer]['emalloc_end'] = memory_get_usage(false);
// TODO: introduce configurable threshold
if (self::$_logCallStack !== false) {
self::$stackLog[$currentPointer]['callstack'] = Varien_Debug::backtrace(true, false);
}
self::$stackLevel--;
array_pop(self::$stack);
array_pop(self::$currentPointerStack);
} | php | public static function stop($name)
{
if (!self::isEnabled()) {
return;
}
$currentName = end(self::$stack);
if ($currentName != $name) {
if (Mage::getStoreConfigFlag('dev/debug/logInvalidNesting')) {
Mage::log('[INVALID NESTING!] Found: ' . $name . " | Expecting: $currentName");
}
if (in_array($name, self::$stack)) {
// trying to stop something that has been started before,
// but there are other unstopped stack items
// -> auto-stop them
while (($latestStackItem = end(self::$stack)) != $name) {
if (Mage::getStoreConfigFlag('dev/debug/logInvalidNesting')) {
Mage::log('Auto-stopping timer "' . $latestStackItem . '" because of incorrect nesting');
}
self::stop($latestStackItem);
}
} else {
// trying to stop something that hasn't been started before -> just ignore
return;
}
// We shouldn't add another name to the stack if we've already crawled up to the current one...
// $name = '[INVALID NESTING!] ' . $name;
// self::start($name);
// return;
// throw new Exception(sprintf("Invalid nesting! Expected: '%s', was: '%s'", $currentName, $name));
}
$currentPointer = end(self::$currentPointerStack);
self::$stackLog[$currentPointer]['time_end'] = microtime(true);
self::$stackLog[$currentPointer]['realmem_end'] = memory_get_usage(true);
// self::$stackLog[$currentPointer]['emalloc_end'] = memory_get_usage(false);
// TODO: introduce configurable threshold
if (self::$_logCallStack !== false) {
self::$stackLog[$currentPointer]['callstack'] = Varien_Debug::backtrace(true, false);
}
self::$stackLevel--;
array_pop(self::$stack);
array_pop(self::$currentPointerStack);
} | [
"public",
"static",
"function",
"stop",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"isEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"currentName",
"=",
"end",
"(",
"self",
"::",
"$",
"stack",
")",
";",
"if",
"(",
"$",
"c... | Pull element from stack
@param string $name
@throws Exception
@return void | [
"Pull",
"element",
"from",
"stack"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L378-L426 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.addData | public static function addData($data, $key = NULL)
{
$currentPointer = end(self::$currentPointerStack);
if (!isset(self::$stackLog[$currentPointer]['messages'])) {
self::$stackLog[$currentPointer]['messages'] = array();
}
if (is_null($key)) {
self::$stackLog[$currentPointer]['messages'][] = $data;
} else {
self::$stackLog[$currentPointer]['messages'][$key] = $data;
}
} | php | public static function addData($data, $key = NULL)
{
$currentPointer = end(self::$currentPointerStack);
if (!isset(self::$stackLog[$currentPointer]['messages'])) {
self::$stackLog[$currentPointer]['messages'] = array();
}
if (is_null($key)) {
self::$stackLog[$currentPointer]['messages'][] = $data;
} else {
self::$stackLog[$currentPointer]['messages'][$key] = $data;
}
} | [
"public",
"static",
"function",
"addData",
"(",
"$",
"data",
",",
"$",
"key",
"=",
"NULL",
")",
"{",
"$",
"currentPointer",
"=",
"end",
"(",
"self",
"::",
"$",
"currentPointerStack",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"stackLo... | Add data to the current stack
@param $data
@param null $key | [
"Add",
"data",
"to",
"the",
"current",
"stack"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L434-L445 | train |
AOEpeople/Aoe_Profiler | app/code/community/Varien/Profiler.php | Varien_Profiler.calculate | public static function calculate()
{
foreach (self::$stackLog as &$data) {
foreach (array('time', 'realmem' /* , 'emalloc' */) as $metric) {
$data[$metric . '_end_relative'] = $data[$metric . '_end'] - self::$startValues[$metric];
$data[$metric . '_start_relative'] = $data[$metric . '_start'] - self::$startValues[$metric];
$data[$metric . '_total'] = $data[$metric . '_end_relative'] - $data[$metric . '_start_relative'];
}
}
} | php | public static function calculate()
{
foreach (self::$stackLog as &$data) {
foreach (array('time', 'realmem' /* , 'emalloc' */) as $metric) {
$data[$metric . '_end_relative'] = $data[$metric . '_end'] - self::$startValues[$metric];
$data[$metric . '_start_relative'] = $data[$metric . '_start'] - self::$startValues[$metric];
$data[$metric . '_total'] = $data[$metric . '_end_relative'] - $data[$metric . '_start_relative'];
}
}
} | [
"public",
"static",
"function",
"calculate",
"(",
")",
"{",
"foreach",
"(",
"self",
"::",
"$",
"stackLog",
"as",
"&",
"$",
"data",
")",
"{",
"foreach",
"(",
"array",
"(",
"'time'",
",",
"'realmem'",
"/* , 'emalloc' */",
")",
"as",
"$",
"metric",
")",
"... | Calculate relative data
@return void | [
"Calculate",
"relative",
"data"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Varien/Profiler.php#L512-L521 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php | Aoe_Profiler_Adminhtml_ProfilerController._initAction | protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu('system/aoe_profiler')
->_addBreadcrumb(Mage::helper('aoe_profiler')->__('System'),
Mage::helper('aoe_profiler')->__('System'))
->_addBreadcrumb(Mage::helper('aoe_profiler')->__('AOE Profiler'),
Mage::helper('aoe_profiler')->__('AOE Profiler'));
return $this;
} | php | protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu('system/aoe_profiler')
->_addBreadcrumb(Mage::helper('aoe_profiler')->__('System'),
Mage::helper('aoe_profiler')->__('System'))
->_addBreadcrumb(Mage::helper('aoe_profiler')->__('AOE Profiler'),
Mage::helper('aoe_profiler')->__('AOE Profiler'));
return $this;
} | [
"protected",
"function",
"_initAction",
"(",
")",
"{",
"$",
"this",
"->",
"loadLayout",
"(",
")",
"->",
"_setActiveMenu",
"(",
"'system/aoe_profiler'",
")",
"->",
"_addBreadcrumb",
"(",
"Mage",
"::",
"helper",
"(",
"'aoe_profiler'",
")",
"->",
"__",
"(",
"'S... | Load layout, set active menu and breadcrumbs
@return $this | [
"Load",
"layout",
"set",
"active",
"menu",
"and",
"breadcrumbs"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php#L16-L25 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php | Aoe_Profiler_Adminhtml_ProfilerController._initStackInstance | protected function _initStackInstance()
{
$this->_title($this->__('System'))->_title($this->__('AOE Profiler'));
$stackId = $this->getRequest()->getParam('stack_id', null);
if ($stackId) {
$stackInstance = Mage::getModel('aoe_profiler/run'); /* @var $stackInstance Aoe_Profiler_Model_Run */
$stackInstance->load($stackId);
if (!$stackInstance->getId()) {
$this->_getSession()->addError(Mage::helper('aoe_profiler')->__('No data found with this id.'));
return false;
}
Mage::register('current_stack_instance', $stackInstance);
return $stackInstance;
}
return false;
} | php | protected function _initStackInstance()
{
$this->_title($this->__('System'))->_title($this->__('AOE Profiler'));
$stackId = $this->getRequest()->getParam('stack_id', null);
if ($stackId) {
$stackInstance = Mage::getModel('aoe_profiler/run'); /* @var $stackInstance Aoe_Profiler_Model_Run */
$stackInstance->load($stackId);
if (!$stackInstance->getId()) {
$this->_getSession()->addError(Mage::helper('aoe_profiler')->__('No data found with this id.'));
return false;
}
Mage::register('current_stack_instance', $stackInstance);
return $stackInstance;
}
return false;
} | [
"protected",
"function",
"_initStackInstance",
"(",
")",
"{",
"$",
"this",
"->",
"_title",
"(",
"$",
"this",
"->",
"__",
"(",
"'System'",
")",
")",
"->",
"_title",
"(",
"$",
"this",
"->",
"__",
"(",
"'AOE Profiler'",
")",
")",
";",
"$",
"stackId",
"=... | Init stack instance object and set it to registry
@return Aoe_Profiler_Model_Run|false | [
"Init",
"stack",
"instance",
"object",
"and",
"set",
"it",
"to",
"registry"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php#L32-L49 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php | Aoe_Profiler_Adminhtml_ProfilerController.deleteAction | public function deleteAction()
{
try {
$stack = $this->_initStackInstance();
if ($stack) {
$stack->delete();
$this->_getSession()->addSuccess( $this->__( 'The entry has been deleted.' ) );
}
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
$this->_redirect('*/*/');
} | php | public function deleteAction()
{
try {
$stack = $this->_initStackInstance();
if ($stack) {
$stack->delete();
$this->_getSession()->addSuccess( $this->__( 'The entry has been deleted.' ) );
}
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
$this->_redirect('*/*/');
} | [
"public",
"function",
"deleteAction",
"(",
")",
"{",
"try",
"{",
"$",
"stack",
"=",
"$",
"this",
"->",
"_initStackInstance",
"(",
")",
";",
"if",
"(",
"$",
"stack",
")",
"{",
"$",
"stack",
"->",
"delete",
"(",
")",
";",
"$",
"this",
"->",
"_getSess... | Delete the selected stack instance.
@return void | [
"Delete",
"the",
"selected",
"stack",
"instance",
"."
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php#L57-L70 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php | Aoe_Profiler_Adminhtml_ProfilerController.viewAction | public function viewAction()
{
$stack = $this->_initStackInstance();
if (!$stack) {
$this->_redirect('*/*/');
return;
}
$this->_initAction();
$this->renderLayout();
} | php | public function viewAction()
{
$stack = $this->_initStackInstance();
if (!$stack) {
$this->_redirect('*/*/');
return;
}
$this->_initAction();
$this->renderLayout();
} | [
"public",
"function",
"viewAction",
"(",
")",
"{",
"$",
"stack",
"=",
"$",
"this",
"->",
"_initStackInstance",
"(",
")",
";",
"if",
"(",
"!",
"$",
"stack",
")",
"{",
"$",
"this",
"->",
"_redirect",
"(",
"'*/*/'",
")",
";",
"return",
";",
"}",
"$",
... | Edit layout instance action | [
"Edit",
"layout",
"instance",
"action"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/controllers/Adminhtml/ProfilerController.php#L122-L131 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/Model/Run.php | Aoe_Profiler_Model_Run.calcRelativeValues | protected function calcRelativeValues()
{
foreach ($this->stackLog as $key => $value) {
foreach ($this->metrics as $metric) {
foreach (array('own', 'sub', 'total') as $column) {
if (!isset($this->stackLog[$key][$metric . '_' . $column])) {
continue;
}
$this->stackLog[$key][$metric . '_rel_' . $column] = $this->stackLog[$key][$metric . '_' . $column] / $this->stackLog['timetracker_0'][$metric . '_total'];
}
$this->stackLog[$key][$metric . '_rel_offset'] = $this->stackLog[$key][$metric . '_start_relative'] / $this->stackLog['timetracker_0'][$metric . '_total'];
}
}
} | php | protected function calcRelativeValues()
{
foreach ($this->stackLog as $key => $value) {
foreach ($this->metrics as $metric) {
foreach (array('own', 'sub', 'total') as $column) {
if (!isset($this->stackLog[$key][$metric . '_' . $column])) {
continue;
}
$this->stackLog[$key][$metric . '_rel_' . $column] = $this->stackLog[$key][$metric . '_' . $column] / $this->stackLog['timetracker_0'][$metric . '_total'];
}
$this->stackLog[$key][$metric . '_rel_offset'] = $this->stackLog[$key][$metric . '_start_relative'] / $this->stackLog['timetracker_0'][$metric . '_total'];
}
}
} | [
"protected",
"function",
"calcRelativeValues",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"stackLog",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"metrics",
"as",
"$",
"metric",
")",
"{",
"foreach",
"(",
... | Calculate relative values | [
"Calculate",
"relative",
"values"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/Model/Run.php#L127-L140 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/Model/Run.php | Aoe_Profiler_Model_Run._beforeSave | protected function _beforeSave()
{
$date = Mage::getModel('core/date')->gmtDate();
if ($this->isObjectNew() && !$this->getCreatedAt()) {
$this->setCreatedAt($date);
}
$this->setStackData(serialize($this->stackLog));
return parent::_beforeSave();
} | php | protected function _beforeSave()
{
$date = Mage::getModel('core/date')->gmtDate();
if ($this->isObjectNew() && !$this->getCreatedAt()) {
$this->setCreatedAt($date);
}
$this->setStackData(serialize($this->stackLog));
return parent::_beforeSave();
} | [
"protected",
"function",
"_beforeSave",
"(",
")",
"{",
"$",
"date",
"=",
"Mage",
"::",
"getModel",
"(",
"'core/date'",
")",
"->",
"gmtDate",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isObjectNew",
"(",
")",
"&&",
"!",
"$",
"this",
"->",
"getCreat... | Before saving...
@return Mage_Core_Model_Abstract | [
"Before",
"saving",
"..."
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/Model/Run.php#L169-L177 | train |
AOEpeople/Aoe_Profiler | app/code/community/Aoe/Profiler/Block/Tree.php | Aoe_Profiler_Block_Tree.renderProgressBar | protected function renderProgressBar($percent1, $percent2 = 0, $offset = 0)
{
$percent1 = round(max(1, $percent1));
$offset = round(max(0, $offset));
$offset = round(min(99, $offset));
$output = '<div class="progress">';
$output .= '<div class="progress-bar">';
$output .= '<div class="progress-bar1" style="width: ' . $percent1 . '%; margin-left: ' . $offset . '%;"></div>';
if ($percent2 > 0) {
$percent2 = round(max(1, $percent2));
if ($percent1 + $percent2 + $offset > 100) {
// preventing line break in css progress bar if widths and margins are bigger than 100%
$percent2 = 100 - $percent1 - $offset;
$percent2 = max(0, $percent2);
}
$output .= '<div class="progress-bar2" style="width: ' . $percent2 . '%"></div>';
}
$output .= '</div>';
$output .= '</div>';
return $output;
} | php | protected function renderProgressBar($percent1, $percent2 = 0, $offset = 0)
{
$percent1 = round(max(1, $percent1));
$offset = round(max(0, $offset));
$offset = round(min(99, $offset));
$output = '<div class="progress">';
$output .= '<div class="progress-bar">';
$output .= '<div class="progress-bar1" style="width: ' . $percent1 . '%; margin-left: ' . $offset . '%;"></div>';
if ($percent2 > 0) {
$percent2 = round(max(1, $percent2));
if ($percent1 + $percent2 + $offset > 100) {
// preventing line break in css progress bar if widths and margins are bigger than 100%
$percent2 = 100 - $percent1 - $offset;
$percent2 = max(0, $percent2);
}
$output .= '<div class="progress-bar2" style="width: ' . $percent2 . '%"></div>';
}
$output .= '</div>';
$output .= '</div>';
return $output;
} | [
"protected",
"function",
"renderProgressBar",
"(",
"$",
"percent1",
",",
"$",
"percent2",
"=",
"0",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"$",
"percent1",
"=",
"round",
"(",
"max",
"(",
"1",
",",
"$",
"percent1",
")",
")",
";",
"$",
"offset",
"="... | Render css progress bar
@param $percent1
@param int $percent2
@param int $offset
@return string | [
"Render",
"css",
"progress",
"bar"
] | dd9fdf94879e687c2bb5140229910450c46e8f7f | https://github.com/AOEpeople/Aoe_Profiler/blob/dd9fdf94879e687c2bb5140229910450c46e8f7f/app/code/community/Aoe/Profiler/Block/Tree.php#L219-L242 | train |
silverstripe/silverstripe-asset-admin | code/Forms/RemoteFileFormFactory.php | RemoteFileFormFactory.getCreateFormFields | protected function getCreateFormFields()
{
return FieldList::create([
TextField::create(
'Url',
'Embed URL'
)
->setInputType('url')
->addExtraClass('insert-embed-modal__url-create')
->setDescription(_t(
__CLASS__.'.UrlDescription',
'Embed Youtube and Vimeo videos, images and other media directly from the web.'
)),
]);
} | php | protected function getCreateFormFields()
{
return FieldList::create([
TextField::create(
'Url',
'Embed URL'
)
->setInputType('url')
->addExtraClass('insert-embed-modal__url-create')
->setDescription(_t(
__CLASS__.'.UrlDescription',
'Embed Youtube and Vimeo videos, images and other media directly from the web.'
)),
]);
} | [
"protected",
"function",
"getCreateFormFields",
"(",
")",
"{",
"return",
"FieldList",
"::",
"create",
"(",
"[",
"TextField",
"::",
"create",
"(",
"'Url'",
",",
"'Embed URL'",
")",
"->",
"setInputType",
"(",
"'url'",
")",
"->",
"addExtraClass",
"(",
"'insert-em... | Get form fields for create new embed
@return FieldList | [
"Get",
"form",
"fields",
"for",
"create",
"new",
"embed"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/RemoteFileFormFactory.php#L202-L216 | train |
silverstripe/silverstripe-asset-admin | code/Forms/RemoteFileFormFactory.php | RemoteFileFormFactory.getEditFormFields | protected function getEditFormFields($context)
{
// Check if the url is valid
$url = (isset($context['url'])) ? $context['url'] : null;
if (empty($url)) {
return $this->getCreateFormFields();
}
$url = trim($url);
// Get embed
$this->validateUrl($url);
/** @var Embeddable $embed */
$embed = Injector::inst()->create(Embeddable::class, $url);
$this->validateEmbed($embed);
// Build form
$alignments = array(
'leftAlone' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentLeftAlone', 'Left'),
'center' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentCenter', 'Center'),
'rightAlone' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentRightAlone', 'Right'),
'left' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentLeft', 'Left wrap'),
'right' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentRight', 'Right wrap'),
);
$width = $embed->getWidth();
$height = $embed->getHeight();
$fields = CompositeField::create([
LiteralField::create(
'Preview',
sprintf(
'<img src="%s" class="%s" />',
$embed->getPreviewURL(),
'insert-embed-modal__preview'
)
)->addExtraClass('insert-embed-modal__preview-container'),
HiddenField::create('PreviewUrl', 'PreviewUrl', $embed->getPreviewURL()),
CompositeField::create([
TextField::create('UrlPreview', $embed->getName(), $url)
->setReadonly(true),
HiddenField::create('Url', false, $url),
TextField::create(
'CaptionText',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Caption', 'Caption')
),
OptionsetField::create(
'Placement',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Placement', 'Placement'),
$alignments
)
->addExtraClass('insert-embed-modal__placement'),
$dimensions = FieldGroup::create(
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageSpecs', 'Dimensions'),
TextField::create('Width', '', $width)
->setRightTitle(_t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageWidth',
'Width'
))
->setMaxLength(5)
->addExtraClass('flexbox-area-grow'),
TextField::create('Height', '', $height)
->setRightTitle(_t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageHeight',
'Height'
))
->setMaxLength(5)
->addExtraClass('flexbox-area-grow')
)->addExtraClass('fieldgroup--fill-width')
->setName('Dimensions')
])->addExtraClass('flexbox-area-grow'),
])->addExtraClass('insert-embed-modal__fields--fill-width');
if ($dimensions && $width && $height) {
$ratio = $width / $height;
$dimensions->setSchemaComponent('ProportionConstraintField');
$dimensions->setSchemaState([
'data' => [
'ratio' => $ratio
]
]);
}
return FieldList::create($fields);
} | php | protected function getEditFormFields($context)
{
// Check if the url is valid
$url = (isset($context['url'])) ? $context['url'] : null;
if (empty($url)) {
return $this->getCreateFormFields();
}
$url = trim($url);
// Get embed
$this->validateUrl($url);
/** @var Embeddable $embed */
$embed = Injector::inst()->create(Embeddable::class, $url);
$this->validateEmbed($embed);
// Build form
$alignments = array(
'leftAlone' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentLeftAlone', 'Left'),
'center' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentCenter', 'Center'),
'rightAlone' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentRightAlone', 'Right'),
'left' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentLeft', 'Left wrap'),
'right' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentRight', 'Right wrap'),
);
$width = $embed->getWidth();
$height = $embed->getHeight();
$fields = CompositeField::create([
LiteralField::create(
'Preview',
sprintf(
'<img src="%s" class="%s" />',
$embed->getPreviewURL(),
'insert-embed-modal__preview'
)
)->addExtraClass('insert-embed-modal__preview-container'),
HiddenField::create('PreviewUrl', 'PreviewUrl', $embed->getPreviewURL()),
CompositeField::create([
TextField::create('UrlPreview', $embed->getName(), $url)
->setReadonly(true),
HiddenField::create('Url', false, $url),
TextField::create(
'CaptionText',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Caption', 'Caption')
),
OptionsetField::create(
'Placement',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Placement', 'Placement'),
$alignments
)
->addExtraClass('insert-embed-modal__placement'),
$dimensions = FieldGroup::create(
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageSpecs', 'Dimensions'),
TextField::create('Width', '', $width)
->setRightTitle(_t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageWidth',
'Width'
))
->setMaxLength(5)
->addExtraClass('flexbox-area-grow'),
TextField::create('Height', '', $height)
->setRightTitle(_t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageHeight',
'Height'
))
->setMaxLength(5)
->addExtraClass('flexbox-area-grow')
)->addExtraClass('fieldgroup--fill-width')
->setName('Dimensions')
])->addExtraClass('flexbox-area-grow'),
])->addExtraClass('insert-embed-modal__fields--fill-width');
if ($dimensions && $width && $height) {
$ratio = $width / $height;
$dimensions->setSchemaComponent('ProportionConstraintField');
$dimensions->setSchemaState([
'data' => [
'ratio' => $ratio
]
]);
}
return FieldList::create($fields);
} | [
"protected",
"function",
"getEditFormFields",
"(",
"$",
"context",
")",
"{",
"// Check if the url is valid",
"$",
"url",
"=",
"(",
"isset",
"(",
"$",
"context",
"[",
"'url'",
"]",
")",
")",
"?",
"$",
"context",
"[",
"'url'",
"]",
":",
"null",
";",
"if",
... | Get form fields for edit form
@param array $context
@return FieldList
@throws InvalidUrlException | [
"Get",
"form",
"fields",
"for",
"edit",
"form"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/RemoteFileFormFactory.php#L225-L310 | train |
silverstripe/silverstripe-asset-admin | code/Forms/AssetFormFactory.php | AssetFormFactory.getFormFieldTabs | protected function getFormFieldTabs($record, $context = [])
{
return TabSet::create(
'Editor',
[
$this->getFormFieldDetailsTab($record, $context),
$this->getFormFieldSecurityTab($record, $context),
]
);
} | php | protected function getFormFieldTabs($record, $context = [])
{
return TabSet::create(
'Editor',
[
$this->getFormFieldDetailsTab($record, $context),
$this->getFormFieldSecurityTab($record, $context),
]
);
} | [
"protected",
"function",
"getFormFieldTabs",
"(",
"$",
"record",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"TabSet",
"::",
"create",
"(",
"'Editor'",
",",
"[",
"$",
"this",
"->",
"getFormFieldDetailsTab",
"(",
"$",
"record",
",",
"$",
"cont... | Gets the main tabs for the file edit form
@param File $record
@param array $context
@return TabSet | [
"Gets",
"the",
"main",
"tabs",
"for",
"the",
"file",
"edit",
"form"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/AssetFormFactory.php#L134-L143 | train |
silverstripe/silverstripe-asset-admin | code/Forms/AssetFormFactory.php | AssetFormFactory.getDeleteAction | protected function getDeleteAction($record)
{
// Delete action
if ($record && $record->isInDB() && $record->canDelete()) {
$deleteText = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.DELETE_BUTTON', 'Delete');
return FormAction::create('delete', $deleteText)
->setIcon('trash-bin');
}
return null;
} | php | protected function getDeleteAction($record)
{
// Delete action
if ($record && $record->isInDB() && $record->canDelete()) {
$deleteText = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.DELETE_BUTTON', 'Delete');
return FormAction::create('delete', $deleteText)
->setIcon('trash-bin');
}
return null;
} | [
"protected",
"function",
"getDeleteAction",
"(",
"$",
"record",
")",
"{",
"// Delete action",
"if",
"(",
"$",
"record",
"&&",
"$",
"record",
"->",
"isInDB",
"(",
")",
"&&",
"$",
"record",
"->",
"canDelete",
"(",
")",
")",
"{",
"$",
"deleteText",
"=",
"... | Get delete action, if this record is deletable
@param File $record
@return FormAction | [
"Get",
"delete",
"action",
"if",
"this",
"record",
"is",
"deletable"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/AssetFormFactory.php#L177-L186 | train |
silverstripe/silverstripe-asset-admin | code/Forms/AssetFormFactory.php | AssetFormFactory.getPopoverMenu | protected function getPopoverMenu($record)
{
// Build popover actions
$popoverActions = $this->getPopoverActions($record);
if ($popoverActions) {
return PopoverField::create($popoverActions)
->setPlacement('top')
->setName('PopoverActions')
->setButtonTooltip(_t(
'SilverStripe\\AssetAdmin\\Forms\\FileFormFactory.OTHER_ACTIONS',
'Other actions'
));
}
return null;
} | php | protected function getPopoverMenu($record)
{
// Build popover actions
$popoverActions = $this->getPopoverActions($record);
if ($popoverActions) {
return PopoverField::create($popoverActions)
->setPlacement('top')
->setName('PopoverActions')
->setButtonTooltip(_t(
'SilverStripe\\AssetAdmin\\Forms\\FileFormFactory.OTHER_ACTIONS',
'Other actions'
));
}
return null;
} | [
"protected",
"function",
"getPopoverMenu",
"(",
"$",
"record",
")",
"{",
"// Build popover actions",
"$",
"popoverActions",
"=",
"$",
"this",
"->",
"getPopoverActions",
"(",
"$",
"record",
")",
";",
"if",
"(",
"$",
"popoverActions",
")",
"{",
"return",
"Popove... | Build popup menu
@param File $record
@return PopoverField | [
"Build",
"popup",
"menu"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/AssetFormFactory.php#L253-L267 | train |
silverstripe/silverstripe-asset-admin | code/Forms/AssetFormFactory.php | AssetFormFactory.getFormFieldDetailsTab | protected function getFormFieldDetailsTab($record, $context = [])
{
/** @var Tab $tab */
$tab = Tab::create(
'Details',
TextField::create('Name', _t(__CLASS__.'.FILENAME', 'Filename')),
$location = TreeDropdownField::create(
'ParentID',
_t(__CLASS__.'.FOLDERLOCATION', 'Location'),
Folder::class
)
->setShowSelectedPath(true)
);
$location
->setEmptyString(_t(__CLASS__.'.ROOTNAME', '(Top level)'))
->setShowSearch(true);
return $tab;
} | php | protected function getFormFieldDetailsTab($record, $context = [])
{
/** @var Tab $tab */
$tab = Tab::create(
'Details',
TextField::create('Name', _t(__CLASS__.'.FILENAME', 'Filename')),
$location = TreeDropdownField::create(
'ParentID',
_t(__CLASS__.'.FOLDERLOCATION', 'Location'),
Folder::class
)
->setShowSelectedPath(true)
);
$location
->setEmptyString(_t(__CLASS__.'.ROOTNAME', '(Top level)'))
->setShowSearch(true);
return $tab;
} | [
"protected",
"function",
"getFormFieldDetailsTab",
"(",
"$",
"record",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"/** @var Tab $tab */",
"$",
"tab",
"=",
"Tab",
"::",
"create",
"(",
"'Details'",
",",
"TextField",
"::",
"create",
"(",
"'Name'",
",",
"_t... | Build "details" formfield tab
@param File $record
@param array $context
@return Tab | [
"Build",
"details",
"formfield",
"tab"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/AssetFormFactory.php#L292-L310 | train |
silverstripe/silverstripe-asset-admin | code/Forms/AssetFormFactory.php | AssetFormFactory.getPath | protected function getPath($record, $context = [])
{
if ($record && $record->isInDB()) {
if ($record->ParentID) {
return $record->Parent()->getFilename();
} else {
return '/';
}
}
if (isset($context['ParentID'])) {
if ($context['ParentID'] === 0) {
return '/';
}
/** @var File $file */
$file = File::get()->byID($context['ParentID']);
if ($file) {
return $file->getFilename();
}
}
return null;
} | php | protected function getPath($record, $context = [])
{
if ($record && $record->isInDB()) {
if ($record->ParentID) {
return $record->Parent()->getFilename();
} else {
return '/';
}
}
if (isset($context['ParentID'])) {
if ($context['ParentID'] === 0) {
return '/';
}
/** @var File $file */
$file = File::get()->byID($context['ParentID']);
if ($file) {
return $file->getFilename();
}
}
return null;
} | [
"protected",
"function",
"getPath",
"(",
"$",
"record",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"record",
"&&",
"$",
"record",
"->",
"isInDB",
"(",
")",
")",
"{",
"if",
"(",
"$",
"record",
"->",
"ParentID",
")",
"{",
"return... | Get user-visible "Path" for this record
@param File $record
@param array $context
@return string | [
"Get",
"user",
"-",
"visible",
"Path",
"for",
"this",
"record"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/AssetFormFactory.php#L319-L339 | train |
silverstripe/silverstripe-asset-admin | code/Forms/AssetFormFactory.php | AssetFormFactory.getFormFieldSecurityTab | protected function getFormFieldSecurityTab($record, $context = [])
{
// Get permissions
$viewersOptionsField = [
'Inherit' => _t(__CLASS__.'.INHERIT', 'Inherit from parent folder'),
'Anyone' => _t(__CLASS__.'.ANYONE', 'Anyone'),
'LoggedInUsers' => _t(__CLASS__.'.LOGGED_IN', 'Logged-in users'),
'OnlyTheseUsers' => _t(__CLASS__.'.ONLY_GROUPS', 'Only these groups (choose from list)')
];
// No "Anyone" editors option
$editorsOptionsField = $viewersOptionsField;
unset($editorsOptionsField['Anyone']);
return Tab::create(
'Permissions',
OptionsetField::create(
'CanViewType',
_t(__CLASS__.'.ACCESSHEADER', 'Who can view this file?')
)
->setSource($viewersOptionsField),
TreeMultiselectField::create(
'ViewerGroups',
_t(__CLASS__.'.VIEWERGROUPS', 'Viewer Groups')
),
OptionsetField::create(
"CanEditType",
_t(__CLASS__.'.EDITHEADER', 'Who can edit this file?')
)
->setSource($editorsOptionsField),
TreeMultiselectField::create(
'EditorGroups',
_t(__CLASS__.'.EDITORGROUPS', 'Editor Groups')
)
);
} | php | protected function getFormFieldSecurityTab($record, $context = [])
{
// Get permissions
$viewersOptionsField = [
'Inherit' => _t(__CLASS__.'.INHERIT', 'Inherit from parent folder'),
'Anyone' => _t(__CLASS__.'.ANYONE', 'Anyone'),
'LoggedInUsers' => _t(__CLASS__.'.LOGGED_IN', 'Logged-in users'),
'OnlyTheseUsers' => _t(__CLASS__.'.ONLY_GROUPS', 'Only these groups (choose from list)')
];
// No "Anyone" editors option
$editorsOptionsField = $viewersOptionsField;
unset($editorsOptionsField['Anyone']);
return Tab::create(
'Permissions',
OptionsetField::create(
'CanViewType',
_t(__CLASS__.'.ACCESSHEADER', 'Who can view this file?')
)
->setSource($viewersOptionsField),
TreeMultiselectField::create(
'ViewerGroups',
_t(__CLASS__.'.VIEWERGROUPS', 'Viewer Groups')
),
OptionsetField::create(
"CanEditType",
_t(__CLASS__.'.EDITHEADER', 'Who can edit this file?')
)
->setSource($editorsOptionsField),
TreeMultiselectField::create(
'EditorGroups',
_t(__CLASS__.'.EDITORGROUPS', 'Editor Groups')
)
);
} | [
"protected",
"function",
"getFormFieldSecurityTab",
"(",
"$",
"record",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"// Get permissions",
"$",
"viewersOptionsField",
"=",
"[",
"'Inherit'",
"=>",
"_t",
"(",
"__CLASS__",
".",
"'.INHERIT'",
",",
"'Inherit from pa... | Build security tab
@param File $record
@param array $context
@return Tab | [
"Build",
"security",
"tab"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/AssetFormFactory.php#L348-L383 | train |
silverstripe/silverstripe-asset-admin | code/Forms/UploadField.php | UploadField.getFolderID | protected function getFolderID()
{
$folderName = $this->getFolderName();
if (!$folderName) {
return 0;
}
$folder = Folder::find_or_make($folderName);
return $folder ? $folder->ID : 0;
} | php | protected function getFolderID()
{
$folderName = $this->getFolderName();
if (!$folderName) {
return 0;
}
$folder = Folder::find_or_make($folderName);
return $folder ? $folder->ID : 0;
} | [
"protected",
"function",
"getFolderID",
"(",
")",
"{",
"$",
"folderName",
"=",
"$",
"this",
"->",
"getFolderName",
"(",
")",
";",
"if",
"(",
"!",
"$",
"folderName",
")",
"{",
"return",
"0",
";",
"}",
"$",
"folder",
"=",
"Folder",
"::",
"find_or_make",
... | Get ID of target parent folder
@return int | [
"Get",
"ID",
"of",
"target",
"parent",
"folder"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/UploadField.php#L185-L193 | train |
silverstripe/silverstripe-asset-admin | code/Forms/UploadField.php | UploadField.getEncodedItems | protected function getEncodedItems()
{
$assetAdmin = AssetAdmin::singleton();
$fileData = [];
foreach ($this->getItems() as $file) {
$fileData[] = $assetAdmin->getMinimalistObjectFromData($file);
}
return $fileData;
} | php | protected function getEncodedItems()
{
$assetAdmin = AssetAdmin::singleton();
$fileData = [];
foreach ($this->getItems() as $file) {
$fileData[] = $assetAdmin->getMinimalistObjectFromData($file);
}
return $fileData;
} | [
"protected",
"function",
"getEncodedItems",
"(",
")",
"{",
"$",
"assetAdmin",
"=",
"AssetAdmin",
"::",
"singleton",
"(",
")",
";",
"$",
"fileData",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getItems",
"(",
")",
"as",
"$",
"file",
")",
"... | Encode selected values for react
@return array | [
"Encode",
"selected",
"values",
"for",
"react"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/UploadField.php#L208-L216 | train |
silverstripe/silverstripe-asset-admin | code/Forms/UploadField.php | UploadField.getIsMultiUpload | public function getIsMultiUpload()
{
if (isset($this->multiUpload)) {
return $this->multiUpload;
}
// Guess from record
$record = $this->getRecord();
$name = $this->getName();
// Disabled for has_one components
if ($record && DataObject::getSchema()->hasOneComponent(get_class($record), $name)) {
return false;
}
return true;
} | php | public function getIsMultiUpload()
{
if (isset($this->multiUpload)) {
return $this->multiUpload;
}
// Guess from record
$record = $this->getRecord();
$name = $this->getName();
// Disabled for has_one components
if ($record && DataObject::getSchema()->hasOneComponent(get_class($record), $name)) {
return false;
}
return true;
} | [
"public",
"function",
"getIsMultiUpload",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"multiUpload",
")",
")",
"{",
"return",
"$",
"this",
"->",
"multiUpload",
";",
"}",
"// Guess from record",
"$",
"record",
"=",
"$",
"this",
"->",
"getRe... | Check if allowed to upload more than one file
@return bool | [
"Check",
"if",
"allowed",
"to",
"upload",
"more",
"than",
"one",
"file"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/UploadField.php#L223-L237 | train |
silverstripe/silverstripe-asset-admin | code/Forms/FileFormFactory.php | FileFormFactory.getFormFieldAttributesTab | protected function getFormFieldAttributesTab($record, $context = [])
{
return Tab::create(
'Placement',
LiteralField::create(
'AttributesDescription',
'<p>' . _t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AttributesDescription',
'These changes will only affect this particular placement of the file.'
) . '</p>'
),
TextField::create('Caption', _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Caption', 'Caption'))
);
} | php | protected function getFormFieldAttributesTab($record, $context = [])
{
return Tab::create(
'Placement',
LiteralField::create(
'AttributesDescription',
'<p>' . _t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AttributesDescription',
'These changes will only affect this particular placement of the file.'
) . '</p>'
),
TextField::create('Caption', _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Caption', 'Caption'))
);
} | [
"protected",
"function",
"getFormFieldAttributesTab",
"(",
"$",
"record",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"Tab",
"::",
"create",
"(",
"'Placement'",
",",
"LiteralField",
"::",
"create",
"(",
"'AttributesDescription'",
",",
"'<p>'",
".",... | Create tab for file attributes
@param File $record
@param array $context
@return Tab | [
"Create",
"tab",
"for",
"file",
"attributes"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/FileFormFactory.php#L169-L182 | train |
silverstripe/silverstripe-asset-admin | code/Forms/FileFormFactory.php | FileFormFactory.getPublishAction | protected function getPublishAction($record)
{
if (!$record || !$record->canPublish()) {
return null;
}
// Build action
$publishText = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.PUBLISH_BUTTON', 'Publish');
/** @var FormAction $action */
$action = FormAction::create('publish', $publishText)
->setIcon('rocket')
->setSchemaState([
'data' => [
'isPublished' => $record->isPublished(),
'isModified' => $record->isModifiedOnDraft(),
'pristineTitle' => _t(__CLASS__ . 'PUBLISHED', 'Published'),
'pristineIcon' => 'tick',
'dirtyTitle' => _t(__CLASS__ . 'PUBLISH', 'Publish'),
'dirtyIcon' => 'rocket',
'pristineClass' => 'btn-outline-primary',
'dirtyClass' => '',
],
])
->setSchemaData(['data' => ['buttonStyle' => 'primary']]);
return $action;
} | php | protected function getPublishAction($record)
{
if (!$record || !$record->canPublish()) {
return null;
}
// Build action
$publishText = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.PUBLISH_BUTTON', 'Publish');
/** @var FormAction $action */
$action = FormAction::create('publish', $publishText)
->setIcon('rocket')
->setSchemaState([
'data' => [
'isPublished' => $record->isPublished(),
'isModified' => $record->isModifiedOnDraft(),
'pristineTitle' => _t(__CLASS__ . 'PUBLISHED', 'Published'),
'pristineIcon' => 'tick',
'dirtyTitle' => _t(__CLASS__ . 'PUBLISH', 'Publish'),
'dirtyIcon' => 'rocket',
'pristineClass' => 'btn-outline-primary',
'dirtyClass' => '',
],
])
->setSchemaData(['data' => ['buttonStyle' => 'primary']]);
return $action;
} | [
"protected",
"function",
"getPublishAction",
"(",
"$",
"record",
")",
"{",
"if",
"(",
"!",
"$",
"record",
"||",
"!",
"$",
"record",
"->",
"canPublish",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Build action",
"$",
"publishText",
"=",
"_t",
"(... | Get publish action
@param File $record
@return FormAction | [
"Get",
"publish",
"action"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/FileFormFactory.php#L243-L269 | train |
silverstripe/silverstripe-asset-admin | code/Forms/FileFormFactory.php | FileFormFactory.getSpecsMarkup | protected function getSpecsMarkup($record)
{
if (!$record || !$record->exists()) {
return null;
}
return sprintf(
'<div class="editor__specs">%s %s</div>',
$record->getSize(),
$this->getStatusFlagMarkup($record)
);
} | php | protected function getSpecsMarkup($record)
{
if (!$record || !$record->exists()) {
return null;
}
return sprintf(
'<div class="editor__specs">%s %s</div>',
$record->getSize(),
$this->getStatusFlagMarkup($record)
);
} | [
"protected",
"function",
"getSpecsMarkup",
"(",
"$",
"record",
")",
"{",
"if",
"(",
"!",
"$",
"record",
"||",
"!",
"$",
"record",
"->",
"exists",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"sprintf",
"(",
"'<div class=\"editor__specs\">%s %s... | get HTML for status icon
@param File $record
@return null|string | [
"get",
"HTML",
"for",
"status",
"icon"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/FileFormFactory.php#L329-L339 | train |
silverstripe/silverstripe-asset-admin | code/Forms/FileFormFactory.php | FileFormFactory.getUnpublishAction | protected function getUnpublishAction($record)
{
// Check if record is unpublishable
if (!$record || !$record->isInDB() || !$record->isPublished() || !$record->canUnpublish()) {
return null;
}
// Count live owners
/** @var Versioned|RecursivePublishable $liveRecord */
$liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE)
->byID($record->ID);
$liveOwners = $liveRecord->findOwners(false)->count();
// Build action
$unpublishText = _t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.UNPUBLISH_BUTTON',
'Unpublish'
);
$action = FormAction::create('unpublish', $unpublishText)
->setIcon('cancel-circled')
->setSchemaData(['data' => ['owners' => $liveOwners]]);
return $action;
} | php | protected function getUnpublishAction($record)
{
// Check if record is unpublishable
if (!$record || !$record->isInDB() || !$record->isPublished() || !$record->canUnpublish()) {
return null;
}
// Count live owners
/** @var Versioned|RecursivePublishable $liveRecord */
$liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE)
->byID($record->ID);
$liveOwners = $liveRecord->findOwners(false)->count();
// Build action
$unpublishText = _t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.UNPUBLISH_BUTTON',
'Unpublish'
);
$action = FormAction::create('unpublish', $unpublishText)
->setIcon('cancel-circled')
->setSchemaData(['data' => ['owners' => $liveOwners]]);
return $action;
} | [
"protected",
"function",
"getUnpublishAction",
"(",
"$",
"record",
")",
"{",
"// Check if record is unpublishable",
"if",
"(",
"!",
"$",
"record",
"||",
"!",
"$",
"record",
"->",
"isInDB",
"(",
")",
"||",
"!",
"$",
"record",
"->",
"isPublished",
"(",
")",
... | Get action for publishing
@param File $record
@return FormAction | [
"Get",
"action",
"for",
"publishing"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/FileFormFactory.php#L361-L383 | train |
silverstripe/silverstripe-asset-admin | code/Forms/FileFormFactory.php | FileFormFactory.getReplaceFileAction | protected function getReplaceFileAction($record)
{
// Check if record exists and user has correct permissions
if (!$record || !$record->isInDB() || !$record->canEdit()) {
return null;
}
$action = FormAction::create('replacefile', _t(__CLASS__ . '.REPLACE_FILE', 'Replace file'))
->setIcon('upload');
return $action;
} | php | protected function getReplaceFileAction($record)
{
// Check if record exists and user has correct permissions
if (!$record || !$record->isInDB() || !$record->canEdit()) {
return null;
}
$action = FormAction::create('replacefile', _t(__CLASS__ . '.REPLACE_FILE', 'Replace file'))
->setIcon('upload');
return $action;
} | [
"protected",
"function",
"getReplaceFileAction",
"(",
"$",
"record",
")",
"{",
"// Check if record exists and user has correct permissions",
"if",
"(",
"!",
"$",
"record",
"||",
"!",
"$",
"record",
"->",
"isInDB",
"(",
")",
"||",
"!",
"$",
"record",
"->",
"canEd... | Get Replace file action
@param File $record
@return FormAction | [
"Get",
"Replace",
"file",
"action"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Forms/FileFormFactory.php#L391-L402 | train |
silverstripe/silverstripe-asset-admin | code/Extensions/RemoteFileModalExtension.php | RemoteFileModalExtension.remoteEditForm | public function remoteEditForm()
{
$url = $this->getRequest()->requestVar('embedurl');
$form = null;
$form = Injector::inst()->get(RemoteFileFormFactory::class)
->getForm(
$this->getOwner(),
'remoteEditForm',
['type' => 'edit', 'url' => $url]
);
return $form;
} | php | public function remoteEditForm()
{
$url = $this->getRequest()->requestVar('embedurl');
$form = null;
$form = Injector::inst()->get(RemoteFileFormFactory::class)
->getForm(
$this->getOwner(),
'remoteEditForm',
['type' => 'edit', 'url' => $url]
);
return $form;
} | [
"public",
"function",
"remoteEditForm",
"(",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"requestVar",
"(",
"'embedurl'",
")",
";",
"$",
"form",
"=",
"null",
";",
"$",
"form",
"=",
"Injector",
"::",
"inst",
"(",
")",
... | Form for editing a OEmbed object in the WYSIWYG, used by the InsertEmbedModal component
@return Form | [
"Form",
"for",
"editing",
"a",
"OEmbed",
"object",
"in",
"the",
"WYSIWYG",
"used",
"by",
"the",
"InsertEmbedModal",
"component"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Extensions/RemoteFileModalExtension.php#L78-L89 | train |
silverstripe/silverstripe-asset-admin | code/Extensions/RemoteFileModalExtension.php | RemoteFileModalExtension.remoteEditFormSchema | public function remoteEditFormSchema(HTTPRequest $request)
{
$schemaID = $request->getURL();
try {
$form = $this->remoteEditForm();
return $this->getSchemaResponse($schemaID, $form);
} catch (InvalidUrlException $exception) {
$errors = ValidationResult::create()
->addError($exception->getMessage());
// @todo - Don't create dummy form (pass $form = null)
$form = Form::create(null, 'Form', FieldList::create(), FieldList::create());
$code = $exception->getCode();
if ($code < 300) {
$code = 500;
}
return $this
->getSchemaResponse($schemaID, $form, $errors)
->setStatusCode($code);
}
} | php | public function remoteEditFormSchema(HTTPRequest $request)
{
$schemaID = $request->getURL();
try {
$form = $this->remoteEditForm();
return $this->getSchemaResponse($schemaID, $form);
} catch (InvalidUrlException $exception) {
$errors = ValidationResult::create()
->addError($exception->getMessage());
// @todo - Don't create dummy form (pass $form = null)
$form = Form::create(null, 'Form', FieldList::create(), FieldList::create());
$code = $exception->getCode();
if ($code < 300) {
$code = 500;
}
return $this
->getSchemaResponse($schemaID, $form, $errors)
->setStatusCode($code);
}
} | [
"public",
"function",
"remoteEditFormSchema",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"schemaID",
"=",
"$",
"request",
"->",
"getURL",
"(",
")",
";",
"try",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"remoteEditForm",
"(",
")",
";",
"return",
... | Capture the schema handling process, as there is validation done to the URL provided before form is generated
@param HTTPRequest $request
@return HTTPResponse | [
"Capture",
"the",
"schema",
"handling",
"process",
"as",
"there",
"is",
"validation",
"done",
"to",
"the",
"URL",
"provided",
"before",
"form",
"is",
"generated"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Extensions/RemoteFileModalExtension.php#L97-L118 | train |
silverstripe/silverstripe-asset-admin | code/Extensions/CampaignAdminExtension.php | CampaignAdminExtension.updatePopoverActions | public function updatePopoverActions(&$actions, $record)
{
if ($record && $record->canPublish()) {
$action = FormAction::create(
'addtocampaign',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ADDTOCAMPAIGN', 'Add to campaign')
)->setIcon('page-multiple');
array_unshift($actions, $action);
}
} | php | public function updatePopoverActions(&$actions, $record)
{
if ($record && $record->canPublish()) {
$action = FormAction::create(
'addtocampaign',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ADDTOCAMPAIGN', 'Add to campaign')
)->setIcon('page-multiple');
array_unshift($actions, $action);
}
} | [
"public",
"function",
"updatePopoverActions",
"(",
"&",
"$",
"actions",
",",
"$",
"record",
")",
"{",
"if",
"(",
"$",
"record",
"&&",
"$",
"record",
"->",
"canPublish",
"(",
")",
")",
"{",
"$",
"action",
"=",
"FormAction",
"::",
"create",
"(",
"'addtoc... | Update the Popover menu of `FileFormFactory` with the "Add to campaign" button.
@param array $actions
@param File $record | [
"Update",
"the",
"Popover",
"menu",
"of",
"FileFormFactory",
"with",
"the",
"Add",
"to",
"campaign",
"button",
"."
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Extensions/CampaignAdminExtension.php#L22-L31 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdminFile.php | AssetAdminFile.getInsertDimensions | protected function getInsertDimensions()
{
$width = $this->owner->getWidth();
$height = $this->owner->getHeight();
if (!$height || !$width) {
return null;
}
$maxWidth = $this->owner->config()->get('insert_width');
$maxHeight = $this->owner->config()->get('insert_height');
// Within bounds
if ($width < $maxWidth && $height < $maxHeight) {
return [
'width' => $width,
'height' => $height,
];
}
// Check if sizing by height or width
if (($width * $maxHeight) < ($height * $maxWidth)) {
// Size by height
return [
'width' => intval(($width * $maxHeight) / $height + 0.5),
'height' => $maxHeight,
];
} else {
// Size by width
return [
'width' => $maxWidth,
'height' => intval(($height * $maxWidth) / $width + 0.5),
];
}
} | php | protected function getInsertDimensions()
{
$width = $this->owner->getWidth();
$height = $this->owner->getHeight();
if (!$height || !$width) {
return null;
}
$maxWidth = $this->owner->config()->get('insert_width');
$maxHeight = $this->owner->config()->get('insert_height');
// Within bounds
if ($width < $maxWidth && $height < $maxHeight) {
return [
'width' => $width,
'height' => $height,
];
}
// Check if sizing by height or width
if (($width * $maxHeight) < ($height * $maxWidth)) {
// Size by height
return [
'width' => intval(($width * $maxHeight) / $height + 0.5),
'height' => $maxHeight,
];
} else {
// Size by width
return [
'width' => $maxWidth,
'height' => intval(($height * $maxWidth) / $width + 0.5),
];
}
} | [
"protected",
"function",
"getInsertDimensions",
"(",
")",
"{",
"$",
"width",
"=",
"$",
"this",
"->",
"owner",
"->",
"getWidth",
"(",
")",
";",
"$",
"height",
"=",
"$",
"this",
"->",
"owner",
"->",
"getHeight",
"(",
")",
";",
"if",
"(",
"!",
"$",
"h... | Get dimensions of this image sized within insert_width x insert_height
@return array|null | [
"Get",
"dimensions",
"of",
"this",
"image",
"sized",
"within",
"insert_width",
"x",
"insert_height"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdminFile.php#L75-L108 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdminFile.php | AssetAdminFile.getFilesInUse | public function getFilesInUse()
{
$list = ArrayList::create();
// Check SiteTreeFileExtension
if ($this->owner instanceof Folder) {
// Join on tracking table
$parents = static::nestedFolderIDs($this->owner->ID);
$linkQuery = FileLink::get()->sql($linkParams);
$list = File::get()->filter('ParentID', $parents)
->innerJoin(
"({$linkQuery})",
'"File"."ID" = "FileLinkTracking"."LinkedID"',
'FileLinkTracking',
20,
$linkParams
);
}
// Allow extension
$this->owner->extend('updateFilesInUse', $list);
return $list;
} | php | public function getFilesInUse()
{
$list = ArrayList::create();
// Check SiteTreeFileExtension
if ($this->owner instanceof Folder) {
// Join on tracking table
$parents = static::nestedFolderIDs($this->owner->ID);
$linkQuery = FileLink::get()->sql($linkParams);
$list = File::get()->filter('ParentID', $parents)
->innerJoin(
"({$linkQuery})",
'"File"."ID" = "FileLinkTracking"."LinkedID"',
'FileLinkTracking',
20,
$linkParams
);
}
// Allow extension
$this->owner->extend('updateFilesInUse', $list);
return $list;
} | [
"public",
"function",
"getFilesInUse",
"(",
")",
"{",
"$",
"list",
"=",
"ArrayList",
"::",
"create",
"(",
")",
";",
"// Check SiteTreeFileExtension",
"if",
"(",
"$",
"this",
"->",
"owner",
"instanceof",
"Folder",
")",
"{",
"// Join on tracking table",
"$",
"pa... | Get the list of all nested files in use
@return SS_List | [
"Get",
"the",
"list",
"of",
"all",
"nested",
"files",
"in",
"use"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdminFile.php#L182-L204 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdminFile.php | AssetAdminFile.nestedFolderIDs | public static function nestedFolderIDs($parentID, $maxDepth = 5)
{
$ids = [$parentID];
if ($maxDepth === 0) {
return $ids;
}
$childIDs = Folder::get()->filter('ParentID', $parentID)->column('ID');
foreach ($childIDs as $childID) {
$ids = array_merge($ids, static::nestedFolderIDs($childID, $maxDepth - 1));
}
return $ids;
} | php | public static function nestedFolderIDs($parentID, $maxDepth = 5)
{
$ids = [$parentID];
if ($maxDepth === 0) {
return $ids;
}
$childIDs = Folder::get()->filter('ParentID', $parentID)->column('ID');
foreach ($childIDs as $childID) {
$ids = array_merge($ids, static::nestedFolderIDs($childID, $maxDepth - 1));
}
return $ids;
} | [
"public",
"static",
"function",
"nestedFolderIDs",
"(",
"$",
"parentID",
",",
"$",
"maxDepth",
"=",
"5",
")",
"{",
"$",
"ids",
"=",
"[",
"$",
"parentID",
"]",
";",
"if",
"(",
"$",
"maxDepth",
"===",
"0",
")",
"{",
"return",
"$",
"ids",
";",
"}",
... | Get recursive parent IDs
@param int $parentID
@param int $maxDepth Hard limit of max depth
@return array List of parent IDs, including $parentID | [
"Get",
"recursive",
"parent",
"IDs"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdminFile.php#L213-L224 | train |
silverstripe/silverstripe-asset-admin | code/Model/ThumbnailGenerator.php | ThumbnailGenerator.generateThumbnailLink | public function generateThumbnailLink(AssetContainer $file, $width, $height)
{
$thumbnail = $this->generateThumbnail($file, $width, $height);
return $this->generateLink($thumbnail);
} | php | public function generateThumbnailLink(AssetContainer $file, $width, $height)
{
$thumbnail = $this->generateThumbnail($file, $width, $height);
return $this->generateLink($thumbnail);
} | [
"public",
"function",
"generateThumbnailLink",
"(",
"AssetContainer",
"$",
"file",
",",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"thumbnail",
"=",
"$",
"this",
"->",
"generateThumbnail",
"(",
"$",
"file",
",",
"$",
"width",
",",
"$",
"height",
")... | Generate thumbnail and return the "src" property for this thumbnail
@param AssetContainer|DBFile|File $file
@param int $width
@param int $height
@return string | [
"Generate",
"thumbnail",
"and",
"return",
"the",
"src",
"property",
"for",
"this",
"thumbnail"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Model/ThumbnailGenerator.php#L70-L75 | train |
silverstripe/silverstripe-asset-admin | code/Model/ThumbnailGenerator.php | ThumbnailGenerator.generateThumbnail | public function generateThumbnail(AssetContainer $file, $width, $height)
{
if (!$file->getIsImage() || !$file->exists()) {
return null;
}
// Disable generation if only querying existing files
if (!$this->getGenerates()) {
$file = $file->existingOnly();
}
// Make large thumbnail
return $file->FitMax($width, $height);
} | php | public function generateThumbnail(AssetContainer $file, $width, $height)
{
if (!$file->getIsImage() || !$file->exists()) {
return null;
}
// Disable generation if only querying existing files
if (!$this->getGenerates()) {
$file = $file->existingOnly();
}
// Make large thumbnail
return $file->FitMax($width, $height);
} | [
"public",
"function",
"generateThumbnail",
"(",
"AssetContainer",
"$",
"file",
",",
"$",
"width",
",",
"$",
"height",
")",
"{",
"if",
"(",
"!",
"$",
"file",
"->",
"getIsImage",
"(",
")",
"||",
"!",
"$",
"file",
"->",
"exists",
"(",
")",
")",
"{",
"... | Generate thumbnail object
@param AssetContainer|DBFile|File $file
@param int $width
@param int $height
@return AssetContainer|DBFile|File | [
"Generate",
"thumbnail",
"object"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Model/ThumbnailGenerator.php#L85-L98 | train |
silverstripe/silverstripe-asset-admin | code/Model/ThumbnailGenerator.php | ThumbnailGenerator.generateLink | public function generateLink(AssetContainer $thumbnail = null)
{
// Check if thumbnail can be found
if (!$thumbnail || !$thumbnail->exists() || !$thumbnail->getIsImage()) {
return null;
}
// Ensure thumbnail doesn't exceed safe bounds
$maxSize = $this->config()->get('max_thumbnail_bytes');
if (!$thumbnail->getAbsoluteSize() > $maxSize) {
return null;
}
// Determine best method to encode this thumbnail
$urlRules = $this->config()->get('thumbnail_links');
$visibility = $thumbnail->getVisibility();
$urlRule = $urlRules[$visibility];
if (!isset($urlRule)) {
throw new LogicException("Invalid visibility {$visibility}");
}
// Build thumbnail
switch ($urlRule) {
case self::URL:
return $thumbnail->getURL();
case self::INLINE:
// Generate inline content
$base64 = base64_encode($thumbnail->getString());
return sprintf(
'data:%s;base64,%s',
$thumbnail->getMimeType(),
$base64
);
default:
throw new LogicException("Invalid url rule {$urlRule}");
}
} | php | public function generateLink(AssetContainer $thumbnail = null)
{
// Check if thumbnail can be found
if (!$thumbnail || !$thumbnail->exists() || !$thumbnail->getIsImage()) {
return null;
}
// Ensure thumbnail doesn't exceed safe bounds
$maxSize = $this->config()->get('max_thumbnail_bytes');
if (!$thumbnail->getAbsoluteSize() > $maxSize) {
return null;
}
// Determine best method to encode this thumbnail
$urlRules = $this->config()->get('thumbnail_links');
$visibility = $thumbnail->getVisibility();
$urlRule = $urlRules[$visibility];
if (!isset($urlRule)) {
throw new LogicException("Invalid visibility {$visibility}");
}
// Build thumbnail
switch ($urlRule) {
case self::URL:
return $thumbnail->getURL();
case self::INLINE:
// Generate inline content
$base64 = base64_encode($thumbnail->getString());
return sprintf(
'data:%s;base64,%s',
$thumbnail->getMimeType(),
$base64
);
default:
throw new LogicException("Invalid url rule {$urlRule}");
}
} | [
"public",
"function",
"generateLink",
"(",
"AssetContainer",
"$",
"thumbnail",
"=",
"null",
")",
"{",
"// Check if thumbnail can be found",
"if",
"(",
"!",
"$",
"thumbnail",
"||",
"!",
"$",
"thumbnail",
"->",
"exists",
"(",
")",
"||",
"!",
"$",
"thumbnail",
... | Generate "src" property for this thumbnail.
This can be either a url or base64 encoded data
@param AssetContainer $thumbnail
@return string | [
"Generate",
"src",
"property",
"for",
"this",
"thumbnail",
".",
"This",
"can",
"be",
"either",
"a",
"url",
"or",
"base64",
"encoded",
"data"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Model/ThumbnailGenerator.php#L107-L143 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.