_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q258300 | Extension.reducing | test | public function reducing($name)
{
// note, once we stop supporting php 5.5, we can rewrite the code below
// to the reducing($name, ...$args) structure.
// http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
if (is_string($name) &&
in_array(
$name,
[
'add',
'chain',
'join',
'max',
'min',
'mul',
'sub',
]
)) {
return call_user_func_array(sprintf('\Zicht\Itertools\reductions\%s', $name), array_slice(func_get_args(), 1));
}
throw new \InvalidArgumentException(sprintf('$NAME "%s" is not a valid reduction.', $name));
} | php | {
"resource": ""
} |
q258301 | ComposerPlugin.dump | test | public static function dump(Event $event)
{
$composer = $event->getComposer();
$installationManager = $composer->getInstallationManager();
$repoManager = $composer->getRepositoryManager();
$localRepo = $repoManager->getLocalRepository();
$package = $composer->getPackage();
$config = $composer->getConfig();
// To enable class-based filtering, we force `--optimize` flag for our
// custom autoloaders, so that all PSR-0 and PSR-4 namespaces are
// iterated and translated to arrays of classes.
$optimize = true;
$vendorDir = $config->get('vendor-dir', Config::RELATIVE_PATHS);
$defaultLocation = "{$vendorDir}/wp-cli/wp-cli/php/WP_CLI/AutoloadSplitter.php";
$suffix = $config->get('autoloader-suffix');
self::$extra = $event->getComposer()
->getPackage()
->getExtra();
$splitterLogic = self::getExtraKey(self::LOGIC_CLASS_KEY, 'WP_CLI\AutoloadSplitter');
$splitterLocation = self::getExtraKey(self::LOGIC_CLASS_LOCATION_KEY, $defaultLocation);
$filePrefixTrue = self::getExtraKey(self::SPLIT_TARGET_PREFIX_TRUE_KEY, 'autoload_commands');
$filePrefixFalse = self::getExtraKey(self::SPLIT_TARGET_PREFIX_FALSE_KEY, 'autoload_framework');
if (!class_exists($splitterLogic)) {
$splitterClassPath = sprintf('%s/%s', getcwd(), $splitterLocation);
// Avoid proceeding if the splitter class file does not exist.
if (!is_readable( $splitterClassPath)) {
return;
}
include_once $splitterClassPath;
}
$generator = new AutoloadGenerator(
$composer->getEventDispatcher(),
$event->getIO(),
$splitterLogic,
$filePrefixTrue,
$filePrefixFalse
);
$generator->dump(
$config,
$localRepo,
$package,
$installationManager,
'composer',
$optimize,
$suffix
);
} | php | {
"resource": ""
} |
q258302 | ComposerPlugin.getExtraKey | test | private static function getExtraKey($key, $fallback)
{
static $autosplitter = null;
if (null === $autosplitter) {
$autosplitter = isset(self::$extra[self::EXTRA_KEY])
? self::$extra[self::EXTRA_KEY]
: array();
}
return isset($autosplitter[$key]) ? $autosplitter[$key] : $fallback;
} | php | {
"resource": ""
} |
q258303 | NormalizerBase.escapePrefix | test | public static function escapePrefix($predicate, array $namespaces) {
$exploded = explode(":", $predicate);
if (!isset($namespaces[$exploded[0]])) {
return $predicate;
}
return $namespaces[$exploded[0]] . $exploded[1];
} | php | {
"resource": ""
} |
q258304 | JsonldContextGenerator.parseCompactedIri | test | protected function parseCompactedIri($iri) {
// As naive as it gets.
list($prefix, $rest) = array_pad(explode(":", $iri, 2), 2, '');
if ((substr($rest, 0, 2) == "//") || ($prefix == $iri)) {
// Means this was never a compacted IRI.
return ['prefix' => NULL, 'term' => $iri];
}
return ['prefix' => $prefix, 'term' => $rest];
} | php | {
"resource": ""
} |
q258305 | JsonldContextGenerator.getTermContextFromField | test | protected function getTermContextFromField($field_type) {
// Be aware that drupal field definitions can be complex.
// e.g text_with_summary has a text, a summary, a number of lines, etc
// we are only dealing with the resulting ->value() of all this separate
// pieces and mapping only that as a whole.
// Default mapping to return in case no $field_type matches
// field_mappings array keys.
$default_mapping = [
"@type" => "xsd:string",
];
// Only load mappings from hooks if we haven't done it
// yet for this instance.
if (empty($this->fieldMappings)) {
// Cribbed from rdf module's rdf_get_namespaces.
foreach (\Drupal::moduleHandler()->getImplementations(self::FIELD_MAPPPINGS_HOOK) as $module) {
$function = $module . '_' . self::FIELD_MAPPPINGS_HOOK;
foreach ($function() as $field => $mapping) {
if (array_key_exists($field, $this->fieldMappings)) {
$this->logger->warning(
t('Tried to map @field_type to @new_type, but @field_type is already mapped to @orig_type.', [
'@field_type' => $field,
'@new_type' => $mapping['@type'],
'@orig_type' => $this->fieldMappings[$field]['@type'],
])
);
}
else {
$this->fieldMappings[$field] = $mapping;
}
}
}
}
return array_key_exists($field_type, $this->fieldMappings) ? $this->fieldMappings[$field_type] : $default_mapping;
} | php | {
"resource": ""
} |
q258306 | Eager.persistCacheIfNeeded | test | public function persistCacheIfNeeded($lifeTime)
{
if ($this->isDirty) {
$this->storage->doSave($this->storageId, $this->content, $lifeTime);
}
} | php | {
"resource": ""
} |
q258307 | JsonldContextController.content | test | public function content($entity_type, $bundle, Request $request) {
// TODO: expose cached/not cached through
// more varied HTTP response codes.
try {
$context = $this->jsonldContextGenerator->getContext("$entity_type.$bundle");
$response = new CacheableJsonResponse(json_decode($context), 200);
$response->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
$response->headers->set('Content-Type', 'application/ld+json');
// For now deal with Cache dependencies manually.
$meta = new CacheableMetadata();
$meta->setCacheContexts(['user.permissions', 'ip', 'url']);
$meta->setCacheTags(RdfMapping::load("$entity_type.$bundle")->getCacheTags());
$meta->setCacheMaxAge(Cache::PERMANENT);
$response->addCacheableDependency($meta);
}
catch (\Exception $e) {
$response = new Response($e->getMessage(), 400);
}
return $response;
} | php | {
"resource": ""
} |
q258308 | FieldNormalizer.normalizeFieldItems | test | protected function normalizeFieldItems(FieldItemListInterface $field, $format, array $context) {
$normalized_field_items = [];
if (!$field->isEmpty()) {
foreach ($field as $field_item) {
$normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);
}
}
return $normalized_field_items;
} | php | {
"resource": ""
} |
q258309 | Chained.doDelete | test | public function doDelete($id)
{
foreach ($this->backends as $backend) {
if ($backend->doContains($id)) {
$backend->doDelete($id);
}
}
return true;
} | php | {
"resource": ""
} |
q258310 | FieldItemNormalizer.createTranslatedInstance | test | protected function createTranslatedInstance(FieldItemInterface $item, $langcode) {
// Remove the untranslated item that was created for the default language
// by FieldNormalizer::denormalize().
$items = $item->getParent();
$delta = $item->getName();
unset($items[$delta]);
// Instead, create a new item for the entity in the requested language.
$entity = $item->getEntity();
$entity_translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
$field_name = $item->getFieldDefinition()->getName();
return $entity_translation->get($field_name)->appendItem();
} | php | {
"resource": ""
} |
q258311 | ContentEntityNormalizer.getEntityUri | test | protected function getEntityUri(EntityInterface $entity) {
// Some entity types don't provide a canonical link template, at least call
// out to ->url().
if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
return $entity->toUrl('canonical', []);
}
$url = $entity->toUrl('canonical', ['absolute' => TRUE]);
return $url->setRouteParameter('_format', 'jsonld')->toString();
} | php | {
"resource": ""
} |
q258312 | ContentEntityNormalizer.getTypedDataIds | test | protected function getTypedDataIds(array $types, array $context = []) {
// The 'type' can potentially contain an array of type objects. By default,
// Drupal only uses a single type in serializing, but allows for multiple
// types when deserializing.
if (isset($types['href'])) {
$types = [$types];
}
foreach ($types as $type) {
if (!isset($type['href'])) {
throw new UnexpectedValueException('Type must contain an \'href\' attribute.');
}
$type_uri = $type['href'];
// Check whether the URI corresponds to a known type on this site. Break
// once one does.
if ($typed_data_ids = $this->linkManager->getTypeInternalIds($type['href'], $context)) {
break;
}
}
// If none of the URIs correspond to an entity type on this site, no entity
// can be created. Throw an exception.
if (empty($typed_data_ids)) {
throw new UnexpectedValueException(sprintf('Type %s does not correspond to an entity on this site.', $type_uri));
}
return $typed_data_ids;
} | php | {
"resource": ""
} |
q258313 | Factory.buildBackend | test | public function buildBackend($type, array $options)
{
switch ($type) {
case 'array':
return $this->buildArrayCache();
case 'file':
return $this->buildFileCache($options);
case 'chained':
return $this->buildChainedCache($options);
case 'null':
return $this->buildNullCache();
case 'redis':
return $this->buildRedisCache($options);
default:
throw new Factory\BackendNotFoundException("Cache backend $type not valid");
}
} | php | {
"resource": ""
} |
q258314 | Lazy.fetch | test | public function fetch($id)
{
$id = $this->getCompletedCacheIdIfValid($id);
return $this->backend->doFetch($id);
} | php | {
"resource": ""
} |
q258315 | SilentResponse.runString | test | protected function runString($callable, array $arguments)
{
if (! function_exists($callable)) {
throw new FunctionNotFoundException("Function $callable not found");
}
$this->startBuffer();
$this->return = call_user_func_array($callable, $arguments);
$this->endBuffer();
return $this;
} | php | {
"resource": ""
} |
q258316 | BaseCommand.error | test | public function error($line)
{
if (is_array($line)) {
$lines = [];
foreach ($line as $one) {
$lines[] = "<error>$one</error>";
}
$this->output->writeln($lines);
return;
}
$this->output->writeln("<error>$line</error>");
} | php | {
"resource": ""
} |
q258317 | BaseCommand.ask | test | public function ask($question, $default = false)
{
$handler = $this->getHelper('question');
$confirmation = new ConfirmationQuestion($question, $default);
return $handler->ask($this->input, $this->output, $confirmation);
} | php | {
"resource": ""
} |
q258318 | AttributeOptionCreateProcessor.execute | test | public function execute($row, $name = null)
{
parent::execute($row, $name);
return $this->getConnection()->lastInsertId();
} | php | {
"resource": ""
} |
q258319 | Factory.create | test | public function create(array $overrides = [])
{
$factory = static::$factories[$this->table]['callback'];
$data = [];
for ($i = 0; $i < $this->times; $i++) {
$values = $this->override($factory(\Faker\Factory::create($this->locale)), $overrides);
$data[] = $this->insert($values);
}
if (count($data) === 1) {
return $data[0];
}
return $data;
} | php | {
"resource": ""
} |
q258320 | Factory.override | test | protected function override(array $values, array $overrides)
{
if (count($overrides) === 0) {
return $values;
}
foreach ($overrides as $key => $value) {
$values[$key] = $overrides[$key];
}
return $values;
} | php | {
"resource": ""
} |
q258321 | Factory.insert | test | protected function insert($values)
{
$id = db_insert($this->table)->fields($values)->execute();
$query = db_select($this->table, 'T');
$query->fields('T');
$query->condition($this->primary_key, $id);
return $query->execute()->fetchObject();
} | php | {
"resource": ""
} |
q258322 | Factory.extractPrimaryKey | test | protected function extractPrimaryKey()
{
if (static::$factories[$this->table]['primary_key'] !== null) {
return static::$factories[$this->table]['primary_key'];
}
if (preg_match('/^chado\./', $this->table)) {
$schema = chado_get_schema(str_replace('chado.', '', $this->table));
if ($schema) {
if (isset($schema['primary key'])) {
return $schema['primary key'][0];
} elseif (isset($schema['primary keys'])) {
return $schema['primary keys'][0];
}
}
}
throw new \Exception("Unable to determine primary key for $this->table factory. Please provide the primary key such as `nid` as a third argument in Factory::define().");
} | php | {
"resource": ""
} |
q258323 | InteractsWithAuthSystem.actingAs | test | public function actingAs($uid)
{
global $user;
// Load the new requested user
if (is_object($uid)) {
if($uid->uid === 0) {
$user = drupal_anonymous_user();
} else{
$user = user_load($uid->uid);
}
} else {
if($uid === 0) {
$user = drupal_anonymous_user();
} else {
$user = user_load($uid);
}
}
$this->_cookies = [
session_name() => session_id()
];
return $this;
} | php | {
"resource": ""
} |
q258324 | InitCommand.copyStubs | test | protected function copyStubs(array $files)
{
foreach ($files as $file => $to) {
$to = "{$this->path}/{$to}";
if (! file_exists($to) || $this->getOption('force') !== false) {
copy("{$this->stubsDir}/{$file}", $to);
} else {
$this->line("TRIPALTEST: $to already exists.");
}
}
} | php | {
"resource": ""
} |
q258325 | InitCommand.configureVariables | test | protected function configureVariables(array $files)
{
foreach ($files as $file => $values) {
$file = "{$this->path}/{$file}";
if (! file_exists($file)) {
throw new \Exception("TRIPALTEST: Unable to configure variables. $file does not exist!");
}
$content = file_get_contents($file);
foreach ($values as $search => $replace) {
$content = str_replace($search, $replace, $content);
}
file_put_contents($file, $content);
}
} | php | {
"resource": ""
} |
q258326 | CatalogAttributeObserver.serializeAdditionalData | test | protected function serializeAdditionalData(array $attr)
{
// serialize the additional data value if available
if (isset($attr[MemberNames::ADDITIONAL_DATA]) && $attr[MemberNames::ADDITIONAL_DATA] !== null) {
$attr[MemberNames::ADDITIONAL_DATA] = json_encode($attr[MemberNames::ADDITIONAL_DATA]);
}
// return the attribute
return $attr;
} | php | {
"resource": ""
} |
q258327 | CatalogAttributeObserver.isSwatchType | test | protected function isSwatchType(array $additionalData)
{
return isset($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE]) && in_array($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE], $this->swatchTypes);
} | php | {
"resource": ""
} |
q258328 | SwatchTypeLoader.loadSwatchType | test | public function loadSwatchType($entityTypeId, $attributeCode)
{
// prepare a unique key for the swatch type from the given code and entity type ID
$key = sprintf('%d-%s', $entityTypeId, $attributeCode);
// query whether or not a swatch type has been set
if ($this->hasSwatchType($key) === false) {
// load the attribute and the catalog attribute data
$attribute = $this->loadAttributeByEntityTypeIdAndAttributeCode($entityTypeId, $attributeCode);
$catalogAttribute = $this->loadCatalogAttribute($attribute[MemberNames::ATTRIBUTE_ID]);
// query whether or not additional data is available (to figure out if the attribute is a swatch type or not)
if (is_array($catalogAttribute[MemberNames::ADDITIONAL_DATA]) && $catalogAttribute[MemberNames::ADDITIONAL_DATA] !== null) {
// unserialize the additional data
$additionalData = json_decode($catalogAttribute[MemberNames::ADDITIONAL_DATA]);
// load and return the swatch type (can be either one of 'text' or 'visual')
return $this->setSwatchType($key, $additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE]);
}
}
// return the actual swatch type
return $this->getSwatchType($key);
} | php | {
"resource": ""
} |
q258329 | DBSeedCommand.handle | test | public function handle()
{
// Let's bootstrap first
new TripalTestBootstrap(false);
$this->loadDatabaseSeeders();
$seeder = $this->getArgument('name');
if ($seeder) {
$this->runSeeder($seeder);
$this->success($seeder);
return;
}
if (empty($this->seeders)) {
$this->error('No database seeders found!');
return;
}
foreach ($this->seeders as $seeder) {
$this->runSeeder($seeder);
$this->success($seeder);
}
} | php | {
"resource": ""
} |
q258330 | DBSeedCommand.prepSeeder | test | protected function prepSeeder($name)
{
$name = trim($name, '\\');
if (strstr($name, 'Tests\\DatabaseSeeders') !== false) {
return $name;
}
return 'Tests\\DatabaseSeeders\\'.$name;
} | php | {
"resource": ""
} |
q258331 | AttributeOptionSwatchRepository.findOneByOptionIdAndStoreId | test | public function findOneByOptionIdAndStoreId($optionId, $storeId)
{
// the parameters of the EAV attribute option to load
$params = array(
MemberNames::OPTION_ID => $optionId,
MemberNames::STORE_ID => $storeId,
);
// load and return the EAV attribute option swatch with the passed parameters
$this->attributeOptionSwatchByOptionIdAndStoreIdStmt->execute($params);
return $this->attributeOptionSwatchByOptionIdAndStoreIdStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258332 | EntityAttributeRepository.findOneByAttributeIdAndAttributeSetId | test | public function findOneByAttributeIdAndAttributeSetId($attributeId, $attributeSetId)
{
// initialize the params
$params = array(
MemberNames::ATTRIBUTE_ID => $attributeId,
MemberNames::ATTRIBUTE_SET_ID => $attributeSetId
);
// load and return the EAV entity attribute with the passed params
$this->entityAttributeByAttributeIdAndAttributeSetIdStmt->execute($params);
return $this->entityAttributeByAttributeIdAndAttributeSetIdStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258333 | AttributeOptionRepository.findOneByEntityTypeIdAndAttributeCodeAndStoreIdAndValue | test | public function findOneByEntityTypeIdAndAttributeCodeAndStoreIdAndValue($entityTypeId, $attributeCode, $storeId, $value)
{
// the parameters of the EAV attribute option to load
$params = array(
MemberNames::ENTITY_TYPE_ID => $entityTypeId,
MemberNames::ATTRIBUTE_CODE => $attributeCode,
MemberNames::STORE_ID => $storeId,
MemberNames::VALUE => $value
);
// load and return the EAV attribute option with the passed parameters
$this->attributeOptionByEntityTypeIdAndAttributeCodeAndStoreIdAndValueStmt->execute($params);
return $this->attributeOptionByEntityTypeIdAndAttributeCodeAndStoreIdAndValueStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258334 | AttributeOptionRepository.findOneByAttributeIdAndHighestSortOrder | test | public function findOneByAttributeIdAndHighestSortOrder($attributeId)
{
// load and return the EAV attribute option with the passed parameters
$this->attributeOptionByAttributeIdOrderBySortOrderDescStmt->execute(array(MemberNames::ATTRIBUTE_ID => $attributeId));
return $this->attributeOptionByAttributeIdOrderBySortOrderDescStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258335 | MakeSeederCommand.createDatabaseSeedersFolder | test | protected function createDatabaseSeedersFolder()
{
$path = getcwd().'/tests';
if (! file_exists($path)) {
throw new FileNotFoundException('Tests folder not found.');
}
if (! file_exists($path.'/DatabaseSeeders')) {
mkdir($path.'/DatabaseSeeders');
}
} | php | {
"resource": ""
} |
q258336 | MakeSeederCommand.makeSeeder | test | protected function makeSeeder()
{
$path = getcwd().'/tests/DatabaseSeeders';
$name = $this->getArgument('name');
$stub = __DIR__.'/../../../stubs/SeederStub.php';
$content = file_get_contents($stub);
$content = str_replace('$$CLASS_NAME$$', $name, $content);
$path = "{$path}/{$name}.php";
if (file_exists($path)) {
throw new \Exception("File already exists at $path");
}
$done = file_put_contents($path, $content);
if ($done === false) {
throw new \Exception("Could not create file at $path");
}
return $path;
} | php | {
"resource": ""
} |
q258337 | AttributeOptionUpdateObserver.initializeAttribute | test | protected function initializeAttribute(array $attr)
{
// load the entity type ID for the value from the system configuration
$entityTypeId = $this->getEntityTypeId();
// initialize the data to load the EAV attribute option
$value = $this->getValue(ColumnKeys::VALUE);
$storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
$attributeCode = $this->getValue(ColumnKeys::ATTRIBUTE_CODE);
// try to load the EAV attribute option
if ($attributeOption = $this->loadAttributeOptionByEntityTypeIdAndAttributeCodeAndStoreIdAndValue($entityTypeId, $attributeCode, $storeId, $value)) {
return $this->mergeEntity($attributeOption, $attr);
}
// simply return the attributes
return $attr;
} | php | {
"resource": ""
} |
q258338 | DBTransaction.DBTransactionSetUp | test | protected function DBTransactionSetUp()
{
$this->_transaction = db_transaction(uniqid());
$shutdown = '\\StatonLab\\TripalTestSuite\\DBTransaction::rollbackTransaction';
register_shutdown_function($shutdown, $this->_transaction);
} | php | {
"resource": ""
} |
q258339 | CatalogAttributeRepository.load | test | public function load($attributeId)
{
// load and return the EAV catalog attribute with the ID
$this->catalogAttributeStmt->execute(array(MemberNames::ATTRIBUTE_ID => $attributeId));
return $this->catalogAttributeStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258340 | MenuCaller.setPath | test | public function setPath($path)
{
$this->path = trim($path, '/');
if(empty($this->path)) {
// Home page requested so let's use /node
$this->path = 'node';
}
return $this;
} | php | {
"resource": ""
} |
q258341 | MenuCaller.addParams | test | public function addParams($params)
{
if (isset($params['form_params'])) {
$params = $params['form_params'];
$params['form_token'] = drupal_get_token();
} elseif (isset($params['query'])) {
$params = $params['query'];
}
foreach ($params as $key => $value) {
$this->params[$key] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q258342 | MenuCaller.send | test | public function send()
{
$allowed_methods = ['POST', 'GET', 'PUT', 'PATCH', 'DELETE'];
if (! in_array($this->method, $allowed_methods)) {
throw new \Exception("Unknown method $this->method.");
}
$_SERVER['REQUEST_METHOD'] = $this->method;
$this->injectParams();
list($status, $value, $headers) = $this->execute();
drupal_add_http_header('Content-Type', null);
return new TestResponseMock([
'status' => $status,
'body' => $value,
'headers' => [
'Cache-Control' => 'no-cache, must-revalidate',
'Connection' => 'Keep-Alive',
'Content-Language' => 'en',
'Content-Type' => 'text/html; charset=utf-8',
'Date' => gmdate('D, d M Y H:is e'),
'Expires' => gmdate('D, d M Y H:is e'),
'Keep-Alive' => 'timeout=5, max=100',
'Server' => 'Apache/2.4.29 (Unix) PHP/'.phpversion(),
'Transfer-Encoding' => 'chunked',
'X-Content-Type-Options' => 'nosniff',
'X-Frame-Options' => 'SAMEORIGIN',
'X-Generator' => 'Drupal 7 (http://drupal.org)',
] + $headers,
]);
} | php | {
"resource": ""
} |
q258343 | MenuCaller.execute | test | protected function execute()
{
$this->resetHeaders();
$this->resetStaticCache();
// Move to drupal root where the index.php is
$current_dir = getcwd();
chdir(DRUPAL_ROOT);
$value = '';
ob_start(function ($str) use (&$value) {
$value .= $str;
});
$buffer = menu_execute_active_handler($this->path, false);
ob_end_clean();
$status = 200;
if ($buffer === MENU_NOT_FOUND) {
$status = 404;
$value = '';
ob_start(function ($str) use (&$value) {
$value .= $str;
});
drupal_not_found();
ob_end_clean();
} elseif ($buffer === MENU_ACCESS_DENIED) {
$status = 403;
$value = '';
ob_start(function ($str) use (&$value) {
$value .= $str;
});
drupal_access_denied();
ob_end_clean();
} elseif (empty($value)) {
$value = drupal_render_page($buffer);
}
// Go back to the test directory
chdir($current_dir);
return [
$status,
$value,
drupal_get_http_header(),
];
} | php | {
"resource": ""
} |
q258344 | MenuCaller.injectParams | test | protected function injectParams()
{
$_GET['q'] = $this->path;
$_SERVER['REQUEST_URI'] = $this->path;
if (in_array($this->method, ['GET', 'DELETE'])) {
foreach ($this->params as $key => $param) {
$_GET[$key] = $param;
}
return;
}
$menu_item = menu_get_item($this->path);
$_POST['form_id'] = isset($menu_item['page_arguments']) ? $menu_item['page_arguments'][0] : '';
foreach ($this->params as $key => $param) {
$_POST[$key] = $param;
}
} | php | {
"resource": ""
} |
q258345 | AttributeRepository.findOneByAttributeCode | test | public function findOneByAttributeCode($attributeCode)
{
// load and return the EAV attribute with the passed code
$this->attributeByAttributeCodeStmt->execute(array(MemberNames::ATTRIBUTE_CODE => $attributeCode));
return $this->attributeByAttributeCodeStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258346 | BunchSubject.tearDown | test | public function tearDown($serial)
{
// invoke the parent method
parent::tearDown($serial);
// load the registry processor
$registryProcessor = $this->getRegistryProcessor();
// update the status
$registryProcessor->mergeAttributesRecursive(
$serial,
array(
RegistryKeys::PRE_LOADED_ATTRIBUTE_IDS => $this->preLoadedAttributeIds,
)
);
} | php | {
"resource": ""
} |
q258347 | BunchSubject.preLoadAttributeId | test | public function preLoadAttributeId(array $attribute)
{
$this->preLoadedAttributeIds[$attribute[MemberNames::ATTRIBUTE_CODE]]= $attribute[MemberNames::ATTRIBUTE_ID];
} | php | {
"resource": ""
} |
q258348 | PublishesData.publish | test | public function publish($data_table, array $ids = [], $primary_key = '')
{
$publisher = new PublishRecords($data_table, $ids, $primary_key);
$publisher->publish();
return $publisher;
} | php | {
"resource": ""
} |
q258349 | BaseResponse.assertSee | test | public function assertSee($content)
{
$response = (string)$this->getResponseBody();
PHPUnit::assertContains($content, $response, "Unable to find [$content] in response.");
return $this;
} | php | {
"resource": ""
} |
q258350 | BaseResponse.json | test | public function json()
{
$json = json_decode($this->getResponseBody(), true);
if (is_null($json)) {
PHPUnit::fail('Unable to decode json response!');
throw new InvalidJSONException('Unable to decode json response!');
}
return $json;
} | php | {
"resource": ""
} |
q258351 | BaseResponse.assertJsonStructure | test | public function assertJsonStructure(array $structure, $data = null)
{
if (is_null($data)) {
try {
$data = $this->json();
} catch (InvalidJSONException $exception) {
PHPUnit::fail('Unable to decode json response!');
}
}
foreach ($structure as $key => $value) {
if (is_array($value)) {
PHPUnit::assertArrayHasKey($key, $data);
// Prevent infinite loops
if (is_null($data[$key])) {
continue;
}
$this->assertJsonStructure($structure[$key], $data[$key]);
continue;
}
PHPUnit::assertArrayHasKey($value, $data);
}
return $this;
} | php | {
"resource": ""
} |
q258352 | BootstrapDrupal.run | test | public function run()
{
// Don't bootstrap twice in runtime
if (static::$bootstrapped) {
return;
}
// Read environment variables to set drupal root
$this->readEnvironmentFile();
// Set the base url if provided in environment
$this->setBaseURL();
// Read environment variables
if (! defined('DRUPAL_ROOT')) {
define('DRUPAL_ROOT', $this->getDrupalRoot());
}
if (empty(DRUPAL_ROOT)) {
throw new TripalTestSuiteException('DRUPAL_ROOT is not configured correctly. Please use .env files to set DRUPAL_ROOT.');
}
require_once DRUPAL_ROOT.'/includes/bootstrap.inc';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$cwd = getcwd();
chdir(DRUPAL_ROOT);
// The bootstrap function won't run twice since drupal checks if it has run it before
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
chdir($cwd);
static::$bootstrapped = true;
} | php | {
"resource": ""
} |
q258353 | BootstrapDrupal.getDrupalRoot | test | protected function getDrupalRoot()
{
if ($path = getenv('DRUPAL_ROOT')) {
return $path;
}
$path = getcwd();
while ($path !== '/') {
if (file_exists($path.'/includes/bootstrap.inc')) {
return $path;
}
$path = dirname($path);
}
return '';
} | php | {
"resource": ""
} |
q258354 | BootstrapDrupal.getEnvironmentFilePath | test | protected function getEnvironmentFilePath()
{
$dir = getcwd();
// If running phpunit from the module root dir
if (file_exists($dir.'/tests/.env')) {
return $dir.'/tests/.env';
}
// If running phpunit from the module root dir
if (file_exists($dir.'/test/.env')) {
return $dir.'/test/.env';
}
// If running php unit from within the tests dir
if (file_exists($dir.'/.env')) {
return $dir.'/.env';
}
return false;
} | php | {
"resource": ""
} |
q258355 | BootstrapDrupal.readEnvironmentFile | test | protected function readEnvironmentFile()
{
$env_file_path = $this->getEnvironmentFilePath();
if ($env_file_path) {
$line_count = 0;
$file = fopen($env_file_path, 'r');
while ($line = fgets($file)) {
$line++;
$line = trim($line);
if (empty($line)) {
continue;
}
// Ignore comments
if(str_begins_with('//', $line) || str_begins_with('-', $line) || str_begins_with('#', $line)) {
continue;
}
if (putenv(str_replace("\n", '', trim($line))) === false) {
throw new TripalTestSuiteException("Could not read environment line $line_count: $line");
}
}
}
} | php | {
"resource": ""
} |
q258356 | PublishRecords.publish | test | public function publish()
{
// Find the bundle
$this->bundles = db_query('SELECT name, bundle_id FROM chado_bundle
JOIN tripal_bundle ON tripal_bundle.id = chado_bundle.bundle_id
WHERE data_table = :data_table', [':data_table' => $this->data_table])->fetchAll();
if (empty($this->bundles)) {
throw new Exception("Unable to find bundles for $this->data_table. Publishing failed!");
}
// Perform the publishing
foreach ($this->bundles as $bundle) {
// Publish Records
try {
$published = $this->tripalChadoPublishRecords($bundle->name, $this->ids);
} catch (Exception $exception) {
$this->delete();
throw $exception;
}
$this->published[] = $published;
}
} | php | {
"resource": ""
} |
q258357 | LoadsDatabaseSeeders.loadDatabaseSeeders | test | public function loadDatabaseSeeders()
{
$workingDir = getcwd();
if (file_exists("$workingDir/tests/DatabaseSeeders")) {
foreach (glob("$workingDir/tests/DatabaseSeeders/*.php") as $seeder) {
require_once $seeder;
// Extract the class name
/** @var \StatonLab\TripalTestSuite\Database\Seeder $className */
$className = $this->getClassName($seeder);
if (! class_exists($className)) {
$error = "Database seeder class $className not found. Make sure the filename and the class name match.";
throw new TripalTestBootstrapException($error);
}
$this->seeders[] = $className;
}
}
return $this->seeders;
} | php | {
"resource": ""
} |
q258358 | AbstractAttributeSubject.getEntityType | test | public function getEntityType($entityTypeCode = null)
{
// set the default entity type code, if non has been passed
if ($entityTypeCode === null) {
$entityTypeCode = $this->getDefaultEntityTypeCode();
}
// query whether or not, the entity type with the passed code is available
if (isset($this->entityTypes[$entityTypeCode])) {
return $this->entityTypes[$entityTypeCode];
}
// throw an exception, if not
throw new \Exception(
sprintf(
'Can\'t find entity type with code %s in file %s on line %d',
$entityTypeCode,
$this->getFilename(),
$this->getLineNumber()
)
);
} | php | {
"resource": ""
} |
q258359 | AbstractAttributeSubject.getEntityTypeId | test | public function getEntityTypeId($entityTypeCode = null)
{
// load the entity type for the given code, or the default one otherwise
$entityType = $this->getEntityType($entityTypeCode ? $entityTypeCode : $this->getDefaultEntityTypeCode());
// return the entity type ID
return $entityType[MemberNames::ENTITY_TYPE_ID];
} | php | {
"resource": ""
} |
q258360 | MakesHTTPRequests._call | test | private function _call($method, $uri, $params = [])
{
if (! str_begins_with('http', $uri)) {
$client = new MenuCaller();
return $client->setPath($uri)->setMethod($method)->addParams($params)->send();
}
try {
$client = new Client();
$uri = $this->_prepareURI($uri);
if (! empty($this->_cookies)) {
$domain = str_replace('http://', '', $GLOBALS['base_url']);
$domain = str_replace('https://', '', $domain);
$cookieJar = CookieJar::fromArray($this->_cookies, $domain);
$params['cookies'] = $cookieJar;
}
return new TestResponse($client->request($method, $uri, $params));
} catch (\GuzzleHttp\Exception\GuzzleException $exception) {
PHPUnit::fail("Failed to send $method request to $uri. ".$exception->getMessage());
}
return null;
} | php | {
"resource": ""
} |
q258361 | MakesHTTPRequests._prepareURI | test | private function _prepareURI($uri)
{
global $base_url;
if (str_begins_with($uri, '/') || ! str_begins_with($uri, 'http')) {
return trim($base_url.'/'.trim($uri, '/'), '/');
}
return trim($uri, '/');
} | php | {
"resource": ""
} |
q258362 | Agent.acceptDistributedTracePayloadHttpsafe | test | public function acceptDistributedTracePayloadHttpsafe(string $payload, string $type = 'HTTP'): bool
{
if (!$this->isLoaded()) {
return false;
}
return newrelic_accept_distributed_trace_payload_httpsafe($payload, $type);
} | php | {
"resource": ""
} |
q258363 | Agent.endTransaction | test | public function endTransaction(bool $ignore = false): bool
{
if (!$this->isLoaded()) {
return false;
}
return newrelic_end_transaction($ignore);
} | php | {
"resource": ""
} |
q258364 | Agent.setAppname | test | public function setAppname($name, string $license = null, bool $xmit = false): bool
{
if (!$this->isLoaded()) {
return false;
}
$name = is_array($name) ? implode(';', $name) : $name;
if (isset($license)) {
return newrelic_set_appname($name, $license, $xmit);
}
return newrelic_set_appname($name);
} | php | {
"resource": ""
} |
q258365 | Agent.setUserAttributes | test | public function setUserAttributes(string $user, string $account, string $product): bool
{
if (!$this->isLoaded()) {
return false;
}
return newrelic_set_user_attributes($user, $account, $product);
} | php | {
"resource": ""
} |
q258366 | Agent.startTransaction | test | public function startTransaction(string $appname, string $license = null): bool
{
if (!$this->isLoaded()) {
return false;
}
if (isset($license)) {
return newrelic_start_transaction($appname, $license);
}
return newrelic_start_transaction($appname);
} | php | {
"resource": ""
} |
q258367 | Redirect.toUrl | test | public function toUrl($url)
{
$allow_not_routed_url = $this->config['allow_not_routed_url'] ?? false;
$exclude_urls = $this->config['options']['exclude_urls'] ?? [];
$exclude_hosts = $this->config['options']['exclude_hosts'] ?? [];
$uriTargetHost = (new Uri($url))->getHost();
if (true === $allow_not_routed_url ||
\in_array($url, $exclude_urls) ||
\in_array($uriTargetHost, $exclude_hosts)
) {
return parent::toUrl($url);
}
$controller = $this->getController();
$request = $controller->getRequest();
$basePath = $request->getBasePath();
$default_url = $this->config['default_url'] ?? '/';
if ($basePath !== '') {
if (\strpos($url, $basePath) !== 0) {
$url = $basePath . $url;
}
if (\strpos($default_url, $basePath) !== 0) {
$default_url = $basePath . $default_url;
}
}
$current_uri = $request->getRequestUri();
$request->setUri($url);
$uriTarget = (new Uri($url))->__toString();
if ($current_uri === $uriTarget) {
$this->getEventManager()->trigger('redirect-same-url');
return;
}
$mvcEvent = $this->getEvent();
$routeMatch = $mvcEvent->getRouteMatch();
$currentRouteMatchName = $routeMatch->getMatchedRouteName();
$router = $mvcEvent->getRouter();
$uriCurrentHost = (new Uri($router->getRequestUri()))->getHost();
if (($routeToBeMatched = $router->match($request))
&& (
$uriTargetHost === null
||
$uriCurrentHost === $uriTargetHost
)
&& (
(
($routeToBeMatchedRouteName = $routeToBeMatched->getMatchedRouteName()) !== $currentRouteMatchName
&& (
$this->manager->has($routeToBeMatched->getParam('controller'))
||
$routeToBeMatched->getParam('middleware') !== false
)
)
||
(
$routeToBeMatched->getParam('action') != $routeMatch->getParam('action')
)
||
(
$routeToBeMatchedRouteName === $currentRouteMatchName
)
)
) {
return parent::toUrl($url);
}
return parent::toUrl($default_url);
} | php | {
"resource": ""
} |
q258368 | ConfigurationUtil.prepareConstructorArgs | test | public static function prepareConstructorArgs(\ReflectionClass $reflectionClass, array $params)
{
// prepare the array for the initialized arguments
$initializedParams = array();
// prepare the array for the arguments in camel case (in configuration we use a '-' notation)
$paramsInCamelCase = array();
// convert the configuration keys to camelcase
foreach ($params as $key => $value) {
$paramsInCamelCase[lcfirst(str_replace('-', '', ucwords($key, '-')))] = $value;
}
// load the constructor's reflection parameters
$constructorParameters = $reflectionClass->getConstructor()->getParameters();
// prepare the arguments by applying the values from the configuration
/** @var \ReflectionParameter $reflectionParameter */
foreach ($constructorParameters as $reflectionParameter) {
if (isset($paramsInCamelCase[$paramName = $reflectionParameter->getName()])) {
$initializedParams[$paramName] = $paramsInCamelCase[$paramName];
} elseif ($reflectionParameter->isOptional()) {
$initializedParams[$paramName] = $reflectionParameter->getDefaultValue();
} else {
$initializedParams[$paramName] = null;
}
}
// return the array with the prepared arguments
return $initializedParams;
} | php | {
"resource": ""
} |
q258369 | AbstractCallback.appendExceptionSuffix | test | protected function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
{
return $this->getSubject()-> appendExceptionSuffix($message, $filename, $lineNumber);
} | php | {
"resource": ""
} |
q258370 | AbstractCallback.wrapException | test | protected function wrapException(
$columnName,
\Exception $parent = null,
$className = '\TechDivision\Import\Exceptions\WrappedColumnException'
) {
return $this->getSubject()->wrapException($columnName, $parent, $className);
} | php | {
"resource": ""
} |
q258371 | Lexer.parse | test | public function parse($filename, InterpreterInterface $interpreter)
{
// for mac's office excel csv
ini_set('auto_detect_line_endings', true);
// initialize the configuration
$delimiter = $this->config->getDelimiter();
$enclosure = $this->config->getEnclosure();
$escape = $this->config->getEscape();
$fromCharset = $this->config->getFromCharset();
$toCharset = $this->config->getToCharset();
$flags = $this->config->getFlags();
$ignoreHeader = $this->config->getIgnoreHeaderLine();
// query whether or not the charset has to be converted
if ($fromCharset === null) {
$url = $filename;
} else {
$url = ConvertMbstringEncoding::getFilterURL($filename, $fromCharset, $toCharset);
}
// initialize the CSV file object
$csv = new \SplFileObject($url);
$csv->setCsvControl($delimiter, $enclosure, $escape);
$csv->setFlags($flags);
// backup current locale
$originalLocale = setlocale(LC_ALL, '0');
setlocale(LC_ALL, 'en_US.UTF-8');
// process each line of the CSV file
foreach ($csv as $lineNumber => $line) {
if ($ignoreHeader && $lineNumber == 0 || (count($line) === 1 && trim($line[0]) === '')) {
continue;
}
$interpreter->interpret($line);
}
// reset locale
$localeArray = array();
parse_str(str_replace(';', '&', $originalLocale), $localeArray);
setlocale(LC_ALL, $localeArray);
} | php | {
"resource": ""
} |
q258372 | EavAttributeGroupRepository.load | test | public function load($id)
{
// execute the prepared statement and return the EAV attribute group with the passed ID
$this->eavAttributeGroupStmt->execute(array($id));
return $this->eavAttributeGroupStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258373 | EavAttributeGroupRepository.findAllByAttributeSetId | test | public function findAllByAttributeSetId($attributeSetId)
{
// initialize the array for the EAV attribute sets
$eavAttributeGroups = array();
// load the attributes
$this->eavAttributeGroupsByAttributeSetIdStmt->execute(array(MemberNames::ATTRIBUTE_SET_ID => $attributeSetId));
// load the available EAV attribute option groups
$availableEavAttributeGroups = $this->eavAttributeGroupsByAttributeSetIdStmt->fetchAll(\PDO::FETCH_ASSOC);
// prepare the array with the attribute group names as keys
foreach ($availableEavAttributeGroups as $eavAttributeGroup) {
$eavAttributeGroups[$eavAttributeGroup[MemberNames::ATTRIBUTE_GROUP_NAME]] = $eavAttributeGroup;
}
// return the array with the EAV attribute groups
return $eavAttributeGroups;
} | php | {
"resource": ""
} |
q258374 | EavAttributeGroupRepository.findOneByEntityTypeCodeAndAttributeSetNameAndAttributeGroupName | test | public function findOneByEntityTypeCodeAndAttributeSetNameAndAttributeGroupName($entityTypeCode, $attributeSetName, $attributeGroupName)
{
// initialize the params
$params = array(
MemberNames::ENTITY_TYPE_CODE => $entityTypeCode,
MemberNames::ATTRIBUTE_SET_NAME => $attributeSetName,
MemberNames::ATTRIBUTE_GROUP_NAME => $attributeGroupName
);
// execute the prepared statement and return the EAV attribute group with the passed params
$this->eavAttributeGroupByEntityTypeCodeAndAttributeSetNameAndAttributeGroupNameStmt->execute($params);
return $this->eavAttributeGroupByEntityTypeCodeAndAttributeSetNameAndAttributeGroupNameStmt->fetch(\PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q258375 | LexerConfigFactory.createLexerConfig | test | public function createLexerConfig()
{
// initialize the lexer configuration
$config = new LexerConfig();
// query whether or not a delimiter character has been configured
if ($delimiter = $this->configuration->getDelimiter()) {
$config->setDelimiter($delimiter);
}
// query whether or not a custom escape character has been configured
if ($escape = $this->configuration->getEscape()) {
$config->setEscape($escape);
}
// query whether or not a custom enclosure character has been configured
if ($enclosure = $this->configuration->getEnclosure()) {
$config->setEnclosure($enclosure);
}
// query whether or not a custom source charset has been configured
if ($fromCharset = $this->configuration->getFromCharset()) {
$config->setFromCharset($fromCharset);
}
// query whether or not a custom target charset has been configured
if ($toCharset = $this->configuration->getToCharset()) {
$config->setToCharset($toCharset);
}
// return the lexer configuratio
return $config;
} | php | {
"resource": ""
} |
q258376 | EavAttributeOptionValueRepository.findOneByOptionIdAndStoreId | test | public function findOneByOptionIdAndStoreId($optionId, $storeId)
{
// the parameters of the EAV attribute option to load
$params = array(
MemberNames::OPTION_ID => $optionId,
MemberNames::STORE_ID => $storeId,
);
// prepare the cache key
$cacheKey = $this->cacheKey(SqlStatementKeys::EAV_ATTRIBUTE_OPTION_VALUE_BY_OPTION_ID_AND_STORE_ID, $params);
// return the cached result if available
if ($this->isCached($cacheKey)) {
return $this->fromCache($cacheKey);
}
// load and return the EAV attribute option value with the passed parameters
$this->eavAttributeOptionValueByOptionIdAndStoreIdStmt->execute($params);
// query whether or not the EAV attribute option value is available in the database
if ($eavAttributeOptionValue = $this->eavAttributeOptionValueByOptionIdAndStoreIdStmt->fetch(\PDO::FETCH_ASSOC)) {
// add the EAV attribute option value to the cache, register the cache key reference as well
$this->toCache(
$eavAttributeOptionValue[MemberNames::VALUE_ID],
$eavAttributeOptionValue,
array($cacheKey => $eavAttributeOptionValue[MemberNames::VALUE_ID])
);
// finally, return it
return $eavAttributeOptionValue;
}
} | php | {
"resource": ""
} |
q258377 | FileResolverFactory.createFileResolver | test | public function createFileResolver(SubjectConfigurationInterface $subject)
{
// create a new file resolver instance for the subject with the passed configuration
$fileResolver = $this->container->get($subject->getFileResolver()->getId());
$fileResolver->setSubjectConfiguration($subject);
// return the file resolver instance
return $fileResolver;
} | php | {
"resource": ""
} |
q258378 | CoreConfigDataRepository.findAll | test | public function findAll()
{
// prepare the core configuration data
$coreConfigDatas = array();
// execute the prepared statement
$this->coreConfigDataStmt->execute();
// load the available core config data
$availableCoreConfigDatas = $this->coreConfigDataStmt->fetchAll(\PDO::FETCH_ASSOC);
// create the array with the resolved category path as keys
foreach ($availableCoreConfigDatas as $coreConfigData) {
// prepare the unique identifier
$uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
// append the config data value with the unique identifier
$coreConfigDatas[$uniqueIdentifier] = $coreConfigData;
}
// return array with the configuration data
return $coreConfigDatas;
} | php | {
"resource": ""
} |
q258379 | SystemLoggerTrait.getSystemLogger | test | public function getSystemLogger($name = LoggerKeys::SYSTEM)
{
// query whether or not, the requested logger is available
if (isset($this->systemLoggers[$name])) {
return $this->systemLoggers[$name];
}
// throw an exception if the requested logger is NOT available
throw new \Exception(sprintf('The requested logger \'%s\' is not available', $name));
} | php | {
"resource": ""
} |
q258380 | PluginFactory.createPlugin | test | public function createPlugin(PluginConfigurationInterface $pluginConfiguration)
{
// load the plugin instance from the DI container and set the plugin configuration
$pluginInstance = $this->container->get($pluginConfiguration->getId());
$pluginInstance->setPluginConfiguration($pluginConfiguration);
// return the plugin instance
return $pluginInstance;
} | php | {
"resource": ""
} |
q258381 | AbstractObserver.mergeEntity | test | protected function mergeEntity(array $entity, array $attr)
{
return array_merge($entity, $attr, array(EntityStatus::MEMBER_NAME => EntityStatus::STATUS_UPDATE));
} | php | {
"resource": ""
} |
q258382 | NumberConverterFactory.createNumberConverter | test | public function createNumberConverter(SubjectConfigurationInterface $subject)
{
// create a new number converter instance for the subject with the passed configuration
$numberConverter = $this->container->get($subject->getNumberConverter()->getId());
$numberConverter->setSubjectConfiguration($subject);
// return the number converter instance
return $numberConverter;
} | php | {
"resource": ""
} |
q258383 | AbstractEavSubject.castValueByBackendType | test | public function castValueByBackendType($backendType, $value)
{
// cast the value to a valid timestamp
if ($backendType === BackendTypeKeys::BACKEND_TYPE_DATETIME) {
return \DateTime::createFromFormat($this->getConfiguration()->getDateConverter()->getSourceDateFormat(), $value)->format('Y-m-d H:i:s');
}
// cast the value to a float value
if ($backendType === BackendTypeKeys::BACKEND_TYPE_FLOAT) {
return (float) $value;
}
// cast the value to an integer
if ($backendType === BackendTypeKeys::BACKEND_TYPE_INT) {
return (int) $value;
}
// we don't need to cast strings
return $value;
} | php | {
"resource": ""
} |
q258384 | AbstractEavSubject.getEntityTypeCode | test | public function getEntityTypeCode()
{
// load the entity type code from the configuration
$entityTypeCode = $this->getConfiguration()->getConfiguration()->getEntityTypeCode();
// try to map the entity type code
if (isset($this->entityTypeCodeToAttributeSetMappings[$entityTypeCode])) {
$entityTypeCode = $this->entityTypeCodeToAttributeSetMappings[$entityTypeCode];
}
// return the (mapped) entity type code
return $entityTypeCode;
} | php | {
"resource": ""
} |
q258385 | AbstractEavSubject.getAttributes | test | public function getAttributes()
{
// query whether or not, the requested EAV attributes are available
if (isset($this->attributes[$entityTypeCode = $this->getEntityTypeCode()])) {
// load the attributes for the entity type code
$attributes = $this->attributes[$entityTypeCode];
// query whether or not an attribute set has been loaded from the source file
if (is_array($this->attributeSet) && isset($this->attributeSet[MemberNames::ATTRIBUTE_SET_NAME])) {
// load the attribute set name
$attributeSetName = $this->attributeSet[MemberNames::ATTRIBUTE_SET_NAME];
// query whether or not attributes for the actual attribute set name
if ($attributeSetName && isset($attributes[$attributeSetName])) {
return $attributes[$attributeSetName];
}
// throw an exception, if not
throw new \Exception(
$this->appendExceptionSuffix(
sprintf('Found invalid attribute set name "%s"', $attributeSetName)
)
);
} else {
return call_user_func_array('array_merge', $attributes);
}
}
// throw an exception, if not
throw new \Exception(
$this->appendExceptionSuffix(
sprintf('Found invalid entity type code "%s"', $entityTypeCode)
)
);
} | php | {
"resource": ""
} |
q258386 | AbstractEavSubject.getEavUserDefinedAttributes | test | public function getEavUserDefinedAttributes()
{
// initialize the array with the user defined EAV attributes
$eavUserDefinedAttributes = array();
// query whether or not user defined EAV attributes for the actualy entity type are available
if (isset($this->userDefinedAttributes[$entityTypeCode = $this->getEntityTypeCode()])) {
$eavUserDefinedAttributes = $this->userDefinedAttributes[$entityTypeCode];
}
// return the array with the user defined EAV attributes
return $eavUserDefinedAttributes;
} | php | {
"resource": ""
} |
q258387 | AbstractEavSubject.getEavAttributeByAttributeCode | test | public function getEavAttributeByAttributeCode($attributeCode)
{
// load the attributes
$attributes = $this->getAttributes();
// query whether or not the attribute exists
if (isset($attributes[$attributeCode])) {
return $attributes[$attributeCode];
}
// throw an exception if the requested attribute is not available
throw new \Exception(
$this->appendExceptionSuffix(
sprintf('Can\'t load attribute with code "%s"', $attributeCode)
)
);
} | php | {
"resource": ""
} |
q258388 | CategoryAssembler.getCategoriesWithResolvedPath | test | public function getCategoriesWithResolvedPath()
{
// prepare the categories
$categories = array();
// load the categories from the database
$availableCategories = $this->categoryRepository->findAll();
// create the array with the resolved category path as keys
foreach ($availableCategories as $category) {
// expload the entity IDs from the category path
$entityIds = explode('/', $category[MemberNames::PATH]);
// cut-off the root category
array_shift($entityIds);
// continue with the next category if no entity IDs are available
if (sizeof($entityIds) === 0) {
continue;
}
// initialize the array for the path elements
$path = array();
foreach ($entityIds as $entityId) {
$cat = $this->categoryVarcharRepository->findByEntityId($entityId);
$path[] = $cat[MemberNames::VALUE];
}
// append the catogory with the string path as key
$categories[implode('/', $path)] = $category;
}
// return array with the categories
return $categories;
} | php | {
"resource": ""
} |
q258389 | CategoryAssembler.getCategoriesWithResolvedPathByStoreView | test | public function getCategoriesWithResolvedPathByStoreView($storeViewId)
{
// prepare the categories
$categories = array();
// load the categories from the database
$availableCategories = $this->categoryRepository->findAllByStoreView($storeViewId);
// create the array with the resolved category path as keys
foreach ($availableCategories as $category) {
// expload the entity IDs from the category path
$entityIds = explode('/', $category[MemberNames::PATH]);
// cut-off the root category
array_shift($entityIds);
// continue with the next category if no entity IDs are available
if (sizeof($entityIds) === 0) {
continue;
}
// initialize the array for the path elements
$path = array();
foreach ($entityIds as $entityId) {
$cat = $this->categoryVarcharRepository->findByEntityId($entityId);
$path[] = $cat[MemberNames::VALUE];
}
// append the catogory with the string path as key
$categories[implode('/', $path)] = $category;
}
// return array with the categories
return $categories;
} | php | {
"resource": ""
} |
q258390 | HeaderTrait.getHeader | test | public function getHeader($name)
{
// map column => attribute name
$name = $this->mapAttributeCodeByHeaderMapping($name);
// query whether or not, the header is available
if (isset($this->headers[$name])) {
return $this->headers[$name];
}
// throw an exception, if not
throw new \InvalidArgumentException(sprintf('Header %s is not available', $name));
} | php | {
"resource": ""
} |
q258391 | HeaderTrait.addHeader | test | public function addHeader($name)
{
// add the header
$this->headers[$name] = $position = sizeof($this->headers);
// return the new header's position
return $position;
} | php | {
"resource": ""
} |
q258392 | HeaderTrait.mapAttributeCodeByHeaderMapping | test | public function mapAttributeCodeByHeaderMapping($attributeCode)
{
// load the header mappings
$headerMappings = $this->getHeaderMappings();
// query weather or not we've a mapping, if yes, map the attribute code
if (isset($headerMappings[$attributeCode])) {
$attributeCode = $headerMappings[$attributeCode];
}
// return the (mapped) attribute code
return $attributeCode;
} | php | {
"resource": ""
} |
q258393 | AbstractSubject.tearDown | test | public function tearDown($serial)
{
// load the registry processor
$registryProcessor = $this->getRegistryProcessor();
// update the source directory for the next subject
$registryProcessor->mergeAttributesRecursive(
$serial,
array(
RegistryKeys::SOURCE_DIRECTORY => $newSourceDir = $this->getNewSourceDir($serial),
RegistryKeys::FILES => array($this->getFilename() => array(RegistryKeys::STATUS => 1))
)
);
// log a debug message with the new source directory
$this->getSystemLogger()->debug(
sprintf('Subject %s successfully updated source directory to %s', get_class($this), $newSourceDir)
);
} | php | {
"resource": ""
} |
q258394 | AbstractSubject.registerObserver | test | public function registerObserver(ObserverInterface $observer, $type)
{
// query whether or not the array with the callbacks for the
// passed type has already been initialized, or not
if (!isset($this->observers[$type])) {
$this->observers[$type] = array();
}
// append the callback with the instance of the passed type
$this->observers[$type][] = $observer;
} | php | {
"resource": ""
} |
q258395 | AbstractSubject.registerCallback | test | public function registerCallback(CallbackInterface $callback, $type)
{
// query whether or not the array with the callbacks for the
// passed type has already been initialized, or not
if (!isset($this->callbacks[$type])) {
$this->callbacks[$type] = array();
}
// append the callback with the instance of the passed type
$this->callbacks[$type][] = $callback;
} | php | {
"resource": ""
} |
q258396 | AbstractSubject.getCallbacksByType | test | public function getCallbacksByType($type)
{
// initialize the array for the callbacks
$callbacks = array();
// query whether or not callbacks for the type are available
if (isset($this->callbacks[$type])) {
$callbacks = $this->callbacks[$type];
}
// return the array with the type's callbacks
return $callbacks;
} | php | {
"resource": ""
} |
q258397 | AbstractSubject.importRow | test | public function importRow(array $row)
{
// initialize the row
$this->row = $row;
// raise the line number and reset the skip row flag
$this->lineNumber++;
$this->skipRow = false;
// invoke the events that has to be fired before the artfact's row will be processed
$this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_ROW_PROCESS_START, $this);
// initialize the headers with the columns from the first line
if (sizeof($this->headers) === 0) {
foreach ($this->row as $value => $key) {
$this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
}
return;
}
// load the available observers
$availableObservers = $this->getObservers();
// process the observers
foreach ($availableObservers as $observers) {
// invoke the pre-import/import and post-import observers
/** @var \TechDivision\Import\Observers\ObserverInterface $observer */
foreach ($observers as $observer) {
// query whether or not we have to skip the row
if ($this->skipRow) {
// log a debug message with the actual line nr/file information
$this->getSystemLogger()->warning(
$this->appendExceptionSuffix(
sprintf(
'Skip processing operation "%s" after observer "%s"',
$this->operationName,
get_class($observer)
)
)
);
// skip the row
break 2;
}
// if not, set the subject and process the observer
if ($observer instanceof ObserverInterface) {
$this->row = $observer->handle($this);
}
}
}
// query whether or not a minute has been passed
if ($this->lastLog < time() - 60) {
// log the number processed rows per minute
$this->getSystemLogger()->info(
sprintf(
'Successfully processed "%d (%d)" rows per minute of file "%s"',
$this->lineNumber - $this->lastLineNumber,
$this->lineNumber,
$this->getFilename()
)
);
// reset the last log time and the line number
$this->lastLog = time();
$this->lastLineNumber = $this->lineNumber;
}
// log a debug message with the actual line nr/file information
$this->getSystemLogger()->debug(
$this->appendExceptionSuffix(
sprintf(
'Successfully processed operation "%s"',
$this->operationName
)
)
);
// invoke the events that has to be fired when the artfact's row has been successfully processed
$this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_ROW_PROCESS_SUCCESS, $this);
} | php | {
"resource": ""
} |
q258398 | AbstractSubject.prepareStoreViewCode | test | public function prepareStoreViewCode()
{
// re-set the store view code
$this->setStoreViewCode(null);
// initialize the store view code
if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
$this->setStoreViewCode($storeViewCode);
}
} | php | {
"resource": ""
} |
q258399 | AbstractSubject.getStoreId | test | public function getStoreId($storeViewCode)
{
// query whether or not, the requested store is available
if (isset($this->stores[$storeViewCode])) {
return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
}
// throw an exception, if not
throw new \Exception(
sprintf(
'Found invalid store view code %s in file %s on line %d',
$storeViewCode,
$this->getFilename(),
$this->getLineNumber()
)
);
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.