_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12100 | Element.range | train | public static function range($name, $value, array $attributes = array())
{
$node = new Node\Range();
if (!is_null($name)) {
$attributes['name'] = $name;
}
if (!is_null($value)) {
$attributes['value'] = $value;
}
return $node->render($attributes);
} | php | {
"resource": ""
} |
q12101 | Element.url | train | public static function url($name, $value, array $attributes = array())
{
$node = new Node\Url();
if (!is_null($name)) {
$attributes['name'] = $name;
}
if (!is_null($value)) {
$attributes['value'] = $value;
}
return $node->render($attributes);
} | php | {
"resource": ""
} |
q12102 | Element.password | train | public static function password($name, $value, array $attributes = array())
{
$node = new Node\Password();
if (!is_null($name)) {
$attributes['name'] = $name;
}
if (!is_null($value)) {
$attributes['value'] = $value;
}
return $node->render($attributes);
} | php | {
"resource": ""
} |
q12103 | Element.object | train | public static function object($width, $height, $data)
{
$node = new Node\Object();
$attributes = array(
'width' => $width,
'height' => $height,
'data' => $data
);
return $node->render($attributes);
} | php | {
"resource": ""
} |
q12104 | Element.audio | train | public static function audio($src, array $attrs = array(), $error = null)
{
$node = new Node\Audio($src, $error);
return $node->render($attrs);
} | php | {
"resource": ""
} |
q12105 | Element.video | train | public static function video($src, array $attrs = array(), $error = null)
{
$node = new Node\Video($src, $error);
return $node->render($attrs);
} | php | {
"resource": ""
} |
q12106 | DocumentEntity.publicValue | train | public function publicValue(): array
{
$public = parent::publicValue();
array_walk_recursive($public, function (&$value) {
if ($value instanceof ObjectID) {
$value = (string)$value;
}
});
return $public;
} | php | {
"resource": ""
} |
q12107 | TaskCommonTrait.runSilentCommand | train | protected function runSilentCommand(TaskInterface $task)
{
return $task->printOutput(false)
// This is weird as you would expect this to give you more
// information, but it suppresses the exit code from display.
->setVerbosityThreshold(VerbosityThresholdInterface::VERBOSITY_DEBUG)
->run();
} | php | {
"resource": ""
} |
q12108 | Select.createDefaultOptionNodes | train | private function createDefaultOptionNodes()
{
$nodes = array();
foreach ($this->defaults as $key => $value) {
// Only scalars are allowed, the rest is ignored
if (is_scalar($value)) {
array_push($nodes, $this->createOptionNode($key, $value));
}
}
return $nodes;
} | php | {
"resource": ""
} |
q12109 | Select.isActiveNode | train | private function isActiveNode($value)
{
if (is_array($this->active)) {
$actives = array_values($this->active);
return in_array($value, $actives);
} else {
// Select all if asterik is provided
if ($this->active === '*') {
return true;
}
// Without type-casting it's error-prone
return (string) $this->active == (string) $value;
}
} | php | {
"resource": ""
} |
q12110 | Select.createOptionNode | train | private function createOptionNode($value, $text)
{
$option = new NodeElement();
$option->openTag('option')
->addAttribute('value', $value);
// Mark as selected on demand
if ($this->isActiveNode($value)) {
$option->addProperty('selected');
}
// If callback is provided, then use it to build attributes
if ($this->optionVisitor instanceof Closure) {
$result = call_user_func($this->optionVisitor, $value, $text);
// Visitor must return an array containing these keys
if (is_array($result)) {
$option->addAttributes($result);
} else {
// Incorrect returned value
throw new UnexpectedValueException(
sprintf('The visitor must return associative array with attribute names and their corresponding values. Received - "%s"', gettype($result))
);
}
}
$option->finalize()
->setText($text)
->closeTag();
return $option;
} | php | {
"resource": ""
} |
q12111 | Select.createOptgroupNode | train | private function createOptgroupNode($label, array $list)
{
$optgroup = new NodeElement();
$optgroup->openTag('optgroup')
->addAttribute('label', $label)
->finalize();
foreach ($this->getOptions($list) as $option) {
$optgroup->appendChild($option);
}
$optgroup->closeTag();
return $optgroup;
} | php | {
"resource": ""
} |
q12112 | Select.getOptions | train | private function getOptions(array $list)
{
// To be returned
$elements = array();
foreach ($list as $value => $text) {
array_push($elements, $this->createOptionNode($value, $text));
}
return $elements;
} | php | {
"resource": ""
} |
q12113 | DataSource.formatIndex | train | protected function formatIndex($name)
{
if (\is_string($name)) {
$exp = explode('.', $name);
if (0 < \count($exp)) {
$name = $exp[\count($exp) - 1];
}
}
return $name;
} | php | {
"resource": ""
} |
q12114 | DataSource.getDataField | train | protected function getDataField($dataRow, $name, \Closure $emptyData = null)
{
$value = null !== $name && '' !== $name
? $this->propertyAccessor->getValue($dataRow, $name)
: null;
if (null === $value && $emptyData instanceof \Closure) {
$value = $emptyData($dataRow, $name);
}
return $value;
} | php | {
"resource": ""
} |
q12115 | DataSource.overrideCellOptions | train | protected function overrideCellOptions(BlockInterface $column, $formatter, $data, array $options)
{
$config = $column->getConfig();
if ($config->hasOption('override_options')
&& ($override = $config->getOption('override_options')) instanceof \Closure) {
/* @var \Closure $override */
$options = $override($options, $data, $formatter);
}
return $options;
} | php | {
"resource": ""
} |
q12116 | DataSource.doPreGetData | train | protected function doPreGetData()
{
foreach ($this->dataTransformers as $dataTransformer) {
if ($dataTransformer instanceof PreGetDataTransformerInterface) {
$dataTransformer->preGetData($this->config);
}
}
} | php | {
"resource": ""
} |
q12117 | DataSource.doPostGetData | train | protected function doPostGetData()
{
foreach ($this->dataTransformers as $dataTransformer) {
if ($dataTransformer instanceof PostGetDataTransformerInterface) {
$dataTransformer->postGetData($this->config);
}
}
} | php | {
"resource": ""
} |
q12118 | DefaultEncoderRegistrant.registerDefaultEncoders | train | public function registerDefaultEncoders(EncoderRegistry $encoders): EncoderRegistry
{
$encoders->registerDefaultObjectEncoder(new ObjectEncoder($encoders, $this->propertyNameFormatter));
$encoders->registerDefaultScalarEncoder(new ScalarEncoder());
$encoders->registerEncoder('array', new ArrayEncoder($encoders));
$dateTimeEncoder = new DateTimeEncoder($this->dateTimeFormat);
$encoders->registerEncoder(DateTime::class, $dateTimeEncoder);
$encoders->registerEncoder(DateTimeImmutable::class, $dateTimeEncoder);
$encoders->registerEncoder(DateTimeInterface::class, $dateTimeEncoder);
return $encoders;
} | php | {
"resource": ""
} |
q12119 | DrupalProjectType.exportDrupalConfig | train | public function exportDrupalConfig()
{
$version = $this->getProjectVersion();
if ($version >= 8) {
$this->runDrushCommand('cex');
$this->saveDrupalUuid();
}
return $this;
} | php | {
"resource": ""
} |
q12120 | DrupalProjectType.importDrupalConfig | train | public function importDrupalConfig($reimport_attempts = 1, $localhost = false)
{
if ($this->getProjectVersion() >= 8) {
try {
$drush = (new DrushCommand(null, $localhost))
->command('cr')
->command('cim');
$this->runDrushCommand($drush, false, $localhost);
} catch (TaskResultRuntimeException $exception) {
if ($reimport_attempts < 1) {
throw $exception;
}
$errors = 0;
$result = null;
// Attempt to resolve import issues by reimporting the
// configurations again. This workaround was added due to
// the following issue:
// @see https://www.drupal.org/project/drupal/issues/2923899
for ($i = 0; $i < $reimport_attempts; $i++) {
$result = $this->runDrushCommand('cim', false, $localhost);
if ($result->getExitCode() === ResultData::EXITCODE_OK) {
break;
}
++$errors;
}
if (!isset($result)) {
throw new \Exception('Missing result object.');
} else if ($errors == $reimport_attempts) {
throw new TaskResultRuntimeException($result);
}
}
}
return $this;
} | php | {
"resource": ""
} |
q12121 | DrupalProjectType.optionForm | train | public function optionForm()
{
$fields = [];
$default = $this->defaultInstallOptions();
$fields[] = (new BooleanField('site', 'Setup Drupal site options?'))
->setDefault(false)
->setSubform(function ($subform, $value) use ($default) {
if ($value === true) {
$subform->addFields([
(new TextField('name', 'Drupal site name?'))
->setDefault($default['site']['name']),
(new TextField('profile', 'Drupal site profile?'))
->setDefault($default['site']['profile']),
]);
}
});
$fields[] = (new BooleanField('account', 'Setup Drupal account options?'))
->setDefault(false)
->setSubform(function ($subform, $value) use ($default) {
if ($value === true) {
$subform->addFields([
(new TextField('mail', 'Account email:'))
->setDefault($default['account']['mail']),
(new TextField('name', 'Account username:'))
->setDefault($default['account']['name']),
(new TextField('pass', 'Account password:'))
->setHidden(true)
->setDefault($default['account']['pass']),
]);
}
});
return (new Form())
->addFields($fields);
} | php | {
"resource": ""
} |
q12122 | DrupalProjectType.setupProject | train | public function setupProject()
{
$this->taskWriteToFile(ProjectX::projectRoot() . '/.gitignore')
->text($this->loadTemplateContents('.gitignore.txt'))
->place('PROJECT_ROOT', $this->getInstallRoot(true))
->run();
return $this;
} | php | {
"resource": ""
} |
q12123 | DrupalProjectType.setupProjectComposer | train | public function setupProjectComposer()
{
$this->mergeProjectComposerTemplate();
$install_root = substr(static::installRoot(), 1);
$version = $this->getProjectVersion();
$this->composer
->setType('project')
->setPreferStable(true)
->setMinimumStability('dev')
->setConfig([
'platform' => [
'php' => "{$this->getEnvPhpVersion()}"
]
])
->addRepository('drupal', [
'type' => 'composer',
'url' => "https://packages.drupal.org/{$version}"
])
->addRequires([
'drupal/core' => static::DRUPAL_8_VERSION,
'composer/installers' => '^1.1',
'cweagans/composer-patches' => '^1.5',
'drupal-composer/drupal-scaffold' => '^2.0'
])
->addExtra('drupal-scaffold', [
'excludes' => [
'robot.txt'
],
'initial' => [
'sites/development.services.yml' => 'sites/development.services.yml',
'sites/example.settings.local.php' => 'sites/example.settings.local.php'
],
'omit-defaults' => false
])
->addExtra('installer-paths', [
$install_root . '/core' => ['type:drupal-core'],
$install_root . '/modules/contrib/{$name}' => ['type:drupal-module'],
$install_root . '/profiles/custom/{$name}' => ['type:drupal-profile'],
$install_root . '/themes/contrib/{$name}'=> ['type:drupal-theme'],
'drush/contrib/{$name}'=> ['type:drupal-drush']
]);
return $this;
} | php | {
"resource": ""
} |
q12124 | DrupalProjectType.packageDrupalBuild | train | public function packageDrupalBuild($build_root)
{
$project_root = ProjectX::projectRoot();
$build_install = $build_root . static::installRoot();
$install_path = $this->getInstallPath();
$stack = $this->taskFilesystemStack();
$static_files = [
"{$project_root}/salt.txt" => "{$build_root}/salt.txt",
"{$install_path}/.htaccess" => "{$build_install}/.htaccess",
"{$install_path}/index.php" => "{$build_install}/index.php",
"{$install_path}/robots.txt" => "{$build_install}/robots.txt",
"{$install_path}/update.php" => "{$build_install}/update.php",
"{$install_path}/web.config" => "{$build_install}/web.config",
"{$install_path}/sites/default/settings.php" => "{$build_install}/sites/default/settings.php",
];
foreach ($static_files as $source => $destination) {
if (!file_exists($source)) {
continue;
}
$stack->copy($source, $destination);
}
$mirror_directories = [
'/config',
static::installRoot() . '/libraries',
static::installRoot() . '/themes/custom',
static::installRoot() . '/modules/custom',
static::installRoot() . '/profiles/custom'
];
foreach ($mirror_directories as $directory) {
$path_to_directory = "{$project_root}{$directory}";
if (!file_exists($path_to_directory)) {
continue;
}
$stack->mirror($path_to_directory, "{$build_root}{$directory}");
}
$stack->run();
return $this;
} | php | {
"resource": ""
} |
q12125 | DrupalProjectType.setupDrush | train | public function setupDrush($exclude_remote = false)
{
$project_root = ProjectX::projectRoot();
$this->taskFilesystemStack()
->mirror($this->getTemplateFilePath('drush'), "$project_root/drush")
->copy($this->getTemplateFilePath('drush.wrapper'), "$project_root/drush.wrapper")
->run();
$this->taskWriteToFile("{$project_root}/drush/drushrc.php")
->append()
->place('PROJECT_ROOT', $this->getInstallRoot(true))
->run();
$this->setupDrushAlias($exclude_remote);
return $this;
} | php | {
"resource": ""
} |
q12126 | DrupalProjectType.setupDrushAlias | train | public function setupDrushAlias($exclude_remote = false)
{
$project_root = ProjectX::projectRoot();
if (!file_exists("$project_root/drush/site-aliases")) {
$continue = $this->askConfirmQuestion(
"Drush aliases haven't been setup for this project.\n"
. "\nDo you want run the Drush alias setup?",
true
);
if (!$continue) {
return $this;
}
$this->setupDrush($exclude_remote);
} else {
$this->setupDrushLocalAlias();
if (!$exclude_remote) {
$this->setupDrushRemoteAliases();
}
}
return $this;
} | php | {
"resource": ""
} |
q12127 | DrupalProjectType.setupDrushLocalAlias | train | public function setupDrushLocalAlias($alias_name = null)
{
$config = ProjectX::getProjectConfig();
$alias_name = isset($alias_name)
? Utiltiy::machineName($alias_name)
: ProjectX::getProjectMachineName();
$alias_content = $this->drushAliasFileContent(
$alias_name,
$config->getHost()['name'],
$this->getInstallPath()
);
$project_root = ProjectX::projectRoot();
$this
->taskWriteToFile("$project_root/drush/site-aliases/local.aliases.drushrc.php")
->line($alias_content)
->run();
return $this;
} | php | {
"resource": ""
} |
q12128 | DrupalProjectType.setupDrushRemoteAliases | train | public function setupDrushRemoteAliases()
{
$project_root = ProjectX::projectRoot();
$drush_aliases_dir = "$project_root/drush/site-aliases";
foreach (ProjectX::getRemoteEnvironments() as $realm => $environment) {
$file_task = $this
->taskWriteToFile("$drush_aliases_dir/$realm.aliases.drushrc.php");
$has_content = false;
for ($i = 0; $i < count($environment); $i++) {
$instance = $environment[$i];
if (!isset($instance['name'])
|| !isset($instance['path'])
|| !isset($instance['uri'])
|| !isset($instance['ssh_url'])) {
continue;
}
list($ssh_user, $ssh_host) = explode('@', $instance['ssh_url']);
$options = [
'remote_user' => $ssh_user,
'remote_host' => $ssh_host
];
$content = $this->drushAliasFileContent(
$instance['name'],
$instance['uri'],
$instance['path'],
$options,
$i === 0
);
$has_content = true;
$file_task->line($content);
}
if ($has_content) {
$file_task->run();
}
}
return $this;
} | php | {
"resource": ""
} |
q12129 | DrupalProjectType.createDrupalLoginLink | train | public function createDrupalLoginLink($user = null, $path = null, $localhost = false)
{
$arg = [];
if (isset($user)) {
$arg[] = $user;
}
if (isset($path)) {
$arg[] = $path;
}
$args = implode(' ', $arg);
$drush = (new DrushCommand(null, $localhost))
->command("uli {$args}");
$this->runDrushCommand($drush, false, $localhost);
return $this;
} | php | {
"resource": ""
} |
q12130 | DrupalProjectType.setupDrupalFilesystem | train | public function setupDrupalFilesystem()
{
$this->taskFilesystemStack()
->chmod($this->sitesPath, 0775, 0000, true)
->mkdir("{$this->sitesPath}/default/files", 0775, true)
->run();
if ($this->getProjectVersion() >= 8) {
$install_path = $this->getInstallPath();
$this->taskFilesystemStack()
->mkdir("{$install_path}/profiles/custom", 0775, true)
->mkdir("{$install_path}/modules/custom", 0775, true)
->mkdir("{$install_path}/modules/contrib", 0775, true)
->run();
}
return $this;
} | php | {
"resource": ""
} |
q12131 | DrupalProjectType.setupDrupalSettings | train | public function setupDrupalSettings()
{
$this->_copy(
"{$this->sitesPath}/default/default.settings.php",
$this->settingFile
);
$install_root = dirname($this->getQualifiedInstallRoot());
if ($this->getProjectVersion() >= 8) {
$this->taskWriteToFile("{$install_root}/salt.txt")
->line(Utility::randomHash())
->run();
$this->taskFilesystemStack()
->mkdir("{$install_root}/config", 0775)
->chmod("{$install_root}/salt.txt", 0775)
->run();
$this->taskWriteToFile($this->settingFile)
->append()
->regexReplace(
'/\#\sif.+\/settings\.local\.php.+\n#.+\n\#\s}/',
$this->drupalSettingsLocalInclude()
)
->replace(
'$config_directories = array();',
'$config_directories[CONFIG_SYNC_DIRECTORY] = dirname(DRUPAL_ROOT) . \'/config\';'
)
->replace(
'$settings[\'hash_salt\'] = \'\';',
'$settings[\'hash_salt\'] = file_get_contents(dirname(DRUPAL_ROOT) . \'/salt.txt\');'
)
->run();
}
return $this;
} | php | {
"resource": ""
} |
q12132 | DrupalProjectType.setupDrupalLocalSettings | train | public function setupDrupalLocalSettings()
{
$version = $this->getProjectVersion();
$local_settings = $this
->templateManager()
->loadTemplate("{$version}/settings.local.txt");
$this->_remove($this->settingLocalFile);
if ($version >= 8) {
$setting_path = "{$this->sitesPath}/example.settings.local.php";
if (file_exists($setting_path)) {
$this->_copy($setting_path, $this->settingLocalFile);
} else {
$this->taskWriteToFile($this->settingLocalFile)
->text("<?php\r\n")
->run();
}
} else {
$this->taskWriteToFile($this->settingLocalFile)
->text("<?php\r\n")
->run();
}
$database = $this->getDatabaseInfo();
$this->taskWriteToFile($this->settingLocalFile)
->append()
->appendUnlessMatches('/\$databases\[.+\]/', $local_settings)
->place('DB_NAME', $database->getDatabase())
->place('DB_USER', $database->getUser())
->place('DB_PASS', $database->getPassword())
->place('DB_HOST', $database->getHostname())
->place('DB_PORT', $database->getPort())
->place('DB_PROTOCOL', $database->getProtocol())
->run();
return $this;
} | php | {
"resource": ""
} |
q12133 | DrupalProjectType.setupDrupalInstall | train | public function setupDrupalInstall($localhost = false)
{
$this->say('Waiting on Drupal database to become available...');
$database = $this->getDatabaseInfo();
$engine = $this->getEngineInstance();
$install_path = $this->getInstallPath();
if ($engine instanceof DockerEngineType && !$localhost) {
$drush = $this->drushInstallCommonStack(
'/var/www/html/vendor/bin/drush',
'/var/www/html' . static::installRoot(),
$database
);
$result = $engine->execRaw(
$drush->getCommand(),
$this->getPhpServiceName()
);
} else {
// Run the drupal installation from the host machine. The host will
// need to have the database client binaries installed.
$database->setHostname('127.0.0.1');
if (!$this->hasDatabaseConnection($database->getHostname(), $database->getPort())) {
throw new \Exception(
sprintf('Unable to connection to Drupal database %s', $database->getHostname())
);
}
// Sometimes it takes awhile after the mysql host is up on the
// network to become totally available to except connections. Due to
// the uncertainty we'll need to sleep for about 30 seconds.
sleep(30);
$result = $this->drushInstallCommonStack(
'drush',
$install_path,
$database
)->run();
}
$this->validateTaskResult($result);
// Update permissions to ensure all files can be accessed on the install
// path for both user and groups.
$this->_chmod($install_path, 0775, 0000, true);
return $this;
} | php | {
"resource": ""
} |
q12134 | DrupalProjectType.removeGitSubmodulesInVendor | train | public function removeGitSubmodulesInVendor($base_path = null)
{
$base_path = isset($base_path) && file_exists($base_path)
? $base_path
: ProjectX::projectRoot();
$composer = $this->getComposer();
$composer_config = $composer->getConfig();
$vendor_dir = isset($composer_config['vendor-dir'])
? $composer_config['vendor-dir']
: 'vendor';
$this->removeGitSubmodules(
[$base_path . "/{$vendor_dir}"],
2
);
return $this;
} | php | {
"resource": ""
} |
q12135 | DrupalProjectType.getValidComposerInstallPaths | train | public function getValidComposerInstallPaths($base_path = null)
{
$filepaths = [];
/** @var ComposerConfig $composer */
$composer = $this->getComposer();
$composer_extra = $composer->getExtra();
$base_path = isset($base_path) && file_exists($base_path)
? $base_path
: ProjectX::projectRoot();
$installed_paths = isset($composer_extra['installer-paths'])
? array_keys($composer_extra['installer-paths'])
: [];
$installed_directory = substr(static::getInstallPath(), strrpos(static::getInstallPath(), '/'));
foreach ($installed_paths as $installed_path) {
$path_info = pathinfo($installed_path);
$directory = "/{$path_info['dirname']}";
if (strpos($directory, $installed_directory) === false) {
continue;
}
$filename = $path_info['filename'] !== '{$name}'
? "/{$path_info['filename']}"
: null;
$filepath = $base_path . $directory . $filename;
if (!file_exists($filepath)) {
continue;
}
$filepaths[] = $filepath;
}
return $filepaths;
} | php | {
"resource": ""
} |
q12136 | DrupalProjectType.runDrushCommand | train | public function runDrushCommand($command, $quiet = false, $localhost = false)
{
if ($command instanceof CommandBuilder) {
$drush = $command;
} else {
$drush = new DrushCommand(null, $localhost);
foreach (explode('&&', $command) as $string) {
$drush->command($string);
}
}
return $this->executeEngineCommand(
$drush,
$this->getPhpServiceName(),
[],
$quiet,
$localhost
);
;
} | php | {
"resource": ""
} |
q12137 | DrupalProjectType.setDrupalUuid | train | public function setDrupalUuid($localhost = false)
{
if ($this->getProjectVersion() >= 8) {
$build_info = $this->getProjectOptionByKey('build_info');
if ($build_info !== false
&& isset($build_info['uuid'])
&& !empty($build_info['uuid'])) {
$drush = new DrushCommand(null, $localhost);
$drush
->command("cset system.site uuid {$build_info['uuid']}")
->command('ev \'\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();\'');
$this->runDrushCommand($drush, false, $localhost);
}
}
return $this;
} | php | {
"resource": ""
} |
q12138 | DrupalProjectType.refreshDatabaseSettings | train | protected function refreshDatabaseSettings()
{
/** @var Database $database */
$database = $this->getDatabaseInfo();
$settings = file_get_contents($this->settingLocalFile);
// Replace database properties based on database info.
foreach ($database->asArray() as $property => $value) {
$settings = $this->replaceDatabaseProperty(
$property,
$value,
$settings
);
}
// Replace the namespace property based on the database protocol.
$namespace_base = addslashes('Drupal\\\\Core\\\\Database\\\\Driver\\\\');
$settings = $this->replaceDatabaseProperty(
'namespace',
"{$namespace_base}{$database->getProtocol()}",
$settings
);
// Check if file contents whats updated.
$status = file_put_contents($this->settingLocalFile, $settings);
if (false === $status) {
throw new \Exception(
sprintf('Unable to refresh database settings in (%s).', $this->settingLocalFile)
);
return false;
}
return true;
} | php | {
"resource": ""
} |
q12139 | DrupalProjectType.setupDatabaseFromRestore | train | protected function setupDatabaseFromRestore(
$method = null,
$localhost = false
) {
/** @var EngineType $engine */
$engine = $this->getEngineInstance();
if ($engine instanceof DockerEngineType) {
$options = $this->databaseRestoreOptions();
if (!isset($method)
|| !in_array($method, $options)) {
$method = $this->doAsk(new ChoiceQuestion(
'Setup the project using? ',
$options
));
}
switch ($method) {
case 'site-config':
$this
->setupDrupalInstall($localhost)
->setDrupalUuid($localhost)
->importDrupalConfig(1, $localhost);
break;
case 'database-import':
$this->importDatabaseToService($this->getPhpServiceName(), null, true, $localhost);
break;
default:
/** @var DrupalPlatformRestoreInterface $platform */
$platform = $this->getPlatformInstance();
if ($platform instanceof DrupalPlatformRestoreInterface) {
$platform->drupalRestore($method);
}
}
$this->clearDrupalCache($localhost);
} else {
$classname = get_class($engine);
throw new \RuntimeException(
sprintf("The engine type %s isn't supported", $classname::getLabel())
);
}
return $this;
} | php | {
"resource": ""
} |
q12140 | DrupalProjectType.databaseRestoreOptions | train | protected function databaseRestoreOptions()
{
$options = [];
if ($this->getProjectVersion() >= 8 && $this->hasDrupalConfig()) {
$options[] = 'site-config';
}
$options[] = 'database-import';
/** @var DrupalPlatformRestoreInterface $platform */
$platform = $this->getPlatformInstance();
if ($platform instanceof DrupalPlatformRestoreInterface) {
$options = array_merge($options, $platform->drupalRestoreOptions());
}
return $options;
} | php | {
"resource": ""
} |
q12141 | DrupalProjectType.hasDatabaseInfoChanged | train | protected function hasDatabaseInfoChanged()
{
$settings_uri = $this->settingLocalFile;
if (file_exists($settings_uri)) {
$settings = file_get_contents($settings_uri);
$match_status = preg_match_all("/\'(database|username|password|host|port|driver)\'\s=>\s\'(.+)\'\,?/", $settings, $matches);
if ($match_status !== false) {
$database = $this->getDatabaseInfo();
$database_file = array_combine($matches[1], $matches[2]);
foreach ($database->asArray() as $property => $value) {
if (isset($database_file[$property])
&& $database_file[$property] != $value) {
return true;
}
}
}
}
return false;
} | php | {
"resource": ""
} |
q12142 | DrupalProjectType.getDrupalUuid | train | protected function getDrupalUuid()
{
$uuid = null;
$version = $this->getProjectVersion();
if ($version >= 8) {
$result = $this->runDrushCommand('cget system.site uuid', true);
if ($result->getExitCode() === ResultData::EXITCODE_OK) {
$message = $result->getMessage();
if ($colon_pos = strrpos($message, ':')) {
$uuid = trim(substr($message, $colon_pos + 1));
}
}
}
return $uuid;
} | php | {
"resource": ""
} |
q12143 | DrupalProjectType.saveDrupalUuid | train | protected function saveDrupalUuid()
{
$config = ProjectX::getProjectConfig();
$options[static::getTypeId()] = [
'build_info' => [
'uuid' => $this->getDrupalUuid()
]
];
$config
->setOptions($options)
->save(ProjectX::getProjectPath());
return $this;
} | php | {
"resource": ""
} |
q12144 | DrupalProjectType.drushInstallCommonStack | train | protected function drushInstallCommonStack(
$executable,
$drupal_root,
DatabaseInterface $database
) {
$options = $this->getInstallOptions();
$db_user = $database->getUser();
$db_port = $database->getPort();
$db_pass = $database->getPassword();
$db_name = $database->getDatabase();
$db_host = $database->getHostname();
$db_protocol = $database->getProtocol();
return $this->taskDrushStack($executable)
->drupalRootDirectory($drupal_root)
->siteName($options['site']['name'])
->accountMail($options['account']['mail'])
->accountName($options['account']['name'])
->accountPass($options['account']['pass'])
->dbUrl("$db_protocol://$db_user:$db_pass@$db_host:$db_port/$db_name")
->siteInstall($options['site']['profile']);
} | php | {
"resource": ""
} |
q12145 | DrupalProjectType.drushAliasFileContent | train | protected function drushAliasFileContent($name, $uri, $root, array $options = [], $include_opentag = true)
{
$name = Utility::machineName($name);
$content = $include_opentag ? "<?php\n\n" : '';
$content .= "\$aliases['$name'] = [";
$content .= "\n\t'uri' => '$uri',";
$content .= "\n\t'root' => '$root',";
// Add remote host to output if defined.
if (isset($options['remote_host'])
&& $remote_host = $options['remote_host']) {
$content .= "\n\t'remote-host' => '$remote_host',";
}
// Add remote user to output if defined.
if (isset($options['remote_user'])
&& $remote_user = $options['remote_user']) {
$content .= "\n\t'remote-user' => '$remote_user',";
}
$content .= "\n\t'path-aliases' => [";
$content .= "\n\t\t'%dump-dir' => '/tmp',";
$content .= "\n\t]";
$content .= "\n];";
return $content;
} | php | {
"resource": ""
} |
q12146 | DrupalProjectType.setupDrupalSettingsLocalInclude | train | protected function setupDrupalSettingsLocalInclude()
{
$this->taskWriteToFile($this->settingFile)
->append()
->appendUnlessMatches(
'/if.+\/settings\.local\.php.+{\n.+\n\}/',
$this->drupalSettingsLocalInclude()
)
->run();
return $this;
} | php | {
"resource": ""
} |
q12147 | UploadChain.upload | train | public function upload($id, array $files)
{
foreach ($this->uploaders as $uploader) {
if (!$uploader->upload($id, $files)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q12148 | PhpService.getDockerfileVariables | train | protected function getDockerfileVariables()
{
// Merge service OS packages definition.
if ($os_packages = $this->getInfoProperty('packages')) {
$this->mergeConfigVariable('PACKAGE_INSTALL', $os_packages);
}
// Merge service PHP pecl packages definition.
if ($pecl_packages = $this->getInfoProperty('pecl_packages')) {
$this->mergeConfigVariable('PHP_PECL', $pecl_packages);
}
// Merge service PHP extensions definition.
if ($php_extensions = $this->getInfoProperty('extensions')) {
$this->mergeConfigVariable('PHP_EXT_INSTALL', $php_extensions);
}
// Merge service PHP docker command definition.
if ($php_command = $this->getInfoProperty('commands')) {
$this->mergeConfigVariable('PHP_COMMANDS', $php_command);
}
return $this->processDockerfileVariables();
} | php | {
"resource": ""
} |
q12149 | PhpService.processDockerfileVariables | train | protected function processDockerfileVariables()
{
$variables = [];
$variables['PHP_VERSION'] = $this->getVersion();
foreach ($this->configs as $key => $values) {
if (!in_array($key, static::DOCKER_VARIABLES)) {
continue;
}
if ($key === 'PHP_EXT_ENABLE'
&& !empty($this->configs['PHP_PECL'])) {
$php_pecl = $this->configs['PHP_PECL'];
// Remove the version from the PECL package.
array_walk($php_pecl, function (&$name) {
$pos = strpos($name, ':');
if ($pos !== false) {
$name = substr($name, 0, $pos);
}
});
$values = array_merge($php_pecl, $values);
}
if (empty($values)) {
continue;
}
$variables[$key] = $this->formatVariables($key, $values);
}
return $variables;
} | php | {
"resource": ""
} |
q12150 | PhpService.formatVariables | train | protected function formatVariables($key, array $values)
{
switch ($key) {
case 'PHP_PECL':
return $this->formatPeclPackages($values);
case 'PHP_COMMANDS':
return $this->formatRunCommand($values);
case 'PHP_EXT_CONFIG':
case 'PHP_EXT_ENABLE':
case 'PHP_EXT_INSTALL':
case 'PACKAGE_INSTALL':
return $this->formatValueDelimiter($values);
}
} | php | {
"resource": ""
} |
q12151 | PhpService.formatPeclPackages | train | protected function formatPeclPackages(array $values)
{
$packages = [];
foreach ($values as $package) {
list($name, $version) = strpos($package, ':') !== false
? explode(':', $package)
: [$package, null];
if ($name === 'xdebug' && !isset($version)) {
$version = version_compare($this->getVersion(), 7.0, '<')
? '2.5.5'
: null;
}
$version = isset($version) ? "-{$version}" : null;
$packages[] = "pecl install {$name}{$version} \\" ;
}
if (empty($packages)) {
return null;
}
return "&& " . implode("\r\n && ", $packages);
} | php | {
"resource": ""
} |
q12152 | Native.generateLocationAuth | train | protected function generateLocationAuth(string $authTicket, float $latitude, float $longitude, float $altitude = 0.0)
{
$seed = hexdec(xxhash32($authTicket, 0x1B845238));
return (int)hexdec(xxhash32($this->getLocationBytes($latitude, $longitude, $altitude), (int)$seed));
} | php | {
"resource": ""
} |
q12153 | Native.generateLocation | train | protected function generateLocation(float $latitude, float $longitude, float $altitude = 0.0) : int
{
return (int)hexdec(xxhash32($this->getLocationBytes($latitude, $longitude, $altitude), 0x1B845238));
} | php | {
"resource": ""
} |
q12154 | Native.generateRequestHash | train | protected function generateRequestHash(string $authTicket, string $request) : int
{
$seed = (unpack("J", pack("H*", xxhash64($authTicket, 0x1B845238))))[1];
return (unpack("J", pack("H*", xxhash64($request, $seed))))[1];
} | php | {
"resource": ""
} |
q12155 | Native.getLocationBytes | train | protected function getLocationBytes(float $latitude, float $longitude, float $altitude) : string
{
return Hex::d2h($latitude) . Hex::d2h($longitude) . Hex::d2h($altitude);
} | php | {
"resource": ""
} |
q12156 | SqlConfigServiceFactory.build | train | public static function build($pdo, $table)
{
$configMapper = new ConfigMapper(new Serializer(), $pdo, $table);
return new SqlConfigService($configMapper, new ArrayConfig());
} | php | {
"resource": ""
} |
q12157 | Action.destroy | train | public function destroy($id)
{
$this->guardAgainstMissingParent('destroy');
$this->shopify->delete($this->path($id));
} | php | {
"resource": ""
} |
q12158 | Action.requiresParent | train | protected function requiresParent(string $methodName)
{
if (in_array('*', $this->requiresParent)) {
return true;
}
return in_array($methodName, $this->requiresParent);
} | php | {
"resource": ""
} |
q12159 | GitAuthorExtractorTrait.getGitRepositoryFor | train | protected function getGitRepositoryFor($path)
{
$git = new GitRepository($this->determineGitRoot($path));
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
$git->getConfig()->setLogger(
new ConsoleLogger($this->output)
);
}
return $git;
} | php | {
"resource": ""
} |
q12160 | GitAuthorExtractorTrait.getAllFilesFromGit | train | private function getAllFilesFromGit($git)
{
$gitDir = $git->getRepositoryPath();
// Sadly no command in our git library for this.
$arguments = [
$git->getConfig()->getGitExecutablePath(),
'ls-tree',
'HEAD',
'-r',
'--full-name',
'--name-only'
];
$process = new Process($this->prepareProcessArguments($arguments), $git->getRepositoryPath());
$git->getConfig()->getLogger()->debug(
\sprintf('[ccabs-repository-git] exec [%s] %s', $process->getWorkingDirectory(), $process->getCommandLine())
);
$process->run();
$output = \rtrim($process->getOutput(), "\r\n");
if (!$process->isSuccessful()) {
throw GitException::createFromProcess('Could not execute git command', $process);
}
$files = [];
foreach (\explode(PHP_EOL, $output) as $file) {
$absolutePath = $gitDir . '/' . $file;
if (!$this->config->isPathExcluded($absolutePath)) {
$files[\trim($absolutePath)] = \trim($absolutePath);
}
}
return $files;
} | php | {
"resource": ""
} |
q12161 | GitAuthorExtractorTrait.getFilePaths | train | public function getFilePaths()
{
$files = [];
foreach ($this->config->getIncludedPaths() as $path) {
$files[] = $this->getAllFilesFromGit($this->getGitRepositoryFor($path));
}
return array_merge(...$files);
} | php | {
"resource": ""
} |
q12162 | GitAuthorExtractorTrait.determineGitRoot | train | private function determineGitRoot($path)
{
// @codingStandardsIgnoreStart
while (\strlen($path) > 1) {
// @codingStandardsIgnoreEnd
if (\is_dir($path . DIRECTORY_SEPARATOR . '.git')) {
return $path;
}
$path = \dirname($path);
}
throw new \RuntimeException('Could not determine git root, starting from ' . \func_get_arg(0));
} | php | {
"resource": ""
} |
q12163 | GitAuthorExtractorTrait.getCurrentUserInfo | train | protected function getCurrentUserInfo($git)
{
// Sadly no command in our git library for this.
$arguments = [
$git->getConfig()->getGitExecutablePath(),
'config',
'--get-regexp',
'user.[name|email]'
];
$process = new Process($this->prepareProcessArguments($arguments), $git->getRepositoryPath());
$git->getConfig()->getLogger()->debug(
\sprintf('[git-php] exec [%s] %s', $process->getWorkingDirectory(), $process->getCommandLine())
);
$process->run();
$output = \rtrim($process->getOutput(), "\r\n");
if (!$process->isSuccessful()) {
throw GitException::createFromProcess('Could not execute git command', $process);
}
$config = array();
foreach (\explode(PHP_EOL, $output) as $line) {
list($name, $value) = \explode(' ', $line, 2);
$config[\trim($name)] = \trim($value);
}
if (isset($config['user.name']) && $config['user.email']) {
return \sprintf('%s <%s>', $config['user.name'], $config['user.email']);
}
return '';
} | php | {
"resource": ""
} |
q12164 | GitAuthorExtractorTrait.runCustomGit | train | private function runCustomGit(array $arguments, GitRepository $git)
{
$process = new Process($this->prepareProcessArguments($arguments), $git->getRepositoryPath());
$git->getConfig()->getLogger()->debug(
\sprintf('[git-php] exec [%s] %s', $process->getWorkingDirectory(), $process->getCommandLine())
);
$process->run();
$result = rtrim($process->getOutput(), "\r\n");
if (!$process->isSuccessful()) {
throw GitException::createFromProcess('Could not execute git command', $process);
}
return $result;
} | php | {
"resource": ""
} |
q12165 | GitAuthorExtractorTrait.prepareProcessArguments | train | protected function prepareProcessArguments(array $arguments)
{
$reflection = new \ReflectionClass(ProcessUtils::class);
if (!$reflection->hasMethod('escapeArgument')) {
return $arguments;
}
return \implode(' ', \array_map([ProcessUtils::class, 'escapeArgument'], $arguments));
} | php | {
"resource": ""
} |
q12166 | Addresses.load | train | public static function load(string $filename = 'my-addresses.php'): array
{
$file = (new static())->getDirectoryPaths()
->map(function ($path) use ($filename) {
return $path . $filename;
})
->first(function ($file) {
return file_exists($file);
});
if (!$file) {
throw new PartialNotFoundException(vsprintf('%s does not exist.', [
$filename,
]));
}
return include $file;
} | php | {
"resource": ""
} |
q12167 | InteractiveMessage.setReplyMarkup | train | public function setReplyMarkup(\KeythKatz\TelegramBotCore\Type\InlineKeyboardMarkup $keyboard): void
{
$this->baseMethod->setReplyMarkup($keyboard);
} | php | {
"resource": ""
} |
q12168 | InteractiveMessage.send | train | public function send(): void
{
$sentMessage = $this->baseMethod->send();
$this->messageId = $sentMessage->getMessageId();
$this->chatId = $sentMessage->getChat()->getId();
$this->saveState();
} | php | {
"resource": ""
} |
q12169 | ListViewMaker.render | train | public function render()
{
$data = $this->createData();
$table = $this->createTable($data, $this->options[self::LISTVIEW_PARAM_TABLE_CLASS]);
return $table->render();
} | php | {
"resource": ""
} |
q12170 | ListViewMaker.createData | train | private function createData()
{
$output = array();
$hasTranslator = $this->translator instanceof TranslatorInterface;
foreach ($this->options[self::LISTVIEW_PARAM_COLUMNS] as $configuration) {
// Do processing only if column available
if (isset($this->data[$configuration[self::LISTVIEW_PARAM_COLUMN]])) {
if (isset($configuration[self::LISTVIEW_PARAM_VALUE]) && is_callable($configuration[self::LISTVIEW_PARAM_VALUE])) {
// Grab value from returned value
$value = $configuration[self::LISTVIEW_PARAM_VALUE]($configuration[self::LISTVIEW_PARAM_COLUMN], $this->data[$configuration[self::LISTVIEW_PARAM_COLUMN]]);
} else {
$value = $this->data[$configuration[self::LISTVIEW_PARAM_COLUMN]];
}
// Need to translate?
if (isset($configuration[self::LISTVIEW_PARAM_TRANSLATE]) && $configuration[self::LISTVIEW_PARAM_TRANSLATE] == true) {
$value = $this->translator->translate($value);
}
// Title
if (isset($configuration[self::LISTVIEW_PARAM_TITLE])) {
$key = $configuration[self::LISTVIEW_PARAM_TITLE];
} else {
// Fallback to column name
$key = TextUtils::normalizeColumn($configuration[self::LISTVIEW_PARAM_COLUMN]);
}
// Prepare key
$key = $hasTranslator ? $this->translator->translate($key) : $key;
$output[$key] = $value;
}
}
return $output;
} | php | {
"resource": ""
} |
q12171 | ListViewMaker.createRow | train | private function createRow($key, $value)
{
$tr = new NodeElement();
$tr->openTag('tr');
$first = new NodeElement();
$first->openTag('td')
->finalize()
->setText($key)
->closeTag();
$second = new NodeElement();
$second->openTag('td')
->finalize()
->setText($value)
->closeTag();
$tr->appendChildren(array($first, $second));
$tr->closeTag();
return $tr;
} | php | {
"resource": ""
} |
q12172 | Builder.build | train | private function build(): void
{
$prefix = "<?xml version='1.0' encoding='UTF-8'?>" . $this->glue() . "<feed xmlns='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'>";
$suffix = '</feed>';
$xml = collect($this->filters)->map(function ($items) {
return $this->buildEntry($items);
})->implode($this->glue());
$this->xml = collect([$prefix, $xml, $suffix])->implode($this->glue());
if ($this->writeFile) {
$this->filesystem->dumpFile($this->outputFile, $this->xml);
}
} | php | {
"resource": ""
} |
q12173 | Builder.buildEntry | train | private function buildEntry(Filter $filter): string
{
$entry = collect($filter->toArray())
->map(function ($value, $key): string {
return $this->buildProperty($value, $key);
})
->implode($this->glue());
return collect(['<entry>', $entry, '</entry>'])->implode($this->glue());
} | php | {
"resource": ""
} |
q12174 | Builder.buildProperty | train | private function buildProperty($value, $key): string
{
if (collect(['from', 'to'])->contains($key)) {
$value = $this->implode($value);
}
return vsprintf("<apps:property name='%s' value='%s'/>", [
$key,
htmlentities($this->implode($value)),
]);
} | php | {
"resource": ""
} |
q12175 | Builder.implode | train | private function implode($value, $separator = '|'): string
{
if (is_string($value)) {
return $value;
}
if (is_array($value) && count($value) === 1) {
return reset($value);
}
return sprintf('(%s)', collect($value)->implode($separator));
} | php | {
"resource": ""
} |
q12176 | ConfigurationAdminController.clearCacheAction | train | public function clearCacheAction() {
$this->getConfigurationManager()->clearCache();
$this->addFlash('sonata_flash_success', 'Cache clear successfully');
return new \Symfony\Component\HttpFoundation\RedirectResponse($this->admin->generateUrl('list'));
} | php | {
"resource": ""
} |
q12177 | EmailObfuscatorRequestProcessor.encode | train | protected function encode($originalString)
{
$encodedString = '';
$nowCodeString = '';
$originalLength = strlen($originalString);
for ($i = 0; $i < $originalLength; $i++) {
$encodeMode = ($i % 2 == 0) ? 1 : 2; // Switch encoding odd/even
switch ($encodeMode) {
case 1: // Decimal code
$nowCodeString = '&#' . ord($originalString[$i]) . ';';
break;
case 2: // Hexadecimal code
$nowCodeString = '&#x' . dechex(ord($originalString[$i])) . ';';
break;
default:
return 'ERROR: wrong encoding mode.';
}
$encodedString .= $nowCodeString;
}
return $encodedString;
} | php | {
"resource": ""
} |
q12178 | RelationBuilder.build | train | public function build(array $data)
{
$relations = array(
self::TREE_PARAM_ITEMS => array(),
self::TREE_PARAM_PARENTS => array()
);
foreach ($data as $row) {
$relations[self::TREE_PARAM_ITEMS][$row[self::TREE_PARAM_ID]] = $row;
$relations[self::TREE_PARAM_PARENTS][$row[self::TREE_PARAM_PARENT_ID]][] = $row[self::TREE_PARAM_ID];
}
return $relations;
} | php | {
"resource": ""
} |
q12179 | Helper.faker | train | final protected function faker(string $locale = 'en_US'): Generator
{
static $fakers = [];
if (!\array_key_exists($locale, $fakers)) {
$faker = Factory::create($locale);
$faker->seed(9001);
$fakers[$locale] = $faker;
}
return $fakers[$locale];
} | php | {
"resource": ""
} |
q12180 | Helper.assertClassesAreAbstractOrFinal | train | final protected function assertClassesAreAbstractOrFinal(string $directory, array $excludeClassNames = []): void
{
$this->assertClassyConstructsSatisfySpecification(
static function (string $className): bool {
$reflection = new \ReflectionClass($className);
return $reflection->isAbstract()
|| $reflection->isFinal()
|| $reflection->isInterface()
|| $reflection->isTrait();
},
$directory,
$excludeClassNames,
"Failed asserting that the classes\n\n%s\n\nare abstract or final."
);
} | php | {
"resource": ""
} |
q12181 | Helper.assertClassyConstructsSatisfySpecification | train | final protected function assertClassyConstructsSatisfySpecification(callable $specification, string $directory, array $excludeClassyNames = [], string $message = ''): void
{
if (!\is_dir($directory)) {
throw Exception\NonExistentDirectory::fromDirectory($directory);
}
\array_walk($excludeClassyNames, static function ($excludeClassyName): void {
if (!\is_string($excludeClassyName)) {
throw Exception\InvalidExcludeClassName::fromClassName($excludeClassyName);
}
if (!\class_exists($excludeClassyName)) {
throw Exception\NonExistentExcludeClass::fromClassName($excludeClassyName);
}
});
$constructs = Classy\Constructs::fromDirectory($directory);
$classyNames = \array_diff(
$constructs,
$excludeClassyNames
);
$classyNamesNotSatisfyingSpecification = \array_filter($classyNames, static function (string $className) use ($specification) {
return false === $specification($className);
});
self::assertEmpty($classyNamesNotSatisfyingSpecification, \sprintf(
'' !== $message ? $message : "Failed asserting that the classy constructs\n\n%s\n\nsatisfy a specification.",
' - ' . \implode("\n - ", $classyNamesNotSatisfyingSpecification)
));
} | php | {
"resource": ""
} |
q12182 | Helper.assertClassExists | train | final protected function assertClassExists(string $className): void
{
self::assertTrue(\class_exists($className), \sprintf(
'Failed asserting that a class "%s" exists.',
$className
));
} | php | {
"resource": ""
} |
q12183 | Helper.assertClassExtends | train | final protected function assertClassExtends(string $parentClassName, string $className): void
{
$this->assertClassExists($parentClassName);
$this->assertClassExists($className);
$reflection = new \ReflectionClass($className);
self::assertTrue($reflection->isSubclassOf($parentClassName), \sprintf(
'Failed asserting that class "%s" extends "%s".',
$className,
$parentClassName
));
} | php | {
"resource": ""
} |
q12184 | Helper.assertClassImplementsInterface | train | final protected function assertClassImplementsInterface(string $interfaceName, string $className): void
{
$this->assertInterfaceExists($interfaceName);
$this->assertClassExists($className);
$reflection = new \ReflectionClass($className);
self::assertTrue($reflection->implementsInterface($interfaceName), \sprintf(
'Failed asserting that class "%s" implements interface "%s".',
$className,
$interfaceName
));
} | php | {
"resource": ""
} |
q12185 | Helper.assertClassIsAbstract | train | final protected function assertClassIsAbstract(string $className): void
{
$this->assertClassExists($className);
$reflection = new \ReflectionClass($className);
self::assertTrue($reflection->isAbstract(), \sprintf(
'Failed asserting that class "%s" is abstract.',
$className
));
} | php | {
"resource": ""
} |
q12186 | Helper.assertClassIsFinal | train | final protected function assertClassIsFinal(string $className): void
{
$this->assertClassExists($className);
$reflection = new \ReflectionClass($className);
self::assertTrue($reflection->isFinal(), \sprintf(
'Failed asserting that class "%s" is final.',
$className
));
} | php | {
"resource": ""
} |
q12187 | Helper.assertClassSatisfiesSpecification | train | final protected function assertClassSatisfiesSpecification(callable $specification, string $className, string $message = ''): void
{
$this->assertClassExists($className);
self::assertTrue($specification($className), \sprintf(
'' !== $message ? $message : 'Failed asserting that class "%s" satisfies a specification.',
$className
));
} | php | {
"resource": ""
} |
q12188 | Helper.assertClassUsesTrait | train | final protected function assertClassUsesTrait(string $traitName, string $className): void
{
$this->assertTraitExists($traitName);
$this->assertClassExists($className);
self::assertContains($traitName, \class_uses($className), \sprintf(
'Failed asserting that class "%s" uses trait "%s".',
$className,
$traitName
));
} | php | {
"resource": ""
} |
q12189 | Helper.assertInterfaceExists | train | final protected function assertInterfaceExists(string $interfaceName): void
{
self::assertTrue(\interface_exists($interfaceName), \sprintf(
'Failed asserting that an interface "%s" exists.',
$interfaceName
));
} | php | {
"resource": ""
} |
q12190 | Helper.assertInterfaceExtends | train | final protected function assertInterfaceExtends(string $parentInterfaceName, string $interfaceName): void
{
$this->assertInterfaceExists($parentInterfaceName);
$this->assertInterfaceExists($interfaceName);
$reflection = new \ReflectionClass($interfaceName);
self::assertTrue($reflection->isSubclassOf($parentInterfaceName), \sprintf(
'Failed asserting that interface "%s" extends "%s".',
$interfaceName,
$parentInterfaceName
));
} | php | {
"resource": ""
} |
q12191 | Helper.assertInterfaceSatisfiesSpecification | train | final protected function assertInterfaceSatisfiesSpecification(callable $specification, string $interfaceName, string $message = ''): void
{
$this->assertInterfaceExists($interfaceName);
self::assertTrue($specification($interfaceName), \sprintf(
'' !== $message ? $message : 'Failed asserting that interface "%s" satisfies a specification.',
$interfaceName
));
} | php | {
"resource": ""
} |
q12192 | Helper.assertTraitExists | train | final protected function assertTraitExists(string $traitName): void
{
self::assertTrue(\trait_exists($traitName), \sprintf(
'Failed asserting that a trait "%s" exists.',
$traitName
));
} | php | {
"resource": ""
} |
q12193 | Helper.assertTraitSatisfiesSpecification | train | final protected function assertTraitSatisfiesSpecification(callable $specification, string $traitName, string $message = ''): void
{
$this->assertTraitExists($traitName);
self::assertTrue($specification($traitName), \sprintf(
'' !== $message ? $message : 'Failed asserting that trait "%s" satisfies a specification.',
$traitName
));
} | php | {
"resource": ""
} |
q12194 | Category.get | train | public static function get(Bookboon $bookboon, string $categoryId, array $bookTypes = ['pdf']) : BookboonResponse
{
$bResponse = $bookboon->rawRequest("/categories/$categoryId", ['bookType' => join(',', $bookTypes)]);
$bResponse->setEntityStore(
new EntityStore(
[
new static($bResponse->getReturnArray())
]
)
);
return $bResponse;
} | php | {
"resource": ""
} |
q12195 | Category.getTree | train | public static function getTree(
Bookboon $bookboon,
array $blacklistedCategoryIds = [],
int $depth = 2
) : BookboonResponse {
$bResponse = $bookboon->rawRequest('/categories', ['depth' => $depth]);
$categories = $bResponse->getReturnArray();
if (count($blacklistedCategoryIds) !== 0) {
self::recursiveBlacklist($categories, $blacklistedCategoryIds);
}
$bResponse->setEntityStore(
new EntityStore(Category::getEntitiesFromArray($categories))
);
return $bResponse;
} | php | {
"resource": ""
} |
q12196 | Headers.set | train | public function set(string $header, string $value) : void
{
$this->headers[$header] = $value;
} | php | {
"resource": ""
} |
q12197 | Headers.getAll | train | public function getAll() : array
{
$headers = [];
foreach ($this->headers as $h => $v) {
$headers[] = $h.': '.$v;
}
return $headers;
} | php | {
"resource": ""
} |
q12198 | Headers.getRemoteAddress | train | private function getRemoteAddress() : ?string
{
$hostname = null;
if (isset($_SERVER['REMOTE_ADDR'])) {
$hostname = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
if (false === $hostname) {
$hostname = null;
}
}
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if ($headers === false) {
return $hostname;
}
foreach ($headers as $k => $v) {
if (strcasecmp($k, 'x-forwarded-for')) {
continue;
}
$hostname = explode(',', $v);
$hostname = trim($hostname[0]);
break;
}
}
return $hostname;
} | php | {
"resource": ""
} |
q12199 | CDatabaseBasic.loadHistory | train | public function loadHistory()
{
$key = $this->options['session_key'];
if (isset($_SESSION['CDatabase'])) {
self::$numQueries = $_SESSION[$key]['numQueries'];
self::$queries = $_SESSION[$key]['queries'];
self::$params = $_SESSION[$key]['params'];
unset($_SESSION[$key]);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.