_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q260200
Collection.first
test
public function first(callable $callback = null, $default = null) { if (is_null($callback)) { return count($this->items) > 0 ? reset($this->items) : null; } return Arr::first($this->items, $callback, $default); }
php
{ "resource": "" }
q260201
Collection.last
test
public function last(callable $callback = null, $default = null) { if (is_null($callback)) { return count($this->items) > 0 ? end($this->items) : value($default); } return Arr::last($this->items, $callback, $default); }
php
{ "resource": "" }
q260202
Collection.max
test
public function max($key = null) { return $this->reduce(function ($result, $item) use ($key) { $value = data_get($item, $key); return is_null($result) || $value > $result ? $value : $result; }); }
php
{ "resource": "" }
q260203
Collection.reject
test
public function reject($callback) { if ($this->useAsCallable($callback)) { return $this->filter(function ($item) use ($callback) { return !$callback($item); }); } return $this->filter(function ($item) use ($callback) { return $item != $callback; }); }
php
{ "resource": "" }
q260204
Collection.toArray
test
public function toArray() { return array_map(function ($value) { return ($value instanceof Arrayable || instance_of_laravel_arrayable($value)) ? $value->toArray() : $value; }, $this->items); }
php
{ "resource": "" }
q260205
Collection.getArrayableItems
test
protected function getArrayableItems($items) { if ($items instanceof self) { return $items->all(); } elseif (($items instanceof Arrayable || instance_of_laravel_arrayable($items))) { return $items->toArray(); } elseif (($items instanceof Jsonable || instance_of_laravel_jsonable($items))) { return json_decode($items->toJson(), true); } return (array)$items; }
php
{ "resource": "" }
q260206
Map.enabled
test
public function enabled($slug, $index) { $map = $this->map; $key = ''; $index = (int)$index == 0 ? 0 : 1 << ($index - 1); foreach (explode(static::DELIMITER, $slug) as $child) { $key = empty($key) ? $child : $key.static::DELIMITER.$child; $isMissing = !$this->slugExists($key); $isDisabled = $isMissing ?: !((int)$map[$key] & $index); if ($isMissing || $isDisabled) { $this->logger->debug('Swivel - "'.$slug.'" is not enabled for bucket '.$index); return false; } } $this->logger->debug('Swivel - "'.$slug.'" is enabled for bucket '.$index); return true; }
php
{ "resource": "" }
q260207
Map.parse
test
public function parse(array $map) { $this->logger->info('Swivel - Parsing feature map.', compact('map')); return array_combine(array_keys($map), array_map([$this, 'reduceToBitmask'], $map)); }
php
{ "resource": "" }
q260208
StructFactory.createHashMap
test
public static function createHashMap(array $items): HashMapInterface { $hashMapItems = []; foreach ($items as $itemKey => $itemValue) { $hashMapItems[] = new HashMapItem($itemKey, $itemValue); } return new HashMap($hashMapItems); }
php
{ "resource": "" }
q260209
Config.getBucket
test
public function getBucket() { return new Bucket($this->map, $this->index, $this->getLogger(), $this->callback); }
php
{ "resource": "" }
q260210
Config.setMap
test
protected function setMap($map) { $logger = $this->getLogger(); if (is_array($map)) { $map = new Map($map, $logger); } elseif ($map instanceof DriverInterface) { $map = $map->getMap(); $map->setLogger($logger); } elseif ($map instanceof MapInterface) { $map->setLogger($logger); } else { throw new \LogicException('Invalid map passed to Zumba\Swivel\Config'); } $this->map = $map; }
php
{ "resource": "" }
q260211
Manager.forFeature
test
public function forFeature($slug) { $this->logger->debug('Swivel - Generating builder for feature "'.$slug.'"'); $builder = new Builder($slug, $this->bucket); $builder->setLogger($this->logger); $this->metrics && $builder->setMetrics($this->metrics); return $builder; }
php
{ "resource": "" }
q260212
Manager.setBucket
test
public function setBucket(BucketInterface $bucket = null) { if ($bucket) { $this->bucket = $bucket; $this->logger->debug('Swivel - User bucket set.', compact('bucket')); } return $this; }
php
{ "resource": "" }
q260213
DbSchemaResource.describeTables
test
public function describeTables($tables, $refresh = false) { $tables = static::validateAsArray( $tables, ',', true, 'The request contains no valid table names or properties.' ); $out = []; foreach ($tables as $table) { $name = (is_array($table)) ? array_get($table, 'name') : $table; $this->validateSchemaAccess($name, Verbs::GET); $out[] = $this->describeTable($table, $refresh); } return $out; }
php
{ "resource": "" }
q260214
DbSchemaResource.describeTable
test
public function describeTable($name, $refresh = false) { $name = (is_array($name) ? array_get($name, 'name') : $name); if (empty($name)) { throw new BadRequestException('Table name can not be empty.'); } try { $table = $this->parent->getTableSchema($name, $refresh); if (!$table) { throw new NotFoundException("Table '$name' does not exist in the database."); } $result = $table->toArray(); $result['access'] = $this->getPermissions($name); return $result; } catch (RestException $ex) { throw $ex; } catch (\Exception $ex) { throw new InternalServerErrorException("Failed to query database schema.\n{$ex->getMessage()}"); } }
php
{ "resource": "" }
q260215
DbSchemaResource.createTables
test
public function createTables($tables, $check_exist = false, $return_schema = false) { $tables = static::validateAsArray($tables, null, true, 'There are no table sets in the request.'); foreach ($tables as $table) { if (null === ($name = array_get($table, 'name'))) { throw new BadRequestException("Table schema received does not have a valid name."); } } $result = $this->updateSchema($tables, !$check_exist); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeTables($tables); } return $result; }
php
{ "resource": "" }
q260216
DbSchemaResource.createTable
test
public function createTable($table, $properties = [], $check_exist = false, $return_schema = false) { $properties = (is_array($properties) ? $properties : []); $properties['name'] = $table; $tables = static::validateAsArray($properties, null, true, 'Bad data format in request.'); $result = $this->updateSchema($tables, !$check_exist); $result = array_get($result, 0, []); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeTable($table); } return $result; }
php
{ "resource": "" }
q260217
DbSchemaResource.createFields
test
public function createFields($table, $fields, $check_exist = false, $return_schema = false) { $fields = static::validateAsArray( $fields, ',', true, 'The request contains no valid table field names or properties.' ); $out = []; foreach ($fields as $field) { $name = (is_array($field)) ? array_get($field, 'name') : $field; $this->validateSchemaAccess($table, Verbs::PUT); $out[] = $this->createField($table, $name, $field, $check_exist, $return_schema); } return $out; }
php
{ "resource": "" }
q260218
DbSchemaResource.createField
test
public function createField($table, $field, $properties = [], $check_exist = false, $return_schema = false) { $properties = (is_array($properties) ? $properties : []); $properties['name'] = $field; $fields = static::validateAsArray($properties, null, true, 'Bad data format in request.'); $tables = [['name' => $table, 'field' => $fields]]; $result = $this->updateSchema($tables, !$check_exist); $result = array_get(array_get($result, 0, []), 'field', []); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeField($table, $field); } return $result; }
php
{ "resource": "" }
q260219
DbSchemaResource.createRelationships
test
public function createRelationships($table, $relationships, $check_exist = false, $return_schema = false) { $relationships = static::validateAsArray( $relationships, ',', true, 'The request contains no valid table relationship names or properties.' ); $out = []; foreach ($relationships as $relationship) { $name = (is_array($relationship)) ? array_get($relationship, 'name') : $relationship; $this->validateSchemaAccess($table, Verbs::PUT); $out[] = $this->createRelationship($table, $name, $relationship, $check_exist, $return_schema); } return $out; }
php
{ "resource": "" }
q260220
DbSchemaResource.createRelationship
test
public function createRelationship( $table, $relationship, $properties = [], $check_exist = false, $return_schema = false ) { $properties = (is_array($properties) ? $properties : []); $properties['name'] = $relationship; $fields = static::validateAsArray($properties, null, true, 'Bad data format in request.'); $tables = [['name' => $table, 'related' => $fields]]; $result = $this->updateSchema($tables, !$check_exist); $result = array_get(array_get($result, 0, []), 'related', []); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeRelationship($table, $relationship); } return $result; }
php
{ "resource": "" }
q260221
DbSchemaResource.updateTables
test
public function updateTables($tables, $allow_delete_fields = false, $return_schema = false) { $tables = static::validateAsArray($tables, null, true, 'There are no table sets in the request.'); foreach ($tables as $table) { $name = (is_array($table)) ? array_get($table, 'name') : $table; if (empty($name)) { throw new BadRequestException("Table schema received does not have a valid name."); } if ($this->doesTableExist($name)) { $this->validateSchemaAccess($name, Verbs::PATCH); } else { $this->validateSchemaAccess(null, Verbs::POST); } } $result = $this->updateSchema($tables, true, $allow_delete_fields); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeTables($tables); } return $result; }
php
{ "resource": "" }
q260222
DbSchemaResource.updateTable
test
public function updateTable($table, $properties, $allow_delete_fields = false, $return_schema = false) { $properties = (is_array($properties) ? $properties : []); $properties['name'] = $table; $tables = static::validateAsArray($properties, null, true, 'Bad data format in request.'); $result = $this->updateSchema($tables, true, $allow_delete_fields); $result = array_get($result, 0, []); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeTable($table); } return $result; }
php
{ "resource": "" }
q260223
DbSchemaResource.updateFields
test
public function updateFields($table, $fields, $allow_delete_parts = false, $return_schema = false) { $fields = static::validateAsArray( $fields, ',', true, 'The request contains no valid table field names or properties.' ); $out = []; foreach ($fields as $field) { $name = (is_array($field)) ? array_get($field, 'name') : $field; $this->validateSchemaAccess($table, Verbs::PUT); $out[] = $this->updateField($table, $name, $field, $allow_delete_parts, $return_schema); } return $out; }
php
{ "resource": "" }
q260224
DbSchemaResource.updateField
test
public function updateField($table, $field, $properties = [], $allow_delete_parts = false, $return_schema = false) { if (empty($table)) { throw new BadRequestException('Table name can not be empty.'); } $properties = (is_array($properties) ? $properties : []); $properties['name'] = $field; $fields = static::validateAsArray($properties, null, true, 'Bad data format in request.'); $tables = [['name' => $table, 'field' => $fields]]; $result = $this->updateSchema($tables, true, false); $result = array_get(array_get($result, 0, []), 'field', []); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeField($table, $field); } return $result; }
php
{ "resource": "" }
q260225
DbSchemaResource.updateRelationships
test
public function updateRelationships($table, $relationships, $allow_delete_parts = false, $return_schema = false) { $relationships = static::validateAsArray( $relationships, ',', true, 'The request contains no valid table relationship names or properties.' ); $out = []; foreach ($relationships as $relationship) { $name = (is_array($relationship)) ? array_get($relationship, 'name') : $relationship; $this->validateSchemaAccess($table, Verbs::PUT); $out[] = $this->updateRelationship($table, $name, $relationship, $allow_delete_parts, $return_schema); } return $out; }
php
{ "resource": "" }
q260226
DbSchemaResource.updateRelationship
test
public function updateRelationship( $table, $relationship, $properties = [], $allow_delete_parts = false, $return_schema = false ) { if (empty($table)) { throw new BadRequestException('Table name can not be empty.'); } $properties = (is_array($properties) ? $properties : []); $properties['name'] = $relationship; $fields = static::validateAsArray($properties, null, true, 'Bad data format in request.'); $tables = [['name' => $table, 'related' => $fields]]; $result = $this->updateSchema($tables, true, false); $result = array_get(array_get($result, 0, []), 'related', []); // Any changes here should refresh cached schema $this->refreshCachedTables(); if ($return_schema) { return $this->describeRelationship($table, $relationship); } return $result; }
php
{ "resource": "" }
q260227
DbSchemaResource.deleteTables
test
public function deleteTables($tables, $check_empty = false) { $tables = static::validateAsArray( $tables, ',', true, 'The request contains no valid table names or properties.' ); $out = []; foreach ($tables as $table) { $name = (is_array($table)) ? array_get($table, 'name') : $table; $this->validateSchemaAccess($name, Verbs::DELETE); $out[] = $this->deleteTable($name, $check_empty); } return $out; }
php
{ "resource": "" }
q260228
DbSchemaResource.deleteTable
test
public function deleteTable($table, $check_empty = false) { if (empty($table)) { throw new BadRequestException('Table name can not be empty.'); } // Does it exist if (!$this->doesTableExist($table)) { throw new NotFoundException("Table '$table' not found."); } if ($check_empty) { // todo exist query here } try { if ($resource = $this->parent->getTableSchema($table)) { $this->parent->getSchema()->dropTable($resource->quotedName); $this->tablesDropped($table); } } catch (\Exception $ex) { \Log::error('Exception dropping table: ' . $ex->getMessage()); throw $ex; } // Any changes here should refresh cached schema $this->refreshCachedTables(); return ['name' => $table]; }
php
{ "resource": "" }
q260229
TextTargetLengthExtension.setTargetLength
test
public function setTargetLength($idealCharCount, $minCharCount = null, $maxCharCount = null) { $field = $this->owner; $idealCharCount = (int)$idealCharCount; if (!$idealCharCount > 0) return $field; // Set defaults if ($minCharCount === null) $minCharCount = round($idealCharCount * .75); if ($maxCharCount === null) $maxCharCount = round($idealCharCount * 1.25); // Validate if (!($maxCharCount >= $idealCharCount && $idealCharCount >= $minCharCount)) return $field; // Activate $field->addExtraClass('target-length'); $field->setAttribute('data-target-ideal-length', $idealCharCount); $field->setAttribute('data-target-min-length', $minCharCount); $field->setAttribute('data-target-max-length', $maxCharCount); $field->setAttribute('data-hint-length-target', _t('TextTargetLength.LengthTarget', 'Length target: <b>{value}%</b> <i>{remark}</i>')); $field->setAttribute('data-hint-length-tooshort', _t('TextTargetLength.LengthTooShort', 'Keep going!')); $field->setAttribute('data-hint-length-toolong', _t('TextTargetLength.LengthTooLong', 'Too long')); $field->setAttribute('data-hint-length-adequate', _t('TextTargetLength.LengthAdequate', 'Okay')); $field->setAttribute('data-hint-length-ideal', _t('TextTargetLength.LengthIdeal', 'Great!')); Requirements::javascript('jonom/silverstripe-text-target-length:client/javascript/text-target-length.js'); Requirements::css('jonom/silverstripe-text-target-length:client/css/text-target-length.css'); return $field; }
php
{ "resource": "" }
q260230
BaseDbTableResource.truncateTable
test
public function truncateTable($table, $extras = []) { // todo faster way? $records = $this->retrieveRecordsByFilter($table, null, null, $extras); if (!empty($records)) { $this->deleteRecords($table, $records, $extras); } return ['success' => true]; }
php
{ "resource": "" }
q260231
Result.pagedResultResponse
test
public function pagedResultResponse($key = null) { $cookie = null; $estimated = null; @ldap_control_paged_result_response($this->link, $this->resource, $cookie, $estimated); switch ($key) { case 'cookie': return $cookie; case 'estimated': return $estimated; default: return [ 'cookie' => $cookie, 'estimated' => $estimated ]; } }
php
{ "resource": "" }
q260232
DataReader.rewind
test
public function rewind() { if ($this->index < 0) { $this->row = $this->statement->fetch(); $this->index = 0; } else { throw new \Exception('DataReader cannot rewind. It is a forward-only reader.'); } }
php
{ "resource": "" }
q260233
Ldap.escape
test
public static function escape($value, $ignore = null, $flags = null) { if (! function_exists('ldap_escape')) { // Bail out, can't work our magic! trigger_error('ldap_escape() is only available in PHP 5.6 or newer', E_USER_ERROR); } return ldap_escape($value, $ignore, $flags); }
php
{ "resource": "" }
q260234
Ldap.add
test
public function add($dn, array $entry) { @ldap_add($this->resource, $dn, $entry); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260235
Ldap.compare
test
public function compare($dn, $attribute, $value) { $retVal = @ldap_compare($this->resource, $dn, $attribute, $value); $this->verifyOperation(); return $retVal; }
php
{ "resource": "" }
q260236
Ldap.connect
test
public function connect($ldapUrl) { // Make sure the connection has been established successfully if (! $this->resource = @ldap_connect($ldapUrl)) { throw new \Exception(sprintf("Unable to connect to ldap server %s", $ldapUrl)); } // Set sane defaults for ldap v3 protocol $this->setOption(LDAP_OPT_PROTOCOL_VERSION, 3) ->setOption(LDAP_OPT_REFERRALS, 0); return $this; }
php
{ "resource": "" }
q260237
Ldap.pagedResult
test
public function pagedResult($pageSize, $isCritical = false, $cookie = '') { ldap_control_paged_result($this->resource, $pageSize, $isCritical, $cookie); return $this; }
php
{ "resource": "" }
q260238
Ldap.bind
test
public function bind($bindDn = null, $bindPassword = null) { @ldap_bind($this->resource, $bindDn, $bindPassword); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260239
Ldap.getOption
test
public function getOption($option) { $retVal = null; ldap_get_option($this->resource, $option, $retVal); return $retVal; }
php
{ "resource": "" }
q260240
Ldap.modAdd
test
public function modAdd($dn, array $entry) { @ldap_mod_add($this->resource, $dn, $entry); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260241
Ldap.modDelete
test
public function modDelete($dn, array $entry) { @ldap_mod_del($this->resource, $dn, $entry); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260242
Ldap.modReplace
test
public function modReplace($dn, array $entry) { @ldap_mod_replace($this->resource, $dn, $entry); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260243
Ldap.modify
test
public function modify($dn, array $entry) { @ldap_modify($this->resource, $dn, $entry); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260244
Ldap.modifyBatch
test
public function modifyBatch($dn, array $entry) { if (! function_exists('ldap_modify_batch')) { // Bail out, can't work our magic! trigger_error( 'ldap_modify_batch() is only available in PHP ~5.4.26 or >=5.5.10', E_USER_ERROR ); } @ldap_modify_batch($this->resource, $dn, $entry); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260245
Ldap.rename
test
public function rename($dn, $newRdn, $newParent, $deleteOldRdn) { @ldap_rename($this->resource, $dn, $newRdn, $newParent, $deleteOldRdn); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260246
Ldap.saslBind
test
public function saslBind( $bindDn = null, $bindPassword = null, $saslMech = null, $saslRealm = null, $saslAuthcId = null, $saslAuthzId = null, $props = null ) { @ldap_sasl_bind( $this->resource, $bindDn, $bindPassword, $saslMech, $saslRealm, $saslAuthcId, $saslAuthzId, $props ); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260247
Ldap.ldapSearch
test
public function ldapSearch( $baseDn, $filter, array $attributes = [], $scope = self::SCOPE_SUBTREE, $attrsOnly = false, $sizeLimit = 0, $timeLimit = 0, $deref = \LDAP_DEREF_NEVER ) { $function = $this->scopeToFunction($scope); // Support for parallel search $baseDn = (array)$baseDn; $filter = (array)$filter; // Sanity check... We need to do this ourselves because we are suppressing errors from the // ldap function call. if (count($baseDn) !== count($filter)) { // This is a programmer error - we should raise an error instead of catchable exception trigger_error('Array sizes of base DNs and filters do not match', E_USER_ERROR); } // Align the resources to match the amount of baseDns and filters provided $resources = array_fill(0, count($baseDn), $this->resource); $results = @$function( $resources, $baseDn, $filter, $attributes, $attrsOnly, $sizeLimit, $timeLimit, $deref ); $this->verifyOperation(); // Convert result resources into Result instances foreach ($results as $key => $result) { if (is_resource($result)) { $results[$key] = new Result($this, $result); } // Else - let it be whatever it was (probably FALSE - a failed search) } // If there is only one result, this was not a parallel search - return it directly return count($results) === 1 ? $results[0] : $results; }
php
{ "resource": "" }
q260248
Ldap.setOption
test
public function setOption($option, $newVal) { @ldap_set_option($this->resource, $option, $newVal); $this->verifyOperation(); return $this; }
php
{ "resource": "" }
q260249
Ldap.verifyOperation
test
protected function verifyOperation() { // This could happen if Ldap::unbind() has been called and then another ldap operation was // attempted with this link - in that case, the resource type will be 'Unknown' // This is an exceptional situation and so I shall throw one at you (see switch below) if (get_resource_type($this->resource) !== 'ldap link') { // I hope this code is not used by ldap... $this->code = -2; $this->message = 'Not a valid ldap link resource'; } else { $this->code = ldap_errno($this->resource); $this->message = ldap_error($this->resource); } // Active Directory conceals some additional error codes in the ErrorMessage of the response // that we cannot get to with ldap_errno() in authentication failures - let's try to extract // them! if ($this->code === 49) { $errorString = $this->getOption(static::OPT_ERROR_STRING); // "LDAP: error code 49 - 80090308: LdapErr: DSID-0C090334, comment: // AcceptSecurityContext error, data 775, vece" // ^^^ // Note for my future self - the code '52e' will not be matched. But that's alright - // you would have replaced it with '49' anyway. preg_match('/(?<=data )[0-9]{2,3}/', $errorString, $matches); // Have we found it? if (count($matches) === 1) { $this->code = $matches[0]; } } switch ($this->code) { // These response codes do not represent a failed operation; everything else does case static::SUCCESS: case static::SIZELIMIT_EXCEEDED: case static::COMPARE_FALSE: case static::COMPARE_TRUE: break; // An ldap operation was performed on a resource that has been already closed case -2: throw new \Exception($this->message, $this->code); default: throw new LdapException($this); } }
php
{ "resource": "" }
q260250
CartesianProduct.addSet
test
private function addSet($set) { if (is_array($set)) { $set = new \ArrayIterator($set); } elseif ($set instanceof \Traversable) { $set = new \IteratorIterator($set); } else { throw new \InvalidArgumentException('Set must be either an array or Traversable'); } $this->sets[] = $set; }
php
{ "resource": "" }
q260251
CartesianProduct.computeReferenceSet
test
private function computeReferenceSet() { if (empty($this->sets)) { return; } $sets = array_reverse($this->sets); $this->referenceSet = array_shift($sets); foreach ($sets as $set) { $this->referenceSet = new Set($set, $this->referenceSet); } }
php
{ "resource": "" }
q260252
CartesianProduct.compute
test
public function compute() { $product = array(); $this->referenceSet->rewind(); while ($this->referenceSet->valid()) { $product[] = $this->referenceSet->current(); $this->referenceSet->next(); } return $product; }
php
{ "resource": "" }
q260253
Schema.getResourceNames
test
public function getResourceNames($type, $schema = '') { switch ($type) { case DbResourceTypes::TYPE_SCHEMA: return $this->getSchemas(); case DbResourceTypes::TYPE_TABLE: return $this->getTableNames($schema); case DbResourceTypes::TYPE_VIEW: return $this->getViewNames($schema); case DbResourceTypes::TYPE_TABLE_CONSTRAINT: return $this->getTableConstraints($schema); case DbResourceTypes::TYPE_PROCEDURE: return $this->getProcedureNames($schema); case DbResourceTypes::TYPE_FUNCTION: return $this->getFunctionNames($schema); default: return []; } }
php
{ "resource": "" }
q260254
Schema.getResource
test
public function getResource($type, &$name) { switch ($type) { case DbResourceTypes::TYPE_SCHEMA: return $name; case DbResourceTypes::TYPE_TABLE: $this->loadTable($name); return $name; case DbResourceTypes::TYPE_VIEW: $this->loadView($name); return $name; case DbResourceTypes::TYPE_PROCEDURE: $this->loadProcedure($name); return $name; case DbResourceTypes::TYPE_FUNCTION: $this->loadFunction($name); return $name; default: return null; } }
php
{ "resource": "" }
q260255
Schema.compareTableNames
test
public function compareTableNames($name1, $name2) { $name1 = str_replace(['"', '`', "'"], '', $name1); $name2 = str_replace(['"', '`', "'"], '', $name2); if (($pos = strrpos($name1, '.')) !== false) { $name1 = substr($name1, $pos + 1); } if (($pos = strrpos($name2, '.')) !== false) { $name2 = substr($name2, $pos + 1); } if ($this->connection->getTablePrefix() !== null) { if (strpos($name1, '{') !== false) { $name1 = $this->connection->getTablePrefix() . str_replace(['{', '}'], '', $name1); } if (strpos($name2, '{') !== false) { $name2 = $this->connection->getTablePrefix() . str_replace(['{', '}'], '', $name2); } } return $name1 === $name2; }
php
{ "resource": "" }
q260256
Schema.addPrimaryKey
test
public function addPrimaryKey($name, $table, $columns) { if (is_string($columns)) { $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY); } foreach ($columns as $i => $col) { $columns[$i] = $this->quoteColumnName($col); } return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT ' . $this->quoteColumnName($name) . ' PRIMARY KEY (' . implode(', ', $columns) . ' )'; }
php
{ "resource": "" }
q260257
Schema.createView
test
public function createView($table, $columns, $select, $options = null) { $sql = "CREATE VIEW " . $this->quoteTableName($table); if (!empty($columns)) { if (is_array($columns)) { foreach ($columns as &$name) { $name = $this->quoteColumnName($name); } $columns = implode(',', $columns); } $sql .= " ($columns)"; } $sql .= " AS " . $select; return $sql; }
php
{ "resource": "" }
q260258
Schema.bindValue
test
public function bindValue($statement, $name, $value, $dataType = null) { if ($dataType === null) { $statement->bindValue($name, $value, $this->getPdoType(gettype($value))); } else { $statement->bindValue($name, $value, $dataType); } }
php
{ "resource": "" }
q260259
Schema.extractPdoType
test
public static function extractPdoType($type) { switch ($type) { case DbSimpleTypes::TYPE_BINARY: return \PDO::PARAM_LOB; default: switch (static::extractPhpType($type)) { case 'boolean': return \PDO::PARAM_BOOL; case 'integer': return \PDO::PARAM_INT; case 'string': return \PDO::PARAM_STR; } } return null; }
php
{ "resource": "" }
q260260
Schema.extractType
test
public function extractType(ColumnSchema $column, $dbType) { if (false !== $simpleType = strstr($dbType, '(', true)) { } elseif (false !== $simpleType = strstr($dbType, '<', true)) { } else { $simpleType = $dbType; } $column->type = static::extractSimpleType($simpleType, $column->size, $column->scale); }
php
{ "resource": "" }
q260261
Schema.extractDefault
test
public function extractDefault(ColumnSchema $field, $defaultValue) { $phpType = DbSimpleTypes::toPhpType($field->type); $field->defaultValue = $this->formatValueToPhpType($defaultValue, $phpType); }
php
{ "resource": "" }
q260262
GroupByResponse.addData
test
public function addData($data) { if(is_object($data)) { $complete = true; foreach($this->requiredObjectFields as $property) { if(!isset($data->$property)) { $complete = false; break; } } if($complete) { $this->data[] = $data; } } else { if(is_array($data)) { $complete = true; foreach($this->requiredObjectFields as $property) { if(!isset($data[$property])) { $complete = false; break; } } if($complete) { $this->data[] = $data; } } } return $this; }
php
{ "resource": "" }
q260263
ReferralsByCompanyGroupByQueryGenerator.generateQuery
test
public function generateQuery(IDruidQueryParameters $params) { // @var ReferralsByCompanyGroupByQueryParameters $params $query = $this->queryTemplate; $query = str_replace('{DATASOURCE}', $params->dataSource, $query); $query = str_replace('{STARTINTERVAL}', $params->startInterval, $query); $query = str_replace('{ENDINTERVAL}', $params->endInterval, $query); return $query; }
php
{ "resource": "" }
q260264
DruidNodeDruidQueryExecutor.createRequest
test
public function createRequest($query) { $client = new \Guzzle\Http\Client(); $method = $this->httpMethod; $uri = $this->getBaseUrl(); $headers = $this->getHeaders(); $options = array(); if ( $method === 'POST' ) { $postBody = $query; $request = $client->createRequest( $method, $uri, $headers, $postBody, $options ); } else if ( $method === 'GET' ) { $request = $client->createRequest( $method, $uri, $headers, null, $options ); if ( $query ) { $queryObject = json_decode($query, true); $query = $request->getQuery(); foreach ($queryObject as $key => $val) { $query->set($key, $val); } } } else { throw new Exception('Unexpected HTTP Method: ' . $method); } return $request; }
php
{ "resource": "" }
q260265
DruidNodeDruidQueryExecutor.executeQuery
test
public function executeQuery(IDruidQueryGenerator $queryGenerator, IDruidQueryParameters $params, IDruidQueryResponseHandler $responseHandler) { $params->validate(); $generatedQuery = $queryGenerator->generateQuery($params); // Create a request $request = $this->createRequest( $generatedQuery ); // Send the request and parse the JSON response into an array try { $response = $request->send(); } catch (\Guzzle\Http\Exception\CurlException $curlException) { throw new $curlException; } $formattedResponse = $responseHandler->handleResponse($response); return $formattedResponse; }
php
{ "resource": "" }
q260266
DruidNodeDruidQueryExecutor.setHttpMethod
test
public function setHttpMethod($method) { $allowed_methods = array('GET', 'POST'); $method = strtoupper( $method ); if ( !in_array( $method, $allowed_methods ) ) { throw new Exception('Unsupported HTTP Method: ' . $method . '. Supported methods are: ' . join($allowed_methods, ', ')); } $this->httpMethod = $method; }
php
{ "resource": "" }
q260267
DruidNodeDruidQueryExecutor.setProtocol
test
public function setProtocol($protocol) { $allowedProtocols = array('http', 'https'); $protocol = strtolower( $protocol ); if ( !in_array( $protocol,$allowedProtocols ) ) { throw new Exception('Unsupported Protocol: ' . $protocol . '. Supported protocols are: ' . join($allowedProtocols, ', ')); } $this->protocol = $protocol; }
php
{ "resource": "" }
q260268
GroupByQueryGenerator.generateQuery
test
public function generateQuery(IDruidQueryParameters $params) { if(!$params instanceof GroupByQueryParameters) { throw new Exception('Expected $params to be instanceof GroupByQueryParameters'); } $params->validate(); $query = $params->getJSONString(); return $query; }
php
{ "resource": "" }
q260269
SimpleGroupByQueryParameters.setAggregators
test
public function setAggregators($aggregatorsArray) { $this->aggregators = array(); foreach( $aggregatorsArray as $aggregator) { $this->aggregators[] = json_encode( $aggregator ); } }
php
{ "resource": "" }
q260270
SimpleGroupByQueryParameters.setFilters
test
public function setFilters($filtersArray) { $this->filters = array(); foreach( $filtersArray as $filter) { $this->filters[] = json_encode( $filter ); } }
php
{ "resource": "" }
q260271
SimpleGroupByQueryParameters.setPostAggregators
test
public function setPostAggregators($postAggregatorsArray) { $this->postAggregators = array(); foreach( $postAggregatorsArray as $postAggregator) { $this->postAggregators[] = json_encode( $postAggregator ); } }
php
{ "resource": "" }
q260272
TinyMce.registerClientScript
test
protected function registerClientScript() { $js = []; $id = $this->options['id']; TinyMceAsset::register($this->view); $this->clientOptions['selector'] = "#{$id}"; if (!empty($this->clientOptions['language'])) { $language_url = LanguageAsset::register($this->view)->baseUrl . "/{$this->clientOptions['language']}.js"; $this->clientOptions['language_url'] = $language_url; } $options = Json::encode($this->clientOptions); $js[] = "tinymce.init($options);"; if ($this->triggerSaveOnBeforeValidateForm) { $js[] = "$('#{$id}').parents('form').on('beforeValidate', function() { tinymce.triggerSave(); });"; } $this->view->registerJs(implode("\n", $js)); }
php
{ "resource": "" }
q260273
GroupByQueryParameters.validate
test
public function validate() { $flag = true; foreach($this->requiredParams as $param) { if(!isset($this->$param)) { $this->missingParameters[] = $param; $flag = false; } else { $val = $this->$param; if(!is_array($val)) { $val = trim($val); } if(empty($val)) { $this->emptyParameters[] = $param; $flag = false; } } } if(count($this->missingParameters) > 0) { throw new MissingParametersException($this->missingParameters); } if(count($this->emptyParameters) > 0) { throw new EmptyParametersException($this->emptyParameters); } return $flag; }
php
{ "resource": "" }
q260274
GroupByQueryParameters.getJSONString
test
public function getJSONString() { $retString = '{[DATA]}'; $buffStringArray = array(); foreach($this->allParameters as $param) { if(isset($this->$param)) { $buffStringArray[] = "\"{$param}\":" . json_encode($this->$param); } } $buffString = implode(',', $buffStringArray); $retString = str_replace('[DATA]', $buffString, $retString); return $retString; }
php
{ "resource": "" }
q260275
SwaggerController.indexAction
test
public function indexAction() { $helperManager = $this->getServiceLocator()->get('viewhelpermanager'); $basePathHelper = $helperManager->get('basePath'); // Default to /api/docs in case the configurable path is not set $swaggerUrl = '/api/docs'; // Get swagger JSON url/path from config if set if (isset($this->config['swagger-json-url'])) { $swaggerUrl = $this->config['swagger-json-url']; } // Run through basePath helper if the string doesn't start with http if (substr($swaggerUrl, 0, 4) !== 'http') { $swaggerUrl = $basePathHelper->__invoke($swaggerUrl); } $viewModel = new ViewModel(); $viewModel->setTerminal(true); $viewModel->setVariable('swaggerUrl', $swaggerUrl); return $viewModel->setTemplate('swagger-ui.phtml'); }
php
{ "resource": "" }
q260276
MigrateTask.prepareDatabase
test
protected function prepareDatabase() { if (!$this->migrator->storageExist()) { $this->callTask(InstallTask::class, 'main', $this->arguments, $this->options); } }
php
{ "resource": "" }
q260277
Builder.hasColumn
test
public function hasColumn($table, $column) { $tableColumns = array_map('strtolower', $this->listColumnsName($table)); return in_array(strtolower($column), $tableColumns); }
php
{ "resource": "" }
q260278
Builder.getColumnType
test
public function getColumnType($table, $column) { $col = $this->describeColumn($table, $column); if (!is_null($col)) { return $col->getType(); } return null; }
php
{ "resource": "" }
q260279
Builder.table
test
public function table($table, Closure $callback) { $this->build(Func::tap($this->createBlueprint($table), function (Blueprint $blueprint) use ($callback) { $blueprint->update(); $callback($blueprint); })); }
php
{ "resource": "" }
q260280
Builder.drop
test
public function drop($table) { $this->build(Func::tap($this->createBlueprint($table), function (Blueprint $blueprint) { $blueprint->drop(); })); }
php
{ "resource": "" }
q260281
Builder.dropAllTables
test
public function dropAllTables() { @$this->disableForeignKeyConstraints(); foreach ($this->db->listTables() as $table) { $this->drop($table); }; @$this->enableForeignKeyConstraints(); }
php
{ "resource": "" }
q260282
Builder.rename
test
public function rename($from, $to) { $this->build(Func::tap($this->createBlueprint($from), function (Blueprint $blueprint) use ($to) { $blueprint->update(); $blueprint->rename($to); })); }
php
{ "resource": "" }
q260283
Builder.execute
test
public function execute($sql) { $this->build(Func::tap($this->createBlueprint(null), function (Blueprint $blueprint) use ($sql) { $blueprint->raw(); $blueprint->sql($sql); })); }
php
{ "resource": "" }
q260284
Media.addFromRequest
test
public function addFromRequest(UploadedFile $uploadedFile, $tag = null) { $this->getMediaAdder() ->performedOn($this->attachment) ->useMediaTag($tag) ->fromFile($uploadedFile); return $this; }
php
{ "resource": "" }
q260285
Media.addFromFile
test
public function addFromFile($filePath, $tag = null) { if (is_null($filePath)) return; $this->getMediaAdder() ->performedOn($this->attachment) ->useMediaTag($tag) ->fromFile(new SymfonyFile($filePath)); return $this; }
php
{ "resource": "" }
q260286
Media.addFromRaw
test
public function addFromRaw($rawData, $filename, $tag = null) { if (is_null($rawData)) return; $tempPath = temp_path($filename); File::put($tempPath, $rawData); $this->addFromFile($tempPath, $tag); File::delete($tempPath); return $this; }
php
{ "resource": "" }
q260287
Media.addFromUrl
test
public function addFromUrl($url, $filename = null, $tag = null) { if (!$stream = @fopen($url, 'rb')) throw new Exception(sprintf('Error opening file "%s"', $url)); return $this->addFromRaw( $stream, !empty($filename) ? $filename : File::basename($url), $tag ); }
php
{ "resource": "" }
q260288
Media.afterDelete
test
public function afterDelete() { try { $this->deleteThumbs(); $this->deleteFile(); } catch (Exception $ex) { Log::error($ex); } }
php
{ "resource": "" }
q260289
Media.getLastModified
test
public function getLastModified($fileName = null) { if (!$fileName) $fileName = $this->disk_name; return $this->getStorageDisk()->lastModified($this->getStoragePath().$fileName); }
php
{ "resource": "" }
q260290
Media.getUniqueName
test
public function getUniqueName() { if (!is_null($this->name)) return $this->name; $ext = strtolower($this->getExtension()); $name = str_replace('.', '', uniqid(null, TRUE)); return $this->name = $name.(strlen($ext) ? '.'.$ext : ''); }
php
{ "resource": "" }
q260291
Media.deleteThumbs
test
public function deleteThumbs() { $pattern = 'thumb_'.$this->id.'_'; $directory = $this->getStoragePath(); $allFiles = $this->getStorageDisk()->files($directory); $paths = array_filter($allFiles, function ($file) use ($pattern) { return starts_with(basename($file), $pattern); }); $this->getStorageDisk()->delete($paths); }
php
{ "resource": "" }
q260292
Media.deleteFile
test
protected function deleteFile($fileName = null) { if (!$fileName) { $fileName = $this->name; } $directory = $this->getStoragePath(); $filePath = $directory.$fileName; if ($this->getStorageDisk()->exists($filePath)) { $this->getStorageDisk()->delete($filePath); } $this->deleteEmptyDirectory($directory); }
php
{ "resource": "" }
q260293
Media.deleteEmptyDirectory
test
protected function deleteEmptyDirectory($directory = null) { if (!$this->isDirectoryEmpty($directory)) return; $this->getStorageDisk()->deleteDirectory($directory); $directory = dirname($directory); if (!$this->isDirectoryEmpty($directory)) return; $this->getStorageDisk()->deleteDirectory($directory); $directory = dirname($directory); if (!$this->isDirectoryEmpty($directory)) return; $this->getStorageDisk()->deleteDirectory($directory); }
php
{ "resource": "" }
q260294
Media.isDirectoryEmpty
test
protected function isDirectoryEmpty($directory) { $path = $this->getStorageDisk()->path($directory); return !(new FilesystemIterator($path))->valid(); }
php
{ "resource": "" }
q260295
Media.hasFile
test
protected function hasFile($fileName = null) { $filePath = $this->getStoragePath().$fileName; return $this->getStorageDisk()->exists($filePath); }
php
{ "resource": "" }
q260296
Media.getThumb
test
public function getThumb($options = []) { if (!$this->isImage()) return $this->getPath(); $options = $this->getDefaultThumbOptions($options); $thumbFile = $this->getThumbFilename($options); if (!$this->hasFile($thumbFile)) $this->makeThumb($thumbFile, $options); return $this->getPublicPath().$this->getPartitionDirectory().$thumbFile; }
php
{ "resource": "" }
q260297
Media.getThumbFilename
test
protected function getThumbFilename($options) { return 'thumb_' .$this->id.'_' .$options['width'].'_'.$options['height'].'_'.$options['fit'].'_' .substr(md5(serialize(array_except($options, ['width', 'height', 'fit']))), 0, 8). '.'.$options['extension']; }
php
{ "resource": "" }
q260298
Media.getDefaultThumbOptions
test
protected function getDefaultThumbOptions($override = []) { $defaultOptions = [ 'fit' => 'contain', 'width' => 0, 'height' => 0, 'quality' => 90, 'sharpen' => 0, 'extension' => 'auto', ]; if (!is_array($override)) $override = ['fit' => $override]; $options = array_merge($defaultOptions, $override); if (strtolower($options['extension']) == 'auto') $options['extension'] = strtolower($this->getExtension()); return $options; }
php
{ "resource": "" }
q260299
Media.makeThumb
test
protected function makeThumb($thumbFile, $options) { $thumbFile = $this->getStoragePath().$thumbFile; $thumbPath = $this->getStorageDisk()->path($thumbFile); $filePath = $this->getStorageDisk()->path($this->getDiskPath()); if (!$this->hasFile($this->name)) $filePath = $this->getDefaultThumbPath($thumbFile, array_get($options, 'default')); Manipulator::make($filePath) ->manipulate(array_except($options, ['extension', 'default'])) ->save($thumbPath); }
php
{ "resource": "" }