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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bugsnag/bugsnag-symfony | example/symfony28/app/SymfonyRequirements.php | RequirementCollection.getFailedRequirements | public function getFailedRequirements()
{
$array = [];
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && !$req->isOptional()) {
$array[] = $req;
}
}
return $array;
} | php | public function getFailedRequirements()
{
$array = [];
foreach ($this->requirements as $req) {
if (!$req->isFulfilled() && !$req->isOptional()) {
$array[] = $req;
}
}
return $array;
} | [
"public",
"function",
"getFailedRequirements",
"(",
")",
"{",
"$",
"array",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"requirements",
"as",
"$",
"req",
")",
"{",
"if",
"(",
"!",
"$",
"req",
"->",
"isFulfilled",
"(",
")",
"&&",
"!",
"$"... | Returns the mandatory requirements that were not met.
@return array Array of Requirement instances | [
"Returns",
"the",
"mandatory",
"requirements",
"that",
"were",
"not",
"met",
"."
] | c8c295905c7a2372a4489bf0d964b42d76c82346 | https://github.com/bugsnag/bugsnag-symfony/blob/c8c295905c7a2372a4489bf0d964b42d76c82346/example/symfony28/app/SymfonyRequirements.php#L297-L307 | train |
bearsunday/BEAR.Package | src/Bootstrap.php | Bootstrap.getApp | public function getApp(string $name, string $contexts, string $appDir = '') : AbstractApp
{
return $this->newApp(new Meta($name, $contexts, $appDir), $contexts);
} | php | public function getApp(string $name, string $contexts, string $appDir = '') : AbstractApp
{
return $this->newApp(new Meta($name, $contexts, $appDir), $contexts);
} | [
"public",
"function",
"getApp",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"contexts",
",",
"string",
"$",
"appDir",
"=",
"''",
")",
":",
"AbstractApp",
"{",
"return",
"$",
"this",
"->",
"newApp",
"(",
"new",
"Meta",
"(",
"$",
"name",
",",
"$",
... | Return application instance
Use newApp() instead for your own AppMeta and Cache.
@param string $name application name 'koriym\blog' (vendor\package)
@param string $contexts application context 'prod-html-app'
@param string $appDir application path | [
"Return",
"application",
"instance"
] | e9c951b0acc413f77314ca83f5d0d1585f4d8b53 | https://github.com/bearsunday/BEAR.Package/blob/e9c951b0acc413f77314ca83f5d0d1585f4d8b53/src/Bootstrap.php#L24-L27 | train |
bearsunday/BEAR.Package | src/Provide/Router/HttpMethodParams.php | HttpMethodParams.getParams | private function getParams($method, array $server, array $post) : array
{
// post data exists
if ($method === 'post' && ! empty($post)) {
return $post;
}
if (\in_array($method, ['post', 'put', 'patch', 'delete'], true)) {
return $this->phpInput($server);
}
return $post;
} | php | private function getParams($method, array $server, array $post) : array
{
// post data exists
if ($method === 'post' && ! empty($post)) {
return $post;
}
if (\in_array($method, ['post', 'put', 'patch', 'delete'], true)) {
return $this->phpInput($server);
}
return $post;
} | [
"private",
"function",
"getParams",
"(",
"$",
"method",
",",
"array",
"$",
"server",
",",
"array",
"$",
"post",
")",
":",
"array",
"{",
"// post data exists",
"if",
"(",
"$",
"method",
"===",
"'post'",
"&&",
"!",
"empty",
"(",
"$",
"post",
")",
")",
... | Return request parameters | [
"Return",
"request",
"parameters"
] | e9c951b0acc413f77314ca83f5d0d1585f4d8b53 | https://github.com/bearsunday/BEAR.Package/blob/e9c951b0acc413f77314ca83f5d0d1585f4d8b53/src/Provide/Router/HttpMethodParams.php#L87-L99 | train |
bearsunday/BEAR.Package | src/Provide/Router/HttpMethodParams.php | HttpMethodParams.phpInput | private function phpInput(array $server) : array
{
$contentType = $this->getContentType($server);
$isFormUrlEncoded = strpos($contentType, self::FORM_URL_ENCODE) !== false;
if ($isFormUrlEncoded) {
parse_str(rtrim($this->getRawBody($server)), $put);
return $put;
}
$isApplicationJson = strpos($contentType, self::APPLICATION_JSON) !== false;
if (! $isApplicationJson) {
return [];
}
$content = json_decode($this->getRawBody($server), true);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
throw new InvalidRequestJsonException(json_last_error_msg());
}
return $content;
} | php | private function phpInput(array $server) : array
{
$contentType = $this->getContentType($server);
$isFormUrlEncoded = strpos($contentType, self::FORM_URL_ENCODE) !== false;
if ($isFormUrlEncoded) {
parse_str(rtrim($this->getRawBody($server)), $put);
return $put;
}
$isApplicationJson = strpos($contentType, self::APPLICATION_JSON) !== false;
if (! $isApplicationJson) {
return [];
}
$content = json_decode($this->getRawBody($server), true);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
throw new InvalidRequestJsonException(json_last_error_msg());
}
return $content;
} | [
"private",
"function",
"phpInput",
"(",
"array",
"$",
"server",
")",
":",
"array",
"{",
"$",
"contentType",
"=",
"$",
"this",
"->",
"getContentType",
"(",
"$",
"server",
")",
";",
"$",
"isFormUrlEncoded",
"=",
"strpos",
"(",
"$",
"contentType",
",",
"sel... | Return request query by media-type | [
"Return",
"request",
"query",
"by",
"media",
"-",
"type"
] | e9c951b0acc413f77314ca83f5d0d1585f4d8b53 | https://github.com/bearsunday/BEAR.Package/blob/e9c951b0acc413f77314ca83f5d0d1585f4d8b53/src/Provide/Router/HttpMethodParams.php#L104-L124 | train |
bearsunday/BEAR.Package | src/Provide/Router/CliRouter.php | CliRouter.getStdIn | private function getStdIn(string $method, array $query, array &$server) : array
{
if ($method === 'put' || $method === 'patch' || $method === 'delete') {
$server[HttpMethodParams::CONTENT_TYPE] = HttpMethodParams::FORM_URL_ENCODE;
file_put_contents($this->stdIn, http_build_query($query));
return $server;
}
return $server;
} | php | private function getStdIn(string $method, array $query, array &$server) : array
{
if ($method === 'put' || $method === 'patch' || $method === 'delete') {
$server[HttpMethodParams::CONTENT_TYPE] = HttpMethodParams::FORM_URL_ENCODE;
file_put_contents($this->stdIn, http_build_query($query));
return $server;
}
return $server;
} | [
"private",
"function",
"getStdIn",
"(",
"string",
"$",
"method",
",",
"array",
"$",
"query",
",",
"array",
"&",
"$",
"server",
")",
":",
"array",
"{",
"if",
"(",
"$",
"method",
"===",
"'put'",
"||",
"$",
"method",
"===",
"'patch'",
"||",
"$",
"method... | Return StdIn in PUT, PATCH or DELETE | [
"Return",
"StdIn",
"in",
"PUT",
"PATCH",
"or",
"DELETE"
] | e9c951b0acc413f77314ca83f5d0d1585f4d8b53 | https://github.com/bearsunday/BEAR.Package/blob/e9c951b0acc413f77314ca83f5d0d1585f4d8b53/src/Provide/Router/CliRouter.php#L134-L144 | train |
gbrock/laravel-table | src/Table.php | Table.addColumn | public function addColumn()
{
$model = $this->models->first();
$new_column = forward_static_call_array([new Column(), 'create'], func_get_args());
$new_column->setOptionsFromModel($model);
$this->columns[] =& $new_column;
return $new_column;
} | php | public function addColumn()
{
$model = $this->models->first();
$new_column = forward_static_call_array([new Column(), 'create'], func_get_args());
$new_column->setOptionsFromModel($model);
$this->columns[] =& $new_column;
return $new_column;
} | [
"public",
"function",
"addColumn",
"(",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"models",
"->",
"first",
"(",
")",
";",
"$",
"new_column",
"=",
"forward_static_call_array",
"(",
"[",
"new",
"Column",
"(",
")",
",",
"'create'",
"]",
",",
"func_g... | Add one column to the table. | [
"Add",
"one",
"column",
"to",
"the",
"table",
"."
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Table.php#L68-L79 | train |
gbrock/laravel-table | src/Table.php | Table.addColumns | protected function addColumns($columns)
{
$model = $this->models->first();
if ($columns) {
foreach ($columns as $key => $field) {
if (is_numeric($key)) {
// Simple non-keyed array passed.
$new_column = Column::create($field);
} else {
// Key also matters, apparently
$new_column = Column::create($key, $field);
}
$new_column->setOptionsFromModel($model);
$this->columns[] = $new_column;
}
}
} | php | protected function addColumns($columns)
{
$model = $this->models->first();
if ($columns) {
foreach ($columns as $key => $field) {
if (is_numeric($key)) {
// Simple non-keyed array passed.
$new_column = Column::create($field);
} else {
// Key also matters, apparently
$new_column = Column::create($key, $field);
}
$new_column->setOptionsFromModel($model);
$this->columns[] = $new_column;
}
}
} | [
"protected",
"function",
"addColumns",
"(",
"$",
"columns",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"models",
"->",
"first",
"(",
")",
";",
"if",
"(",
"$",
"columns",
")",
"{",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"key",
"=>",
"$",
... | Add multiple columns at a time
@param $columns
@throws ColumnKeyNotProvidedException | [
"Add",
"multiple",
"columns",
"at",
"a",
"time"
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Table.php#L86-L105 | train |
gbrock/laravel-table | src/Table.php | Table.getFieldsFromModels | protected function getFieldsFromModels($models)
{
if (!$models->first()) {
// No models, we can't add any columns.
return [];
}
$model = $models->first();
// These are the Laravel basic timestamp fields which we don't want to display, by default
$timestamp_fields = ['created_at', 'updated_at', 'deleted_at'];
// Grab the basic fields from the first model
$fields = array_keys($model->toArray());
// Remove the timestamp fields
$fields = array_diff($fields, $timestamp_fields);
if ($model->isSortable) {
// Add the fields from the model's sortable array
$fields = array_unique(array_merge($fields, $model->getSortable()));
}
return $fields;
} | php | protected function getFieldsFromModels($models)
{
if (!$models->first()) {
// No models, we can't add any columns.
return [];
}
$model = $models->first();
// These are the Laravel basic timestamp fields which we don't want to display, by default
$timestamp_fields = ['created_at', 'updated_at', 'deleted_at'];
// Grab the basic fields from the first model
$fields = array_keys($model->toArray());
// Remove the timestamp fields
$fields = array_diff($fields, $timestamp_fields);
if ($model->isSortable) {
// Add the fields from the model's sortable array
$fields = array_unique(array_merge($fields, $model->getSortable()));
}
return $fields;
} | [
"protected",
"function",
"getFieldsFromModels",
"(",
"$",
"models",
")",
"{",
"if",
"(",
"!",
"$",
"models",
"->",
"first",
"(",
")",
")",
"{",
"// No models, we can't add any columns.",
"return",
"[",
"]",
";",
"}",
"$",
"model",
"=",
"$",
"models",
"->",... | Get fields based on a collection of models
@param $models
@return array | [
"Get",
"fields",
"based",
"on",
"a",
"collection",
"of",
"models"
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Table.php#L112-L133 | train |
gbrock/laravel-table | src/Table.php | Table.setModels | public function setModels($models)
{
if (!is_object($models)) {
if (is_array($models)) {
$models = collect($models);
}
}
if(class_basename($models->first()) == 'stdClass')
{
$models = $models->map(function ($array) {
return new BlankModel($array);
});
}
$this->models = $models;
} | php | public function setModels($models)
{
if (!is_object($models)) {
if (is_array($models)) {
$models = collect($models);
}
}
if(class_basename($models->first()) == 'stdClass')
{
$models = $models->map(function ($array) {
return new BlankModel($array);
});
}
$this->models = $models;
} | [
"public",
"function",
"setModels",
"(",
"$",
"models",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"models",
")",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"models",
")",
")",
"{",
"$",
"models",
"=",
"collect",
"(",
"$",
"models",
")",
";"... | Overwrite all current rows with the ones passed.
@param $models | [
"Overwrite",
"all",
"current",
"rows",
"with",
"the",
"ones",
"passed",
"."
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Table.php#L190-L206 | train |
gbrock/laravel-table | src/Table.php | Table.appendPaginationLinks | private function appendPaginationLinks()
{
if (class_basename($this->models) == 'LengthAwarePaginator') {
// This set of models was paginated. Make it append our current view variables.
$this->models->appends(Input::only(config('gbrock-tables.key_field'),
config('gbrock-tables.key_direction')));
}
} | php | private function appendPaginationLinks()
{
if (class_basename($this->models) == 'LengthAwarePaginator') {
// This set of models was paginated. Make it append our current view variables.
$this->models->appends(Input::only(config('gbrock-tables.key_field'),
config('gbrock-tables.key_direction')));
}
} | [
"private",
"function",
"appendPaginationLinks",
"(",
")",
"{",
"if",
"(",
"class_basename",
"(",
"$",
"this",
"->",
"models",
")",
"==",
"'LengthAwarePaginator'",
")",
"{",
"// This set of models was paginated. Make it append our current view variables.",
"$",
"this",
"-... | If rows were paginated, add our variables to the pagination query string | [
"If",
"rows",
"were",
"paginated",
"add",
"our",
"variables",
"to",
"the",
"pagination",
"query",
"string"
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Table.php#L219-L226 | train |
GoogleCloudPlatform/php-tools | src/Utils/Flex/FlexExecCommand.php | FlexExecCommand.resolveImage | protected function resolveImage(
InputInterface $input,
OutputInterface $output
) {
$service = $input->getOption('service');
if (empty($service)) {
$service = self::DEFAULT_SERVICE;
}
$version = $input->getOption('target-version');
if (empty($version)) {
$version = $this->detectLatestDeployedVersion(
$service,
$input,
$output
);
}
$output->writeln("Using service: <info>$service</info>");
$output->writeln("Using version: <info>$version</info>");
list($ret, $cmdOutput) = $this->gcloud->exec(
[
'app',
'versions',
'describe',
$version,
"--service=$service",
"--format=json"
]
);
if ($ret !== 0) {
$output->writeln('<error>Failed running `gcloud app versions describe`</error>');
exit(1);
}
$describe = json_decode(implode(PHP_EOL, $cmdOutput), true);
if (empty($describe)) {
$output->writeln('<error>Could not decode the result of `gcloud app versions describe`</error>');
exit(1);
}
if ($describe['env'] !== 'flexible') {
$output->writeln('<error>The deployment must be for App Engine Flex</error>');
exit(1);
}
$image = $describe['deployment']['container']['image'];
$cloudSqlInstances = '';
if (array_key_exists('betaSettings', $describe)
&& array_key_exists('cloud_sql_instances', $describe['betaSettings'])) {
$cloudSqlInstances = $describe['betaSettings']['cloud_sql_instances'];
}
return [$image, $cloudSqlInstances];
} | php | protected function resolveImage(
InputInterface $input,
OutputInterface $output
) {
$service = $input->getOption('service');
if (empty($service)) {
$service = self::DEFAULT_SERVICE;
}
$version = $input->getOption('target-version');
if (empty($version)) {
$version = $this->detectLatestDeployedVersion(
$service,
$input,
$output
);
}
$output->writeln("Using service: <info>$service</info>");
$output->writeln("Using version: <info>$version</info>");
list($ret, $cmdOutput) = $this->gcloud->exec(
[
'app',
'versions',
'describe',
$version,
"--service=$service",
"--format=json"
]
);
if ($ret !== 0) {
$output->writeln('<error>Failed running `gcloud app versions describe`</error>');
exit(1);
}
$describe = json_decode(implode(PHP_EOL, $cmdOutput), true);
if (empty($describe)) {
$output->writeln('<error>Could not decode the result of `gcloud app versions describe`</error>');
exit(1);
}
if ($describe['env'] !== 'flexible') {
$output->writeln('<error>The deployment must be for App Engine Flex</error>');
exit(1);
}
$image = $describe['deployment']['container']['image'];
$cloudSqlInstances = '';
if (array_key_exists('betaSettings', $describe)
&& array_key_exists('cloud_sql_instances', $describe['betaSettings'])) {
$cloudSqlInstances = $describe['betaSettings']['cloud_sql_instances'];
}
return [$image, $cloudSqlInstances];
} | [
"protected",
"function",
"resolveImage",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"service",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'service'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"service",
")",
... | Resolve the image name for the command execution. If the service is not
specified, it uses `default` service. If the version is not specified,
it will use the version of the latest deployment for the service.
@param InputInterface $input
@param OutputInterface $output
@return array An array with two values, the first is the image name and
the second is the Cloud SQL instance names. | [
"Resolve",
"the",
"image",
"name",
"for",
"the",
"command",
"execution",
".",
"If",
"the",
"service",
"is",
"not",
"specified",
"it",
"uses",
"default",
"service",
".",
"If",
"the",
"version",
"is",
"not",
"specified",
"it",
"will",
"use",
"the",
"version"... | a1eb4e2df5dbc96f5bf27707787456880d4945cd | https://github.com/GoogleCloudPlatform/php-tools/blob/a1eb4e2df5dbc96f5bf27707787456880d4945cd/src/Utils/Flex/FlexExecCommand.php#L190-L238 | train |
GoogleCloudPlatform/php-tools | src/Utils/ContainerExec.php | ContainerExec.run | public function run()
{
$template = $this->twig->load('cloudbuild.yaml.tmpl');
$context = [
'cloud_sql_instances' => $this->cloudSqlInstances,
'cloud_sql_proxy_image' => self::CLOUD_SQL_PROXY_IMAGE,
'target_image' => $this->image,
'commands' => implode(
',',
array_map('escapeshellarg', $this->commands)
)
];
$cloudBuildYaml = $template->render($context);
file_put_contents("$this->workdir/cloudbuild.yaml", $cloudBuildYaml);
list($result, $cmdOutput) = $this->gcloud->exec(
[
'container',
'builds',
'submit',
"--config=$this->workdir/cloudbuild.yaml",
"$this->workdir"
]
);
file_put_contents(
"$this->workdir/cloudbuild.log",
implode(PHP_EOL, $cmdOutput)
);
if ($result !== 0) {
throw new \RuntimeException("Failed to run the command");
}
$ret = '';
if ($this->cloudSqlInstances) {
$targetStep = 'Step #3';
} else {
$targetStep = 'Step #1';
}
foreach ($cmdOutput as $line) {
if (\strpos($line, $targetStep) !== false) {
$ret .= $line . PHP_EOL;
}
}
return $ret;
} | php | public function run()
{
$template = $this->twig->load('cloudbuild.yaml.tmpl');
$context = [
'cloud_sql_instances' => $this->cloudSqlInstances,
'cloud_sql_proxy_image' => self::CLOUD_SQL_PROXY_IMAGE,
'target_image' => $this->image,
'commands' => implode(
',',
array_map('escapeshellarg', $this->commands)
)
];
$cloudBuildYaml = $template->render($context);
file_put_contents("$this->workdir/cloudbuild.yaml", $cloudBuildYaml);
list($result, $cmdOutput) = $this->gcloud->exec(
[
'container',
'builds',
'submit',
"--config=$this->workdir/cloudbuild.yaml",
"$this->workdir"
]
);
file_put_contents(
"$this->workdir/cloudbuild.log",
implode(PHP_EOL, $cmdOutput)
);
if ($result !== 0) {
throw new \RuntimeException("Failed to run the command");
}
$ret = '';
if ($this->cloudSqlInstances) {
$targetStep = 'Step #3';
} else {
$targetStep = 'Step #1';
}
foreach ($cmdOutput as $line) {
if (\strpos($line, $targetStep) !== false) {
$ret .= $line . PHP_EOL;
}
}
return $ret;
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"twig",
"->",
"load",
"(",
"'cloudbuild.yaml.tmpl'",
")",
";",
"$",
"context",
"=",
"[",
"'cloud_sql_instances'",
"=>",
"$",
"this",
"->",
"cloudSqlInstances",
",",
"'clou... | Run the commands within the image, using Cloud Container Builder
@return string The output of the relevant build step of the Container
Builder job.
@throws \RuntimeException thrown when the command failed | [
"Run",
"the",
"commands",
"within",
"the",
"image",
"using",
"Cloud",
"Container",
"Builder"
] | a1eb4e2df5dbc96f5bf27707787456880d4945cd | https://github.com/GoogleCloudPlatform/php-tools/blob/a1eb4e2df5dbc96f5bf27707787456880d4945cd/src/Utils/ContainerExec.php#L80-L122 | train |
gbrock/laravel-table | src/Providers/TableServiceProvider.php | TableServiceProvider.boot | public function boot()
{
$root = __DIR__.'/../../';
// Load views
$this->loadViewsFrom($root . 'resources/views', 'gbrock');
// Publish views
$this->publishes([
$root . 'resources/views' => base_path('resources/views/vendor/gbrock'),
]);
// Publish configuration
$this->publishes([
$root . 'config/tables.php' => config_path('gbrock-tables.php'),
]);
// Merge user config, passing in our defaults
$this->mergeConfigFrom(
$root . 'config/tables.php', 'gbrock-tables'
);
// Publish assets
// $this->publishes([
// $root . 'build/assets' => public_path('vendor/gbrock/tables'),
// ], 'public');
} | php | public function boot()
{
$root = __DIR__.'/../../';
// Load views
$this->loadViewsFrom($root . 'resources/views', 'gbrock');
// Publish views
$this->publishes([
$root . 'resources/views' => base_path('resources/views/vendor/gbrock'),
]);
// Publish configuration
$this->publishes([
$root . 'config/tables.php' => config_path('gbrock-tables.php'),
]);
// Merge user config, passing in our defaults
$this->mergeConfigFrom(
$root . 'config/tables.php', 'gbrock-tables'
);
// Publish assets
// $this->publishes([
// $root . 'build/assets' => public_path('vendor/gbrock/tables'),
// ], 'public');
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"root",
"=",
"__DIR__",
".",
"'/../../'",
";",
"// Load views",
"$",
"this",
"->",
"loadViewsFrom",
"(",
"$",
"root",
".",
"'resources/views'",
",",
"'gbrock'",
")",
";",
"// Publish views",
"$",
"this",
"-... | Bootstrap the application files.
@return void | [
"Bootstrap",
"the",
"application",
"files",
"."
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Providers/TableServiceProvider.php#L24-L49 | train |
gbrock/laravel-table | src/Column.php | Column.setOptionsFromModel | public function setOptionsFromModel($model)
{
if (!$model) {
return $this;
}
if ($model->is_sortable && in_array($this->getField(), $model->getSortable())) {
// The model dictates that this column should be sortable
$this->setSortable(true);
}
$this->model = $model;
return $this;
} | php | public function setOptionsFromModel($model)
{
if (!$model) {
return $this;
}
if ($model->is_sortable && in_array($this->getField(), $model->getSortable())) {
// The model dictates that this column should be sortable
$this->setSortable(true);
}
$this->model = $model;
return $this;
} | [
"public",
"function",
"setOptionsFromModel",
"(",
"$",
"model",
")",
"{",
"if",
"(",
"!",
"$",
"model",
")",
"{",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"$",
"model",
"->",
"is_sortable",
"&&",
"in_array",
"(",
"$",
"this",
"->",
"getField",
"("... | Sets some common-sense options based on the underlying data model.
@param Model $model
@return $this | [
"Sets",
"some",
"common",
"-",
"sense",
"options",
"based",
"on",
"the",
"underlying",
"data",
"model",
"."
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Column.php#L79-L93 | train |
gbrock/laravel-table | src/Column.php | Column.isSorted | public function isSorted()
{
if (Request::input(config('gbrock-tables.key_field')) == $this->getField()) {
return true;
}
if (!Request::input(config('gbrock-tables.key_field')) && $this->model && $this->model->getSortingField() == $this->getField()) {
// No sorting was requested, but this is the default field.
return true;
}
return false;
} | php | public function isSorted()
{
if (Request::input(config('gbrock-tables.key_field')) == $this->getField()) {
return true;
}
if (!Request::input(config('gbrock-tables.key_field')) && $this->model && $this->model->getSortingField() == $this->getField()) {
// No sorting was requested, but this is the default field.
return true;
}
return false;
} | [
"public",
"function",
"isSorted",
"(",
")",
"{",
"if",
"(",
"Request",
"::",
"input",
"(",
"config",
"(",
"'gbrock-tables.key_field'",
")",
")",
"==",
"$",
"this",
"->",
"getField",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"Req... | Checks if this column is currently being sorted. | [
"Checks",
"if",
"this",
"column",
"is",
"currently",
"being",
"sorted",
"."
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Column.php#L98-L110 | train |
gbrock/laravel-table | src/Column.php | Column.getSortURL | public function getSortURL($direction = false)
{
if (!$direction) {
// No direction indicated, determine automatically from defaults.
$direction = $this->getDirection();
if ($this->isSorted()) {
// If we are already sorting by this column, swap the direction
$direction = $direction == 'asc' ? 'desc' : 'asc';
}
}
// Generate and return a URL which may be used to sort this column
return $this->generateUrl(array_filter([
config('gbrock-tables.key_field') => $this->getField(),
config('gbrock-tables.key_direction') => $direction,
]));
} | php | public function getSortURL($direction = false)
{
if (!$direction) {
// No direction indicated, determine automatically from defaults.
$direction = $this->getDirection();
if ($this->isSorted()) {
// If we are already sorting by this column, swap the direction
$direction = $direction == 'asc' ? 'desc' : 'asc';
}
}
// Generate and return a URL which may be used to sort this column
return $this->generateUrl(array_filter([
config('gbrock-tables.key_field') => $this->getField(),
config('gbrock-tables.key_direction') => $direction,
]));
} | [
"public",
"function",
"getSortURL",
"(",
"$",
"direction",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"direction",
")",
"{",
"// No direction indicated, determine automatically from defaults.",
"$",
"direction",
"=",
"$",
"this",
"->",
"getDirection",
"(",
")",
... | Generates a URL to toggle sorting by this column. | [
"Generates",
"a",
"URL",
"to",
"toggle",
"sorting",
"by",
"this",
"column",
"."
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Column.php#L115-L132 | train |
gbrock/laravel-table | src/Column.php | Column.getDirection | public function getDirection()
{
if ($this->isSorted()) {
// If the column is currently being sorted, grab the direction from the query string
$this->direction = Request::input(config('gbrock-tables.key_direction'));
}
if (!$this->direction) {
$this->direction = config('gbrock-tables.default_direction');
}
return $this->direction;
} | php | public function getDirection()
{
if ($this->isSorted()) {
// If the column is currently being sorted, grab the direction from the query string
$this->direction = Request::input(config('gbrock-tables.key_direction'));
}
if (!$this->direction) {
$this->direction = config('gbrock-tables.default_direction');
}
return $this->direction;
} | [
"public",
"function",
"getDirection",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isSorted",
"(",
")",
")",
"{",
"// If the column is currently being sorted, grab the direction from the query string",
"$",
"this",
"->",
"direction",
"=",
"Request",
"::",
"input",
... | Returns the default sorting
@return string | [
"Returns",
"the",
"default",
"sorting"
] | 6c953016e127502f0df857d1515a571863d01319 | https://github.com/gbrock/laravel-table/blob/6c953016e127502f0df857d1515a571863d01319/src/Column.php#L138-L150 | train |
GoogleCloudPlatform/php-tools | src/Utils/Gcloud.php | Gcloud.exec | public function exec($args)
{
$cmd = 'gcloud ' . implode(' ', array_map('escapeshellarg', $args));
exec($cmd, $output, $ret);
return [$ret, $output];
} | php | public function exec($args)
{
$cmd = 'gcloud ' . implode(' ', array_map('escapeshellarg', $args));
exec($cmd, $output, $ret);
return [$ret, $output];
} | [
"public",
"function",
"exec",
"(",
"$",
"args",
")",
"{",
"$",
"cmd",
"=",
"'gcloud '",
".",
"implode",
"(",
"' '",
",",
"array_map",
"(",
"'escapeshellarg'",
",",
"$",
"args",
")",
")",
";",
"exec",
"(",
"$",
"cmd",
",",
"$",
"output",
",",
"$",
... | Execute gcloud with the given argument.
@param array<string> $args
@return array [int, string] The shell return value and the command output | [
"Execute",
"gcloud",
"with",
"the",
"given",
"argument",
"."
] | a1eb4e2df5dbc96f5bf27707787456880d4945cd | https://github.com/GoogleCloudPlatform/php-tools/blob/a1eb4e2df5dbc96f5bf27707787456880d4945cd/src/Utils/Gcloud.php#L59-L64 | train |
GoogleCloudPlatform/php-tools | src/Utils/WordPress/Project.php | Project.initializeDatabase | public function initializeDatabase()
{
// Get the database region
$region = $this->input->getOption('db_region');
$availableDbRegions = $this->getAvailableDbRegions();
if (!in_array($region, $availableDbRegions)) {
$q = new ChoiceQuestion(
'Please select the region of your Cloud SQL instance '
. sprintf('(defaults to %s)', self::DEFAULT_DB_REGION),
$availableDbRegions,
array_search(self::DEFAULT_DB_REGION, $availableDbRegions)
);
$q->setErrorMessage('DB region %s is invalid.');
$region = $this->ask($q);
$this->output->writeln("Using db_region <info>$region</info>");
}
// Get the other DB parameters
$params = $this->askParameters([
'project_id' => '',
'db_instance' => '',
'db_name' => '',
'db_user' => 'root',
'db_password' => '',
]);
// Set the database connection string
$params['db_connection'] = sprintf(
'%s:%s:%s',
$params['project_id'],
$region,
$params['db_instance']
);
// Set parameters for a local database
$q = new ConfirmationQuestion(
'Do you want to use the same db user and password for local run? '
. '(Y/n)'
);
if ($this->ask($q)) {
$params += [
'local_db_user' => $params['db_user'],
'local_db_password' => $params['db_password'],
];
} else {
$params += $this->askParameters([
'local_db_user' => 'root',
'local_db_password' => '',
]);
}
return $params;
} | php | public function initializeDatabase()
{
// Get the database region
$region = $this->input->getOption('db_region');
$availableDbRegions = $this->getAvailableDbRegions();
if (!in_array($region, $availableDbRegions)) {
$q = new ChoiceQuestion(
'Please select the region of your Cloud SQL instance '
. sprintf('(defaults to %s)', self::DEFAULT_DB_REGION),
$availableDbRegions,
array_search(self::DEFAULT_DB_REGION, $availableDbRegions)
);
$q->setErrorMessage('DB region %s is invalid.');
$region = $this->ask($q);
$this->output->writeln("Using db_region <info>$region</info>");
}
// Get the other DB parameters
$params = $this->askParameters([
'project_id' => '',
'db_instance' => '',
'db_name' => '',
'db_user' => 'root',
'db_password' => '',
]);
// Set the database connection string
$params['db_connection'] = sprintf(
'%s:%s:%s',
$params['project_id'],
$region,
$params['db_instance']
);
// Set parameters for a local database
$q = new ConfirmationQuestion(
'Do you want to use the same db user and password for local run? '
. '(Y/n)'
);
if ($this->ask($q)) {
$params += [
'local_db_user' => $params['db_user'],
'local_db_password' => $params['db_password'],
];
} else {
$params += $this->askParameters([
'local_db_user' => 'root',
'local_db_password' => '',
]);
}
return $params;
} | [
"public",
"function",
"initializeDatabase",
"(",
")",
"{",
"// Get the database region",
"$",
"region",
"=",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'db_region'",
")",
";",
"$",
"availableDbRegions",
"=",
"$",
"this",
"->",
"getAvailableDbRegions",
... | Set up WordPress for Cloud SQL Generation 2 | [
"Set",
"up",
"WordPress",
"for",
"Cloud",
"SQL",
"Generation",
"2"
] | a1eb4e2df5dbc96f5bf27707787456880d4945cd | https://github.com/GoogleCloudPlatform/php-tools/blob/a1eb4e2df5dbc96f5bf27707787456880d4945cd/src/Utils/WordPress/Project.php#L97-L149 | train |
ozee31/cakephp-cors | src/Error/AppExceptionRenderer.php | AppExceptionRenderer._getController | protected function _getController()
{
$controller = parent::_getController();
$cors = new CorsMiddleware();
$controller->response = $cors(
$controller->request, $controller->response,
function($request, $response){ return $response; }
);
return $controller;
} | php | protected function _getController()
{
$controller = parent::_getController();
$cors = new CorsMiddleware();
$controller->response = $cors(
$controller->request, $controller->response,
function($request, $response){ return $response; }
);
return $controller;
} | [
"protected",
"function",
"_getController",
"(",
")",
"{",
"$",
"controller",
"=",
"parent",
"::",
"_getController",
"(",
")",
";",
"$",
"cors",
"=",
"new",
"CorsMiddleware",
"(",
")",
";",
"$",
"controller",
"->",
"response",
"=",
"$",
"cors",
"(",
"$",
... | Returns the current controller.
@return \Cake\Controller\Controller | [
"Returns",
"the",
"current",
"controller",
"."
] | da42a1aaf3a9093eda82cc40f11b84c90af79b79 | https://github.com/ozee31/cakephp-cors/blob/da42a1aaf3a9093eda82cc40f11b84c90af79b79/src/Error/AppExceptionRenderer.php#L25-L34 | train |
ADmad/CakePHP-HybridAuth | src/Controller/HybridAuthController.php | HybridAuthController.authenticated | public function authenticated()
{
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$this->dispatchEvent('HybridAuth.login', ['user' => $user]);
return $this->redirect($this->Auth->redirectUrl());
}
return $this->redirect($this->Auth->config('loginAction'));
} | php | public function authenticated()
{
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$this->dispatchEvent('HybridAuth.login', ['user' => $user]);
return $this->redirect($this->Auth->redirectUrl());
}
return $this->redirect($this->Auth->config('loginAction'));
} | [
"public",
"function",
"authenticated",
"(",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"Auth",
"->",
"identify",
"(",
")",
";",
"if",
"(",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"Auth",
"->",
"setUser",
"(",
"$",
"user",
")",
";",
"$",
"... | This action exists just to ensure AuthComponent fetches user info from
hybridauth after successful login
Hyridauth's `hauth_return_to` is set to this action.
@return \Cake\Network\Response | [
"This",
"action",
"exists",
"just",
"to",
"ensure",
"AuthComponent",
"fetches",
"user",
"info",
"from",
"hybridauth",
"after",
"successful",
"login"
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Controller/HybridAuthController.php#L47-L59 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate._init | protected function _init(Request $request)
{
if ($this->_initDone) {
return;
}
$this->_userModel = TableRegistry::get($this->_config['userModel']);
$this->_profileModel = TableRegistry::get($this->_config['profileModel']);
$request->session()->start();
$hybridConfig = Configure::read('HybridAuth');
if (empty($hybridConfig['base_url'])) {
$hybridConfig['base_url'] = [
'plugin' => 'ADmad/HybridAuth',
'controller' => 'HybridAuth',
'action' => 'endpoint',
'prefix' => false
];
}
$hybridConfig['base_url'] = $this->_appendRedirectQueryString(
$hybridConfig['base_url'],
$request->query(static::QUERY_STRING_REDIRECT)
);
$hybridConfig['base_url'] = Router::url($hybridConfig['base_url'], true);
try {
Hybrid_Auth::initialize($hybridConfig);
} catch (\Exception $e) {
if ($e->getCode() < 5) {
throw new \RuntimeException($e->getMessage());
} else {
$this->_registry->Auth->flash($e->getMessage());
Hybrid_Auth::initialize($hybridConfig);
}
}
} | php | protected function _init(Request $request)
{
if ($this->_initDone) {
return;
}
$this->_userModel = TableRegistry::get($this->_config['userModel']);
$this->_profileModel = TableRegistry::get($this->_config['profileModel']);
$request->session()->start();
$hybridConfig = Configure::read('HybridAuth');
if (empty($hybridConfig['base_url'])) {
$hybridConfig['base_url'] = [
'plugin' => 'ADmad/HybridAuth',
'controller' => 'HybridAuth',
'action' => 'endpoint',
'prefix' => false
];
}
$hybridConfig['base_url'] = $this->_appendRedirectQueryString(
$hybridConfig['base_url'],
$request->query(static::QUERY_STRING_REDIRECT)
);
$hybridConfig['base_url'] = Router::url($hybridConfig['base_url'], true);
try {
Hybrid_Auth::initialize($hybridConfig);
} catch (\Exception $e) {
if ($e->getCode() < 5) {
throw new \RuntimeException($e->getMessage());
} else {
$this->_registry->Auth->flash($e->getMessage());
Hybrid_Auth::initialize($hybridConfig);
}
}
} | [
"protected",
"function",
"_init",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_initDone",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"_userModel",
"=",
"TableRegistry",
"::",
"get",
"(",
"$",
"this",
"->",
"_config",
... | Initialize HybridAuth and this authenticator.
@param \Cake\Network\Request $request Request instance.
@return void
@throws \RuntimeException Incase case of unknown error. | [
"Initialize",
"HybridAuth",
"and",
"this",
"authenticator",
"."
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L99-L138 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate.getUser | public function getUser(Request $request)
{
$this->_init($request);
$providers = Hybrid_Auth::getConnectedProviders();
foreach ($providers as $provider) {
$adapter = Hybrid_Auth::getAdapter($provider);
return $this->_getUser($adapter);
}
return false;
} | php | public function getUser(Request $request)
{
$this->_init($request);
$providers = Hybrid_Auth::getConnectedProviders();
foreach ($providers as $provider) {
$adapter = Hybrid_Auth::getAdapter($provider);
return $this->_getUser($adapter);
}
return false;
} | [
"public",
"function",
"getUser",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"_init",
"(",
"$",
"request",
")",
";",
"$",
"providers",
"=",
"Hybrid_Auth",
"::",
"getConnectedProviders",
"(",
")",
";",
"foreach",
"(",
"$",
"providers",
"a... | Check if a provider is already connected, return user record if available.
@param \Cake\Network\Request $request Request instance.
@return array|bool User array on success, false on failure. | [
"Check",
"if",
"a",
"provider",
"is",
"already",
"connected",
"return",
"user",
"record",
"if",
"available",
"."
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L176-L188 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate._checkProvider | protected function _checkProvider($data)
{
$fields = $this->_config['fields'];
if (empty($data[$fields['provider']])) {
return false;
}
$provider = $data[$fields['provider']];
if ($provider === 'OpenID' && empty($data[$fields['openid_identifier']])) {
return false;
}
return $provider;
} | php | protected function _checkProvider($data)
{
$fields = $this->_config['fields'];
if (empty($data[$fields['provider']])) {
return false;
}
$provider = $data[$fields['provider']];
if ($provider === 'OpenID' && empty($data[$fields['openid_identifier']])) {
return false;
}
return $provider;
} | [
"protected",
"function",
"_checkProvider",
"(",
"$",
"data",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"_config",
"[",
"'fields'",
"]",
";",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"$",
"fields",
"[",
"'provider'",
"]",
"]",
")",
")",
"{"... | Checks whether provider is supplied.
@param array $data Data array to check.
@return string|bool Provider name if it exists, false if required fields have
not been supplied. | [
"Checks",
"whether",
"provider",
"is",
"supplied",
"."
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L244-L259 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate._getUser | protected function _getUser($adapter)
{
try {
$providerProfile = $adapter->getUserProfile();
$this->adapter($adapter);
$this->profile($providerProfile);
} catch (\Exception $e) {
$adapter->logout();
throw $e;
}
$config = $this->_config;
$userModel = $this->_userModel;
$user = null;
$profile = $this->_query($providerProfile->identifier)->first();
if ($profile) {
$userId = $profile->get($config['profileModelFkField']);
$user = $this->_userModel->find($config['finder'])
->where([
$userModel->aliasField($userModel->primaryKey()) => $userId
])
->first();
// User record exists but finder conditions did not match,
// so just update social profile record and return false.
if (!$user) {
$profile = $this->_profileEntity($profile);
if (!$this->_profileModel->save($profile)) {
throw new \RuntimeException('Unable to save social profile.');
}
return false;
}
} elseif ($providerProfile->email) {
$user = $this->_userModel->find($config['finder'])
->where([
$this->_userModel->aliasField($config['fields']['email']) => $providerProfile->email
])
->first();
}
$profile = $this->_profileEntity($profile);
if (!$user) {
$user = $this->_newUser($profile);
}
$profile->{$config['profileModelFkField']} = $user->{$userModel->primaryKey()};
$profile = $this->_profileModel->save($profile);
if (!$profile) {
throw new \RuntimeException('Unable to save social profile.');
}
$user->set('social_profile', $profile);
$user->unsetProperty($config['fields']['password']);
return $user->toArray();
} | php | protected function _getUser($adapter)
{
try {
$providerProfile = $adapter->getUserProfile();
$this->adapter($adapter);
$this->profile($providerProfile);
} catch (\Exception $e) {
$adapter->logout();
throw $e;
}
$config = $this->_config;
$userModel = $this->_userModel;
$user = null;
$profile = $this->_query($providerProfile->identifier)->first();
if ($profile) {
$userId = $profile->get($config['profileModelFkField']);
$user = $this->_userModel->find($config['finder'])
->where([
$userModel->aliasField($userModel->primaryKey()) => $userId
])
->first();
// User record exists but finder conditions did not match,
// so just update social profile record and return false.
if (!$user) {
$profile = $this->_profileEntity($profile);
if (!$this->_profileModel->save($profile)) {
throw new \RuntimeException('Unable to save social profile.');
}
return false;
}
} elseif ($providerProfile->email) {
$user = $this->_userModel->find($config['finder'])
->where([
$this->_userModel->aliasField($config['fields']['email']) => $providerProfile->email
])
->first();
}
$profile = $this->_profileEntity($profile);
if (!$user) {
$user = $this->_newUser($profile);
}
$profile->{$config['profileModelFkField']} = $user->{$userModel->primaryKey()};
$profile = $this->_profileModel->save($profile);
if (!$profile) {
throw new \RuntimeException('Unable to save social profile.');
}
$user->set('social_profile', $profile);
$user->unsetProperty($config['fields']['password']);
return $user->toArray();
} | [
"protected",
"function",
"_getUser",
"(",
"$",
"adapter",
")",
"{",
"try",
"{",
"$",
"providerProfile",
"=",
"$",
"adapter",
"->",
"getUserProfile",
"(",
")",
";",
"$",
"this",
"->",
"adapter",
"(",
"$",
"adapter",
")",
";",
"$",
"this",
"->",
"profile... | Get user record for HybridAuth adapter and try to get associated user record
from your application's database.
If app user record is not found a 'HybridAuth.newUser' event is dispatched
with profile info from HyridAuth. The event listener should create associated
user record and return user entity as event result.
@param \Hybrid_Provider_Model $adapter Hybrid auth adapter instance.
@return array User record
@throws \Exception Thrown when a profile cannot be retrieved.
@throws \RuntimeException If profile entity cannot be persisted. | [
"Get",
"user",
"record",
"for",
"HybridAuth",
"adapter",
"and",
"try",
"to",
"get",
"associated",
"user",
"record",
"from",
"your",
"application",
"s",
"database",
"."
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L274-L332 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate._query | protected function _query($identifier)
{
list(, $userAlias) = pluginSplit($this->_config['userModel']);
$provider = $this->adapter()->id;
return $this->_profileModel->find()
->where([
$this->_profileModel->aliasField('provider') => $provider,
$this->_profileModel->aliasField('identifier') => $identifier
]);
} | php | protected function _query($identifier)
{
list(, $userAlias) = pluginSplit($this->_config['userModel']);
$provider = $this->adapter()->id;
return $this->_profileModel->find()
->where([
$this->_profileModel->aliasField('provider') => $provider,
$this->_profileModel->aliasField('identifier') => $identifier
]);
} | [
"protected",
"function",
"_query",
"(",
"$",
"identifier",
")",
"{",
"list",
"(",
",",
"$",
"userAlias",
")",
"=",
"pluginSplit",
"(",
"$",
"this",
"->",
"_config",
"[",
"'userModel'",
"]",
")",
";",
"$",
"provider",
"=",
"$",
"this",
"->",
"adapter",
... | Get query to fetch social profile record.
@param string $identifier Provider's identifier.
@return \Cake\ORM\Query | [
"Get",
"query",
"to",
"fetch",
"social",
"profile",
"record",
"."
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L367-L377 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate._profileEntity | protected function _profileEntity($profile = null)
{
if (!$profile) {
$profile = $this->_profileModel->newEntity([
'provider' => $this->adapter()->id,
]);
}
foreach (get_object_vars($this->profile()) as $key => $value) {
switch ($key) {
case 'webSiteURL':
$profile->set('website_url', $value);
break;
case 'profileURL':
$profile->set('profile_url', $value);
break;
case 'photoURL':
$profile->set('photo_url', $value);
break;
default:
$profile->set(Inflector::underscore($key), $value);
break;
}
}
return $profile;
} | php | protected function _profileEntity($profile = null)
{
if (!$profile) {
$profile = $this->_profileModel->newEntity([
'provider' => $this->adapter()->id,
]);
}
foreach (get_object_vars($this->profile()) as $key => $value) {
switch ($key) {
case 'webSiteURL':
$profile->set('website_url', $value);
break;
case 'profileURL':
$profile->set('profile_url', $value);
break;
case 'photoURL':
$profile->set('photo_url', $value);
break;
default:
$profile->set(Inflector::underscore($key), $value);
break;
}
}
return $profile;
} | [
"protected",
"function",
"_profileEntity",
"(",
"$",
"profile",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"profile",
")",
"{",
"$",
"profile",
"=",
"$",
"this",
"->",
"_profileModel",
"->",
"newEntity",
"(",
"[",
"'provider'",
"=>",
"$",
"this",
"->"... | Get social profile entity
@param \Cake\ORM\Entity $profile Social profile entity
@return \Cake\ORM\Entity | [
"Get",
"social",
"profile",
"entity"
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L385-L414 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate.logout | public function logout(Event $event, array $user)
{
$this->_init($event->subject()->request);
Hybrid_Auth::logoutAllProviders();
} | php | public function logout(Event $event, array $user)
{
$this->_init($event->subject()->request);
Hybrid_Auth::logoutAllProviders();
} | [
"public",
"function",
"logout",
"(",
"Event",
"$",
"event",
",",
"array",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"_init",
"(",
"$",
"event",
"->",
"subject",
"(",
")",
"->",
"request",
")",
";",
"Hybrid_Auth",
"::",
"logoutAllProviders",
"(",
")",
... | Logout all providers
@param \Cake\Event\Event $event Event.
@param array $user The user about to be logged out.
@return void | [
"Logout",
"all",
"providers"
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L423-L427 | train |
ADmad/CakePHP-HybridAuth | src/Auth/HybridAuthAuthenticate.php | HybridAuthAuthenticate._appendRedirectQueryString | protected function _appendRedirectQueryString($url, $redirectQueryString)
{
if (!$redirectQueryString) {
return $url;
}
if (is_array($url)) {
$url['?'][static::QUERY_STRING_REDIRECT] = $redirectQueryString;
} else {
$char = strpos($url, '?') === false ? '?' : '&';
$url .= $char . static::QUERY_STRING_REDIRECT . '=' . urlencode($redirectQueryString);
}
return $url;
} | php | protected function _appendRedirectQueryString($url, $redirectQueryString)
{
if (!$redirectQueryString) {
return $url;
}
if (is_array($url)) {
$url['?'][static::QUERY_STRING_REDIRECT] = $redirectQueryString;
} else {
$char = strpos($url, '?') === false ? '?' : '&';
$url .= $char . static::QUERY_STRING_REDIRECT . '=' . urlencode($redirectQueryString);
}
return $url;
} | [
"protected",
"function",
"_appendRedirectQueryString",
"(",
"$",
"url",
",",
"$",
"redirectQueryString",
")",
"{",
"if",
"(",
"!",
"$",
"redirectQueryString",
")",
"{",
"return",
"$",
"url",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"url",
")",
")",
"{"... | Append the "redirect" query string param to URL.
@param string|array $url URL
@param string $redirectQueryString Redirect query string
@return string URL | [
"Append",
"the",
"redirect",
"query",
"string",
"param",
"to",
"URL",
"."
] | f2b68a3c28aad717b8529adb72f2929aaaffb0a3 | https://github.com/ADmad/CakePHP-HybridAuth/blob/f2b68a3c28aad717b8529adb72f2929aaaffb0a3/src/Auth/HybridAuthAuthenticate.php#L446-L460 | train |
vinkla/laravel-algolia | src/AlgoliaFactory.php | AlgoliaFactory.make | public function make(array $config): SearchClient
{
$config = $this->getConfig($config);
return $this->getClient($config);
} | php | public function make(array $config): SearchClient
{
$config = $this->getConfig($config);
return $this->getClient($config);
} | [
"public",
"function",
"make",
"(",
"array",
"$",
"config",
")",
":",
"SearchClient",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"$",
"config",
")",
";",
"return",
"$",
"this",
"->",
"getClient",
"(",
"$",
"config",
")",
";",
"}"
] | Make a new Algolia client.
@param array $config
@return \Algolia\AlgoliaSearch\SearchClient | [
"Make",
"a",
"new",
"Algolia",
"client",
"."
] | 2280f268285073d1edf882b32bb7e59581e831ea | https://github.com/vinkla/laravel-algolia/blob/2280f268285073d1edf882b32bb7e59581e831ea/src/AlgoliaFactory.php#L33-L38 | train |
payjp/payjp-php | lib/Util/Util.php | Util.convertPayjpObjectToArray | public static function convertPayjpObjectToArray($values)
{
$results = array();
foreach ($values as $k => $v) {
// FIXME: this is an encapsulation violation
if ($k[0] == '_') {
continue;
}
if ($v instanceof PayjpObject) {
$results[$k] = $v->__toArray(true);
} elseif (is_array($v)) {
$results[$k] = self::convertPayjpObjectToArray($v);
} else {
$results[$k] = $v;
}
}
return $results;
} | php | public static function convertPayjpObjectToArray($values)
{
$results = array();
foreach ($values as $k => $v) {
// FIXME: this is an encapsulation violation
if ($k[0] == '_') {
continue;
}
if ($v instanceof PayjpObject) {
$results[$k] = $v->__toArray(true);
} elseif (is_array($v)) {
$results[$k] = self::convertPayjpObjectToArray($v);
} else {
$results[$k] = $v;
}
}
return $results;
} | [
"public",
"static",
"function",
"convertPayjpObjectToArray",
"(",
"$",
"values",
")",
"{",
"$",
"results",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"// FIXME: this is an encapsulation violation",
"... | Recursively converts the PHP Payjp object to an array.
@param array $values The PHP Payjp object to convert.
@return array | [
"Recursively",
"converts",
"the",
"PHP",
"Payjp",
"object",
"to",
"an",
"array",
"."
] | f4bf823cfabe83011f2f14cc8e862380fb3e6232 | https://github.com/payjp/payjp-php/blob/f4bf823cfabe83011f2f14cc8e862380fb3e6232/lib/Util/Util.php#L36-L53 | train |
payjp/payjp-php | lib/Util/Util.php | Util.convertToPayjpObject | public static function convertToPayjpObject($resp, $opts)
{
$types = array(
'account' => 'Payjp\\Account',
'card' => 'Payjp\\Card',
'charge' => 'Payjp\\Charge',
'customer' => 'Payjp\\Customer',
'list' => 'Payjp\\Collection',
'event' => 'Payjp\\Event',
'token' => 'Payjp\\Token',
'transfer' => 'Payjp\\Transfer',
'plan' => 'Payjp\\Plan',
'subscription' => 'Payjp\\Subscription',
);
if (self::isList($resp)) {
$mapped = array();
foreach ($resp as $i) {
array_push($mapped, self::convertToPayjpObject($i, $opts));
}
return $mapped;
} elseif (is_array($resp)) {
if (isset($resp['object']) && is_string($resp['object']) && isset($types[$resp['object']])) {
$class = $types[$resp['object']];
} else {
$class = 'Payjp\\PayjpObject';
}
return $class::constructFrom($resp, $opts);
} else {
return $resp;
}
} | php | public static function convertToPayjpObject($resp, $opts)
{
$types = array(
'account' => 'Payjp\\Account',
'card' => 'Payjp\\Card',
'charge' => 'Payjp\\Charge',
'customer' => 'Payjp\\Customer',
'list' => 'Payjp\\Collection',
'event' => 'Payjp\\Event',
'token' => 'Payjp\\Token',
'transfer' => 'Payjp\\Transfer',
'plan' => 'Payjp\\Plan',
'subscription' => 'Payjp\\Subscription',
);
if (self::isList($resp)) {
$mapped = array();
foreach ($resp as $i) {
array_push($mapped, self::convertToPayjpObject($i, $opts));
}
return $mapped;
} elseif (is_array($resp)) {
if (isset($resp['object']) && is_string($resp['object']) && isset($types[$resp['object']])) {
$class = $types[$resp['object']];
} else {
$class = 'Payjp\\PayjpObject';
}
return $class::constructFrom($resp, $opts);
} else {
return $resp;
}
} | [
"public",
"static",
"function",
"convertToPayjpObject",
"(",
"$",
"resp",
",",
"$",
"opts",
")",
"{",
"$",
"types",
"=",
"array",
"(",
"'account'",
"=>",
"'Payjp\\\\Account'",
",",
"'card'",
"=>",
"'Payjp\\\\Card'",
",",
"'charge'",
"=>",
"'Payjp\\\\Charge'",
... | Converts a response from the Payjp API to the corresponding PHP object.
@param array $resp The response from the Payjp API.
@param array $opts
@return Object|array | [
"Converts",
"a",
"response",
"from",
"the",
"Payjp",
"API",
"to",
"the",
"corresponding",
"PHP",
"object",
"."
] | f4bf823cfabe83011f2f14cc8e862380fb3e6232 | https://github.com/payjp/payjp-php/blob/f4bf823cfabe83011f2f14cc8e862380fb3e6232/lib/Util/Util.php#L62-L92 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/Result.php | Result.findItem | private function findItem($item, $arr, $key) {
for($j = 0; $j < count($arr); $j++) {
if($arr[$j]->$key == $item->$key) {
return $j;
}
}
return false;
} | php | private function findItem($item, $arr, $key) {
for($j = 0; $j < count($arr); $j++) {
if($arr[$j]->$key == $item->$key) {
return $j;
}
}
return false;
} | [
"private",
"function",
"findItem",
"(",
"$",
"item",
",",
"$",
"arr",
",",
"$",
"key",
")",
"{",
"for",
"(",
"$",
"j",
"=",
"0",
";",
"$",
"j",
"<",
"count",
"(",
"$",
"arr",
")",
";",
"$",
"j",
"++",
")",
"{",
"if",
"(",
"$",
"arr",
"[",... | finds if an array contains an item, comparing the property given as key
@param $item
@param $arr
@param $key
@return the position that was removed, false if not found | [
"finds",
"if",
"an",
"array",
"contains",
"an",
"item",
"comparing",
"the",
"property",
"given",
"as",
"key"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/Result.php#L372-L379 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/Client.php | Client.imageStatus | function imageStatus($key, $url) {
$request = curl_init();
curl_setopt_array($request, $this->options);
//$this->prepareJSONRequest(self::API_STATUS_ENDPOINT(), $request, array('key' => $key), 'post', array());
curl_setopt($request, CURLOPT_URL, self::IMAGE_STATUS_ENDPOINT());
curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($request, CURLOPT_HTTPHEADER, array());
$params = array('key' => $key, 'url' => $url);
curl_setopt($request, CURLOPT_POSTFIELDS, json_encode($params));
return $this->sendRequest($request, 1);
} | php | function imageStatus($key, $url) {
$request = curl_init();
curl_setopt_array($request, $this->options);
//$this->prepareJSONRequest(self::API_STATUS_ENDPOINT(), $request, array('key' => $key), 'post', array());
curl_setopt($request, CURLOPT_URL, self::IMAGE_STATUS_ENDPOINT());
curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($request, CURLOPT_HTTPHEADER, array());
$params = array('key' => $key, 'url' => $url);
curl_setopt($request, CURLOPT_POSTFIELDS, json_encode($params));
return $this->sendRequest($request, 1);
} | [
"function",
"imageStatus",
"(",
"$",
"key",
",",
"$",
"url",
")",
"{",
"$",
"request",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt_array",
"(",
"$",
"request",
",",
"$",
"this",
"->",
"options",
")",
";",
"//$this->prepareJSONRequest(self::API_STATUS_ENDPOIN... | Method that checks the status of an image being optimized
@param $key
@param $url
@return array
@throws ConnectionException | [
"Method",
"that",
"checks",
"the",
"status",
"of",
"an",
"image",
"being",
"optimized"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/Client.php#L501-L511 | train |
semaio/Magento2-ConfigImportExport | Model/Validator/ScopeValidator.php | ScopeValidator.validate | public function validate($scope, $scopeId)
{
$valid = true;
if ($scope === 'default') { // Default Store only valid for id 0
if ($scopeId !== 0) {
$valid = false;
}
} elseif ($scope === 'websites') { // Check if website with id exists
$valid = $this->isValidWebsiteId($scopeId);
} elseif ($scope === 'stores') { // Check if store with id exists
$valid = $this->isValidStoreId($scopeId);
}
return $valid;
} | php | public function validate($scope, $scopeId)
{
$valid = true;
if ($scope === 'default') { // Default Store only valid for id 0
if ($scopeId !== 0) {
$valid = false;
}
} elseif ($scope === 'websites') { // Check if website with id exists
$valid = $this->isValidWebsiteId($scopeId);
} elseif ($scope === 'stores') { // Check if store with id exists
$valid = $this->isValidStoreId($scopeId);
}
return $valid;
} | [
"public",
"function",
"validate",
"(",
"$",
"scope",
",",
"$",
"scopeId",
")",
"{",
"$",
"valid",
"=",
"true",
";",
"if",
"(",
"$",
"scope",
"===",
"'default'",
")",
"{",
"// Default Store only valid for id 0",
"if",
"(",
"$",
"scopeId",
"!==",
"0",
")",... | Validates the given scope and scope id
@param string $scope Scope
@param int $scopeId Scope ID
@return bool | [
"Validates",
"the",
"given",
"scope",
"and",
"scope",
"id"
] | e14c49b13abd9a2ef01dafb94ebb9d91589e85a0 | https://github.com/semaio/Magento2-ConfigImportExport/blob/e14c49b13abd9a2ef01dafb94ebb9d91589e85a0/Model/Validator/ScopeValidator.php#L39-L53 | train |
semaio/Magento2-ConfigImportExport | Model/Validator/ScopeValidator.php | ScopeValidator.isValidWebsiteId | private function isValidWebsiteId($websiteId)
{
$websites = $this->storeManager->getWebsites();
if (array_key_exists($websiteId, $websites)) {
return true;
}
if (is_numeric($websiteId)) {
// Dont bother checking website codes on numeric input
return false;
}
// @todo hs: build up array of websiteCodes, to prevent wasting time looping
/** @var Website $website */
foreach ($websites as $website) {
if ($website->getCode() == $websiteId) {
return true;
}
}
return false;
} | php | private function isValidWebsiteId($websiteId)
{
$websites = $this->storeManager->getWebsites();
if (array_key_exists($websiteId, $websites)) {
return true;
}
if (is_numeric($websiteId)) {
// Dont bother checking website codes on numeric input
return false;
}
// @todo hs: build up array of websiteCodes, to prevent wasting time looping
/** @var Website $website */
foreach ($websites as $website) {
if ($website->getCode() == $websiteId) {
return true;
}
}
return false;
} | [
"private",
"function",
"isValidWebsiteId",
"(",
"$",
"websiteId",
")",
"{",
"$",
"websites",
"=",
"$",
"this",
"->",
"storeManager",
"->",
"getWebsites",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"websiteId",
",",
"$",
"websites",
")",
")",
... | Check if the given website id is a valid website id
@param int $websiteId Website ID
@return bool | [
"Check",
"if",
"the",
"given",
"website",
"id",
"is",
"a",
"valid",
"website",
"id"
] | e14c49b13abd9a2ef01dafb94ebb9d91589e85a0 | https://github.com/semaio/Magento2-ConfigImportExport/blob/e14c49b13abd9a2ef01dafb94ebb9d91589e85a0/Model/Validator/ScopeValidator.php#L61-L81 | train |
semaio/Magento2-ConfigImportExport | Model/Validator/ScopeValidator.php | ScopeValidator.isValidStoreId | private function isValidStoreId($storeId)
{
$stores = $this->storeManager->getStores(true);
if (array_key_exists($storeId, $stores)) {
return true;
}
// @todo hs: build up array of storeCodes, to prevent wasting time looping
if (is_numeric($storeId)) {
// Dont bother checking store codes on numeric input
return false;
}
/** @var Store $store */
foreach ($stores as $store) {
if ($store->getCode() == $storeId) {
return true;
}
}
return false;
} | php | private function isValidStoreId($storeId)
{
$stores = $this->storeManager->getStores(true);
if (array_key_exists($storeId, $stores)) {
return true;
}
// @todo hs: build up array of storeCodes, to prevent wasting time looping
if (is_numeric($storeId)) {
// Dont bother checking store codes on numeric input
return false;
}
/** @var Store $store */
foreach ($stores as $store) {
if ($store->getCode() == $storeId) {
return true;
}
}
return false;
} | [
"private",
"function",
"isValidStoreId",
"(",
"$",
"storeId",
")",
"{",
"$",
"stores",
"=",
"$",
"this",
"->",
"storeManager",
"->",
"getStores",
"(",
"true",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"storeId",
",",
"$",
"stores",
")",
")",
"... | Check if the given store id is a valid store id
@param int $storeId Store ID
@return bool | [
"Check",
"if",
"the",
"given",
"store",
"id",
"is",
"a",
"valid",
"store",
"id"
] | e14c49b13abd9a2ef01dafb94ebb9d91589e85a0 | https://github.com/semaio/Magento2-ConfigImportExport/blob/e14c49b13abd9a2ef01dafb94ebb9d91589e85a0/Model/Validator/ScopeValidator.php#L89-L109 | train |
semaio/Magento2-ConfigImportExport | Model/Converter/ScopeConverter.php | ScopeConverter.convert | public function convert($scopeId, $scope)
{
if (is_numeric($scopeId)) {
return $scopeId;
}
$entities = $this->getEntityStore($scope);
if (isset($entities[$scopeId])) {
return $entities[$scopeId]->getId();
}
throw new ScopeConvertException(sprintf('Unable to process code "%s" for scope "%s"', $scopeId, $scope));
} | php | public function convert($scopeId, $scope)
{
if (is_numeric($scopeId)) {
return $scopeId;
}
$entities = $this->getEntityStore($scope);
if (isset($entities[$scopeId])) {
return $entities[$scopeId]->getId();
}
throw new ScopeConvertException(sprintf('Unable to process code "%s" for scope "%s"', $scopeId, $scope));
} | [
"public",
"function",
"convert",
"(",
"$",
"scopeId",
",",
"$",
"scope",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"scopeId",
")",
")",
"{",
"return",
"$",
"scopeId",
";",
"}",
"$",
"entities",
"=",
"$",
"this",
"->",
"getEntityStore",
"(",
"$",
... | Converts a string scope to integer scope id if needed
@param string|int $scopeId Scope ID
@param string|mixed $scope Scope
@return int | [
"Converts",
"a",
"string",
"scope",
"to",
"integer",
"scope",
"id",
"if",
"needed"
] | e14c49b13abd9a2ef01dafb94ebb9d91589e85a0 | https://github.com/semaio/Magento2-ConfigImportExport/blob/e14c49b13abd9a2ef01dafb94ebb9d91589e85a0/Model/Converter/ScopeConverter.php#L42-L54 | train |
semaio/Magento2-ConfigImportExport | Model/Converter/ScopeConverter.php | ScopeConverter.getEntityStore | private function getEntityStore($scope)
{
if (isset($this->entityStore[$scope])) {
return $this->entityStore[$scope];
}
switch ($scope) {
case self::SCOPE_STORES:
$this->entityStore[$scope] = $this->storeManager->getStores(true, true);
break;
case self::SCOPE_WEBSITES:
$this->entityStore[$scope] = $this->storeManager->getWebsites(true, true);
break;
default:
throw new ScopeConvertException(sprintf('Unknown scope "%s"', $scope));
}
return $this->entityStore[$scope];
} | php | private function getEntityStore($scope)
{
if (isset($this->entityStore[$scope])) {
return $this->entityStore[$scope];
}
switch ($scope) {
case self::SCOPE_STORES:
$this->entityStore[$scope] = $this->storeManager->getStores(true, true);
break;
case self::SCOPE_WEBSITES:
$this->entityStore[$scope] = $this->storeManager->getWebsites(true, true);
break;
default:
throw new ScopeConvertException(sprintf('Unknown scope "%s"', $scope));
}
return $this->entityStore[$scope];
} | [
"private",
"function",
"getEntityStore",
"(",
"$",
"scope",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"entityStore",
"[",
"$",
"scope",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"entityStore",
"[",
"$",
"scope",
"]",
";",
"}",
"s... | Retrieve the entities for the given scope
@param string $scope Scope
@return \Magento\Store\Api\Data\WebsiteInterface[]|\Magento\Store\Api\Data\StoreInterface[] | [
"Retrieve",
"the",
"entities",
"for",
"the",
"given",
"scope"
] | e14c49b13abd9a2ef01dafb94ebb9d91589e85a0 | https://github.com/semaio/Magento2-ConfigImportExport/blob/e14c49b13abd9a2ef01dafb94ebb9d91589e85a0/Model/Converter/ScopeConverter.php#L62-L82 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/SPLog.php | SPLog.format | public static function format($msg, $processId = false, $time = false, $flags = self::FLAG_NONE) {
return "\n" . ($processId ? "$processId@" : "")
. date("Y-m-d H:i:s")
. ($time ? " (" . number_format(microtime(true) - $time, 2) . "s)" : "")
. ($flags | self::FLAG_MEMORY ? " (M: " . number_format(memory_get_usage()) . ")" : ""). " > $msg\n";
} | php | public static function format($msg, $processId = false, $time = false, $flags = self::FLAG_NONE) {
return "\n" . ($processId ? "$processId@" : "")
. date("Y-m-d H:i:s")
. ($time ? " (" . number_format(microtime(true) - $time, 2) . "s)" : "")
. ($flags | self::FLAG_MEMORY ? " (M: " . number_format(memory_get_usage()) . ")" : ""). " > $msg\n";
} | [
"public",
"static",
"function",
"format",
"(",
"$",
"msg",
",",
"$",
"processId",
"=",
"false",
",",
"$",
"time",
"=",
"false",
",",
"$",
"flags",
"=",
"self",
"::",
"FLAG_NONE",
")",
"{",
"return",
"\"\\n\"",
".",
"(",
"$",
"processId",
"?",
"\"$pro... | formats a log message
@param $processId
@param $msg
@param $time
@return string | [
"formats",
"a",
"log",
"message"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/SPLog.php#L54-L59 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/SPLog.php | SPLog.log | public function log($producer, $msg, $object = false) {
if(!($this->acceptedProducers & $producer)) { return; }
$msgFmt = self::format($msg, $this->processId, $this->time, $this->flags);
if($object) {
$msgFmt .= " " . json_encode($object);
}
$this->logRaw($msgFmt);
} | php | public function log($producer, $msg, $object = false) {
if(!($this->acceptedProducers & $producer)) { return; }
$msgFmt = self::format($msg, $this->processId, $this->time, $this->flags);
if($object) {
$msgFmt .= " " . json_encode($object);
}
$this->logRaw($msgFmt);
} | [
"public",
"function",
"log",
"(",
"$",
"producer",
",",
"$",
"msg",
",",
"$",
"object",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"acceptedProducers",
"&",
"$",
"producer",
")",
")",
"{",
"return",
";",
"}",
"$",
"msgFmt",
"... | Log the message if the logger is configured to log from this producer
@param $producer the source of logging ( one of the SPLog::PRODUCER_* values )
@param $msg the actual message
@param bool $object | [
"Log",
"the",
"message",
"if",
"the",
"logger",
"is",
"configured",
"to",
"log",
"from",
"this",
"producer"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/SPLog.php#L67-L75 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/SPLog.php | SPLog.logFirst | public function logFirst($key, $producer, $msg, $object = false) {
if(!($this->acceptedProducers & $producer)) { return; }
if(!in_array($key, $this->loggedAlready)) {
$this->loggedAlready[] = $key;
$this->log($producer, $msg, $object);
}
} | php | public function logFirst($key, $producer, $msg, $object = false) {
if(!($this->acceptedProducers & $producer)) { return; }
if(!in_array($key, $this->loggedAlready)) {
$this->loggedAlready[] = $key;
$this->log($producer, $msg, $object);
}
} | [
"public",
"function",
"logFirst",
"(",
"$",
"key",
",",
"$",
"producer",
",",
"$",
"msg",
",",
"$",
"object",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"acceptedProducers",
"&",
"$",
"producer",
")",
")",
"{",
"return",
";",
... | Log only the first call with that key
@param $key
@param $producer
@param $msg
@param $object | [
"Log",
"only",
"the",
"first",
"call",
"with",
"that",
"key"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/SPLog.php#L84-L92 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/SPLog.php | SPLog.bye | public function bye($producer, $msg, $object = false) {
$this->log($producer, $msg, $object); echo("\n");die();
} | php | public function bye($producer, $msg, $object = false) {
$this->log($producer, $msg, $object); echo("\n");die();
} | [
"public",
"function",
"bye",
"(",
"$",
"producer",
",",
"$",
"msg",
",",
"$",
"object",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"$",
"producer",
",",
"$",
"msg",
",",
"$",
"object",
")",
";",
"echo",
"(",
"\"\\n\"",
")",
";",
"di... | Log the message if the logger is configured to log from this producer AND EXIT ANYWAY
@param $producer the source of logging ( one of the SPLog::PRODUCER_* values )
@param $msg the actual message
@param bool $object | [
"Log",
"the",
"message",
"if",
"the",
"logger",
"is",
"configured",
"to",
"log",
"from",
"this",
"producer",
"AND",
"EXIT",
"ANYWAY"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/SPLog.php#L122-L124 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/SPLog.php | SPLog.Init | public static function Init($processId, $acceptedProducers, $target = self::TARGET_CONSOLE, $targetName = false, $flags = SPLog::FLAG_NONE) {
self::$instance = new SPLog($processId, $acceptedProducers, $target, $targetName, $flags);
return self::$instance;
} | php | public static function Init($processId, $acceptedProducers, $target = self::TARGET_CONSOLE, $targetName = false, $flags = SPLog::FLAG_NONE) {
self::$instance = new SPLog($processId, $acceptedProducers, $target, $targetName, $flags);
return self::$instance;
} | [
"public",
"static",
"function",
"Init",
"(",
"$",
"processId",
",",
"$",
"acceptedProducers",
",",
"$",
"target",
"=",
"self",
"::",
"TARGET_CONSOLE",
",",
"$",
"targetName",
"=",
"false",
",",
"$",
"flags",
"=",
"SPLog",
"::",
"FLAG_NONE",
")",
"{",
"se... | init the logger singleton
@param $processId
@param $acceptedProducers - the producers from which the logger will log, ignoring gracefully the others
@param int $target - the log type
@param bool|false $targetName the log name if needed
@return SPLog the newly created logger instance | [
"init",
"the",
"logger",
"singleton"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/SPLog.php#L134-L137 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/SPLog.php | SPLog.Get | public static function Get($producer) {
if( !(self::$instance && ($producer & self::$instance->acceptedProducers)) ) {
if(!isset(self::$dummy)) {
self::$dummy = new SPLog(0, self::PRODUCER_NONE, self::TARGET_CONSOLE, false);
}
return self::$dummy;
}
return self::$instance;
} | php | public static function Get($producer) {
if( !(self::$instance && ($producer & self::$instance->acceptedProducers)) ) {
if(!isset(self::$dummy)) {
self::$dummy = new SPLog(0, self::PRODUCER_NONE, self::TARGET_CONSOLE, false);
}
return self::$dummy;
}
return self::$instance;
} | [
"public",
"static",
"function",
"Get",
"(",
"$",
"producer",
")",
"{",
"if",
"(",
"!",
"(",
"self",
"::",
"$",
"instance",
"&&",
"(",
"$",
"producer",
"&",
"self",
"::",
"$",
"instance",
"->",
"acceptedProducers",
")",
")",
")",
"{",
"if",
"(",
"!"... | returns the current logger. If the logger is not set to log from that producer or if the log is not initialized, will return a dummy logger which doesn't log.
@param $producer
@return SPLog | [
"returns",
"the",
"current",
"logger",
".",
"If",
"the",
"logger",
"is",
"not",
"set",
"to",
"log",
"from",
"that",
"producer",
"or",
"if",
"the",
"log",
"is",
"not",
"initialized",
"will",
"return",
"a",
"dummy",
"logger",
"which",
"doesn",
"t",
"log",
... | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/SPLog.php#L144-L152 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/Commander.php | Commander.notifyMe | public function notifyMe($callbackURL) {
throw new ClientException("NotifyMe not yet implemented");
$this->commands = array_merge($this->commands, array("notify_me" => $callbackURL));
return $this->execute();
} | php | public function notifyMe($callbackURL) {
throw new ClientException("NotifyMe not yet implemented");
$this->commands = array_merge($this->commands, array("notify_me" => $callbackURL));
return $this->execute();
} | [
"public",
"function",
"notifyMe",
"(",
"$",
"callbackURL",
")",
"{",
"throw",
"new",
"ClientException",
"(",
"\"NotifyMe not yet implemented\"",
")",
";",
"$",
"this",
"->",
"commands",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"commands",
",",
"array",
"(",... | Not yet implemented
@param $callbackURL the full url of the notify.php script that handles the notification postback
@return mixed | [
"Not",
"yet",
"implemented"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/Commander.php#L91-L95 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/persist/PNGReader.php | PNGReader.get_chunks | public function get_chunks($type) {
if (!isset($this->_chunks[$type]) || $this->_chunks[$type] === null)
return null;
$chunks = array ();
foreach ($this->_chunks[$type] as $chunk) {
if ($chunk['size'] > 0) {
fseek($this->_fp, $chunk['offset'], SEEK_SET);
$chunks[] = fread($this->_fp, $chunk['size']);
} else {
$chunks[] = '';
}
}
return $chunks;
} | php | public function get_chunks($type) {
if (!isset($this->_chunks[$type]) || $this->_chunks[$type] === null)
return null;
$chunks = array ();
foreach ($this->_chunks[$type] as $chunk) {
if ($chunk['size'] > 0) {
fseek($this->_fp, $chunk['offset'], SEEK_SET);
$chunks[] = fread($this->_fp, $chunk['size']);
} else {
$chunks[] = '';
}
}
return $chunks;
} | [
"public",
"function",
"get_chunks",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_chunks",
"[",
"$",
"type",
"]",
")",
"||",
"$",
"this",
"->",
"_chunks",
"[",
"$",
"type",
"]",
"===",
"null",
")",
"return",
"null... | Returns all chunks of said type | [
"Returns",
"all",
"chunks",
"of",
"said",
"type"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/persist/PNGReader.php#L55-L71 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/Source.php | Source.folderInfo | public function folderInfo($path, $recurse = true, $fileList = false, $exclude = array(), $persistPath = false, $recurseDepth = PHP_INT_MAX, $retrySkipped = false){
$persister = ShortPixel::getPersister($path);
if(!$persister) {
throw new PersistException("Persist is not enabled in options, needed for fetching folder info");
}
return $persister->info($path, $recurse, $fileList, $exclude, $persistPath, $recurseDepth, $retrySkipped);
} | php | public function folderInfo($path, $recurse = true, $fileList = false, $exclude = array(), $persistPath = false, $recurseDepth = PHP_INT_MAX, $retrySkipped = false){
$persister = ShortPixel::getPersister($path);
if(!$persister) {
throw new PersistException("Persist is not enabled in options, needed for fetching folder info");
}
return $persister->info($path, $recurse, $fileList, $exclude, $persistPath, $recurseDepth, $retrySkipped);
} | [
"public",
"function",
"folderInfo",
"(",
"$",
"path",
",",
"$",
"recurse",
"=",
"true",
",",
"$",
"fileList",
"=",
"false",
",",
"$",
"exclude",
"=",
"array",
"(",
")",
",",
"$",
"persistPath",
"=",
"false",
",",
"$",
"recurseDepth",
"=",
"PHP_INT_MAX"... | returns the optimization counters of the folder and subfolders
@param $path - the file path on the local drive
@param bool $recurse - boolean - go into subfolders or not
@param bool $fileList - return the list of files with optimization status (only current folder, not subfolders)
@param array $exclude - array of folder names that you want to exclude from the optimization
@param bool $persistPath - the path where to look for the metadata, if different from the $path
@param int $recurseDepth - how many subfolders deep to go. Defaults to PHP_INT_MAX
@param bool $retrySkipped - if true, all skipped files will be reset to pending with retries = 0
@return object|void (object)array('status', 'total', 'succeeded', 'pending', 'same', 'failed')
@throws PersistException | [
"returns",
"the",
"optimization",
"counters",
"of",
"the",
"folder",
"and",
"subfolders"
] | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/Source.php#L56-L62 | train |
short-pixel-optimizer/shortpixel-php | lib/ShortPixel/Source.php | Source.fromFolder | public function fromFolder($path, $maxFiles = 0, $exclude = array(), $persistFolder = false, $maxTotalFileSize = ShortPixel::CLIENT_MAX_BODY_SIZE, $recurseDepth = PHP_INT_MAX) {
if($maxFiles == 0) {
$maxFiles = ShortPixel::MAX_ALLOWED_FILES_PER_CALL;
}
//sanitize
$maxFiles = max(1, min(ShortPixel::MAX_ALLOWED_FILES_PER_CALL, intval($maxFiles)));
$persister = ShortPixel::getPersister($path);
if(!$persister) {
throw new PersistException("Persist is not enabled in options, needed for folder optimization");
}
$paths = $persister->getTodo($path, $maxFiles, $exclude, $persistFolder, $maxTotalFileSize, $recurseDepth);
if($paths) {
ShortPixel::setOptions(array("base_source_path" => $path));
return $this->fromFiles($paths->files, null, $paths->filesPending);
}
throw new ClientException("Couldn't find any processable file at given path ($path).", 2);
} | php | public function fromFolder($path, $maxFiles = 0, $exclude = array(), $persistFolder = false, $maxTotalFileSize = ShortPixel::CLIENT_MAX_BODY_SIZE, $recurseDepth = PHP_INT_MAX) {
if($maxFiles == 0) {
$maxFiles = ShortPixel::MAX_ALLOWED_FILES_PER_CALL;
}
//sanitize
$maxFiles = max(1, min(ShortPixel::MAX_ALLOWED_FILES_PER_CALL, intval($maxFiles)));
$persister = ShortPixel::getPersister($path);
if(!$persister) {
throw new PersistException("Persist is not enabled in options, needed for folder optimization");
}
$paths = $persister->getTodo($path, $maxFiles, $exclude, $persistFolder, $maxTotalFileSize, $recurseDepth);
if($paths) {
ShortPixel::setOptions(array("base_source_path" => $path));
return $this->fromFiles($paths->files, null, $paths->filesPending);
}
throw new ClientException("Couldn't find any processable file at given path ($path).", 2);
} | [
"public",
"function",
"fromFolder",
"(",
"$",
"path",
",",
"$",
"maxFiles",
"=",
"0",
",",
"$",
"exclude",
"=",
"array",
"(",
")",
",",
"$",
"persistFolder",
"=",
"false",
",",
"$",
"maxTotalFileSize",
"=",
"ShortPixel",
"::",
"CLIENT_MAX_BODY_SIZE",
",",
... | processes a chunk of MAX_ALLOWED files from the folder, based on the persisted information about which images are processed and which not. This information is offered by the Persister object.
@param $path - the folder path on the local drive
@param int $maxFiles - maximum number of files to select from the folder
@param array $exclude - exclude files based on regex patterns
@param bool $persistFolder - the path where to store the metadata, if different from the $path (usually the target path)
@param int $maxTotalFileSize - max summed up file size in MB
@param int $recurseDepth - how many subfolders deep to go. Defaults to PHP_INT_MAX
@return Commander - the class that handles the optimization commands
@throws ClientException
@throws PersistException | [
"processes",
"a",
"chunk",
"of",
"MAX_ALLOWED",
"files",
"from",
"the",
"folder",
"based",
"on",
"the",
"persisted",
"information",
"about",
"which",
"images",
"are",
"processed",
"and",
"which",
"not",
".",
"This",
"information",
"is",
"offered",
"by",
"the",... | 18c6b9e463e18dd6d87c0a618d28ffebdbee54b7 | https://github.com/short-pixel-optimizer/shortpixel-php/blob/18c6b9e463e18dd6d87c0a618d28ffebdbee54b7/lib/ShortPixel/Source.php#L76-L93 | train |
semaio/Magento2-ConfigImportExport | Model/File/Writer/YamlWriter.php | YamlWriter.generateYaml | private function generateYaml(array $data)
{
$fileContent = array();
$header = array();
foreach ($data as $path => $scopes) {
$paths = explode('/', $path);
if (!isset($header[$paths[0]])) {
$header[$paths[0]] = true;
$length = strlen($paths[0]) + 2;
$fileContent[] = PHP_EOL . $this->getIndentation($length, '#') . PHP_EOL . '# ' . $paths[0] . PHP_EOL . $this->getIndentation($length, '#');
}
$fileContent[] = $path . ':';
foreach ($scopes as $scope => $scopeValues) {
$fileContent[] = $this->getIndentation(2) . $scope . ':';
foreach ($scopeValues as $scopeId => $value) {
$fileContent[] = $this->getIndentation(4) . $scopeId . ': ' . $this->prepareValue($value);
}
}
}
return implode(PHP_EOL, $fileContent);
} | php | private function generateYaml(array $data)
{
$fileContent = array();
$header = array();
foreach ($data as $path => $scopes) {
$paths = explode('/', $path);
if (!isset($header[$paths[0]])) {
$header[$paths[0]] = true;
$length = strlen($paths[0]) + 2;
$fileContent[] = PHP_EOL . $this->getIndentation($length, '#') . PHP_EOL . '# ' . $paths[0] . PHP_EOL . $this->getIndentation($length, '#');
}
$fileContent[] = $path . ':';
foreach ($scopes as $scope => $scopeValues) {
$fileContent[] = $this->getIndentation(2) . $scope . ':';
foreach ($scopeValues as $scopeId => $value) {
$fileContent[] = $this->getIndentation(4) . $scopeId . ': ' . $this->prepareValue($value);
}
}
}
return implode(PHP_EOL, $fileContent);
} | [
"private",
"function",
"generateYaml",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"fileContent",
"=",
"array",
"(",
")",
";",
"$",
"header",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"path",
"=>",
"$",
"scopes",
")",
"{",
... | Custom format with nice headers only for flat structure available
@param array $data
@return string | [
"Custom",
"format",
"with",
"nice",
"headers",
"only",
"for",
"flat",
"structure",
"available"
] | e14c49b13abd9a2ef01dafb94ebb9d91589e85a0 | https://github.com/semaio/Magento2-ConfigImportExport/blob/e14c49b13abd9a2ef01dafb94ebb9d91589e85a0/Model/File/Writer/YamlWriter.php#L57-L79 | train |
vanderlee/php-sentence | src/Multibyte.php | Multibyte.split | public static function split($pattern, $string, $limit = -1, $flags = 0)
{
$offset_capture = (bool)($flags & PREG_SPLIT_OFFSET_CAPTURE);
$lengths = self::getSplitLengths($pattern, $string);
// Substrings
$parts = [];
$position = 0;
$count = 1;
foreach ($lengths as $length) {
if (self::isLastPart($length, $flags, $limit, $count)) {
$parts[] = self::makePart($string, $position, null, $offset_capture);
return $parts;
}
if (self::isPart($length, $flags)) {
$parts[] = self::makePart($string, $position, $length[0], $offset_capture);
}
$position += $length[0];
}
return $parts;
} | php | public static function split($pattern, $string, $limit = -1, $flags = 0)
{
$offset_capture = (bool)($flags & PREG_SPLIT_OFFSET_CAPTURE);
$lengths = self::getSplitLengths($pattern, $string);
// Substrings
$parts = [];
$position = 0;
$count = 1;
foreach ($lengths as $length) {
if (self::isLastPart($length, $flags, $limit, $count)) {
$parts[] = self::makePart($string, $position, null, $offset_capture);
return $parts;
}
if (self::isPart($length, $flags)) {
$parts[] = self::makePart($string, $position, $length[0], $offset_capture);
}
$position += $length[0];
}
return $parts;
} | [
"public",
"static",
"function",
"split",
"(",
"$",
"pattern",
",",
"$",
"string",
",",
"$",
"limit",
"=",
"-",
"1",
",",
"$",
"flags",
"=",
"0",
")",
"{",
"$",
"offset_capture",
"=",
"(",
"bool",
")",
"(",
"$",
"flags",
"&",
"PREG_SPLIT_OFFSET_CAPTUR... | A cross between mb_split and preg_split, adding the preg_split flags
to mb_split.
@param string $pattern
@param string $string
@param int $limit
@param int $flags
@return array | [
"A",
"cross",
"between",
"mb_split",
"and",
"preg_split",
"adding",
"the",
"preg_split",
"flags",
"to",
"mb_split",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Multibyte.php#L72-L96 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.linebreakSplit | private static function linebreakSplit($text)
{
$lines = [];
$line = '';
foreach (Multibyte::split('([\r\n]+)', $text, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) {
$line .= $part;
if (Multibyte::trim($part) === '') {
$lines[] = $line;
$line = '';
}
}
$lines[] = $line;
return $lines;
} | php | private static function linebreakSplit($text)
{
$lines = [];
$line = '';
foreach (Multibyte::split('([\r\n]+)', $text, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) {
$line .= $part;
if (Multibyte::trim($part) === '') {
$lines[] = $line;
$line = '';
}
}
$lines[] = $line;
return $lines;
} | [
"private",
"static",
"function",
"linebreakSplit",
"(",
"$",
"text",
")",
"{",
"$",
"lines",
"=",
"[",
"]",
";",
"$",
"line",
"=",
"''",
";",
"foreach",
"(",
"Multibyte",
"::",
"split",
"(",
"'([\\r\\n]+)'",
",",
"$",
"text",
",",
"-",
"1",
",",
"P... | Breaks a piece of text into lines by linebreak.
Eats up any linebreak characters as if one.
Multibyte.php safe
@param string $text
@return string[] | [
"Breaks",
"a",
"piece",
"of",
"text",
"into",
"lines",
"by",
"linebreak",
".",
"Eats",
"up",
"any",
"linebreak",
"characters",
"as",
"if",
"one",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L48-L63 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.punctuationMerge | private function punctuationMerge($punctuations)
{
$definite_terminals = array_diff($this->terminals, $this->abbreviators);
$merges = [];
$merge = '';
$filtered = array_filter($punctuations, function ($p) {
return $p !== '';
});
foreach ($filtered as $punctuation) {
$merge .= $punctuation;
if (mb_strlen($punctuation) === 1
&& in_array($punctuation, $this->terminals)) {
$merges[] = $merge;
$merge = '';
} else {
foreach ($definite_terminals as $terminal) {
if (mb_strpos($punctuation, $terminal) !== false) {
$merges[] = $merge;
$merge = '';
break;
}
}
}
}
if (!empty($merge)) {
$merges[] = $merge;
}
return $merges;
} | php | private function punctuationMerge($punctuations)
{
$definite_terminals = array_diff($this->terminals, $this->abbreviators);
$merges = [];
$merge = '';
$filtered = array_filter($punctuations, function ($p) {
return $p !== '';
});
foreach ($filtered as $punctuation) {
$merge .= $punctuation;
if (mb_strlen($punctuation) === 1
&& in_array($punctuation, $this->terminals)) {
$merges[] = $merge;
$merge = '';
} else {
foreach ($definite_terminals as $terminal) {
if (mb_strpos($punctuation, $terminal) !== false) {
$merges[] = $merge;
$merge = '';
break;
}
}
}
}
if (!empty($merge)) {
$merges[] = $merge;
}
return $merges;
} | [
"private",
"function",
"punctuationMerge",
"(",
"$",
"punctuations",
")",
"{",
"$",
"definite_terminals",
"=",
"array_diff",
"(",
"$",
"this",
"->",
"terminals",
",",
"$",
"this",
"->",
"abbreviators",
")",
";",
"$",
"merges",
"=",
"[",
"]",
";",
"$",
"m... | Appends each terminal item after it's preceding
non-terminals.
Multibyte.php safe (atleast for UTF-8)
For example:
[ "There ", "...", " is", ".", " More", "!" ]
... becomes ...
[ "There ... is.", "More!" ]
@param string[] $punctuations
@return string[] | [
"Appends",
"each",
"terminal",
"item",
"after",
"it",
"s",
"preceding",
"non",
"-",
"terminals",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L117-L149 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.abbreviationMerge | private function abbreviationMerge($fragments)
{
$return_fragment = [];
$previous_fragment = '';
$previous_is_abbreviation = false;
$i = 0;
foreach ($fragments as $fragment) {
$is_abbreviation = self::isAbreviation($fragment);
// merge previous fragment with this
if ($previous_is_abbreviation) {
$fragment = $previous_fragment . $fragment;
}
$return_fragment[$i] = $fragment;
$previous_is_abbreviation = $is_abbreviation;
$previous_fragment = $fragment;
// only increment if this isn't an abbreviation
if (!$is_abbreviation) {
$i++;
}
}
return $return_fragment;
} | php | private function abbreviationMerge($fragments)
{
$return_fragment = [];
$previous_fragment = '';
$previous_is_abbreviation = false;
$i = 0;
foreach ($fragments as $fragment) {
$is_abbreviation = self::isAbreviation($fragment);
// merge previous fragment with this
if ($previous_is_abbreviation) {
$fragment = $previous_fragment . $fragment;
}
$return_fragment[$i] = $fragment;
$previous_is_abbreviation = $is_abbreviation;
$previous_fragment = $fragment;
// only increment if this isn't an abbreviation
if (!$is_abbreviation) {
$i++;
}
}
return $return_fragment;
} | [
"private",
"function",
"abbreviationMerge",
"(",
"$",
"fragments",
")",
"{",
"$",
"return_fragment",
"=",
"[",
"]",
";",
"$",
"previous_fragment",
"=",
"''",
";",
"$",
"previous_is_abbreviation",
"=",
"false",
";",
"$",
"i",
"=",
"0",
";",
"foreach",
"(",
... | Looks for capitalized abbreviations & includes them with the following fragment.
For example:
[ "Last week, former director of the F.B.I. James B. Comey was fired. Mr. Comey was not available for comment." ]
... becomes ...
[ "Last week, former director of the F.B.I. James B. Comey was fired." ]
[ "Mr. Comey was not available for comment." ]
@param string[] $fragments
@return string[] | [
"Looks",
"for",
"capitalized",
"abbreviations",
"&",
"includes",
"them",
"with",
"the",
"following",
"fragment",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L163-L188 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.isAbreviation | private static function isAbreviation($fragment)
{
$words = mb_split('\s+', Multibyte::trim($fragment));
$word_count = count($words);
$last_word = Multibyte::trim($words[$word_count - 1]);
$last_is_capital = preg_match('#^\p{Lu}#u', $last_word);
$last_is_abbreviation = mb_substr(Multibyte::trim($fragment), -1) === '.';
return $last_is_capital > 0
&& $last_is_abbreviation > 0
&& mb_strlen($last_word) <= 3;
} | php | private static function isAbreviation($fragment)
{
$words = mb_split('\s+', Multibyte::trim($fragment));
$word_count = count($words);
$last_word = Multibyte::trim($words[$word_count - 1]);
$last_is_capital = preg_match('#^\p{Lu}#u', $last_word);
$last_is_abbreviation = mb_substr(Multibyte::trim($fragment), -1) === '.';
return $last_is_capital > 0
&& $last_is_abbreviation > 0
&& mb_strlen($last_word) <= 3;
} | [
"private",
"static",
"function",
"isAbreviation",
"(",
"$",
"fragment",
")",
"{",
"$",
"words",
"=",
"mb_split",
"(",
"'\\s+'",
",",
"Multibyte",
"::",
"trim",
"(",
"$",
"fragment",
")",
")",
";",
"$",
"word_count",
"=",
"count",
"(",
"$",
"words",
")"... | Check if the last word of fragment starts with a Capital, ends in "." & has less than 3 characters.
@param $fragment
@return bool | [
"Check",
"if",
"the",
"last",
"word",
"of",
"fragment",
"starts",
"with",
"a",
"Capital",
"ends",
"in",
".",
"&",
"has",
"less",
"than",
"3",
"characters",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L196-L209 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.parenthesesMerge | private function parenthesesMerge($parts)
{
$subsentences = [];
foreach ($parts as $part) {
if ($part[0] === ')') {
$subsentences[count($subsentences) - 1] .= $part;
} else {
$subsentences[] = $part;
}
}
return $subsentences;
} | php | private function parenthesesMerge($parts)
{
$subsentences = [];
foreach ($parts as $part) {
if ($part[0] === ')') {
$subsentences[count($subsentences) - 1] .= $part;
} else {
$subsentences[] = $part;
}
}
return $subsentences;
} | [
"private",
"function",
"parenthesesMerge",
"(",
"$",
"parts",
")",
"{",
"$",
"subsentences",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"parts",
"as",
"$",
"part",
")",
"{",
"if",
"(",
"$",
"part",
"[",
"0",
"]",
"===",
"')'",
")",
"{",
"$",
"subse... | Merges any part starting with a closing parenthesis ')' to the previous
part.
@param string[] $parts
@return string[] | [
"Merges",
"any",
"part",
"starting",
"with",
"a",
"closing",
"parenthesis",
")",
"to",
"the",
"previous",
"part",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L218-L231 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.closeQuotesMerge | private function closeQuotesMerge($statements)
{
$i = 0;
$previous_statement = '';
$return = [];
foreach ($statements as $statement) {
if (self::isEndQuote($statement)) {
$statement = $previous_statement . $statement;
} else {
$i++;
}
$return[$i] = $statement;
$previous_statement = $statement;
}
return $return;
} | php | private function closeQuotesMerge($statements)
{
$i = 0;
$previous_statement = '';
$return = [];
foreach ($statements as $statement) {
if (self::isEndQuote($statement)) {
$statement = $previous_statement . $statement;
} else {
$i++;
}
$return[$i] = $statement;
$previous_statement = $statement;
}
return $return;
} | [
"private",
"function",
"closeQuotesMerge",
"(",
"$",
"statements",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"previous_statement",
"=",
"''",
";",
"$",
"return",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"statements",
"as",
"$",
"statement",
")",
"{",
"... | Looks for closing quotes to include them with the previous statement.
"That was very interesting," he said.
"That was very interesting."
@param string[] $statements
@return string[] | [
"Looks",
"for",
"closing",
"quotes",
"to",
"include",
"them",
"with",
"the",
"previous",
"statement",
".",
"That",
"was",
"very",
"interesting",
"he",
"said",
".",
"That",
"was",
"very",
"interesting",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L241-L258 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.isEndQuote | private static function isEndQuote($statement)
{
$trimmed = Multibyte::trim($statement);
$first = mb_substr($statement, 0, 1);
return in_array($trimmed, ['"', '\''])
|| (
in_array($first, ['"', '\''])
&& mb_substr($statement, 1, 1) === ' '
&& ctype_lower(mb_substr($statement, 2, 1)) === true
);
} | php | private static function isEndQuote($statement)
{
$trimmed = Multibyte::trim($statement);
$first = mb_substr($statement, 0, 1);
return in_array($trimmed, ['"', '\''])
|| (
in_array($first, ['"', '\''])
&& mb_substr($statement, 1, 1) === ' '
&& ctype_lower(mb_substr($statement, 2, 1)) === true
);
} | [
"private",
"static",
"function",
"isEndQuote",
"(",
"$",
"statement",
")",
"{",
"$",
"trimmed",
"=",
"Multibyte",
"::",
"trim",
"(",
"$",
"statement",
")",
";",
"$",
"first",
"=",
"mb_substr",
"(",
"$",
"statement",
",",
"0",
",",
"1",
")",
";",
"ret... | Check if the entire string is a quotation mark or quote, then space, then lowercase.
@param $statement
@return bool | [
"Check",
"if",
"the",
"entire",
"string",
"is",
"a",
"quotation",
"mark",
"or",
"quote",
"then",
"space",
"then",
"lowercase",
"."
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L266-L277 | train |
vanderlee/php-sentence | src/Sentence.php | Sentence.sentenceMerge | private function sentenceMerge($shorts)
{
$non_abbreviating_terminals = array_diff($this->terminals, $this->abbreviators);
$sentences = [];
$sentence = '';
$has_words = false;
$previous_word_ending = null;
foreach ($shorts as $short) {
$word_count = count(mb_split('\s+', Multibyte::trim($short)));
$after_non_abbreviating_terminal = in_array($previous_word_ending, $non_abbreviating_terminals);
if ($after_non_abbreviating_terminal
|| ($has_words && $word_count > 1)) {
$sentences[] = $sentence;
$sentence = '';
$has_words = false;
}
$has_words = $has_words
|| $word_count > 1;
$sentence .= $short;
$previous_word_ending = mb_substr($short, -1);
}
if (!empty($sentence)) {
$sentences[] = $sentence;
}
return $sentences;
} | php | private function sentenceMerge($shorts)
{
$non_abbreviating_terminals = array_diff($this->terminals, $this->abbreviators);
$sentences = [];
$sentence = '';
$has_words = false;
$previous_word_ending = null;
foreach ($shorts as $short) {
$word_count = count(mb_split('\s+', Multibyte::trim($short)));
$after_non_abbreviating_terminal = in_array($previous_word_ending, $non_abbreviating_terminals);
if ($after_non_abbreviating_terminal
|| ($has_words && $word_count > 1)) {
$sentences[] = $sentence;
$sentence = '';
$has_words = false;
}
$has_words = $has_words
|| $word_count > 1;
$sentence .= $short;
$previous_word_ending = mb_substr($short, -1);
}
if (!empty($sentence)) {
$sentences[] = $sentence;
}
return $sentences;
} | [
"private",
"function",
"sentenceMerge",
"(",
"$",
"shorts",
")",
"{",
"$",
"non_abbreviating_terminals",
"=",
"array_diff",
"(",
"$",
"this",
"->",
"terminals",
",",
"$",
"this",
"->",
"abbreviators",
")",
";",
"$",
"sentences",
"=",
"[",
"]",
";",
"$",
... | Merges items into larger sentences.
Multibyte.php safe
@param string[] $shorts
@return string[] | [
"Merges",
"items",
"into",
"larger",
"sentences",
".",
"Multibyte",
".",
"php",
"safe"
] | ee9c89dbb86cd293421184c2fd2baea4ebada54d | https://github.com/vanderlee/php-sentence/blob/ee9c89dbb86cd293421184c2fd2baea4ebada54d/src/Sentence.php#L286-L320 | train |
bradcornford/Backup | src/Cornford/Backup/Commands/BackupCommandAbstract.php | BackupCommandAbstract.getBackupInstance | public function getBackupInstance($database = null)
{
$configuration = array_merge($this->getConfig('database'), $this->getConfig('backup::config'));
$this->backupInstance = $this->backupFactory->build($configuration, $database);
return $this->backupInstance;
} | php | public function getBackupInstance($database = null)
{
$configuration = array_merge($this->getConfig('database'), $this->getConfig('backup::config'));
$this->backupInstance = $this->backupFactory->build($configuration, $database);
return $this->backupInstance;
} | [
"public",
"function",
"getBackupInstance",
"(",
"$",
"database",
"=",
"null",
")",
"{",
"$",
"configuration",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'database'",
")",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'backup::config'",
")",
... | Get a backup instance.
@param string $database
@return BackupInterface | [
"Get",
"a",
"backup",
"instance",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Commands/BackupCommandAbstract.php#L55-L61 | train |
bradcornford/Backup | src/Cornford/Backup/Backup.php | Backup.export | public function export($filename = null)
{
if (!$this->getEnabled()) {
return false;
}
if ($filename === null) {
$filename = $this->getFilename();
}
$path = $this->getPath();
if (!$this->getBackupFilesystemInstance()->checkPathExists($path)) {
throw new BackupExportException('Unable to export to path "' . $path . '" as it doesn\'t exist.');
}
$filepath = $path . '/' . $filename . '.' . $this->getBackupEngineInstance()->getFileExtension();
$this->setWorkingFilepath($filepath);
$result = $this->getBackupEngineInstance()->export($filepath);
if ($result) {
if ($this->getCompress()) {
$filepath = $this->compressFile($filepath);
}
$this->setWorkingFilepath($filepath);
} else {
$this->removeTemporaryFiles($filepath, true);
$this->setWorkingFilepath(null);
}
return $result;
} | php | public function export($filename = null)
{
if (!$this->getEnabled()) {
return false;
}
if ($filename === null) {
$filename = $this->getFilename();
}
$path = $this->getPath();
if (!$this->getBackupFilesystemInstance()->checkPathExists($path)) {
throw new BackupExportException('Unable to export to path "' . $path . '" as it doesn\'t exist.');
}
$filepath = $path . '/' . $filename . '.' . $this->getBackupEngineInstance()->getFileExtension();
$this->setWorkingFilepath($filepath);
$result = $this->getBackupEngineInstance()->export($filepath);
if ($result) {
if ($this->getCompress()) {
$filepath = $this->compressFile($filepath);
}
$this->setWorkingFilepath($filepath);
} else {
$this->removeTemporaryFiles($filepath, true);
$this->setWorkingFilepath(null);
}
return $result;
} | [
"public",
"function",
"export",
"(",
"$",
"filename",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getEnabled",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"filename",
"===",
"null",
")",
"{",
"$",
"filename",
"... | Export database to file.
@param string $filename
@throws BackupExportException
@return boolean | [
"Export",
"database",
"to",
"file",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Backup.php#L21-L54 | train |
bradcornford/Backup | src/Cornford/Backup/Backup.php | Backup.restore | public function restore($filepath)
{
if (!$this->getEnabled()) {
return false;
}
if (!$this->getBackupFilesystemInstance()->checkFileExists($filepath)) {
throw new BackupRestoreException('Unable to restore file "' . $filepath . '" as it doesn\'t exist.');
}
$this->setWorkingFilepath($filepath);
if ($this->getBackupFilesystemInstance()->checkFileEmpty($filepath)) {
$this->getBackupFilesystemInstance()->removeFile($filepath);
return false;
}
if ($this->isCompressed($filepath)) {
$filepath = $this->decompressFile($filepath);
}
$result = $this->getBackupEngineInstance()->restore($filepath);
$this->removeTemporaryFiles($this->getWorkingFilepath());
return $result;
} | php | public function restore($filepath)
{
if (!$this->getEnabled()) {
return false;
}
if (!$this->getBackupFilesystemInstance()->checkFileExists($filepath)) {
throw new BackupRestoreException('Unable to restore file "' . $filepath . '" as it doesn\'t exist.');
}
$this->setWorkingFilepath($filepath);
if ($this->getBackupFilesystemInstance()->checkFileEmpty($filepath)) {
$this->getBackupFilesystemInstance()->removeFile($filepath);
return false;
}
if ($this->isCompressed($filepath)) {
$filepath = $this->decompressFile($filepath);
}
$result = $this->getBackupEngineInstance()->restore($filepath);
$this->removeTemporaryFiles($this->getWorkingFilepath());
return $result;
} | [
"public",
"function",
"restore",
"(",
"$",
"filepath",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getEnabled",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"getBackupFilesystemInstance",
"(",
")",
"->",
"chec... | Restore database from file path.
@param string $filepath
@throws BackupRestoreException
@return boolean | [
"Restore",
"database",
"from",
"file",
"path",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Backup.php#L65-L92 | train |
bradcornford/Backup | src/Cornford/Backup/Backup.php | Backup.removeTemporaryFiles | protected function removeTemporaryFiles($filepath, $force = false)
{
if ($force || $filepath !== $this->getUncompressedFilepath($filepath)) {
$this->getBackupFilesystemInstance()->removeFile($this->getUncompressedFilepath($filepath));
}
} | php | protected function removeTemporaryFiles($filepath, $force = false)
{
if ($force || $filepath !== $this->getUncompressedFilepath($filepath)) {
$this->getBackupFilesystemInstance()->removeFile($this->getUncompressedFilepath($filepath));
}
} | [
"protected",
"function",
"removeTemporaryFiles",
"(",
"$",
"filepath",
",",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"force",
"||",
"$",
"filepath",
"!==",
"$",
"this",
"->",
"getUncompressedFilepath",
"(",
"$",
"filepath",
")",
")",
"{",
"$... | Remove temporary files.
@param string $filepath
@param boolean $force
@return void | [
"Remove",
"temporary",
"files",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Backup.php#L114-L119 | train |
bradcornford/Backup | src/Cornford/Backup/Backup.php | Backup.compressFile | protected function compressFile($filepath)
{
if (!$this->getBackupFilesystemInstance()->checkFunctionExists('gzencode')) {
throw new BackupException('The method: "gzencode" isn\'t currently enabled.');
}
$compressedFilepath = $this->getCompressedFilepath($filepath);
$this->getBackupFilesystemInstance()->writeCompressedFile($compressedFilepath, $filepath);
$this->getBackupFilesystemInstance()->removeFile($filepath);
return $compressedFilepath;
} | php | protected function compressFile($filepath)
{
if (!$this->getBackupFilesystemInstance()->checkFunctionExists('gzencode')) {
throw new BackupException('The method: "gzencode" isn\'t currently enabled.');
}
$compressedFilepath = $this->getCompressedFilepath($filepath);
$this->getBackupFilesystemInstance()->writeCompressedFile($compressedFilepath, $filepath);
$this->getBackupFilesystemInstance()->removeFile($filepath);
return $compressedFilepath;
} | [
"protected",
"function",
"compressFile",
"(",
"$",
"filepath",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getBackupFilesystemInstance",
"(",
")",
"->",
"checkFunctionExists",
"(",
"'gzencode'",
")",
")",
"{",
"throw",
"new",
"BackupException",
"(",
"'The me... | Compress a file with gzip.
@param string $filepath
@throws BackupException
@return string | [
"Compress",
"a",
"file",
"with",
"gzip",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Backup.php#L130-L141 | train |
bradcornford/Backup | src/Cornford/Backup/Backup.php | Backup.decompressFile | protected function decompressFile($filepath)
{
if (!$this->getBackupFilesystemInstance()->checkFunctionExists('gzdecode')) {
throw new BackupException('The method: "gzdecode" isn\'t currently enabled.');
}
$uncompressedFilepath = $this->getUncompressedFilepath($filepath);
$this->getBackupFilesystemInstance()->writeUncompressedFile($uncompressedFilepath, $filepath);
return $uncompressedFilepath;
} | php | protected function decompressFile($filepath)
{
if (!$this->getBackupFilesystemInstance()->checkFunctionExists('gzdecode')) {
throw new BackupException('The method: "gzdecode" isn\'t currently enabled.');
}
$uncompressedFilepath = $this->getUncompressedFilepath($filepath);
$this->getBackupFilesystemInstance()->writeUncompressedFile($uncompressedFilepath, $filepath);
return $uncompressedFilepath;
} | [
"protected",
"function",
"decompressFile",
"(",
"$",
"filepath",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getBackupFilesystemInstance",
"(",
")",
"->",
"checkFunctionExists",
"(",
"'gzdecode'",
")",
")",
"{",
"throw",
"new",
"BackupException",
"(",
"'The ... | Decompress a file with gzip.
@param string $filepath
@throws BackupException
@return string | [
"Decompress",
"a",
"file",
"with",
"gzip",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Backup.php#L152-L162 | train |
bradcornford/Backup | src/Cornford/Backup/Backup.php | Backup.getRestorationFiles | public function getRestorationFiles($path = null)
{
if ($path === null) {
$path = $this->getPath();
}
$results = [];
if (!$this->getBackupFilesystemInstance()->checkPathExists($path)) {
throw new BackupException('Unable to get restoration files as path "' . $path . '" doesn\'t exist');
}
try {
foreach (new DirectoryIterator($path) as $fileinfo) {
if ($fileinfo->isDot() ||
!$fileinfo->isFile() ||
in_array($fileinfo->getFilename(), BackupFilesystem::$ignoredFiles) ||
substr($fileinfo->getFilename(), 0, 1) == '.'
) {
continue;
}
$results[] = $fileinfo->getPathname();
}
} catch (Exception $exception) {
// Exception thrown continue and return empty result set
}
return $results;
} | php | public function getRestorationFiles($path = null)
{
if ($path === null) {
$path = $this->getPath();
}
$results = [];
if (!$this->getBackupFilesystemInstance()->checkPathExists($path)) {
throw new BackupException('Unable to get restoration files as path "' . $path . '" doesn\'t exist');
}
try {
foreach (new DirectoryIterator($path) as $fileinfo) {
if ($fileinfo->isDot() ||
!$fileinfo->isFile() ||
in_array($fileinfo->getFilename(), BackupFilesystem::$ignoredFiles) ||
substr($fileinfo->getFilename(), 0, 1) == '.'
) {
continue;
}
$results[] = $fileinfo->getPathname();
}
} catch (Exception $exception) {
// Exception thrown continue and return empty result set
}
return $results;
} | [
"public",
"function",
"getRestorationFiles",
"(",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"path",
"===",
"null",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
";",
"}",
"$",
"results",
"=",
"[",
"]",
";",
"if",
... | Get database restoration files.
@param string $path
@throws BackupException
@return array | [
"Get",
"database",
"restoration",
"files",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Backup.php#L197-L226 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFactory.php | BackupFactory.build | public function build(
array $options = [],
$database = null
) {
$backupEngine = $this->buildBackupEngine($options);
$backupFilesystem = $this->buildBackupFilesystem();
return $this->buildBackup($backupEngine, $backupFilesystem, $options, $database);
} | php | public function build(
array $options = [],
$database = null
) {
$backupEngine = $this->buildBackupEngine($options);
$backupFilesystem = $this->buildBackupFilesystem();
return $this->buildBackup($backupEngine, $backupFilesystem, $options, $database);
} | [
"public",
"function",
"build",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"database",
"=",
"null",
")",
"{",
"$",
"backupEngine",
"=",
"$",
"this",
"->",
"buildBackupEngine",
"(",
"$",
"options",
")",
";",
"$",
"backupFilesystem",
"=",
"$",... | Build a new Backup object and its dependencies.
@param array $options
@param string $database
@return \Cornford\Backup\Contracts\BackupInterface | [
"Build",
"a",
"new",
"Backup",
"object",
"and",
"its",
"dependencies",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFactory.php#L24-L32 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFactory.php | BackupFactory.buildBackup | public function buildBackup(
BackupEngineInterface $backupEngine,
BackupFilesystemInterface $backupFilesystem,
array $options = []
) {
return new Backup($backupEngine, $backupFilesystem, $options);
} | php | public function buildBackup(
BackupEngineInterface $backupEngine,
BackupFilesystemInterface $backupFilesystem,
array $options = []
) {
return new Backup($backupEngine, $backupFilesystem, $options);
} | [
"public",
"function",
"buildBackup",
"(",
"BackupEngineInterface",
"$",
"backupEngine",
",",
"BackupFilesystemInterface",
"$",
"backupFilesystem",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"new",
"Backup",
"(",
"$",
"backupEngine",
",",
"$... | Build the Backup object.
@param BackupEngineInterface $backupEngine
@param BackupFilesystemInterface $backupFilesystem
@param array $options
@return \Cornford\Backup\Contracts\BackupInterface | [
"Build",
"the",
"Backup",
"object",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFactory.php#L43-L49 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFactory.php | BackupFactory.buildBackupEngine | public function buildBackupEngine(
array $options = [],
$database = null
) {
$backupProcessInstance = new BackupProcess(new Process(''));
switch ($database ? $database : $options['default'])
{
case 'mysql':
return new BackupEngineMysql(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
$options['connections'][$options['default']]['host'],
isset($options['connections'][$options['default']]['port']) ? $options['connections'][$options['default']]['port'] : 3306,
$options['connections'][$options['default']]['username'],
$options['connections'][$options['default']]['password'],
$options
);
case 'pgsql':
return new BackupEnginePgsql(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
$options['connections'][$options['default']]['host'],
null,
$options['connections'][$options['default']]['username'],
$options['connections'][$options['default']]['password'],
$options
);
case 'sqlite':
return new BackupEngineSqlite(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
null,
null,
null,
null,
$options
);
case 'sqlsrv':
return new BackupEngineSqlsrv(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
$options['connections'][$options['default']]['host'],
null,
$options['connections'][$options['default']]['username'],
$options['connections'][$options['default']]['password'],
$options
);
default:
throw new BackupException('Database driver isn\'t supported.');
}
} | php | public function buildBackupEngine(
array $options = [],
$database = null
) {
$backupProcessInstance = new BackupProcess(new Process(''));
switch ($database ? $database : $options['default'])
{
case 'mysql':
return new BackupEngineMysql(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
$options['connections'][$options['default']]['host'],
isset($options['connections'][$options['default']]['port']) ? $options['connections'][$options['default']]['port'] : 3306,
$options['connections'][$options['default']]['username'],
$options['connections'][$options['default']]['password'],
$options
);
case 'pgsql':
return new BackupEnginePgsql(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
$options['connections'][$options['default']]['host'],
null,
$options['connections'][$options['default']]['username'],
$options['connections'][$options['default']]['password'],
$options
);
case 'sqlite':
return new BackupEngineSqlite(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
null,
null,
null,
null,
$options
);
case 'sqlsrv':
return new BackupEngineSqlsrv(
$backupProcessInstance,
$options['connections'][$options['default']]['database'],
$options['connections'][$options['default']]['host'],
null,
$options['connections'][$options['default']]['username'],
$options['connections'][$options['default']]['password'],
$options
);
default:
throw new BackupException('Database driver isn\'t supported.');
}
} | [
"public",
"function",
"buildBackupEngine",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"database",
"=",
"null",
")",
"{",
"$",
"backupProcessInstance",
"=",
"new",
"BackupProcess",
"(",
"new",
"Process",
"(",
"''",
")",
")",
";",
"switch",
"("... | Build a new Backup Engine object.
@param array $options
@param string $database
@throws BackupException
@return \Cornford\Backup\Contracts\BackupEngineInterface | [
"Build",
"a",
"new",
"Backup",
"Engine",
"object",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFactory.php#L61-L112 | train |
bradcornford/Backup | src/Cornford/Backup/BackupProcess.php | BackupProcess.run | public function run($command, $operation = 'default')
{
$this->output = null;
try {
$this->processInstance->setCommandLine($command);
$this->processInstance->setTimeout(self::PROCESS_TIMEOUT);
$this->processInstance->run();
if (!$this->processInstance->isSuccessful()) {
$this->output = $this->processInstance->getErrorOutput();
return false;
}
} catch (Exception $exception) {
$message = 'An error occurred that prevented the operation ' . $operation . ': ' . $exception->getMessage();
switch ($operation) {
case 'export':
throw new BackupExportException($message);
case 'restore':
throw new BackupRestoreException($message);
default:
throw new BackupException($message);
}
}
return true;
} | php | public function run($command, $operation = 'default')
{
$this->output = null;
try {
$this->processInstance->setCommandLine($command);
$this->processInstance->setTimeout(self::PROCESS_TIMEOUT);
$this->processInstance->run();
if (!$this->processInstance->isSuccessful()) {
$this->output = $this->processInstance->getErrorOutput();
return false;
}
} catch (Exception $exception) {
$message = 'An error occurred that prevented the operation ' . $operation . ': ' . $exception->getMessage();
switch ($operation) {
case 'export':
throw new BackupExportException($message);
case 'restore':
throw new BackupRestoreException($message);
default:
throw new BackupException($message);
}
}
return true;
} | [
"public",
"function",
"run",
"(",
"$",
"command",
",",
"$",
"operation",
"=",
"'default'",
")",
"{",
"$",
"this",
"->",
"output",
"=",
"null",
";",
"try",
"{",
"$",
"this",
"->",
"processInstance",
"->",
"setCommandLine",
"(",
"$",
"command",
")",
";",... | Execute a command process.
@param string $command
@param string $operation
@throws BackupException
@throws BackupExportException
@throws BackupRestoreException
@return boolean | [
"Execute",
"a",
"command",
"process",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupProcess.php#L101-L129 | train |
bradcornford/Backup | src/Cornford/Backup/Engines/BackupEnginePgsql.php | BackupEnginePgsql.export | public function export($filepath)
{
$command = sprintf(
'PGPASSWORD=%s %s -Fc --no-acl --no-owner -h %s -U %s %s > %s',
escapeshellarg($this->getPassword()),
$this->getExportCommand(),
escapeshellarg($this->getHostname()),
escapeshellarg($this->getUsername()),
escapeshellarg($this->getDatabase()),
escapeshellarg($filepath)
);
return $this->getBackupProcess()->run($command, __FUNCTION__);
} | php | public function export($filepath)
{
$command = sprintf(
'PGPASSWORD=%s %s -Fc --no-acl --no-owner -h %s -U %s %s > %s',
escapeshellarg($this->getPassword()),
$this->getExportCommand(),
escapeshellarg($this->getHostname()),
escapeshellarg($this->getUsername()),
escapeshellarg($this->getDatabase()),
escapeshellarg($filepath)
);
return $this->getBackupProcess()->run($command, __FUNCTION__);
} | [
"public",
"function",
"export",
"(",
"$",
"filepath",
")",
"{",
"$",
"command",
"=",
"sprintf",
"(",
"'PGPASSWORD=%s %s -Fc --no-acl --no-owner -h %s -U %s %s > %s'",
",",
"escapeshellarg",
"(",
"$",
"this",
"->",
"getPassword",
"(",
")",
")",
",",
"$",
"this",
... | Export the database to a file path.
@param string $filepath
@return boolean | [
"Export",
"the",
"database",
"to",
"a",
"file",
"path",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Engines/BackupEnginePgsql.php#L47-L60 | train |
bradcornford/Backup | src/Cornford/Backup/Engines/BackupEnginePgsql.php | BackupEnginePgsql.restore | public function restore($filepath)
{
$command = sprintf('PGPASSWORD=%s %s --verbose --clean --no-acl --no-owner -h %s -U %s -d %s %s',
escapeshellarg($this->getPassword()),
$this->getRestoreCommand(),
escapeshellarg($this->getHostname()),
escapeshellarg($this->getUsername()),
escapeshellarg($this->getDatabase()),
escapeshellarg($filepath)
);
return $this->getBackupProcess()->run($command, __FUNCTION__);
} | php | public function restore($filepath)
{
$command = sprintf('PGPASSWORD=%s %s --verbose --clean --no-acl --no-owner -h %s -U %s -d %s %s',
escapeshellarg($this->getPassword()),
$this->getRestoreCommand(),
escapeshellarg($this->getHostname()),
escapeshellarg($this->getUsername()),
escapeshellarg($this->getDatabase()),
escapeshellarg($filepath)
);
return $this->getBackupProcess()->run($command, __FUNCTION__);
} | [
"public",
"function",
"restore",
"(",
"$",
"filepath",
")",
"{",
"$",
"command",
"=",
"sprintf",
"(",
"'PGPASSWORD=%s %s --verbose --clean --no-acl --no-owner -h %s -U %s -d %s %s'",
",",
"escapeshellarg",
"(",
"$",
"this",
"->",
"getPassword",
"(",
")",
")",
",",
"... | Restore the database from a file path.
@param string $filepath
@return boolean | [
"Restore",
"the",
"database",
"from",
"a",
"file",
"path",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/Engines/BackupEnginePgsql.php#L69-L81 | train |
bradcornford/Backup | src/Cornford/Backup/BackupAbstract.php | BackupAbstract.getPath | public function getPath()
{
$path = getcwd() . DIRECTORY_SEPARATOR . $this->path;
if (substr($this->path, 0, 1) == '/' || substr($this->path, 1, 1) == ':') {
$path = $this->path;
}
return realpath($path);
} | php | public function getPath()
{
$path = getcwd() . DIRECTORY_SEPARATOR . $this->path;
if (substr($this->path, 0, 1) == '/' || substr($this->path, 1, 1) == ':') {
$path = $this->path;
}
return realpath($path);
} | [
"public",
"function",
"getPath",
"(",
")",
"{",
"$",
"path",
"=",
"getcwd",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"this",
"->",
"path",
";",
"if",
"(",
"substr",
"(",
"$",
"this",
"->",
"path",
",",
"0",
",",
"1",
")",
"==",
"'/'",
"||"... | Get the backup path.
@return string | [
"Get",
"the",
"backup",
"path",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupAbstract.php#L242-L251 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFilesystem.php | BackupFilesystem.writeCompressedFile | public function writeCompressedFile($compressedFilepath, $filepath)
{
$filePointer = fopen($compressedFilepath, 'w');
fwrite($filePointer, gzencode(file_get_contents($filepath), 9));
fclose($filePointer);
} | php | public function writeCompressedFile($compressedFilepath, $filepath)
{
$filePointer = fopen($compressedFilepath, 'w');
fwrite($filePointer, gzencode(file_get_contents($filepath), 9));
fclose($filePointer);
} | [
"public",
"function",
"writeCompressedFile",
"(",
"$",
"compressedFilepath",
",",
"$",
"filepath",
")",
"{",
"$",
"filePointer",
"=",
"fopen",
"(",
"$",
"compressedFilepath",
",",
"'w'",
")",
";",
"fwrite",
"(",
"$",
"filePointer",
",",
"gzencode",
"(",
"fil... | Write a compressed file.
@param string $compressedFilepath
@param string $filepath
@return void | [
"Write",
"a",
"compressed",
"file",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFilesystem.php#L90-L95 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFilesystem.php | BackupFilesystem.writeUncompressedFile | public function writeUncompressedFile($uncompressedFilepath, $filepath)
{
$filePointer = fopen($uncompressedFilepath, 'w');
fwrite($filePointer, gzdecode(file_get_contents($filepath, 9)));
fclose($filePointer);
} | php | public function writeUncompressedFile($uncompressedFilepath, $filepath)
{
$filePointer = fopen($uncompressedFilepath, 'w');
fwrite($filePointer, gzdecode(file_get_contents($filepath, 9)));
fclose($filePointer);
} | [
"public",
"function",
"writeUncompressedFile",
"(",
"$",
"uncompressedFilepath",
",",
"$",
"filepath",
")",
"{",
"$",
"filePointer",
"=",
"fopen",
"(",
"$",
"uncompressedFilepath",
",",
"'w'",
")",
";",
"fwrite",
"(",
"$",
"filePointer",
",",
"gzdecode",
"(",
... | Write an uncompressed file.
@param string $uncompressedFilepath
@param string $filepath
@return void | [
"Write",
"an",
"uncompressed",
"file",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFilesystem.php#L105-L110 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFilesystem.php | BackupFilesystem.getOperatingSystem | public function getOperatingSystem()
{
switch (true) {
case stristr(PHP_OS, 'DAR'):
return self::OS_OSX;
case stristr(PHP_OS, 'WIN'):
return self::OS_WIN;
case stristr(PHP_OS, 'LINUX'):
return self::OS_LINUX;
default:
return self::OS_UNKNOWN;
}
} | php | public function getOperatingSystem()
{
switch (true) {
case stristr(PHP_OS, 'DAR'):
return self::OS_OSX;
case stristr(PHP_OS, 'WIN'):
return self::OS_WIN;
case stristr(PHP_OS, 'LINUX'):
return self::OS_LINUX;
default:
return self::OS_UNKNOWN;
}
} | [
"public",
"function",
"getOperatingSystem",
"(",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"stristr",
"(",
"PHP_OS",
",",
"'DAR'",
")",
":",
"return",
"self",
"::",
"OS_OSX",
";",
"case",
"stristr",
"(",
"PHP_OS",
",",
"'WIN'",
")",
":",
"retu... | Get the operating system.
@return integer | [
"Get",
"the",
"operating",
"system",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFilesystem.php#L117-L129 | train |
bradcornford/Backup | src/Cornford/Backup/BackupFilesystem.php | BackupFilesystem.locateCommand | public function locateCommand($command)
{
switch ($this->getOperatingSystem()) {
case self::OS_OSX:
case self::OS_LINUX:
exec(sprintf('/usr/bin/which %s', $command), $result, $returnCode);
if (isset($result[0])) {
$result = $result[0];
}
break;
case self::OS_WIN:
exec(sprintf('where %s', $command), $result, $returnCode);
if (isset($result[0])) {
$result = $result[0];
}
break;
default:
return false;
}
if (empty($result)) {
return false;
}
return $result;
} | php | public function locateCommand($command)
{
switch ($this->getOperatingSystem()) {
case self::OS_OSX:
case self::OS_LINUX:
exec(sprintf('/usr/bin/which %s', $command), $result, $returnCode);
if (isset($result[0])) {
$result = $result[0];
}
break;
case self::OS_WIN:
exec(sprintf('where %s', $command), $result, $returnCode);
if (isset($result[0])) {
$result = $result[0];
}
break;
default:
return false;
}
if (empty($result)) {
return false;
}
return $result;
} | [
"public",
"function",
"locateCommand",
"(",
"$",
"command",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"getOperatingSystem",
"(",
")",
")",
"{",
"case",
"self",
"::",
"OS_OSX",
":",
"case",
"self",
"::",
"OS_LINUX",
":",
"exec",
"(",
"sprintf",
"(",
"... | Locate command location.
@param string $command
@return string|false | [
"Locate",
"command",
"location",
"."
] | 30ffbb85a539d3ac515874bd31ca923fb196c218 | https://github.com/bradcornford/Backup/blob/30ffbb85a539d3ac515874bd31ca923fb196c218/src/Cornford/Backup/BackupFilesystem.php#L138-L163 | train |
aklump/loft_data_grids | docs/core/src/AKlump/LoftDocs/SearchHtml.php | SearchHtml.getData | public function getData($url = '')
{
$url = empty($url) ? $this->url : $url;
$title = $tags = '';
$contents = $this->html;
if (preg_match('/(<h.+?>(.+?)<\/h.>)/si', $this->html, $matches)) {
$title = $matches[2];
// Pull out the meta data section.
$tags = substr($contents, 0, strpos($contents, $matches[1]));
$contents = substr($contents, strpos($contents, $matches[1]));
// Remove the title from the contents.
$contents = str_replace($matches[0], '', $contents);
}
if ($tags && preg_match('/tags\s*:(.*?)</si', $tags, $matches)) {
$tags = explode(' ', $matches[1]);
}
else {
$tags = array();
}
// Insert spaces for new lines to help format the strip_tags.
$contents = implode(' ', explode(PHP_EOL, $contents));
$contents = strip_tags($contents);
return new SearchPageData($url, $title, $contents, $tags);
} | php | public function getData($url = '')
{
$url = empty($url) ? $this->url : $url;
$title = $tags = '';
$contents = $this->html;
if (preg_match('/(<h.+?>(.+?)<\/h.>)/si', $this->html, $matches)) {
$title = $matches[2];
// Pull out the meta data section.
$tags = substr($contents, 0, strpos($contents, $matches[1]));
$contents = substr($contents, strpos($contents, $matches[1]));
// Remove the title from the contents.
$contents = str_replace($matches[0], '', $contents);
}
if ($tags && preg_match('/tags\s*:(.*?)</si', $tags, $matches)) {
$tags = explode(' ', $matches[1]);
}
else {
$tags = array();
}
// Insert spaces for new lines to help format the strip_tags.
$contents = implode(' ', explode(PHP_EOL, $contents));
$contents = strip_tags($contents);
return new SearchPageData($url, $title, $contents, $tags);
} | [
"public",
"function",
"getData",
"(",
"$",
"url",
"=",
"''",
")",
"{",
"$",
"url",
"=",
"empty",
"(",
"$",
"url",
")",
"?",
"$",
"this",
"->",
"url",
":",
"$",
"url",
";",
"$",
"title",
"=",
"$",
"tags",
"=",
"''",
";",
"$",
"contents",
"=",
... | Returns the parsed data from the html
@param string $url This should be provided if you did not instantiate
with a file, if you did the url will be parsed from
that. You may provide an url that would override a
parsed one to0.
@return SearchPageData | [
"Returns",
"the",
"parsed",
"data",
"from",
"the",
"html"
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/docs/core/src/AKlump/LoftDocs/SearchHtml.php#L47-L76 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/XLSXExporter.php | XLSXExporter.formatColumn | public function formatColumn($column, $format_code)
{
// By default we'll use USD.
$format_code = isset($format_code) ? $format_code : 'USD';
$phpexcel_format = \PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
// Map to specific formats in PHPExcel
if ($format_code === 'USD') {
$phpexcel_format = \PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
}
elseif ($format_code === \PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE) {
$format_code = 'USD';
}
$columns = $this->getPHPExcelColumns();
if (!array_key_exists($column, $columns)) {
return;
}
$phpexcel_column = $columns[$column];
$page = $this->excel->getActiveSheet();
foreach ($page->getRowIterator() as $row) {
$row_index = $row->getRowIndex();
$page->getStyle("$phpexcel_column$row_index")
->getNumberFormat()
->setFormatCode($phpexcel_format);
}
return parent::formatColumn($column, $format_code);
} | php | public function formatColumn($column, $format_code)
{
// By default we'll use USD.
$format_code = isset($format_code) ? $format_code : 'USD';
$phpexcel_format = \PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
// Map to specific formats in PHPExcel
if ($format_code === 'USD') {
$phpexcel_format = \PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
}
elseif ($format_code === \PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE) {
$format_code = 'USD';
}
$columns = $this->getPHPExcelColumns();
if (!array_key_exists($column, $columns)) {
return;
}
$phpexcel_column = $columns[$column];
$page = $this->excel->getActiveSheet();
foreach ($page->getRowIterator() as $row) {
$row_index = $row->getRowIndex();
$page->getStyle("$phpexcel_column$row_index")
->getNumberFormat()
->setFormatCode($phpexcel_format);
}
return parent::formatColumn($column, $format_code);
} | [
"public",
"function",
"formatColumn",
"(",
"$",
"column",
",",
"$",
"format_code",
")",
"{",
"// By default we'll use USD.",
"$",
"format_code",
"=",
"isset",
"(",
"$",
"format_code",
")",
"?",
"$",
"format_code",
":",
"'USD'",
";",
"$",
"phpexcel_format",
"="... | Format a single column with a number format
You must do this after calling $this->compile!
@param string $column
@param string $format_code
- USD OR PHPExcel_Style_NumberFormat::setFormatCode()
@return $this | [
"Format",
"a",
"single",
"column",
"with",
"a",
"number",
"format"
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/XLSXExporter.php#L180-L209 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/XLSXExporter.php | XLSXExporter.getProperty | public function getProperty($property_name)
{
$obj = $this->excel->getProperties();
$method = "get$property_name";
return method_exists($obj, $method) ? $obj->$method() : null;
} | php | public function getProperty($property_name)
{
$obj = $this->excel->getProperties();
$method = "get$property_name";
return method_exists($obj, $method) ? $obj->$method() : null;
} | [
"public",
"function",
"getProperty",
"(",
"$",
"property_name",
")",
"{",
"$",
"obj",
"=",
"$",
"this",
"->",
"excel",
"->",
"getProperties",
"(",
")",
";",
"$",
"method",
"=",
"\"get$property_name\"",
";",
"return",
"method_exists",
"(",
"$",
"obj",
",",
... | Return the value of a single property or NULL
@param string $property_name e.g. Creator
@return mixed | [
"Return",
"the",
"value",
"of",
"a",
"single",
"property",
"or",
"NULL"
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/XLSXExporter.php#L239-L245 | train |
pixelpeter/laravel5-genderize-api-client | src/Models/Name.php | Name.prepareData | protected function prepareData($data)
{
$default = new \StdClass;
$default->name = null;
$default->gender = null;
$default->probability = null;
$default->count = null;
return (object) array_merge(
(array) $default,
(array) $data
);
} | php | protected function prepareData($data)
{
$default = new \StdClass;
$default->name = null;
$default->gender = null;
$default->probability = null;
$default->count = null;
return (object) array_merge(
(array) $default,
(array) $data
);
} | [
"protected",
"function",
"prepareData",
"(",
"$",
"data",
")",
"{",
"$",
"default",
"=",
"new",
"\\",
"StdClass",
";",
"$",
"default",
"->",
"name",
"=",
"null",
";",
"$",
"default",
"->",
"gender",
"=",
"null",
";",
"$",
"default",
"->",
"probability"... | Merge data with default so every field is available
@param $data
@return object | [
"Merge",
"data",
"with",
"default",
"so",
"every",
"field",
"is",
"available"
] | fde6f31f973fd1e39880c59f138645079b65b576 | https://github.com/pixelpeter/laravel5-genderize-api-client/blob/fde6f31f973fd1e39880c59f138645079b65b576/src/Models/Name.php#L34-L46 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/ScheduleData.php | ScheduleData.makeSchedule | public function makeSchedule()
{
// Pull out the first page to distribute it; then delete.
$items = $this->getRows();
$id = $this->getCurrentPageId();
$this->deletePage($id);
$this->date = clone $this->getStartDate();
$this->avoidHolidaysAndWeekdaysOff();
$this->stats['start date'] = $this->date->format($this->getPageIdFormat());
$this->stats['hours per day'] = $this->getHoursPerDay();
$this->stats['total items'] = count($items);
$this->stats['dates off'] = array();
$this->setDatePage($this->date);
$dayTotal = 0;
$this->stats['total hours'] = 0;
while (($item = array_shift($items))) {
$this->stats['total hours'] += $item[$this->getHoursKey()];
$this->processItem($item, $item[$this->getHoursKey()], $dayTotal);
}
$this->stats['end date'] = $this->date->format($this->getPageIdFormat());
if ($this->todoStatsPage) {
$this->addStatsPage($this->todoStatsPage);
}
return $this;
} | php | public function makeSchedule()
{
// Pull out the first page to distribute it; then delete.
$items = $this->getRows();
$id = $this->getCurrentPageId();
$this->deletePage($id);
$this->date = clone $this->getStartDate();
$this->avoidHolidaysAndWeekdaysOff();
$this->stats['start date'] = $this->date->format($this->getPageIdFormat());
$this->stats['hours per day'] = $this->getHoursPerDay();
$this->stats['total items'] = count($items);
$this->stats['dates off'] = array();
$this->setDatePage($this->date);
$dayTotal = 0;
$this->stats['total hours'] = 0;
while (($item = array_shift($items))) {
$this->stats['total hours'] += $item[$this->getHoursKey()];
$this->processItem($item, $item[$this->getHoursKey()], $dayTotal);
}
$this->stats['end date'] = $this->date->format($this->getPageIdFormat());
if ($this->todoStatsPage) {
$this->addStatsPage($this->todoStatsPage);
}
return $this;
} | [
"public",
"function",
"makeSchedule",
"(",
")",
"{",
"// Pull out the first page to distribute it; then delete.",
"$",
"items",
"=",
"$",
"this",
"->",
"getRows",
"(",
")",
";",
"$",
"id",
"=",
"$",
"this",
"->",
"getCurrentPageId",
"(",
")",
";",
"$",
"this",... | Split the current page up into a number of pages based on workload.
@return $this | [
"Split",
"the",
"current",
"page",
"up",
"into",
"a",
"number",
"of",
"pages",
"based",
"on",
"workload",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/ScheduleData.php#L70-L98 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/ScheduleData.php | ScheduleData.avoidHolidaysAndWeekdaysOff | protected function avoidHolidaysAndWeekdaysOff()
{
while (in_array($this->date, $this->datesOff)
|| in_array($this->date->format('D'), $this->weekdaysOff)) {
$this->stats['dates off'][] = $this->date->format($this->getPageIdFormat());
$this->date->add(new \DateInterval('P1D'));
}
} | php | protected function avoidHolidaysAndWeekdaysOff()
{
while (in_array($this->date, $this->datesOff)
|| in_array($this->date->format('D'), $this->weekdaysOff)) {
$this->stats['dates off'][] = $this->date->format($this->getPageIdFormat());
$this->date->add(new \DateInterval('P1D'));
}
} | [
"protected",
"function",
"avoidHolidaysAndWeekdaysOff",
"(",
")",
"{",
"while",
"(",
"in_array",
"(",
"$",
"this",
"->",
"date",
",",
"$",
"this",
"->",
"datesOff",
")",
"||",
"in_array",
"(",
"$",
"this",
"->",
"date",
"->",
"format",
"(",
"'D'",
")",
... | Increment the internal date until it falls on neither a holiday nor a
weekday that can't be worked. | [
"Increment",
"the",
"internal",
"date",
"until",
"it",
"falls",
"on",
"neither",
"a",
"holiday",
"nor",
"a",
"weekday",
"that",
"can",
"t",
"be",
"worked",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/ScheduleData.php#L126-L133 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/ScheduleData.php | ScheduleData.nextDay | protected function nextDay()
{
$this->date->add(new \DateInterval('P1D'));
$this->avoidHolidaysAndWeekdaysOff();
$this->setDatePage($this->date);
} | php | protected function nextDay()
{
$this->date->add(new \DateInterval('P1D'));
$this->avoidHolidaysAndWeekdaysOff();
$this->setDatePage($this->date);
} | [
"protected",
"function",
"nextDay",
"(",
")",
"{",
"$",
"this",
"->",
"date",
"->",
"add",
"(",
"new",
"\\",
"DateInterval",
"(",
"'P1D'",
")",
")",
";",
"$",
"this",
"->",
"avoidHolidaysAndWeekdaysOff",
"(",
")",
";",
"$",
"this",
"->",
"setDatePage",
... | Advance to the next available work day. | [
"Advance",
"to",
"the",
"next",
"available",
"work",
"day",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/ScheduleData.php#L258-L263 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/ScheduleData.php | ScheduleData.addWeekdayOff | public function addWeekdayOff($value)
{
$value = ucfirst(strtolower($value));
if (!(date_create_from_format('D', $value))) {
throw new \InvalidArgumentException("Bad format of day of week.");
}
$this->weekdaysOff[] = $value;
return $this;
} | php | public function addWeekdayOff($value)
{
$value = ucfirst(strtolower($value));
if (!(date_create_from_format('D', $value))) {
throw new \InvalidArgumentException("Bad format of day of week.");
}
$this->weekdaysOff[] = $value;
return $this;
} | [
"public",
"function",
"addWeekdayOff",
"(",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"ucfirst",
"(",
"strtolower",
"(",
"$",
"value",
")",
")",
";",
"if",
"(",
"!",
"(",
"date_create_from_format",
"(",
"'D'",
",",
"$",
"value",
")",
")",
")",
"{",
... | Mark a single weekday as unworked.
@param string $value Three char word ,e.g. 'Sun', 'Mon'...
@return $this | [
"Mark",
"a",
"single",
"weekday",
"as",
"unworked",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/ScheduleData.php#L288-L297 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/Exporter.php | Exporter.dataTransform | protected function dataTransform(&$value)
{
if (is_object($value)) {
// Convert dates to the settings for date_format.
if (($dateFormat = $this->getSettings()->dateFormat) && $value instanceof \DateTime) {
$value = $value->format($dateFormat);
}
// Handle other objects as needed.
if (method_exists($this, 'objectHandler')) {
$value = $this->objectHandler($key, $value);
}
}
} | php | protected function dataTransform(&$value)
{
if (is_object($value)) {
// Convert dates to the settings for date_format.
if (($dateFormat = $this->getSettings()->dateFormat) && $value instanceof \DateTime) {
$value = $value->format($dateFormat);
}
// Handle other objects as needed.
if (method_exists($this, 'objectHandler')) {
$value = $this->objectHandler($key, $value);
}
}
} | [
"protected",
"function",
"dataTransform",
"(",
"&",
"$",
"value",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"value",
")",
")",
"{",
"// Convert dates to the settings for date_format.",
"if",
"(",
"(",
"$",
"dateFormat",
"=",
"$",
"this",
"->",
"getSettings",... | Iterate over all cells and transform data as appropriate. | [
"Iterate",
"over",
"all",
"cells",
"and",
"transform",
"data",
"as",
"appropriate",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/Exporter.php#L287-L301 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/Exporter.php | Exporter.getDataAsTransformedArray | protected function getDataAsTransformedArray($page_id = null, $page_id_key = null)
{
$data = $this->getData()->get();
if (!is_null($page_id)) {
$data = is_null($page_id_key) ? array($data[$page_id]) : array($page_id_key => $data[$page_id]);
}
foreach ($data as &$page) {
foreach ($page as &$row) {
foreach ($row as &$cell) {
$this->dataTransform($cell);
}
}
}
return $data;
} | php | protected function getDataAsTransformedArray($page_id = null, $page_id_key = null)
{
$data = $this->getData()->get();
if (!is_null($page_id)) {
$data = is_null($page_id_key) ? array($data[$page_id]) : array($page_id_key => $data[$page_id]);
}
foreach ($data as &$page) {
foreach ($page as &$row) {
foreach ($row as &$cell) {
$this->dataTransform($cell);
}
}
}
return $data;
} | [
"protected",
"function",
"getDataAsTransformedArray",
"(",
"$",
"page_id",
"=",
"null",
",",
"$",
"page_id_key",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"getData",
"(",
")",
"->",
"get",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"... | Convert ExportData to an array transforming every cell.
@param mixed $page_id The page id from which to pull data or
empty for all pages.
@param mixed $page_id_key If $page_id is provided, set this to the
key value to use to indicate the page
id, for example JSON keeps this as NULL
and XML uses the page id.
@return array
@see $this->dataTransform(). | [
"Convert",
"ExportData",
"to",
"an",
"array",
"transforming",
"every",
"cell",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/Exporter.php#L317-L332 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/Exporter.php | Exporter.filenameSafe | protected function filenameSafe($string, $options = array())
{
$options += array(
'extensions' => array('txt', 'md'),
'ext' => 'txt',
);
$string = preg_replace('/[^a-z0-9\-\.]/', '-', strtolower($string));
$string = preg_replace('/-{2,}/', '-', $string);
// Add an extension if not found
if ($options['ext'] && !preg_match('/\.[a-z]{1,5}$/', $string)) {
$string .= '.' . trim($options['ext'], '.');
}
if ($string && function_exists('file_munge_filename')) {
$string = file_munge_filename($string, implode(' ', $options['extensions']), false);
}
//@todo Add in the module that cleans name if it's installed
return $string;
} | php | protected function filenameSafe($string, $options = array())
{
$options += array(
'extensions' => array('txt', 'md'),
'ext' => 'txt',
);
$string = preg_replace('/[^a-z0-9\-\.]/', '-', strtolower($string));
$string = preg_replace('/-{2,}/', '-', $string);
// Add an extension if not found
if ($options['ext'] && !preg_match('/\.[a-z]{1,5}$/', $string)) {
$string .= '.' . trim($options['ext'], '.');
}
if ($string && function_exists('file_munge_filename')) {
$string = file_munge_filename($string, implode(' ', $options['extensions']), false);
}
//@todo Add in the module that cleans name if it's installed
return $string;
} | [
"protected",
"function",
"filenameSafe",
"(",
"$",
"string",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"options",
"+=",
"array",
"(",
"'extensions'",
"=>",
"array",
"(",
"'txt'",
",",
"'md'",
")",
",",
"'ext'",
"=>",
"'txt'",
",",
"... | Return a string as a safe filename
@param string $string
The candidtate filename.
@param array $options
- array extensions: allowable extensions no periods
- string ext: default extension if non found; blank for none no period
@return string
- lowercased, with only letters, numbers, dots and hyphens
@see file_munge_filename(). | [
"Return",
"a",
"string",
"as",
"a",
"safe",
"filename"
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/Exporter.php#L348-L368 | train |
aklump/loft_data_grids | docs/core/src/AKlump/LoftDocs/TipueSearch.php | TipueSearch.addPage | public function addPage(SearchPageData $data)
{
$url = $data->getUrl();
$this->pages[$url] = array(
'title' => $data->getTitle(),
'text' => $data->getContents(),
'tags' => $data->getTags(true),
'url' => $url,
);
return $this;
} | php | public function addPage(SearchPageData $data)
{
$url = $data->getUrl();
$this->pages[$url] = array(
'title' => $data->getTitle(),
'text' => $data->getContents(),
'tags' => $data->getTags(true),
'url' => $url,
);
return $this;
} | [
"public",
"function",
"addPage",
"(",
"SearchPageData",
"$",
"data",
")",
"{",
"$",
"url",
"=",
"$",
"data",
"->",
"getUrl",
"(",
")",
";",
"$",
"this",
"->",
"pages",
"[",
"$",
"url",
"]",
"=",
"array",
"(",
"'title'",
"=>",
"$",
"data",
"->",
"... | Adds a page to the index.
@param SearchPageData $data | [
"Adds",
"a",
"page",
"to",
"the",
"index",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/docs/core/src/AKlump/LoftDocs/TipueSearch.php#L28-L39 | train |
aklump/loft_data_grids | docs/core/src/AKlump/LoftDocs/TipueSearch.php | TipueSearch.buildFileContents | public function buildFileContents()
{
$data = array('pages' => $this->getPages());
$output = array();
$output[] = "var tipuesearch = " . json_encode($data) . ";";
$output[] = null;
return implode(PHP_EOL, $output);
} | php | public function buildFileContents()
{
$data = array('pages' => $this->getPages());
$output = array();
$output[] = "var tipuesearch = " . json_encode($data) . ";";
$output[] = null;
return implode(PHP_EOL, $output);
} | [
"public",
"function",
"buildFileContents",
"(",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"'pages'",
"=>",
"$",
"this",
"->",
"getPages",
"(",
")",
")",
";",
"$",
"output",
"=",
"array",
"(",
")",
";",
"$",
"output",
"[",
"]",
"=",
"\"var tipuesearch... | Builds the search content file contents as a string.
@return string | [
"Builds",
"the",
"search",
"content",
"file",
"contents",
"as",
"a",
"string",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/docs/core/src/AKlump/LoftDocs/TipueSearch.php#L46-L54 | train |
aklump/loft_data_grids | docs/core/src/AKlump/LoftDocs/TipueSearch.php | TipueSearch.getPages | protected function getPages()
{
$pages = $this->pages;
ksort($pages);
$pages = array_values($pages);
return $pages;
} | php | protected function getPages()
{
$pages = $this->pages;
ksort($pages);
$pages = array_values($pages);
return $pages;
} | [
"protected",
"function",
"getPages",
"(",
")",
"{",
"$",
"pages",
"=",
"$",
"this",
"->",
"pages",
";",
"ksort",
"(",
"$",
"pages",
")",
";",
"$",
"pages",
"=",
"array_values",
"(",
"$",
"pages",
")",
";",
"return",
"$",
"pages",
";",
"}"
] | Returns all pages sorted and made unique with numerical keys.
@return array | [
"Returns",
"all",
"pages",
"sorted",
"and",
"made",
"unique",
"with",
"numerical",
"keys",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/docs/core/src/AKlump/LoftDocs/TipueSearch.php#L87-L94 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/CSVExporter.php | CSVExporter.collapseCell | protected function collapseCell($cell, $column)
{
//compress a complex cell
if (is_array($cell)) {
$cell = isset($cell['data']) ? $cell['data'] : '';
}
if (!$this->format->html) {
$cell = strip_tags($cell);
}
// Escape chars that conflice with delimiters
if (!empty($this->format->escape)) {
$escapeables = array($this->format->left, $this->format->right);
$escapeables = array_filter(array_unique($escapeables));
foreach ($escapeables as $find) {
$cell = str_replace($find, $this->format->escape . $find, $cell);
}
}
return $this->format->left . $cell . $this->format->right;
} | php | protected function collapseCell($cell, $column)
{
//compress a complex cell
if (is_array($cell)) {
$cell = isset($cell['data']) ? $cell['data'] : '';
}
if (!$this->format->html) {
$cell = strip_tags($cell);
}
// Escape chars that conflice with delimiters
if (!empty($this->format->escape)) {
$escapeables = array($this->format->left, $this->format->right);
$escapeables = array_filter(array_unique($escapeables));
foreach ($escapeables as $find) {
$cell = str_replace($find, $this->format->escape . $find, $cell);
}
}
return $this->format->left . $cell . $this->format->right;
} | [
"protected",
"function",
"collapseCell",
"(",
"$",
"cell",
",",
"$",
"column",
")",
"{",
"//compress a complex cell",
"if",
"(",
"is_array",
"(",
"$",
"cell",
")",
")",
"{",
"$",
"cell",
"=",
"isset",
"(",
"$",
"cell",
"[",
"'data'",
"]",
")",
"?",
"... | Collapse a single cell in a row.
@param array $cell
@return string | [
"Collapse",
"a",
"single",
"cell",
"in",
"a",
"row",
"."
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/CSVExporter.php#L98-L119 | train |
aklump/loft_data_grids | src/AKlump/LoftDataGrids/ExportData.php | ExportData.getPointer | public function getPointer()
{
if (!isset($this->current_pointers[$this->current_page])) {
$this->current_pointers[$this->current_page] = 0;
}
return $this->current_pointers[$this->current_page];
} | php | public function getPointer()
{
if (!isset($this->current_pointers[$this->current_page])) {
$this->current_pointers[$this->current_page] = 0;
}
return $this->current_pointers[$this->current_page];
} | [
"public",
"function",
"getPointer",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"current_pointers",
"[",
"$",
"this",
"->",
"current_page",
"]",
")",
")",
"{",
"$",
"this",
"->",
"current_pointers",
"[",
"$",
"this",
"->",
"current_... | Return the current record pointer for the current page | [
"Return",
"the",
"current",
"record",
"pointer",
"for",
"the",
"current",
"page"
] | 52578d025514729f6c2d0d223ad6be88ce12abb3 | https://github.com/aklump/loft_data_grids/blob/52578d025514729f6c2d0d223ad6be88ce12abb3/src/AKlump/LoftDataGrids/ExportData.php#L170-L177 | train |
pixelpeter/laravel5-genderize-api-client | src/GenderizeClient.php | GenderizeClient.name | public function name($name = '')
{
if (is_array($name)) {
return $this->names($name);
}
$this->names = [$name];
return $this;
} | php | public function name($name = '')
{
if (is_array($name)) {
return $this->names($name);
}
$this->names = [$name];
return $this;
} | [
"public",
"function",
"name",
"(",
"$",
"name",
"=",
"''",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"names",
"(",
"$",
"name",
")",
";",
"}",
"$",
"this",
"->",
"names",
"=",
"[",
"$",
"na... | Fluent setter for names given as string
@param string $name
@return $this|GenderizeClient | [
"Fluent",
"setter",
"for",
"names",
"given",
"as",
"string"
] | fde6f31f973fd1e39880c59f138645079b65b576 | https://github.com/pixelpeter/laravel5-genderize-api-client/blob/fde6f31f973fd1e39880c59f138645079b65b576/src/GenderizeClient.php#L56-L65 | train |
verbb/image-resizer | src/services/Resize.php | Resize._createRemoteFile | private function _createRemoteFile(VolumeInterface $volume, string $filename, string $path)
{
// Delete already existing file
$volume->deleteFile($filename);
// Create new file
$stream = @fopen($path, 'rb');
$volume->createFileByStream($filename, $stream, []);
} | php | private function _createRemoteFile(VolumeInterface $volume, string $filename, string $path)
{
// Delete already existing file
$volume->deleteFile($filename);
// Create new file
$stream = @fopen($path, 'rb');
$volume->createFileByStream($filename, $stream, []);
} | [
"private",
"function",
"_createRemoteFile",
"(",
"VolumeInterface",
"$",
"volume",
",",
"string",
"$",
"filename",
",",
"string",
"$",
"path",
")",
"{",
"// Delete already existing file",
"$",
"volume",
"->",
"deleteFile",
"(",
"$",
"filename",
")",
";",
"// Cre... | Store new created file on cloud server
@param VolumeInterface $volume
@param string $filename
@param string $path
@throws \craft\errors\VolumeException
@throws \craft\errors\VolumeObjectExistsException | [
"Store",
"new",
"created",
"file",
"on",
"cloud",
"server"
] | e08a08ee66feafeb03b16e9b3bbddbf6fd54041b | https://github.com/verbb/image-resizer/blob/e08a08ee66feafeb03b16e9b3bbddbf6fd54041b/src/services/Resize.php#L199-L207 | train |
rollerworks/version | src/Version.php | Version.getNextVersionCandidates | public function getNextVersionCandidates(): array
{
$candidates = [];
// Pre first-stable, so 0.x-[rc,beta,stable] releases are not considered.
// Use alpha as stability with metaver 1, 0.2-alpha2 is simple ignored.
// If anyone really uses this... not our problem :)
if (0 === $this->major) {
$candidates[] = $this->getNextIncreaseOf('patch');
$candidates[] = $this->getNextIncreaseOf('minor');
$candidates[] = self::fromString('1.0.0-BETA1');
// stable (RC usually follows *after* beta, but jumps to stable are accepted)
// RC is technically valid, but not very common and therefor ignored.
$candidates[] = self::fromString('1.0.0');
return $candidates;
}
// Latest is unstable, may increase stability or metaver (nothing else)
// 1.0.1-beta1 is not accepted, an (un)stability only applies for x.0.0
if ($this->stability < self::STABILITY_STABLE) {
$candidates[] = new self($this->major, $this->minor, 0, $this->stability, $this->metaver + 1);
for ($s = $this->stability + 1; $s < 3; ++$s) {
$candidates[] = new self($this->major, $this->minor, 0, $s, 1);
}
$candidates[] = new self($this->major, $this->minor, 0, self::STABILITY_STABLE);
return $candidates;
}
// Stable, so a patch, major or new minor (with lower stability) version is possible, RC is excluded.
$candidates[] = $this->getNextIncreaseOf('patch');
$candidates[] = $this->getNextIncreaseOf('beta');
$candidates[] = $this->getNextIncreaseOf('minor');
// New (un)stable major (excluding RC)
$candidates[] = new self($this->major + 1, 0, 0, self::STABILITY_ALPHA, 1);
$candidates[] = new self($this->major + 1, 0, 0, self::STABILITY_BETA, 1);
$candidates[] = new self($this->major + 1, 0, 0, self::STABILITY_STABLE);
return $candidates;
} | php | public function getNextVersionCandidates(): array
{
$candidates = [];
// Pre first-stable, so 0.x-[rc,beta,stable] releases are not considered.
// Use alpha as stability with metaver 1, 0.2-alpha2 is simple ignored.
// If anyone really uses this... not our problem :)
if (0 === $this->major) {
$candidates[] = $this->getNextIncreaseOf('patch');
$candidates[] = $this->getNextIncreaseOf('minor');
$candidates[] = self::fromString('1.0.0-BETA1');
// stable (RC usually follows *after* beta, but jumps to stable are accepted)
// RC is technically valid, but not very common and therefor ignored.
$candidates[] = self::fromString('1.0.0');
return $candidates;
}
// Latest is unstable, may increase stability or metaver (nothing else)
// 1.0.1-beta1 is not accepted, an (un)stability only applies for x.0.0
if ($this->stability < self::STABILITY_STABLE) {
$candidates[] = new self($this->major, $this->minor, 0, $this->stability, $this->metaver + 1);
for ($s = $this->stability + 1; $s < 3; ++$s) {
$candidates[] = new self($this->major, $this->minor, 0, $s, 1);
}
$candidates[] = new self($this->major, $this->minor, 0, self::STABILITY_STABLE);
return $candidates;
}
// Stable, so a patch, major or new minor (with lower stability) version is possible, RC is excluded.
$candidates[] = $this->getNextIncreaseOf('patch');
$candidates[] = $this->getNextIncreaseOf('beta');
$candidates[] = $this->getNextIncreaseOf('minor');
// New (un)stable major (excluding RC)
$candidates[] = new self($this->major + 1, 0, 0, self::STABILITY_ALPHA, 1);
$candidates[] = new self($this->major + 1, 0, 0, self::STABILITY_BETA, 1);
$candidates[] = new self($this->major + 1, 0, 0, self::STABILITY_STABLE);
return $candidates;
} | [
"public",
"function",
"getNextVersionCandidates",
"(",
")",
":",
"array",
"{",
"$",
"candidates",
"=",
"[",
"]",
";",
"// Pre first-stable, so 0.x-[rc,beta,stable] releases are not considered.",
"// Use alpha as stability with metaver 1, 0.2-alpha2 is simple ignored.",
"// If anyone ... | Returns a list of possible feature versions.
* 0.1.0 -> [0.1.1, 0.2.0, 1.0.0-beta1, 1.0.0]
* 1.0.0 -> [1.0.1, 1.1.0, 2.0.0-beta1, 2.0.0]
* 1.0.1 -> [1.0.2, 1.2.0, 2.0.0-beta1, 2.0.0]
* 1.1.0 -> [1.2.0, 1.2.0-beta1, 2.0.0-beta1, 2.0.0]
* 1.0.0-beta1 -> [1.0.0-beta2, 1.0.0] (no minor or major increases)
* 1.0.0-alpha1 -> [1.0.0-alpha2, 1.0.0-beta1, 1.0.0] (no minor or major increases)
@return Version[] | [
"Returns",
"a",
"list",
"of",
"possible",
"feature",
"versions",
"."
] | a1b8fbd1476ac78a7e0193d84009509ea34f64c6 | https://github.com/rollerworks/version/blob/a1b8fbd1476ac78a7e0193d84009509ea34f64c6/src/Version.php#L130-L174 | train |
rollerworks/version | src/Version.php | Version.getNextIncreaseOf | public function getNextIncreaseOf(string $stability): self
{
switch ($stability) {
case 'patch':
if ($this->major > 0 && $this->metaver > 0) {
return $this->getIncreaseOfNextPossibleMinorOrMeta();
}
return new self($this->major, $this->minor, $this->patch + 1, self::STABILITY_STABLE);
case 'minor':
return new self($this->major, $this->minor + 1, 0, self::STABILITY_STABLE);
case 'major':
return $this->getIncreaseByMajor();
case 'alpha':
case 'beta':
case 'rc':
return $this->getIncreaseOfMetaver($stability);
case 'stable':
return $this->getIncreaseOfStable();
case 'next':
return $this->getIncreaseOfNextPossibleMinorOrMeta();
default:
throw new \InvalidArgumentException(
sprintf(
'Unknown stability "%s", accepts "%s".',
$stability,
implode('", "', ['alpha', 'beta', 'rc', 'stable', 'major', 'next', 'minor', 'patch'])
)
);
}
} | php | public function getNextIncreaseOf(string $stability): self
{
switch ($stability) {
case 'patch':
if ($this->major > 0 && $this->metaver > 0) {
return $this->getIncreaseOfNextPossibleMinorOrMeta();
}
return new self($this->major, $this->minor, $this->patch + 1, self::STABILITY_STABLE);
case 'minor':
return new self($this->major, $this->minor + 1, 0, self::STABILITY_STABLE);
case 'major':
return $this->getIncreaseByMajor();
case 'alpha':
case 'beta':
case 'rc':
return $this->getIncreaseOfMetaver($stability);
case 'stable':
return $this->getIncreaseOfStable();
case 'next':
return $this->getIncreaseOfNextPossibleMinorOrMeta();
default:
throw new \InvalidArgumentException(
sprintf(
'Unknown stability "%s", accepts "%s".',
$stability,
implode('", "', ['alpha', 'beta', 'rc', 'stable', 'major', 'next', 'minor', 'patch'])
)
);
}
} | [
"public",
"function",
"getNextIncreaseOf",
"(",
"string",
"$",
"stability",
")",
":",
"self",
"{",
"switch",
"(",
"$",
"stability",
")",
"{",
"case",
"'patch'",
":",
"if",
"(",
"$",
"this",
"->",
"major",
">",
"0",
"&&",
"$",
"this",
"->",
"metaver",
... | Returns the increased Version based on the stability.
Note:
* Using 'major' on a beta release produces a stable release for *that* major version.
* Using 'stable' on an existing stable will increase the minor version.
* Using 'patch' on an unstable release increases the metaver instead.
@param string $stability either alpha, beta, rc, stable, major, minor or patch
@return self A new version instance with the changes applied | [
"Returns",
"the",
"increased",
"Version",
"based",
"on",
"the",
"stability",
"."
] | a1b8fbd1476ac78a7e0193d84009509ea34f64c6 | https://github.com/rollerworks/version/blob/a1b8fbd1476ac78a7e0193d84009509ea34f64c6/src/Version.php#L194-L230 | train |
phprtflite/PHPRtfLite | lib/PHPRtfLite/Border/Format.php | PHPRtfLite_Border_Format.getContent | public function getContent()
{
$content = ($this->_size > 0 ? $this->getTypeAsRtfCode() : '')
. '\brdrw' . $this->_size
. '\brsp' . $this->_space;
if ($this->_color && $this->_colorTable) {
$colorIndex = $this->_colorTable->getColorIndex($this->_color);
if ($colorIndex !== false) {
$content .= '\brdrcf' . $colorIndex;
}
}
return $content . ' ';
} | php | public function getContent()
{
$content = ($this->_size > 0 ? $this->getTypeAsRtfCode() : '')
. '\brdrw' . $this->_size
. '\brsp' . $this->_space;
if ($this->_color && $this->_colorTable) {
$colorIndex = $this->_colorTable->getColorIndex($this->_color);
if ($colorIndex !== false) {
$content .= '\brdrcf' . $colorIndex;
}
}
return $content . ' ';
} | [
"public",
"function",
"getContent",
"(",
")",
"{",
"$",
"content",
"=",
"(",
"$",
"this",
"->",
"_size",
">",
"0",
"?",
"$",
"this",
"->",
"getTypeAsRtfCode",
"(",
")",
":",
"''",
")",
".",
"'\\brdrw'",
".",
"$",
"this",
"->",
"_size",
".",
"'\\brs... | gets rtf code
@return string rtf code | [
"gets",
"rtf",
"code"
] | 0cf7bfd3018ae62058d9be9e3e519cb17c6672a8 | https://github.com/phprtflite/PHPRtfLite/blob/0cf7bfd3018ae62058d9be9e3e519cb17c6672a8/lib/PHPRtfLite/Border/Format.php#L179-L193 | train |
phprtflite/PHPRtfLite | lib/PHPRtfLite/Utf8.php | PHPRtfLite_Utf8.getUnicodeEntities | public static function getUnicodeEntities($text, $inCharset)
{
if ($inCharset != 'UTF-8') {
if (extension_loaded('iconv')) {
$text = iconv($inCharset, 'UTF-8//TRANSLIT', $text);
}
else {
throw new PHPRtfLite_Exception('Iconv extension is not available! '
. 'Activate this extension or use UTF-8 encoded texts!');
}
}
$text = self::utf8ToUnicode($text);
return self::unicodeToEntitiesPreservingAscii($text);
} | php | public static function getUnicodeEntities($text, $inCharset)
{
if ($inCharset != 'UTF-8') {
if (extension_loaded('iconv')) {
$text = iconv($inCharset, 'UTF-8//TRANSLIT', $text);
}
else {
throw new PHPRtfLite_Exception('Iconv extension is not available! '
. 'Activate this extension or use UTF-8 encoded texts!');
}
}
$text = self::utf8ToUnicode($text);
return self::unicodeToEntitiesPreservingAscii($text);
} | [
"public",
"static",
"function",
"getUnicodeEntities",
"(",
"$",
"text",
",",
"$",
"inCharset",
")",
"{",
"if",
"(",
"$",
"inCharset",
"!=",
"'UTF-8'",
")",
"{",
"if",
"(",
"extension_loaded",
"(",
"'iconv'",
")",
")",
"{",
"$",
"text",
"=",
"iconv",
"(... | converts text with utf8 characters into rtf utf8 entites
@param string $text | [
"converts",
"text",
"with",
"utf8",
"characters",
"into",
"rtf",
"utf8",
"entites"
] | 0cf7bfd3018ae62058d9be9e3e519cb17c6672a8 | https://github.com/phprtflite/PHPRtfLite/blob/0cf7bfd3018ae62058d9be9e3e519cb17c6672a8/lib/PHPRtfLite/Utf8.php#L39-L52 | train |
phprtflite/PHPRtfLite | lib/PHPRtfLite/Utf8.php | PHPRtfLite_Utf8.unicodeToEntitiesPreservingAscii | private static function unicodeToEntitiesPreservingAscii($unicode)
{
$entities = '';
foreach ($unicode as $value) {
if ($value != 65279) {
$entities .= $value > 127
? '\uc0{\u' . $value . '}'
: chr($value);
}
}
return $entities;
} | php | private static function unicodeToEntitiesPreservingAscii($unicode)
{
$entities = '';
foreach ($unicode as $value) {
if ($value != 65279) {
$entities .= $value > 127
? '\uc0{\u' . $value . '}'
: chr($value);
}
}
return $entities;
} | [
"private",
"static",
"function",
"unicodeToEntitiesPreservingAscii",
"(",
"$",
"unicode",
")",
"{",
"$",
"entities",
"=",
"''",
";",
"foreach",
"(",
"$",
"unicode",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"!=",
"65279",
")",
"{",
"$",
"e... | converts text with utf8 characters into rtf utf8 entites preserving ascii
@param string $unicode
@return string | [
"converts",
"text",
"with",
"utf8",
"characters",
"into",
"rtf",
"utf8",
"entites",
"preserving",
"ascii"
] | 0cf7bfd3018ae62058d9be9e3e519cb17c6672a8 | https://github.com/phprtflite/PHPRtfLite/blob/0cf7bfd3018ae62058d9be9e3e519cb17c6672a8/lib/PHPRtfLite/Utf8.php#L102-L115 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.