_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4500
Serializer.getRanges
train
protected function getRanges(array $values) { $i = 0; $cnt = count($values); $start = $values[0]; $end = $start; $ranges = []; while (++$i < $cnt) { if ($values[$i] === $end + 1) { ++$end; } else { $ranges[] = [$start, $end]; $start = $end = $values[$i]; } } $ranges[] = [$start, $end]; return $ranges; }
php
{ "resource": "" }
q4501
Serializer.serializeCharacterClass
train
protected function serializeCharacterClass(array $values) { $expr = '['; foreach ($this->getRanges($values) as list($start, $end)) { $expr .= $this->serializeCharacterClassUnit($start); if ($end > $start) { if ($end > $start + 1) { $expr .= '-'; } $expr .= $this->serializeCharacterClassUnit($end); } } $expr .= ']'; return $expr; }
php
{ "resource": "" }
q4502
Serializer.serializeElement
train
protected function serializeElement($element) { return (is_array($element)) ? $this->serializeStrings($element) : $this->serializeLiteral($element); }
php
{ "resource": "" }
q4503
Serializer.serializeValue
train
protected function serializeValue($value, $escapeMethod) { return ($value < 0) ? $this->meta->getExpression($value) : $this->escaper->$escapeMethod($this->output->output($value)); }
php
{ "resource": "" }
q4504
StringTools.mb_ucfirst
train
public static function mb_ucfirst($str, $encoding = 'UTF-8') { $length = mb_strlen($str, $encoding); $firstChar = mb_substr($str, 0, 1, $encoding); $then = mb_substr($str, 1, $length - 1, $encoding); return mb_strtoupper($firstChar, $encoding) . $then; }
php
{ "resource": "" }
q4505
OmmuPlugins.getPlugin
train
public static function getPlugin($actived=null, $keypath=null, $array=true) { $criteria=new CDbCriteria; if($actived != null) $criteria->compare('actived', $actived); $criteria->addNotInCondition('orders', array(0)); if($actived == null || $actived == 0) $criteria->order = 'folder ASC'; else $criteria->order = 'orders ASC'; $model = self::model()->findAll($criteria); if($array == true) { $items = array(); if($model != null) { foreach($model as $key => $val) { if($keypath == null || $keypath == 'id') $items[$val->plugin_id] = $val->name; else $items[$val->folder] = $val->name; } return $items; } else return false; } else return $model; }
php
{ "resource": "" }
q4506
MultiCurrencySum.times
train
public function times($multiplier) { return new self($this->getAugend()->times($multiplier), $this->getAddend()->times($multiplier)); }
php
{ "resource": "" }
q4507
Parser.get_dataset
train
private function get_dataset($index, $apiindex) { if (isset($this->data[$index])) { return $this->data[$index]; } $data = array(); foreach ($this->raw as $k => $v) { $pos = strpos($k, $apiindex); if ($pos !== 0) { continue; } $data[] = substr($k, strlen($apiindex)); } $this->data[$index] = $data; return $data; }
php
{ "resource": "" }
q4508
Parser.get_lists
train
public function get_lists($timeperiod) { $lists = array(); foreach ($this->get_all_lists() as $list) { $object = $this->get_list($list); if ($object->get_time_period() == $timeperiod) { $lists[] = $list; } } return $lists; }
php
{ "resource": "" }
q4509
Parser.get_list
train
public function get_list($id) { foreach (array(self::INDEX_LISTS, self::INDEX_LIST) as $k) { $key = $this->baseurl . '/' . $k . $id; if (isset($this->raw[$key])) { return new ReadingList($this->api, $this->baseurl, $id, $this->raw[$key]); } } return null; }
php
{ "resource": "" }
q4510
Parser.get_category
train
public function get_category($url) { if (isset($this->raw[$url])) { return new Category($this->api, $this->baseurl, $url, $this->raw[$url]); } return null; }
php
{ "resource": "" }
q4511
PhpDoc.firstLine
train
public static function firstLine(string $comment): string { $docLines = \preg_split('~\R~u', $comment); if (isset($docLines[1])) { return \trim($docLines[1], "/\t *"); } return ''; }
php
{ "resource": "" }
q4512
PhpDoc.description
train
public static function description(string $comment): string { $comment = \str_replace("\r", '', \trim(\preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/')))); if (\preg_match('/^\s*@\w+/m', $comment, $matches, \PREG_OFFSET_CAPTURE)) { $comment = \trim(\substr($comment, 0, $matches[0][1])); } return $comment; }
php
{ "resource": "" }
q4513
Response.sendHeader
train
public function sendHeader(string $name, ?string $value): void { if (headers_sent($file, $line)) { throw new HttpException(sprintf("Cannot use '%s()', headers already sent in %s:%s", __method__, $file, $line)); } // null means remove if ($value === null) { $this->removeHeader($name); header_remove($name); } else { $this->setHeader($name, $value); header(sprintf('%s: %s', $name, $value)); } }
php
{ "resource": "" }
q4514
Response.sendCookie
train
public function sendCookie(string $name, ?string $value, int $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httpOnly = false): void { // check name if (!preg_match('~^[a-z0-9_\-\.]+$~i', $name)) { throw new HttpException("Invalid cookie name '{$name}' given"); } $value = (string) $value; if ($expire < 0) { $value = ''; } setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly); }
php
{ "resource": "" }
q4515
Response.sendCookies
train
public function sendCookies(): void { foreach ((array) $this->cookies as $cookie) { $this->sendCookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']); } }
php
{ "resource": "" }
q4516
SqliteDb.alterTableMigrate
train
private function alterTableMigrate(array $alterDef, array $options = []) { $table = $alterDef['name']; $currentDef = $this->fetchTableDef($table); // Merge the table definitions if we aren't dropping stuff. if (!self::val(Db::OPTION_DROP, $options)) { $tableDef = $this->mergeTableDefs($currentDef, $alterDef); } else { $tableDef = $alterDef['def']; } // Drop all of the indexes on the current table. foreach (self::val('indexes', $currentDef, []) as $indexDef) { if (self::val('type', $indexDef, Db::INDEX_IX) === Db::INDEX_IX) { $this->dropIndex($indexDef['name']); } } $tmpTable = $table.'_'.time(); // Rename the current table. $this->renameTable($table, $tmpTable); // Create the new table. $this->createTableDb($tableDef, $options); // Figure out the columns that we can insert. $columns = array_keys(array_intersect_key($tableDef['columns'], $currentDef['columns'])); // Build the insert/select statement. $sql = 'insert into '.$this->prefixTable($table)."\n". $this->bracketList($columns, '`')."\n". $this->buildSelect($tmpTable, [], ['columns' => $columns]); $this->queryDefine($sql); // Drop the temp table. $this->dropTable($tmpTable); }
php
{ "resource": "" }
q4517
SqliteDb.fetchColumnDefsDb
train
protected function fetchColumnDefsDb(string $table) { $cdefs = $this->query('pragma table_info('.$this->prefixTable($table, false).')')->fetchAll(PDO::FETCH_ASSOC); if (empty($cdefs)) { return null; } $columns = []; $pk = []; foreach ($cdefs as $cdef) { $column = Db::typeDef($cdef['type']); if ($column === null) { throw new \Exception("Unknown type '$columnType'.", 500); } $column['allowNull'] = !filter_var($cdef['notnull'], FILTER_VALIDATE_BOOLEAN); if ($cdef['pk']) { $pk[] = $cdef['name']; if (strcasecmp($cdef['type'], 'integer') === 0) { $column['autoIncrement'] = true; } else { $column['primary'] = true; } } if ($cdef['dflt_value'] !== null) { $column['default'] = $this->forceType($cdef['dflt_value'], $column['type']); } $columns[$cdef['name']] = $column; } // $tdef = ['columns' => $columns]; // if (!empty($pk)) { // $tdef['indexes'][Db::INDEX_PK] = [ // 'columns' => $pk, // 'type' => Db::INDEX_PK // ]; // } // $this->tables[$table] = $tdef; return $columns; }
php
{ "resource": "" }
q4518
SqliteDb.fetchIndexesDb
train
protected function fetchIndexesDb($table = '') { $indexes = []; $indexInfos = $this->query('pragma index_list('.$this->prefixTable($table).')')->fetchAll(PDO::FETCH_ASSOC); foreach ($indexInfos as $row) { $indexName = $row['name']; if ($row['unique']) { $type = Db::INDEX_UNIQUE; } else { $type = Db::INDEX_IX; } // Query the columns in the index. $columns = $this->query('pragma index_info('.$this->quote($indexName).')')->fetchAll(PDO::FETCH_ASSOC); $index = [ 'name' => $indexName, 'columns' => array_column($columns, 'name'), 'type' => $type ]; $indexes[] = $index; } return $indexes; }
php
{ "resource": "" }
q4519
SqliteDb.getPKValue
train
private function getPKValue($table, array $row, $quick = false) { if ($quick && isset($row[$table.'ID'])) { return [$table.'ID' => $row[$table.'ID']]; } $tdef = $this->fetchTableDef($table); $cols = []; foreach ($tdef['columns'] as $name => $cdef) { if (empty($cdef['primary'])) { break; } if (!array_key_exists($name, $row)) { return null; } $cols[$name] = $row[$name]; } return $cols; }
php
{ "resource": "" }
q4520
SqliteDb.fetchTableNamesDb
train
protected function fetchTableNamesDb() { // Get the table names. $tables = $this->get( new Identifier('sqlite_master'), [ 'type' => 'table', 'name' => [Db::OP_LIKE => $this->escapeLike($this->getPx()).'%'] ], [ 'columns' => ['name'] ] )->fetchAll(PDO::FETCH_COLUMN); // Remove internal tables. $tables = array_filter($tables, function ($name) { return substr($name, 0, 7) !== 'sqlite_'; }); return $tables; }
php
{ "resource": "" }
q4521
CsrfGuard.forbidden
train
public function forbidden(ServerRequestInterface $request, ResponseInterface $response) { $contentType = $this->determineContentType($request); switch ($contentType) { case 'application/json': $output = $this->renderJsonErrorMessage(); break; case 'text/html': $output = $this->renderHtmlErrorMessage(); break; default: throw new Exception('Cannot render unknown content type ' . $contentType); } return $response ->withStatus(403) ->withHeader('Content-type', $contentType) ->write($output); }
php
{ "resource": "" }
q4522
MdsClient.request
train
public function request($url, $content = false, $customRequest = false) { $request_parts = explode('/', $url); $request = $request_parts[3]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if(strpos($url,'test')){ curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->testPassword); }else{ curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password); } curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/xml;charset=UTF-8")); if ($content && !$customRequest) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $content); } if ($customRequest) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $customRequest); } $output = curl_exec($ch); $outputINFO = curl_getinfo($ch); $this->log([ "httpcode" => $outputINFO['http_code'], "url" => $url, "endpoint" => $request, "output" => $output ]); if ($outputINFO['http_code'] >= 400 || curl_errno($ch)) { $this->log(curl_error($ch), "error"); $this->log($output, "error"); } else { $this->log(".datacite.".$request.".response:".$output); } curl_close($ch); return $output; }
php
{ "resource": "" }
q4523
CoalesceSingleCharacterPrefix.filterEligibleKeys
train
protected function filterEligibleKeys(array $eligibleKeys) { $filteredKeys = []; foreach ($eligibleKeys as $k => $keys) { if (count($keys) > 1) { $filteredKeys[] = $keys; } } return $filteredKeys; }
php
{ "resource": "" }
q4524
CoalesceSingleCharacterPrefix.getEligibleKeys
train
protected function getEligibleKeys(array $strings) { $eligibleKeys = []; foreach ($strings as $k => $string) { if (!is_array($string[0]) && isset($string[1])) { $suffix = serialize(array_slice($string, 1)); $eligibleKeys[$suffix][] = $k; } } return $this->filterEligibleKeys($eligibleKeys); }
php
{ "resource": "" }
q4525
ReadingList.get_time_period
train
public function get_time_period() { $period = $this->data[Parser::INDEX_LISTS_TIME_PERIOD][0]['value']; return substr($period, strpos($period, Parser::INDEX_TIME_PERIOD) + strlen(Parser::INDEX_TIME_PERIOD)); }
php
{ "resource": "" }
q4526
ReadingList.get_items
train
public function get_items() { if (!isset($this->data[Parser::INDEX_CHILDREN_SPEC])) { return array(); } $items = array(); foreach ($this->data[Parser::INDEX_CHILDREN_SPEC] as $k => $data) { $items[] = $this->api->get_item($data['value']); } return $items; }
php
{ "resource": "" }
q4527
ReadingList.get_item_count
train
public function get_item_count() { $data = $this->data; $count = 0; if (isset($data[Parser::INDEX_LISTS_LIST_ITEMS])) { foreach ($data[Parser::INDEX_LISTS_LIST_ITEMS] as $things) { if (preg_match('#/items/#', $things['value'])) { $count++; } } } return $count; }
php
{ "resource": "" }
q4528
ReadingList.get_categories
train
public function get_categories() { $data = $this->data; if (empty($data[Parser::INDEX_PARENT_SPEC])) { return array(); } // Okay. We first grab all of our categories. $categories = array(); foreach ($data[Parser::INDEX_PARENT_SPEC] as $category) { $categories[] = $this->api->get_category($category['value']); } return $categories; }
php
{ "resource": "" }
q4529
ReadingList.get_last_updated
train
public function get_last_updated($asstring = false) { $data = $this->data; $time = null; if (isset($data[Parser::INDEX_LISTS_LIST_UPDATED])) { $time = $data[Parser::INDEX_LISTS_LIST_UPDATED][0]['value']; $time = strtotime($time); } if ($asstring && $time) { return $this->contextual_time($time); } return $time; }
php
{ "resource": "" }
q4530
EmailAwareTrait.emailFromArray
train
protected function emailFromArray(array $arr) { if (isset($arr['address'])) { $arr['email'] = $arr['address']; unset($arr['address']); } if (!isset($arr['email'])) { throw new InvalidArgumentException( 'The array must contain at least the "address" key.' ); } $email = strval(filter_var($arr['email'], FILTER_SANITIZE_EMAIL)); if (!isset($arr['name']) || $arr['name'] === '') { return $email; } $name = str_replace('"', '', filter_var($arr['name'], FILTER_SANITIZE_STRING)); return sprintf('"%s" <%s>', $name, $email); }
php
{ "resource": "" }
q4531
BannersPositionsController.add
train
public function add() { $position = $this->BannersPositions->newEntity(); if ($this->request->is('post')) { $position = $this->BannersPositions->patchEntity($position, $this->request->getData()); if ($this->BannersPositions->save($position)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('position')); }
php
{ "resource": "" }
q4532
BannersPositionsController.edit
train
public function edit($id = null) { $position = $this->BannersPositions->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $position = $this->BannersPositions->patchEntity($position, $this->request->getData()); if ($this->BannersPositions->save($position)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('position')); }
php
{ "resource": "" }
q4533
BannersPositionsController.delete
train
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $position = $this->BannersPositions->get($id); //Before deleting, it checks if the position has some banners if (!$position->banner_count) { $this->BannersPositions->deleteOrFail($position); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4534
Gettext.getTranslations
train
protected function getTranslations( $domain ) { if( !isset( $this->files[$domain] ) ) { if ( !isset( $this->sources[$domain] ) ) { $msg = sprintf( 'No translation directory for domain "%1$s" available', $domain ); throw new \Aimeos\MW\Translation\Exception( $msg ); } // Reverse locations so the former gets not overwritten by the later $locations = array_reverse( $this->getTranslationFileLocations( $this->sources[$domain], $this->getLocale() ) ); foreach( $locations as $location ) { $this->files[$domain][$location] = new \Aimeos\MW\Translation\File\Mo( $location ); } } return ( isset( $this->files[$domain] ) ? $this->files[$domain] : [] ); }
php
{ "resource": "" }
q4535
MigrateScript.syncRelatedFields
train
protected function syncRelatedFields( IdProperty $newProp, PropertyField $newField, IdProperty $oldProp, PropertyField $oldField ) { unset($newProp, $oldProp, $oldField); $cli = $this->climate(); if (!$this->quiet()) { $cli->br(); $cli->comment('Syncing new IDs to pivot table.'); } $pivot = $this->pivotModel(); $attach = $this->targetModel(); $pivotSource = $pivot->source(); $pivotTable = $pivotSource->table(); $attachSource = $attach->source(); $attachTable = $attachSource->table(); $db = $attachSource->db(); $binds = [ // Join Model '%pivotTable' => $pivotTable, '%objectType' => 'object_type', '%objectId' => 'object_id', '%targetId' => 'attachment_id', // Attachment Model '%targetTable' => $attachTable, '%targetType' => 'type', '%newKey' => $newField->ident(), '%oldKey' => $attach->key(), ]; // Update simple object → attachment associations $sql = 'UPDATE `%pivotTable` AS p JOIN `%targetTable` AS a ON p.`%targetId` = a.`%oldKey` SET p.`%targetId` = a.`%newKey`;'; $db->query(strtr($sql, $binds)); // Update nested attachment → attachment associations $sql = 'UPDATE `%pivotTable` AS p JOIN `%targetTable` AS a ON p.`%objectId` = a.`%oldKey` AND p.`%objectType` = a.`%targetType` SET p.`%objectId` = a.`%newKey`;'; $db->query(strtr($sql, $binds)); return $this; }
php
{ "resource": "" }
q4536
MigrateScript.targetModel
train
public function targetModel() { if (!isset($this->targetModel)) { $this->targetModel = $this->modelFactory()->get(Attachment::class); } return $this->targetModel; }
php
{ "resource": "" }
q4537
MigrateScript.pivotModel
train
public function pivotModel() { if (!isset($this->pivotModel)) { $this->pivotModel = $this->modelFactory()->get(Join::class); } return $this->pivotModel; }
php
{ "resource": "" }
q4538
Message.getCookie
train
public final function getCookie(string $name, ?string $valueDefault = null): ?string { return $this->cookies[$name] ?? $valueDefault; }
php
{ "resource": "" }
q4539
Message.removeCookie
train
public function removeCookie(string $name, bool $defer = false): self { if ($this->type == self::TYPE_REQUEST) { throw new HttpException('You cannot modify request cookies'); } unset($this->cookies[$name]); if (!$defer) { // remove instantly $this->sendCookie($name, null, 0); } return $this; }
php
{ "resource": "" }
q4540
UsersController.loginWithCookie
train
protected function loginWithCookie() { $username = $this->request->getCookie('login.username'); $password = $this->request->getCookie('login.password'); //Checks if the cookies exist if (!$username || !$password) { return; } //Tries to login $this->request = $this->request->withParsedBody(compact('username', 'password')); $user = $this->Auth->identify(); if (!$user || !$user['active'] || $user['banned']) { return $this->buildLogout(); } $this->Auth->setUser($user); $this->LoginRecorder->setConfig('user', $user['id'])->write(); return $this->redirect($this->Auth->redirectUrl()); }
php
{ "resource": "" }
q4541
UsersController.buildLogout
train
protected function buildLogout() { //Deletes some cookies and KCFinder session $cookies = $this->request->getCookieCollection()->remove('login')->remove('sidebar-lastmenu'); $this->request = $this->request->withCookieCollection($cookies); $this->request->getSession()->delete('KCFINDER'); return $this->redirect($this->Auth->logout()); }
php
{ "resource": "" }
q4542
UsersController.sendActivationMail
train
protected function sendActivationMail($user) { //Creates the token $token = $this->Token->create($user->email, ['type' => 'signup', 'user_id' => $user->id]); return $this->getMailer('MeCms.User') ->set('url', Router::url(['_name' => 'activation', $user->id, $token], true)) ->send('activation', [$user]); }
php
{ "resource": "" }
q4543
OmmuWallComment.getGridColumn
train
public function getGridColumn($columns=null) { if($columns !== null) { foreach($columns as $val) { /* if(trim($val) == 'enabled') { $this->defaultColumns[] = array( 'name' => 'enabled', 'value' => '$data->enabled == 1? "Ya": "Tidak"', ); } */ $this->defaultColumns[] = $val; } } else { //$this->defaultColumns[] = 'comment_id'; $this->defaultColumns[] = 'publish'; $this->defaultColumns[] = 'parent_id'; $this->defaultColumns[] = 'wall_id'; $this->defaultColumns[] = 'user_id'; $this->defaultColumns[] = 'comment'; $this->defaultColumns[] = 'creation_date'; $this->defaultColumns[] = 'modified_date'; } return $this->defaultColumns; }
php
{ "resource": "" }
q4544
App.go
train
public function go( $sEntryPoint, InputInterface $oInputInterface = null, OutputInterface $oOutputInterface = null, $bAutoExit = true ) { /* *--------------------------------------------------------------- * App Bootstrapper: preSystem *--------------------------------------------------------------- * Allows the app to execute code very early on in the console tool lifecycle */ if (class_exists('\App\Console\Bootstrap') && is_callable('\App\Console\Bootstrap::preSystem')) { \App\Console\Bootstrap::preSystem($this); } /* *--------------------------------------------------------------- * Nails Bootstrapper *--------------------------------------------------------------- */ \Nails\Bootstrap::run($sEntryPoint); /* *--------------------------------------------------------------- * Command line can run forever *--------------------------------------------------------------- */ set_time_limit(0); /* *--------------------------------------------------------------- * Instantiate CI's Utf8 library; so we have the appropriate * constants defined *--------------------------------------------------------------- */ $oUtf8 = new Utf8(); /* *--------------------------------------------------------------- * CLI only *--------------------------------------------------------------- */ $oInput = Factory::service('Input'); if (!$oInput::isCli()) { ErrorHandler::halt('This tool can only be used on the command line.'); } /* *--------------------------------------------------------------- * Instantiate the application *--------------------------------------------------------------- */ $oApp = new Application(); /* *--------------------------------------------------------------- * Set auto-exit behaviour *--------------------------------------------------------------- */ $oApp->setAutoExit($bAutoExit); /* *--------------------------------------------------------------- * Command Locations *--------------------------------------------------------------- * Define which directories to look in for Console Commands */ $aCommandLocations = [ [NAILS_APP_PATH . 'vendor/nails/common/src/Common/Console/Command/', 'Nails\Common\Console\Command'], [NAILS_APP_PATH . 'src/Console/Command/', 'App\Console\Command'], ]; $aModules = Components::modules(); foreach ($aModules as $oModule) { $aCommandLocations[] = [ $oModule->path . 'src/Console/Command', $oModule->namespace . 'Console\Command', ]; } /* *--------------------------------------------------------------- * Load Commands *--------------------------------------------------------------- * Recursively look for commands */ Factory::helper('directory'); $aCommands = []; function findCommands(&$aCommands, $sPath, $sNamespace) { $aDirMap = directory_map($sPath); if (!empty($aDirMap)) { foreach ($aDirMap as $sDir => $sFile) { if (is_array($sFile)) { findCommands($aCommands, $sPath . DIRECTORY_SEPARATOR . $sDir, $sNamespace . '\\' . trim($sDir, '/')); } else { $aFileInfo = pathinfo($sFile); $sFileName = basename($sFile, '.' . $aFileInfo['extension']); $aCommands[] = $sNamespace . '\\' . $sFileName; } } } } foreach ($aCommandLocations as $aLocation) { list($sPath, $sNamespace) = $aLocation; findCommands($aCommands, $sPath, $sNamespace); } foreach ($aCommands as $sCommandClass) { $oApp->add(new $sCommandClass()); } /* *--------------------------------------------------------------- * App Bootstrapper: preCommand *--------------------------------------------------------------- * Allows the app to execute code just before the command is called */ if (class_exists('\App\Console\Bootstrap') && is_callable('\App\Console\Bootstrap::preCommand')) { \App\Console\Bootstrap::preCommand($this); } /* *--------------------------------------------------------------- * Run the application *--------------------------------------------------------------- * Go, go, go! */ $oApp->run($oInputInterface, $oOutputInterface); /* *--------------------------------------------------------------- * App Bootstrapper: postCommand *--------------------------------------------------------------- * Allows the app to execute code just after the command is called */ if (class_exists('\App\Console\Bootstrap') && is_callable('\App\Console\Bootstrap::postCommand')) { \App\Console\Bootstrap::postCommand($this); } /* *--------------------------------------------------------------- * Nails Shotdown Handler *--------------------------------------------------------------- */ \Nails\Bootstrap::shutdown(); /* *--------------------------------------------------------------- * App Bootstrapper: postSystem *--------------------------------------------------------------- * Allows the app to execute code at the very end of the console tool lifecycle */ if (class_exists('\App\Console\Bootstrap') && is_callable('\App\Console\Bootstrap::postSystem')) { \App\Console\Bootstrap::postSystem($this); } }
php
{ "resource": "" }
q4545
MailhideHelper.obfuscate
train
protected function obfuscate($mail) { return preg_replace_callback('/^([^@]+)(.*)$/', function ($matches) { $lenght = floor(strlen($matches[1]) / 2); $name = substr($matches[1], 0, $lenght) . str_repeat('*', $lenght); return $name . $matches[2]; }, $mail); }
php
{ "resource": "" }
q4546
MailhideHelper.link
train
public function link($title, $mail, array $options = []) { //Obfuscates the title, if the title is the email address $title = filter_var($title, FILTER_VALIDATE_EMAIL) ? $this->obfuscate($title) : $title; $mail = Security::encryptMail($mail); $url = Router::url(['_name' => 'mailhide', '?' => compact('mail')], true); $options['escape'] = false; $options['onClick'] = sprintf('window.open(\'%s\',\'%s\',\'resizable,height=547,width=334\'); return false;', $url, $title); $options += ['class' => 'recaptcha-mailhide', 'title' => $title]; return $this->Html->link($title, $url, $options); }
php
{ "resource": "" }
q4547
Query.beginBracket
train
private function beginBracket($op) { $this->currentWhere[] = [$op => []]; $this->whereStack[] = &$this->currentWhere; end($this->currentWhere); $this->currentWhere = &$this->currentWhere[key($this->currentWhere)][$op]; return $this; }
php
{ "resource": "" }
q4548
Query.end
train
public function end() { // First unset the reference so it doesn't overwrite the original where clause. unset($this->currentWhere); // Move the pointer in the where stack back one level. if (empty($this->whereStack)) { trigger_error("Call to Query->end() without a corresponding call to Query->begin*().", E_USER_NOTICE); $this->currentWhere = &$this->where; } else { $key = key(end($this->whereStack)); $this->currentWhere = &$this->whereStack[$key]; unset($this->whereStack[$key]); } return $this; }
php
{ "resource": "" }
q4549
Query.addLike
train
public function addLike($column, $value) { $r = $this->addWhere($column, [Db::OP_LIKE => $value]); return $r; }
php
{ "resource": "" }
q4550
Query.addIn
train
public function addIn($column, array $values) { $r = $this->addWhere($column, [Db::OP_IN, $values]); return $r; }
php
{ "resource": "" }
q4551
Query.addWheres
train
public function addWheres(array $where) { foreach ($where as $column => $value) { $this->addWhere($column, $value); } return $this; }
php
{ "resource": "" }
q4552
Query.toArray
train
public function toArray() { $r = [ 'from' => $this->from, 'where' => $this->where, 'order' => $this->order, 'limit' => $this->limit, 'offset' => $this->offset ]; return $r; }
php
{ "resource": "" }
q4553
Query.exec
train
public function exec(Db $db) { $options = [ 'limit' => $this->limit, 'offset' => $this->offset ]; $r = $db->get($this->from, $this->where, $options); return $r; }
php
{ "resource": "" }
q4554
IsOwnedByTrait.isOwnedBy
train
public function isOwnedBy($recordId, $userId = null) { return (bool)$this->find() ->where(['id' => $recordId, 'user_id' => $userId]) ->first(); }
php
{ "resource": "" }
q4555
MenuHelper.posts
train
public function posts() { $links[] = [__d('me_cms', 'List posts'), [ 'controller' => 'Posts', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add post'), [ 'controller' => 'Posts', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; //Only admins and managers can access these actions if ($this->Auth->isGroup(['admin', 'manager'])) { $links[] = [__d('me_cms', 'List categories'), [ 'controller' => 'PostsCategories', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add category'), [ 'controller' => 'PostsCategories', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; } $links[] = [__d('me_cms', 'List tags'), [ 'controller' => 'PostsTags', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; return [$links, I18N_POSTS, ['icon' => 'far file-alt']]; }
php
{ "resource": "" }
q4556
MenuHelper.pages
train
public function pages() { $links[] = [__d('me_cms', 'List pages'), [ 'controller' => 'Pages', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; //Only admins and managers can access these actions if ($this->Auth->isGroup(['admin', 'manager'])) { $links[] = [__d('me_cms', 'Add page'), [ 'controller' => 'Pages', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'List categories'), [ 'controller' => 'PagesCategories', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add category'), [ 'controller' => 'PagesCategories', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; } $links[] = [__d('me_cms', 'List static pages'), [ 'controller' => 'Pages', 'action' => 'indexStatics', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; return [$links, I18N_PAGES, ['icon' => 'far copy']]; }
php
{ "resource": "" }
q4557
MenuHelper.photos
train
public function photos() { $links[] = [__d('me_cms', 'List photos'), [ 'controller' => 'Photos', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Upload photos'), [ 'controller' => 'Photos', 'action' => 'upload', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'List albums'), [ 'controller' => 'PhotosAlbums', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add album'), [ 'controller' => 'PhotosAlbums', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; return [$links, I18N_PHOTOS, ['icon' => 'camera-retro']]; }
php
{ "resource": "" }
q4558
MenuHelper.banners
train
public function banners() { //Only admins and managers can access these controllers if (!$this->Auth->isGroup(['admin', 'manager'])) { return; } $links[] = [__d('me_cms', 'List banners'), [ 'controller' => 'Banners', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Upload banners'), [ 'controller' => 'Banners', 'action' => 'upload', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; //Only admin can access this controller if ($this->Auth->isGroup('admin')) { $links[] = [__d('me_cms', 'List positions'), [ 'controller' => 'BannersPositions', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add position'), [ 'controller' => 'BannersPositions', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; } return [$links, __d('me_cms', 'Banners'), ['icon' => 'shopping-cart']]; }
php
{ "resource": "" }
q4559
MenuHelper.users
train
public function users() { //Only admins and managers can access this controller if (!$this->Auth->isGroup(['admin', 'manager'])) { return; } $links[] = [__d('me_cms', 'List users'), [ 'controller' => 'Users', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add user'), [ 'controller' => 'Users', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; //Only admins can access these actions if ($this->Auth->isGroup('admin')) { $links[] = [__d('me_cms', 'List groups'), [ 'controller' => 'UsersGroups', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add group'), [ 'controller' => 'UsersGroups', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; } return [$links, I18N_USERS, ['icon' => 'users']]; }
php
{ "resource": "" }
q4560
MenuHelper.backups
train
public function backups() { //Only admins can access this controller if (!$this->Auth->isGroup('admin')) { return; } $links[] = [__d('me_cms', 'List backups'), [ 'controller' => 'Backups', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Add backup'), [ 'controller' => 'Backups', 'action' => 'add', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; return [$links, __d('me_cms', 'Backups'), ['icon' => 'database']]; }
php
{ "resource": "" }
q4561
MenuHelper.systems
train
public function systems() { //Only admins and managers can access this controller if (!$this->Auth->isGroup(['admin', 'manager'])) { return; } $links[] = [__d('me_cms', 'Temporary files'), [ 'controller' => 'Systems', 'action' => 'tmpViewer', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; //Only admins can manage logs if ($this->Auth->isGroup('admin')) { $links[] = [__d('me_cms', 'Log management'), [ 'controller' => 'Logs', 'action' => 'index', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; } $links[] = [__d('me_cms', 'System checkup'), [ 'controller' => 'Systems', 'action' => 'checkup', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Media browser'), [ 'controller' => 'Systems', 'action' => 'browser', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; $links[] = [__d('me_cms', 'Changelogs'), [ 'controller' => 'Systems', 'action' => 'changelogs', 'plugin' => 'MeCms', 'prefix' => ADMIN_PREFIX, ]]; return [$links, __d('me_cms', 'System'), ['icon' => 'wrench']]; }
php
{ "resource": "" }
q4562
ControllerTrait.dispatch
train
protected function dispatch($request, $response) { $this->setRequest($request); $this->setResponse($response); if (!$this->responder) { $this->responder = Respond::getResponder(); } return $this->_execInternalMethods(); }
php
{ "resource": "" }
q4563
DoctrineSpool.sendEmails
train
protected function sendEmails(Swift_Transport $transport, &$failedRecipients, array $emails) { $count = 0; $time = time(); $emails = $this->prepareEmails($emails); $skip = false; foreach ($emails as $email) { if ($skip) { $email->setStatus(SpoolEmailStatus::STATUS_FAILED); $email->setStatusMessage('The time limit of execution is exceeded'); continue; } $count += $this->sendEmail($transport, $email, $failedRecipients); $this->flushEmail($email); if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit()) { $skip = true; } } return $count; }
php
{ "resource": "" }
q4564
DoctrineSpool.prepareEmails
train
protected function prepareEmails(array $emails) { foreach ($emails as $email) { $email->setStatus(SpoolEmailStatus::STATUS_SENDING); $email->setSentAt(null); $this->om->persist($email); } $this->om->flush(); reset($emails); return $emails; }
php
{ "resource": "" }
q4565
DoctrineSpool.sendEmail
train
protected function sendEmail(Swift_Transport $transport, SpoolEmailInterface $email, &$failedRecipients) { $count = 0; try { if ($transport->send($email->getMessage(), $failedRecipients)) { $email->setStatus(SpoolEmailStatus::STATUS_SUCCESS); ++$count; } else { $email->setStatus(SpoolEmailStatus::STATUS_FAILED); } } catch (\Swift_TransportException $e) { $email->setStatus(SpoolEmailStatus::STATUS_FAILED); $email->setStatusMessage($e->getMessage()); } return $count; }
php
{ "resource": "" }
q4566
DoctrineSpool.flushEmail
train
protected function flushEmail(SpoolEmailInterface $email): void { $email->setSentAt(new \DateTime()); $this->om->persist($email); $this->om->flush(); if (SpoolEmailStatus::STATUS_SUCCESS === $email->getStatus()) { $this->om->remove($email); $this->om->flush(); } $this->om->detach($email); }
php
{ "resource": "" }
q4567
AppTable.beforeSave
train
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) { if (empty($entity->created)) { $entity->created = new Time; } elseif (!empty($entity->created) && !$entity->created instanceof Time) { $entity->created = new Time($entity->created); } }
php
{ "resource": "" }
q4568
AppTable.findRandom
train
public function findRandom(Query $query, array $options) { $query->order('rand()'); if (!$query->clause('limit')) { $query->limit(1); } return $query; }
php
{ "resource": "" }
q4569
AppTable.getCacheName
train
public function getCacheName($associations = false) { $values = $this->cache ?: null; if ($associations) { $values = [$values]; foreach ($this->associations()->getIterator() as $association) { if (method_exists($association->getTarget(), 'getCacheName') && $association->getTarget()->getCacheName()) { $values[] = $association->getTarget()->getCacheName(); } } $values = array_values(array_unique(array_filter($values))); } return $values; }
php
{ "resource": "" }
q4570
AppTable.getList
train
public function getList() { return $this->find('list') ->order([$this->getDisplayField() => 'ASC']) ->cache(sprintf('%s_list', $this->getTable()), $this->getCacheName()); }
php
{ "resource": "" }
q4571
DatasetTrait.setPage
train
public function setPage(int $page) { if ($page < 0) { throw new \InvalidArgumentException("Invalid page '$page.'", 500); } $this->setOffset(($page - 1) * $this->getLimit()); return $this; }
php
{ "resource": "" }
q4572
DatasetTrait.setOffset
train
public function setOffset($offset) { if (!is_numeric($offset) || $offset < 0) { throw new \InvalidArgumentException("Invalid offset '$offset.'", 500); } $this->offset = (int)$offset; return $this; }
php
{ "resource": "" }
q4573
BaseMaker.getResource
train
protected function getResource(string $sFile, array $aFields): string { if (empty(static::RESOURCE_PATH)) { throw new NailsException('RESOURCE_PATH is not defined'); } $sResource = require static::RESOURCE_PATH . $sFile; foreach ($aFields as $sField => $sValue) { $sKey = '{{' . strtoupper($sField) . '}}'; $sResource = str_replace($sKey, $sValue, $sResource); } return $sResource; }
php
{ "resource": "" }
q4574
BaseMaker.createPath
train
protected function createPath(string $sPath): BaseMaker { if (!is_dir($sPath)) { if (!@mkdir($sPath, self::FILE_PERMISSION, true)) { throw new DoesNotExistException('Path "' . $sPath . '" does not exist and could not be created'); } } if (!is_writable($sPath)) { throw new IsNotWritableException('Path "' . $sPath . '" exists, but is not writable'); } return $this; }
php
{ "resource": "" }
q4575
BaseMaker.getArguments
train
protected function getArguments(): array { Factory::helper('string'); $aArguments = []; if (!empty($this->aArguments)) { foreach ($this->aArguments as $aArgument) { $aArguments[] = (object) [ 'name' => getFromArray('name', $aArgument), 'value' => $this->oInput->getArgument(getFromArray('name', $aArgument)), 'required' => getFromArray('required', $aArgument), ]; } } else { $aArgumentsRaw = array_slice($this->oInput->getArguments(), 1); foreach ($aArgumentsRaw as $sField => $sValue) { $sField = strtoupper(camelcase_to_underscore($sField)); $aArguments[] = (object) [ 'name' => $sField, 'value' => $sValue, 'required' => true, ]; } } unset($sField); unset($sValue); foreach ($aArguments as &$oArgument) { if (empty($oArgument->value)) { $sLabel = str_replace('_', ' ', $oArgument->name); $sLabel = ucwords(strtolower($sLabel)); $sError = ''; do { $oArgument->value = $this->ask($sError . $sLabel . ':', ''); $sError = '<error>Please specify</error> '; if ($oArgument->required && empty($oArgument->value)) { $bAskAgain = true; } else { $bAskAgain = false; } } while ($bAskAgain); } } unset($oArgument); // Finally set as key values $aOut = []; foreach ($aArguments as $oArgument) { $aOut[strtoupper($oArgument->name)] = $oArgument->value; } return $aOut; }
php
{ "resource": "" }
q4576
BaseMaker.validateServiceFile
train
protected function validateServiceFile(string $sToken = null): BaseMaker { if (empty($sToken) && empty(static::SERVICE_TOKEN)) { throw new ConsoleException( 'SERVICE_TOKEN is not set' ); } elseif (empty($sToken)) { $sToken = static::SERVICE_TOKEN; } // Detect the services file if (!file_exists(static::SERVICE_PATH)) { throw new ConsoleException( 'Could not detect the app\'s services.php file: ' . static::SERVICE_PATH ); } // Look for the generator token $this->fServicesHandle = fopen(static::SERVICE_PATH, 'r+');; $bFound = false; if ($this->fServicesHandle) { $iLocation = 0; while (($sLine = fgets($this->fServicesHandle)) !== false) { if (preg_match('#^(\s*)// GENERATOR\[' . $sToken . '\]#', $sLine, $aMatches)) { $bFound = true; $this->iServicesIndent = strlen($aMatches[1]); $this->iServicesTokenLocation = $iLocation; break; } $iLocation = ftell($this->fServicesHandle); } if (!$bFound) { fclose($this->fServicesHandle); throw new ConsoleException( 'Services file does not contain the generator token (i.e // GENERATOR[' . $sToken . ']) ' . 'This token is required so that the tool can safely insert new definitions' ); } } else { throw new ConsoleException( 'Failed to open the services file for reading and writing: ' . static::SERVICE_PATH ); } return $this; }
php
{ "resource": "" }
q4577
BaseMaker.writeServiceFile
train
protected function writeServiceFile(array $aServiceDefinitions = []): BaseMaker { // Create a temporary file $fTempHandle = fopen(static::SERVICE_TEMP_PATH, 'w+'); rewind($this->fServicesHandle); $iLocation = 0; while (($sLine = fgets($this->fServicesHandle)) !== false) { if ($iLocation === $this->iServicesTokenLocation) { fwrite( $fTempHandle, implode("\n", $aServiceDefinitions) . "\n" ); } fwrite($fTempHandle, $sLine); $iLocation = ftell($this->fServicesHandle); } // @todo (Pablo - 2019-02-11) - Sort the services by name // Move the temp services file into place unlink(static::SERVICE_PATH); rename(static::SERVICE_TEMP_PATH, static::SERVICE_PATH); fclose($fTempHandle); fclose($this->fServicesHandle); return $this; }
php
{ "resource": "" }
q4578
CoalesceOptionalStrings.buildCoalescedStrings
train
protected function buildCoalescedStrings(array $prefixStrings, array $suffix) { $strings = $this->runPass($this->buildPrefix($prefixStrings)); if (count($strings) === 1 && $strings[0][0][0] === []) { // If the prefix has been remerged into a list of strings which contains only one string // of which the first element is an optional alternations, we only need to append the // suffix $strings[0][] = $suffix; } else { // Put the current list of strings that form the prefix into a new list of strings, of // which the only string is composed of our optional prefix followed by the suffix array_unshift($strings, []); $strings = [[$strings, $suffix]]; } return $strings; }
php
{ "resource": "" }
q4579
CoalesceOptionalStrings.buildPrefix
train
protected function buildPrefix(array $strings) { $prefix = []; foreach ($strings as $string) { // Remove the last element (suffix) of each string before adding it array_pop($string); $prefix[] = $string; } return $prefix; }
php
{ "resource": "" }
q4580
CoalesceOptionalStrings.buildSuffix
train
protected function buildSuffix(array $strings) { $suffix = [[]]; foreach ($strings as $string) { if ($this->isCharacterClassString($string)) { foreach ($string[0] as $element) { $suffix[] = $element; } } else { $suffix[] = $string; } } return $suffix; }
php
{ "resource": "" }
q4581
CoalesceOptionalStrings.getPrefixGroups
train
protected function getPrefixGroups(array $strings) { $groups = []; foreach ($strings as $k => $string) { if ($this->hasOptionalSuffix($string)) { $groups[serialize(end($string))][$k] = $string; } } return $groups; }
php
{ "resource": "" }
q4582
URLScheme.match
train
public function match($url) { if (!$this->pattern) { $this->pattern = self::buildPatternFromScheme($this); } return (bool) preg_match($this->pattern, $url); }
php
{ "resource": "" }
q4583
URLScheme.buildPatternFromScheme
train
static protected function buildPatternFromScheme(URLScheme $scheme) { // generate a unique random string $uniq = md5(mt_rand()); // replace the wildcard sub-domain if exists $scheme = str_replace( '://'.self::WILDCARD_CHARACTER.'.', '://'.$uniq, $scheme->__tostring() ); // replace the wildcards $scheme = str_replace( self::WILDCARD_CHARACTER, $uniq, $scheme ); // set the pattern wrap $wrap = '|'; // quote the pattern $pattern = preg_quote($scheme, $wrap); // replace the unique string by the character class $pattern = str_replace($uniq, '.*', $pattern); return $wrap.$pattern.$wrap.'iu'; }
php
{ "resource": "" }
q4584
ExperiencesTable.toLevel
train
public function toLevel(Experiences $experiences): Level { $woundsBonus = $this->toWoundsBonus($experiences); return new Level($this->bonusToLevelValue($woundsBonus), $this); }
php
{ "resource": "" }
q4585
ExperiencesTable.toTotalLevel
train
public function toTotalLevel(Experiences $experiences): Level { $currentExperiences = 0; $usedExperiences = 0; $maxLevelValue = 0; while ($usedExperiences + $currentExperiences <= $experiences->getValue()) { $level = $this->toLevel(new Experiences($currentExperiences, $this)); if ($maxLevelValue < $level->getValue()) { $usedExperiences += $currentExperiences; $maxLevelValue = $level->getValue(); } $currentExperiences++; } return new Level($maxLevelValue, $this); }
php
{ "resource": "" }
q4586
ExperiencesTable.toTotalExperiences
train
public function toTotalExperiences(Level $level): Experiences { $experiencesSum = 0; for ($levelValueToCast = $level->getValue(); $levelValueToCast > 0; $levelValueToCast--) { if ($levelValueToCast > 1) { // main profession has first level for free $currentLevel = new Level($levelValueToCast, $this); $experiencesSum += $currentLevel->getExperiences()->getValue(); } } return new Experiences($experiencesSum, $this); }
php
{ "resource": "" }
q4587
Db.driverClass
train
public static function driverClass($driver) { if ($driver instanceof PDO) { $name = $driver->getAttribute(PDO::ATTR_DRIVER_NAME); } else { $name = (string)$driver; } $name = strtolower($name); return isset(self::$drivers[$name]) ? self::$drivers[$name] : null; }
php
{ "resource": "" }
q4588
Db.dropTable
train
final public function dropTable(string $table, array $options = []) { $options += [Db::OPTION_IGNORE => false]; $this->dropTableDb($table, $options); $tableKey = strtolower($table); unset($this->tables[$tableKey], $this->tableNames[$tableKey]); }
php
{ "resource": "" }
q4589
Db.fetchTableNames
train
final public function fetchTableNames() { if ($this->tableNames !== null) { return array_values($this->tableNames); } $names = $this->fetchTableNamesDb(); $this->tableNames = []; foreach ($names as $name) { $name = $this->stripPrefix($name); $this->tableNames[strtolower($name)] = $name; } return array_values($this->tableNames); }
php
{ "resource": "" }
q4590
Db.fetchTableDef
train
final public function fetchTableDef(string $table) { $tableKey = strtolower($table); // First check the table cache. if (isset($this->tables[$tableKey])) { $tableDef = $this->tables[$tableKey]; if (isset($tableDef['columns'], $tableDef['indexes'])) { return $tableDef; } } elseif ($this->tableNames !== null && !isset($this->tableNames[$tableKey])) { return null; } $tableDef = $this->fetchTableDefDb($table); if ($tableDef !== null) { $this->fixIndexes($tableDef['name'], $tableDef); $this->tables[$tableKey] = $tableDef; } return $tableDef; }
php
{ "resource": "" }
q4591
Db.fetchColumnDefs
train
final public function fetchColumnDefs(string $table) { $tableKey = strtolower($table); if (!empty($this->tables[$tableKey]['columns'])) { $this->tables[$tableKey]['columns']; } elseif ($this->tableNames !== null && !isset($this->tableNames[$tableKey])) { return null; } $columnDefs = $this->fetchColumnDefsDb($table); if ($columnDefs !== null) { $this->tables[$tableKey]['columns'] = $columnDefs; } return $columnDefs; }
php
{ "resource": "" }
q4592
Db.typeDef
train
public static function typeDef(string $type) { // Check for the unsigned signifier. $unsigned = null; if ($type[0] === 'u') { $unsigned = true; $type = substr($type, 1); } elseif (preg_match('`(.+)\s+unsigned`i', $type, $m)) { $unsigned = true; $type = $m[1]; } // Remove brackets from the type. $brackets = null; if (preg_match('`^(.*)\((.*)\)$`', $type, $m)) { $brackets = $m[2]; $type = $m[1]; } // Look for the type. $type = strtolower($type); if (isset(self::$types[$type])) { $row = self::$types[$type]; $dbtype = $type; // Resolve an alias. if (is_string($row)) { $dbtype = $row; $row = self::$types[$row]; } } else { return null; } // Now that we have a type row we can build a schema for it. $schema = [ 'type' => $row['type'], 'dbtype' => $dbtype ]; if (!empty($row['schema'])) { $schema += $row['schema']; } if ($row['type'] === 'integer' && $unsigned) { $schema['unsigned'] = true; if (!empty($schema['maximum'])) { $schema['maximum'] = $schema['maximum'] * 2 + 1; $schema['minimum'] = 0; } } if (!empty($row['length'])) { $schema['maxLength'] = (int)$brackets ?: 255; } if (!empty($row['precision'])) { $parts = array_map('trim', explode(',', $brackets)); $schema['precision'] = (int)$parts[0]; if (isset($parts[1])) { $schema['scale'] = (int)$parts[1]; } } if (!empty($row['enum'])) { $enum = explode(',', $brackets); $schema['enum'] = array_map(function ($str) { return trim($str, "'\" \t\n\r\0\x0B"); }, $enum); } return $schema; }
php
{ "resource": "" }
q4593
Db.dbType
train
protected static function dbType(array $typeDef) { $dbtype = $typeDef['dbtype']; if (!empty($typeDef['maxLength'])) { $dbtype .= "({$typeDef['maxLength']})"; } elseif (!empty($typeDef['unsigned'])) { $dbtype = 'u'.$dbtype; } elseif (!empty($typeDef['precision'])) { $dbtype .= "({$typeDef['precision']}"; if (!empty($typeDef['scale'])) { $dbtype .= ",{$typeDef['scale']}"; } $dbtype .= ')'; } elseif (!empty($typeDef['enum'])) { $parts = array_map(function ($str) { return "'{$str}'"; }, $typeDef['enum']); $dbtype .= '('.implode(',', $parts).')'; } return $dbtype; }
php
{ "resource": "" }
q4594
Db.findPrimaryKeyIndex
train
protected function findPrimaryKeyIndex(array $indexes) { foreach ($indexes as $index) { if ($index['type'] === Db::INDEX_PK) { return $index; } } return null; }
php
{ "resource": "" }
q4595
Db.fixIndexes
train
private function fixIndexes(string $tableName, array &$tableDef, $curTableDef = null) { $tableDef += ['indexes' => []]; // Loop through the columns and add the primary key index. $primaryColumns = []; foreach ($tableDef['columns'] as $cname => $cdef) { if (!empty($cdef['primary'])) { $primaryColumns[] = $cname; } } // Massage the primary key index. $primaryFound = false; foreach ($tableDef['indexes'] as &$indexDef) { $indexDef += ['name' => $this->buildIndexName($tableName, $indexDef), 'type' => null]; if ($indexDef['type'] === Db::INDEX_PK) { $primaryFound = true; if (empty($primaryColumns)) { foreach ($indexDef['columns'] as $cname) { $tableDef['columns'][$cname]['primary'] = true; } } elseif (array_diff($primaryColumns, $indexDef['columns'])) { throw new \Exception("There is a mismatch in the primary key index and primary key columns.", 500); } } elseif (isset($curTableDef['indexes'])) { foreach ($curTableDef['indexes'] as $curIndexDef) { if ($this->indexCompare($indexDef, $curIndexDef) === 0) { if (!empty($curIndexDef['name'])) { $indexDef['name'] = $curIndexDef['name']; } break; } } } } if (!$primaryFound && !empty($primaryColumns)) { $tableDef['indexes'][] = [ 'columns' => $primaryColumns, 'type' => Db::INDEX_PK ]; } }
php
{ "resource": "" }
q4596
Db.indexCompare
train
private function indexCompare(array $a, array $b): int { if ($a['columns'] > $b['columns']) { return 1; } elseif ($a['columns'] < $b['columns']) { return -1; } return strcmp( isset($a['type']) ? $a['type'] : '', isset($b['type']) ? $b['type'] : '' ); }
php
{ "resource": "" }
q4597
Db.getOne
train
final public function getOne($table, array $where, array $options = []) { $rows = $this->get($table, $where, $options); $row = $rows->fetch(); return $row === false ? null : $row; }
php
{ "resource": "" }
q4598
Db.load
train
public function load(string $table, $rows, array $options = []) { foreach ($rows as $row) { $this->insert($table, $row, $options); } }
php
{ "resource": "" }
q4599
Db.buildIndexName
train
protected function buildIndexName(string $tableName, array $indexDef): string { $indexDef += ['type' => Db::INDEX_IX, 'suffix' => '']; $type = $indexDef['type']; if ($type === Db::INDEX_PK) { return 'primary'; } $px = self::val($type, [Db::INDEX_IX => 'ix_', Db::INDEX_UNIQUE => 'ux_'], 'ix_'); $sx = $indexDef['suffix']; $result = $px.$tableName.'_'.($sx ?: implode('', $indexDef['columns'])); return $result; }
php
{ "resource": "" }